diff --git "a/5140.jsonl" "b/5140.jsonl" new file mode 100644--- /dev/null +++ "b/5140.jsonl" @@ -0,0 +1,733 @@ +{"seq_id":"110096320","text":"from __future__ import print_function\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Convolutional neural network (two convolutional layers)\nclass ConvNet(nn.Module):\n # Our batch shape for input x is (3, 1000, 1000)\n # nn.Conv2d(3, 16, kernel_size=5, stride=1, padding=2),\n # model 要運算導數(derivative)及梯度(gradient)需要的資訊都在裡頭\n def __init__(self, num_classes=4): # 定義 model 中需要的參數,weight、bias 等\n super(ConvNet, self).__init__()\n # Input channels = 1(gray) or 3(rgb), output channels = 32\n # 初始化卷积层\n self.layer1 = nn.Sequential( # input shape (1, 256, 256)\n nn.Conv2d(\n in_channels=3, # input height\n out_channels=16, # n_filters\n kernel_size=3, # filter size\n stride=1, # filter movement/step\n padding=1 # zero-padding\n ), # output shape 16, 256, 256), padding=(kernel_size-1)/2 当 stride=1\n nn.BatchNorm2d(num_features=16),\n nn.ReLU(True), # activation\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0) # 池化層(池化核爲2*2,步長爲2)=最大池化 # output shape (16, 128, 128)\n )\n self.layer2 = nn.Sequential( # input shape (16, 128, 128)\n nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1), # output shape (32, 128, 128)\n nn.BatchNorm2d(num_features=32),\n nn.ReLU(True), # activation\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0) # output shape (32, 64, 64)\n )\n self.layer3 = nn.Sequential(\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1), # output shape (64, 64, 64)\n nn.BatchNorm2d(num_features=64),\n nn.ReLU(True),\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0) # output shape (64, 32, 32), zero-padding\n )\n self.drop_out = nn.Dropout(p=0.2, inplace=False) # 防止过拟合\n # self.drop_out = nn.Dropout2d(p=0.25, inplace=False)\n self.fc_drop = nn.Dropout(p=0.2, inplace=False) # 防止过拟合\n\n # self.fc = nn.Linear(125 * 125 * 64, num_classes)\n # self.fc = nn.Linear(250 * 250 * 32, num_classes)\n # 2,000,000 input features, 32 output features (see sizing flow below)\n # self.fc1 = nn.Linear(233 * 90 * 64, args.fc1)\n # self.fc2 = nn.Linear(args.fc1, args.classes)\n # 32 input features, 4 output features for our 4 defined classes\n # self.fc3 = nn.Linear(16, 4)\n # 初始化卷积层, full connection\n # fully connected layer, output 4 classes\n self.fc_layers = nn.Sequential(\n nn.Linear(in_features=32 * 32 * 64, out_features=512), # 256x256\n # nn.Linear(in_features=64 * 64 * 64, out_features=512), # 512x512\n # nn.Linear(in_features=80 * 80 * 64, out_features=512), # 640x640\n # nn.ReLU(),\n nn.ReLU(True),\n # nn.LeakyReLU(),\n # nn.Dropout(0.2),\n # nn.Dropout(0.2, inplace=False),\n nn.Linear(in_features=512, out_features=256),\n nn.Linear(in_features=256, out_features=num_classes)\n )\n\n def forward(self, input): # 定義 model 接收 input 時,data 要怎麼傳遞、經過哪些 activation function 等\n # 拼接层\n output = self.layer1(input)\n output = self.layer2(output)\n output = self.layer3(output)\n # flattens the data dimensions from 233 x 90 x 32 into 3164 x 1\n # 左行右列, -1在哪边哪边固定只有一列\n # output = output.reshape(output.size(0), -1)\n output = output.view(output.size(0), -1)\n # 以一定概率丢掉一些神经单元,防止过拟合\n output = self.drop_out(output)\n # output = self.fc1(output)\n # output = self.fc2(output)\n # output = self.fc3(output)\n output = self.fc_layers(output)\n output = self.fc_drop(output)\n # return output # return output for visualization\n return F.log_softmax(output, dim=1) # 輸出用 softmax 處理\n","sub_path":"model_rgb.py","file_name":"model_rgb.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"171418837","text":"import logging\nfrom elasticsearch import Elasticsearch\n\ndef connect_elasticsearch():\n _es = None\n _es = Elasticsearch([{'host': 'localhost', 'port': 9200}])\n if _es.ping():\n print('Yay Connect')\n else:\n print('Awww it could not connect!')\n return _es\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.ERROR)\n es = connect_elasticsearch()","sub_path":"Assignment 4 - Databases and Integration/Task - 2 and 3 - Products Webapp/flaskr/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"4970674","text":"from django.shortcuts import render, redirect\nfrom .form import BuscarZonaForm, BuscarEmpresaForm, BuscarTematicaForm\nfrom django.http import HttpResponse\nfrom cursos.models import Curso\nfrom practicas.models import Practica\nfrom empresa.models import Empresa\n\ndef index(request):\n\treturn render(request,'djangoPW/index.html')\n\n\ndef buscar_zona(request):\n\tif request.method == 'POST':\n\t\tform = BuscarZonaForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tzona=request.POST['zona']\n\t\t\turl='/buscar_zona/'+str(zona)\n\t\t\treturn redirect(url)\n\telse:\n\t\tform = BuscarZonaForm()\n\tcontext={'form':form}\n\treturn render(request,'djangoPW/Buscar_zona.html',context)\n\ndef listar_zona(request, zona):\n\tlista_curso=Curso.objects.filter(zona__icontains=zona)\n\tlista_practica=Practica.objects.filter(zona__icontains=zona)\n\tcontext={'lista_curso':lista_curso, 'lista_practica':lista_practica,'zona':zona}\n\treturn render(request,'djangoPW/Lista_zona.html',context)\n\ndef buscar_empresa(request):\n\tif request.method == 'POST':\n\t\tform=BuscarEmpresaForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tempresa=request.POST['empresa']\n\t\t\tlista_empresas=Empresa.objects.filter(nombre__icontains=empresa)\n\t\t\treturn render(request,'djangoPW/Listar_empresas.html',{'empresa':empresa,'lista_empresas':lista_empresas})\n\telse:\n\t\tform=BuscarEmpresaForm()\n\tcontext={'form':form}\n\treturn render(request,'djangoPW/Buscar_empresa.html',context)\n\ndef buscar_tematica(request):\n\tif request.method == 'POST':\n\t\tform=BuscarTematicaForm(request.POST)\n\t\tif form.is_valid():\n\t\t\ttema=request.POST['tema']\n\t\t\tlista_cursos=Curso.objects.filter(descripcion__icontains=tema)\n\t\t\tlista_practicas=Practica.objects.filter(descripcion__icontains=tema)\n\t\t\tcontext={'tema':tema,'lista_cursos':lista_cursos,'lista_practicas':lista_practicas}\n\t\t\treturn render(request,'djangoPW/Listar_tematica.html',context)\n\telse:\n\t\tform=BuscarTematicaForm()\n\tcontext={'form':form}\n\treturn render(request,'djangoPW/Buscar_tematica.html',context)","sub_path":"Primer_cuatrimestre/PW/Trabajo/entregables/09-01-2017-gestor/djangoPW/djangoPW/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"311019616","text":"# MNIST\r\n\r\n'''https://www.kaggle.com/ngbolin/mnist-dataset-digit-recognizer/data'''\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nnp.random.seed(1212)\r\nimport keras\r\nfrom keras.models import Model\r\nfrom keras.layers import *\r\nfrom keras import optimizers\r\n\r\ndf_train = pd.read_csv('D:\\Programming Tutorials\\Machine Learning\\Projects\\Datasets\\mnsit train.csv')\r\ndf_test = pd.read_csv('D:\\Programming Tutorials\\Machine Learning\\Projects\\Datasets\\mnsit test.csv')\r\n\r\ndf_train.head()\r\n\r\ndf_features = df_train.iloc[:, 1:785]\r\ndf_label = df_train.iloc[:, 0]\r\n\r\nX_test = df_test.iloc[:, 0:784]\r\n\r\nprint(X_test.shape)\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_cv, y_train, y_cv = train_test_split(df_features, df_label, \r\n test_size = 0.2,\r\n random_state = 1212)\r\n\r\nX_train = X_train.as_matrix().reshape(33600, 784) #(33600, 784)\r\nX_cv = X_cv.as_matrix().reshape(8400, 784) #(8400, 784)\r\n\r\nX_test = X_test.as_matrix().reshape(28000, 784)\r\n\r\nprint((min(X_train[1]), max(X_train[1])))\r\n\r\n# Feature Normalization \r\nX_train = X_train.astype('float32'); X_cv= X_cv.astype('float32'); X_test = X_test.astype('float32')\r\nX_train /= 255; X_cv /= 255; X_test /= 255\r\n\r\n# Convert labels to One Hot Encoded\r\nnum_digits = 10\r\ny_train = keras.utils.to_categorical(y_train, num_digits)\r\ny_cv = keras.utils.to_categorical(y_cv, num_digits)\r\n\r\n# Printing 2 examples of labels after conversion\r\nprint(y_train[0]) # 2\r\nprint(y_train[3]) # 7\r\n\r\n","sub_path":"MNIST.py","file_name":"MNIST.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"143561723","text":"# coding=UTF-8\r\nimport numpy as np\r\n\r\n\r\nclass AHP():\r\n\r\n def __init__(self, metodo, precisao, alternativas, criterios, subCriterios, matrizesPreferencias, log=False):\r\n self.metodo = metodo\r\n self.precisao = precisao\r\n self.alternativas = alternativas\r\n self.criterios = criterios\r\n self.subCriterios = subCriterios\r\n self.matrizesPreferencias = matrizesPreferencias\r\n self.log = log\r\n\r\n self.prioridadesGlobais = []\r\n\r\n @staticmethod\r\n def Aproximado(matriz, precisao):\r\n soma_colunas = matriz.sum(axis=0)\r\n matriz_norm = np.divide(matriz, soma_colunas)\r\n media_linhas = matriz_norm.mean(axis=1)\r\n\r\n return media_linhas.round(precisao)\r\n\r\n @staticmethod\r\n def Geometrico(matriz, precisao):\r\n media_geometrica = [np.prod(linha) ** (1 / len(linha)) for linha in matriz]\r\n media_geometrica_norm = media_geometrica / sum(media_geometrica)\r\n\r\n return media_geometrica_norm.round(precisao)\r\n\r\n @staticmethod\r\n def Autovalor(matriz, precisao, interacao=100, autovetor_anterior=None):\r\n matriz_quadrada = np.linalg.matrix_power(matriz, 2)\r\n soma_linhas = np.sum(matriz_quadrada, axis=1)\r\n soma_coluna = np.sum(soma_linhas, axis=0)\r\n autovetor_atual = np.divide(soma_linhas, soma_coluna)\r\n\r\n if autovetor_anterior is None:\r\n autovetor_anterior = np.zeros(matriz.shape[0])\r\n\r\n diferenca = np.subtract(autovetor_atual, autovetor_anterior).round(precisao)\r\n if not np.any(diferenca):\r\n return autovetor_atual.round(precisao)\r\n\r\n interacao -= 1\r\n if interacao > 0:\r\n return AHP.Autovalor(matriz_quadrada, precisao, interacao, autovetor_atual)\r\n else:\r\n return autovetor_atual.round(precisao)\r\n\r\n @staticmethod\r\n def Consistencia(matriz):\r\n if matriz.shape[0] and matriz.shape[1] > 2:\r\n # Teorema de Perron-Frobenius\r\n lambda_max = np.real(np.linalg.eigvals(matriz).max())\r\n ic = (lambda_max - len(matriz)) / (len(matriz) - 1)\r\n ri = {3: 0.52, 4: 0.89, 5: 1.11, 6: 1.25, 7: 1.35, 8: 1.40, 9: 1.45,\r\n 10: 1.49, 11: 1.52, 12: 1.54, 13: 1.56, 14: 1.58, 15: 1.59}\r\n rc = ic / ri[len(matriz)]\r\n else:\r\n lambda_max = 0\r\n ic = 0\r\n rc = 0\r\n\r\n return lambda_max, ic, rc\r\n\r\n def VetorPrioridadesLocais(self):\r\n vetor_prioridades_locais = {}\r\n for criterio in self.matrizesPreferencias:\r\n matriz = np.array(self.matrizesPreferencias[criterio])\r\n if self.metodo == 'aproximado':\r\n prioridades_locais = self.Aproximado(matriz, self.precisao)\r\n elif self.metodo == 'geometrico':\r\n prioridades_locais = self.Geometrico(matriz, self.precisao)\r\n else:\r\n if matriz.shape[0] and matriz.shape[1] >= 2:\r\n prioridades_locais = self.Autovalor(matriz, self.precisao)\r\n else:\r\n prioridades_locais = self.Aproximado(matriz, self.precisao)\r\n\r\n vetor_prioridades_locais[criterio] = prioridades_locais\r\n\r\n lambda_max, ic, rc = self.Consistencia(matriz)\r\n\r\n if self.log:\r\n print('\\nPrioridades locais do criterio ' + criterio + ':\\n', prioridades_locais)\r\n print('Soma: ', np.round(np.sum(prioridades_locais), self.precisao))\r\n print('Lambda_max = ', lambda_max)\r\n print('Indice de Consistencia ' + criterio + ' = ', round(ic, self.precisao))\r\n print('Razão de Concistência ' + criterio + ' = ', round(rc, 2))\r\n\r\n return vetor_prioridades_locais\r\n\r\n def VetorPrioridadesGlobais(self, prioridades, pesos, criterios):\r\n for criterio in criterios:\r\n peso = pesos[criterios.index(criterio)]\r\n prioridades_locais = prioridades[criterio]\r\n prioridade_global = np.round(peso * prioridades_locais, self.precisao)\r\n\r\n if criterio in self.subCriterios:\r\n self.VetorPrioridadesGlobais(prioridades, prioridade_global, self.subCriterios[criterio])\r\n else:\r\n self.prioridadesGlobais.append(prioridade_global)\r\n\r\n if self.log:\r\n print('\\nPrioridades globais do criterio ' + criterio + '\\n', prioridade_global)\r\n print('Soma: ', sum(prioridade_global).round(self.precisao))\r\n\r\n def Resultado(self):\r\n prioridades = self.VetorPrioridadesLocais()\r\n self.VetorPrioridadesGlobais(prioridades, prioridades['criterios'], self.criterios)\r\n prioridades = np.array(self.prioridadesGlobais)\r\n prioridades = prioridades.sum(axis=0).round(self.precisao)\r\n\r\n return dict(zip(self.alternativas, prioridades))\r\n","sub_path":"original/AnalyticHierarchyProcess.py","file_name":"AnalyticHierarchyProcess.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"201072365","text":"import socket\n\nhost = socket.gethostname()\nport = 586\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((host,port))\nwhile True:\n msg = input('Enter Message to Send\\t:\\t')\n msg.encode()\n s.send(msg)\n data = s.recv(1024)\n print('Received ', repr(data))\n# s.close()\n","sub_path":"networking/client_2.py","file_name":"client_2.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"18762174","text":"'''\n给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,\n返回移除后数组的新长度。不要使用额外的数组空间,你必须在原地修改输入数组\n并在使用 O(1) 额外空间的条件下完成。\n示例 1:\n给定数组 nums = [1,1,2], \n函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 \n你不需要考虑数组中超出新长度后面的元素。\n示例 2:\n给定 nums = [0,0,1,1,1,2,2,3,3,4],\n函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。\n你不需要考虑数组中超出新长度后面的元素。\n说明:\n为什么返回数值是整数,但输出的答案是数组呢?\n请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。\n你可以想象内部操作如下:\n// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝\nint len = removeDuplicates(nums);\n// 在函数里修改输入数组对于调用者是可见的。\n// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。\nfor (int i = 0; i < len; i++) {\n print(nums[i]);\n}\n链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array\n'''\n\n\n# 解法一:本人的菜鸟解法\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n nums_Remove_Duplicates = list(set(nums))\n nums_Remove_Duplicates.sort()\n len_n = len(nums_Remove_Duplicates)\n for i in range(len_n):\n nums[i] = nums_Remove_Duplicates[i]\n\n return len_n\n\n\n\n# 解法二:\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n for i in range(len(nums)-1, 0, -1):\n if nums[i] == num[i-1]:\n nums.pop(i)\n return len(nums)\n\n'''\n1.时间效率O(N^2)空间效率O(1),逆遍历可以防止删除某个元素后影响下一步索引的定位。\n2.每次删除数组元素会引发大量的数据迁移操作,使用以下算法解题效率更高\n'''\n\n\n# 解法三:(最优)\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n i = 0\n for j in range(1, len(nums)):\n if nums[j] != nums[i]:\n nums[i+1] = nums[j]\n i += 1\n return i + 1 if nums else 0\n\n'''\n1.此解法思路同官方题解,时间效率为O(N)\n2.数组完成排序后,我们可以放置两个指针 i 和 j,其中 i 是慢指针,而 j 是快指针。\n 只要 nums[i] = nums[j],我们就增加 j 以跳过重复项。当我们遇到 nums[j] != nums[i]时,\n 跳过重复项的运行已经结束,因此我们必须把它(nums[j])的值复制到 nums[i + 1]。然后递增 i,\n 接着我们将再次重复相同的过程,直到 j 到达数组的末尾为止\n''' \n","sub_path":"1_Array/026.删除排序数组中的重复项.py","file_name":"026.删除排序数组中的重复项.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"92964644","text":"#For Sachathya\nfrom schLib import schLookups as lookups\n\nclass myClassCls():\n \n def __init__(self,parent):\n self.tag=self.__class__.__name__.replace('Cls','').upper()\n self.sch=parent\n self.ttls=self.sch.ttls\n self.sch.display(\"myClass is ready!\", self.tag)\n\n def initialize(self):\n self.sch.display(\"myClass initialized!\", self.tag)\n\nif __name__ == '__main__':\n if(not hasattr(sch, 'myClassObj') or sch.devMode): \n sch.myClassObj = myClassCls(sch)\n sch.myClassObj.initialize()\n","sub_path":"schPack/additionalFiles/templateConsoleScript.py","file_name":"templateConsoleScript.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"383687677","text":"from back import DataFile,months\nfrom event import *\nimport json\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom PIL import Image as image\nfrom PyQt4 import QtCore,QtGui\nimport random\nimport sys\nimport threading\nimport time\n\ndebug=False\n\n# Class that does basic fullscreen handling shit\nclass Generic_Window(QtGui.QWidget):\n def __init__(self,title=\"\"):\n super(Generic_Window,self).__init__()\n\n def update_time_label():\n # Debugging\n if debug:\n def visibility_status():\n print(\"Testing Generic_Window visibility.\\nIs window visible?: \" + str(self.isVisible()))\n visibility_thread = threading.Thread(group=None,target=visibility_status,name=\"Checking for visibility\")\n visibility_thread.start()\n # Perhaps the window needs a moment to load up (although the time chosen is arbitrary)\n if not self.isVisible():\n print(\"It is recommended to place the thread.start() method after window.show() method to guarantee visibility.\")\n time.sleep(2)\n\n while self.isVisible():\n self.time_label.setText(\"Current date and time: \" + time.ctime())\n time.sleep(1)\n\n # Set the title of the main window\n self.setWindowTitle(title)\n\n # QtGui.QGridLayout instance that is used to hold the QtGui.QCalendarWidget instance in the StartWindow class\n self.tableManager = QtGui.QGridLayout()\n\n # Screen geometry variables for window dimensions and placement\n self.screenwidth = QtGui.QDesktopWidget().screenGeometry().width()\n self.screenheight = QtGui.QDesktopWidget().screenGeometry().height()\n #self.setGeometry(self.screenwidth/2-self.width()/2,self.screenheight/2-self.height()/2,self.width(),self.height())\n\n # Boolean for determining whether the application window is currently fullscreen\n self.isFullScreen = False\n\n # The grid layout manager\n self.grid_manager = QtGui.QGridLayout()\n\n # The timer_thread to be used by each subclass\n self.timer_thread = threading.Thread(group=None,target=update_time_label,name=\"Time thread\")\n\n def timeLayout(self):\n # Time label that contains the current time of day\n self.time_label = QtGui.QLabel(time.ctime())\n self.time_label.setFont(QtGui.QFont(\"Courier\",12))\n\n self.time_box = QtGui.QHBoxLayout()\n self.time_box.addWidget(self.time_label,0)\n\n self.time_box.addSpacing(10)\n\n self.grid_manager.addLayout(self.time_box,0,0,1,1)\n\n def create_widgets(self):\n pass\n \n\nclass MainApp(QtGui.QApplication):\n def __init__(self,cmdArgs=[],title=\"\"):\n QtGui.QApplication.__init__(self,cmdArgs)\n self.title=title\n\n # Set the icon for the window in the taskbar\n pngPath = \"icon.png\"\n self.setWindowIcon(QtGui.QIcon(pngPath))\n\n # Dictionary to hold all the windows\n self.windows = {}\n\n # Create start window\n self.startWindow = StartWindow(self.title)\n\n # Index self.startWindow with StartWindow in self.windows dictionary\n self.windows[StartWindow] = self.startWindow\n\n # Not sure what to do with this yet\n def globalManager(self):\n while self.startWindow.isVisible():\n pass\n #print(random.randint(0,100))\n print(\"Done...\")\n\nclass StartWindow(Generic_Window):\n def __init__(self,title=\"\"):\n super(StartWindow,self).__init__()\n\n # Create Widgets\n self.create_widgets()\n\n # Method to run after widget setup is complete\n self.show()\n\n # Keyboard event detection\n self.keyReleaseEvent = self.keyUp\n\n # Thread to update timer\n self.timer_thread.start()\n\n # Set the calendar to fullscreen\n #self.showFullScreen()\n\n ## When the program detects that a key has been pressed, \n def keyUp(self, event):\n super(StartWindow,self).keyPressEvent(event)\n key = event.key()\n if key == QtCore.Qt.Key_Return:\n self.addDayEvent()\n if key == QtCore.Qt.Key_F11:\n if not self.isFullScreen:\n self.showFullScreen()\n else:\n self.showNormal()\n self.isFullScreen = not self.isFullScreen\n if key == QtCore.Qt.Key_Save:\n print(\"Saved\")\n\n def create_widgets(self):\n self.timeLayout()\n\n self.cal = QtGui.QCalendarWidget()\n self.cal.setGridVisible(True)\n self.cal.clicked.connect(self.addDayEvent)\n\n self.tableManager.addWidget(self.cal)\n self.grid_manager.addLayout(self.tableManager,1,0,1,1)\n\n self.setLayout(self.grid_manager)\n \n def addDayEvent(self):\n self.dayObj = Day(self.cal.selectedDate(),self)\n #self.setVisible(False)\n self.dayObj.setVisible(True)\n\n## This class is to display the current time just like the previous class, and will also \n# show the events that have been recorded for this day, if any exist. The creation of new events\n# and editing of previous ones should be readily accessible from this window. This will likely be \n# the most in-depth part of the programming so far, except implementing a prioritization\n# system for events and a daemon that sends alerts to the desktop and phone like a standard\n# calendar application.\n# (This class will require a connection to the backend and to the file, cal.doc)\n\nclass Day(Generic_Window):\n def __init__(self,date=\"\",parent=None):\n super(Day,self).__init__()\n\n # Date variable\n self.date = date\n\n #Visibility watcher thread\n #visibilityWatcher = threading.Thread(target=self.check_visibility)\n #visibilityWatcher.start()\n\n # Previous window that was just closed\n self.parent = parent\n\n # Data file I/O object\n self.fIO = DataFile(\"cal.dat\")\n\n # F11 Keybindings\n self.keyReleaseEvent = self.keyUp\n\n # Set the title of the main window\n self.current_year = self.date.year()\n self.currentMonth = self.date.month()\n self.currentDay = self.date.day()\n self.setWindowTitle(str(self.current_year) + \", \" + str(months[self.currentMonth]) + \" \" + str(self.currentDay))\n\n # Find events for this day if they exist. Must run before the create_widgets method.\n self.get_events()\n\n # Create the lower group before calling create widgets\n self.create_lower_group()\n\n # Create layouts and buttons and data entries\n self.create_widgets()\n\n # Call before self.timer_thread.start() to ensure visibility for time updater\n self.show()\n\n # To be run after self.show(), to guarantee visibility\n self.timer_thread.start()\n \n # Method to set the previous window visible if this one is killed\n def check_visibility(self):\n time.sleep(2)\n while self.isVisible():\n pass\n self.parent.setVisible(True)\n\n # This method's purpose is to locate any events for the day selected in the cal.doc file if they exist and create a list with each event inside of it. \n def get_events(self):\n self.fIO.get_events()\n self.events = self.fIO.get_day_events((self.current_year,self.currentMonth,self.currentDay))\n self.list_of_events = list(self.events.values())\n\n # Sort the events by the time of day\n self.list_of_events.sort(\n key = self.sort_events\n )\n\n # self.priorities currently don't have a use right now\n self.priorities = []\n for event in self.list_of_events:\n self.priorities.append(QtGui.QStandardItem(event.getPriority()))\n\n # Two layouts will be created: one on the right for displaying events and the other on the left for creating new events.\n def create_widgets(self):\n self.timeLayout()\n\n # The group will contain an HBoxLayout which contains the Layout\n self.eventGroup = QtGui.QGroupBox(\"Events for \" + str(self.date.getDate()))\n\n self.eventLayout = QtGui.QHBoxLayout()\n self.lowerLayout = QtGui.QVBoxLayout()\n\n self.setAutoFillBackground(True)\n \n self.listView = QtGui.QListView()\n model = QtGui.QStandardItemModel()\n self.listView.setModel(model)\n\n if len(self.list_of_events) > 0:\n for event in self.list_of_events:\n item = QtGui.QStandardItem(event.getName() + \" at %.2d:%.2d\" % (event.getHour(),event.getMin()))\n item.setForeground(QtGui.QColor(\"#ffffff\"))\n item.setFont(QtGui.QFont(\"Courier\",14,5))\n model.appendRow(item)\n\n self.eventLayout.addWidget(self.listView)\n\n self.eventGroup.setLayout(self.eventLayout)\n self.grid_manager.addWidget(self.eventGroup,1,0,1,1)\n self.grid_manager.addWidget(self.lowerGroup,2,0,1,1)\n self.grid_manager.setRowStretch(1,1)\n \n self.setLayout(self.grid_manager)\n\n def create_lower_group(self):\n def dateSubmitted():\n self.eName = nameEdit.text()\n if self.eName != \"\":\n split = dateEdit.text().split(\"/\")\n self.eYear = 2000 + int(split[2].split(\" \")[0])\n self.eMonth = int(split[0])\n self.eDay = int(split[1])\n if int(split[2].split(\" \")[1].split(\":\")[0]) == 12 and split[2].split(\" \")[2].strip() == \"AM\":\n self.eHour = 0\n else:\n self.eHour = int(split[2].split(\" \")[1].split(\":\")[0]) + int(split[2].split(\" \")[2].strip() == \"PM\")*12\n self.eMin = int(split[2].split(\" \")[1].split(\":\")[1])\n newEvent = Event(self.eName,self.eYear,self.eMonth,self.eDay,self.eHour,self.eMin,priority=prioritySpinBox.text().split(\":\")[1].strip())\n self.fIO.makeEvent(newEvent)\n string =\"Name: \" + self.eName + \\\n \"\\nYear: \" + str(self.eYear) + \\\n \"\\nMonth: \" + str(self.eMonth) + \\\n \"\\nDay: \" + str(self.eDay) + \\\n \"\\nHour: \" + str(self.eHour) + \\\n \"\\nMin: \" + str(self.eMin)\n print(string)\n self.setVisible(False)\n else:\n print(\"Enter a name for the event.\")\n\n self.lowerGroup = QtGui.QGroupBox(\"Add event: \")\n\n nameEdit = QtGui.QLineEdit(self.lowerGroup)\n\n dateEdit = QtGui.QDateTimeEdit(QtCore.QDateTime(self.current_year,self.currentMonth,self.currentDay,time.localtime()[3],time.localtime()[4]),self.lowerGroup)\n\n prioritySpinBox = QtGui.QSpinBox(self.lowerGroup)\n prioritySpinBox.setPrefix(\"Priority: \")\n prioritySpinBox.setMinimum(1)\n prioritySpinBox.setMaximum(10)\n\n self.submit = QtGui.QPushButton(\"Submit\")\n self.submit.pressed.connect(dateSubmitted)\n\n layout = QtGui.QGridLayout()\n layout.addWidget(nameEdit,0,0,1,1)\n layout.addWidget(dateEdit,1,0,1,1)\n layout.addWidget(prioritySpinBox,2,0,1,1)\n layout.addWidget(self.submit,3,0,1,1)\n\n self.lowerGroup.setLayout(layout)\n\n def keyUp(self,event):\n key = event.key()\n if key == QtCore.Qt.Key_F11:\n if not self.isFullScreen:\n self.showFullScreen()\n else:\n self.showNormal()\n self.isFullScreen = not self.isFullScreen\n if key == QtCore.Qt.Key_Return:\n self.submit.click()\n def sort_events(self,event):\n return event.getTimeValue()\n\ndef timer_thread(callback_function):\n pass\n\n\nif __name__==\"__main__\":\n title=\"Scheduler\"\n\n app = MainApp(title=title)\n\n # Set the style sheet to be used for PyQt4\n app.setStyleSheet(open(\"scheduler.css\").read())\n #app.setStyle(\"Fusion\")\n\n sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"177249092","text":"import re\nimport string\nimport will.nameextractor\nfrom dateutil.parser import parse\n\n\ndef Name_Extract(sentence):\n '''Use nameextractor.py to try to find names'''\n names = nameextractor.main(sentence)\n return names\n\n\ndef Timedate_Extract(sentence):\n '''Find dates and times'''\n lst = (\n 'today', 'tomorrow', 'yesterday', 'am', 'a.m', 'a.m.', 'pm', 'p.m', 'p.m.', 'january', 'february', 'march',\n 'april',\n 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december', 'Today', 'Tomorrow',\n 'Yesterday',\n 'AM', 'A.M', 'A.M.', 'PM', 'P.M', 'P.M.', 'January', 'February', 'March', 'April', 'May', 'June', 'July',\n 'August',\n 'September', 'October', 'November', 'December')\n try:\n for i in lst:\n if i in sentence:\n p = parse(sentence, fuzzy=True)\n td_lst = str(p).split(\" \")\n date_lst = td_lst[0].split(\"-\")\n if \"tomorrow\" in sentence:\n date_lst[2] = int(date_lst[2]) + 1\n\n elif \"yesterday\" in sentence:\n date_lst[2] = int(date_lst[2]) - 1\n\n p = [str(date_lst[0]) + \"-\" + str(date_lst[1]) +\n \"-\" + str(date_lst[2]), td_lst[1]]\n break\n else:\n p = \"None\"\n return p\n\n except ValueError:\n pass\n return \"None\"\n\n\ndef Email_Extract(sentence):\n '''Use regex to find emails'''\n expression = re.compile(r\"(\\S+)@(\\S+)\")\n result = expression.findall(sentence)\n if result != []:\n return result\n else:\n return \"None\"\n\n\ndef Phone_Extract(sentence):\n '''Use regex to find phone numbers'''\n reg = re.compile(\".*?(\\(?\\d{3}\\D{0,3}\\d{3}\\D{0,3}\\d{4}).*?\", re.S)\n num = reg.findall(sentence)\n if num != []:\n return num\n else:\n return \"None\"\n\n\ndef main(sentence):\n '''Extract data from command'''\n SKtime_date = Timedate_Extract(sentence)\n if SKtime_date != \"None\":\n SKdate = SKtime_date[0]\n SKtime = SKtime_date[1]\n else:\n SKdate = \"None\"\n SKtime = \"None\"\n SKemail = Email_Extract(sentence)\n if SKemail != \"None\":\n SKemail = SKemail[0][0] + \"@\" + SKemail[0][1]\n SKphonenumbers = Phone_Extract(sentence)\n if SKphonenumbers != \"None\":\n SKphonenumbers = SKphonenumbers[0]\n SKnames = Name_Extract(sentence)\n if str(SKnames) != \"None\":\n names = \"\"\n for i in SKnames:\n names = names + \"\" + i\n else:\n names = \"None\"\n alphabet = list(string.ascii_lowercase)\n if names not in alphabet:\n names = \"None\"\n data = \"Time: \" + SKtime + \"\\n\" + \"Date: \" + SKdate + \"\\n\" + \"Email: \" + \\\n SKemail + \"\\n\" + \"Phone: \" + SKphonenumbers + \"\\n\" + \"Names: \" + names\n f = open(\"content.txt\", 'w+')\n f.write(data)\n f.close()\n","sub_path":"will/contentextract.py","file_name":"contentextract.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"473397850","text":"\r\n\r\n### Overall, quite a decent job, Gaurav. Score 17/20\r\n### Please go through the comments for each question.###\r\n### I've also provided the solutions, go through it for learning about different approaches ###\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pandas_datareader.data as web\r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport talib as ta\r\n\r\n\r\n####Question 1\r\n\r\n#help(ta)\r\nprint(ta.get_function_groups())\r\n\r\nos.chdir('E:\\Quantinsti\\EPAT 06 - ATP\\ATP 2')\r\n\r\ndf = pd.read_csv(\"MSFT.csv\", index_col='Date', parse_dates = True)\r\ndf2 = df\r\n\r\nopen = []\r\nhigh = []\r\nlow = []\r\nclose = []\r\n\r\nopen = df2['Open']\r\nhigh = df2['High']\r\nlow = df2['Low']\r\nclose = df2['Close']\r\n\r\ndf2['ema']= ta.EMA(np.array(close),timeperiod = 10)\r\n\r\ndf2['MACD'],df2['MACDSignal'],df2['MACDHist'] = ta.MACD(np.array(close), fastperiod=12, slowperiod = 26, signalperiod = 9)\r\n\r\ndf2['3white'] = ta.CDL3WHITESOLDIERS(np.array(open),np.array(high),np.array(low),np.array(close))\r\n\r\n################################################################\r\n###Question 2\r\n\r\n# We Buy when Price > 10-month SMA\r\n# We Sell and move to cash when Price < 10-month SMA\r\n\r\nbuyPrice = 0.0\r\nsellPrice = 0.0\r\nmaWealth = 1.0\r\ncash = 1\r\nstock = 0\r\nsma = 200\r\n\r\nma = np.round(df2['Close'].rolling(window=sma, center=False).mean(), 2)\r\n\r\nn_days = len(df2['Close'])\r\n\r\nclosePrices = df2['Close']\r\n\r\nbuy_data = []\r\n\r\nsell_data = []\r\n\r\ntrade_price = []\r\n\r\nwealth = []\r\n\r\ndef signal(buyPrice, sellPrice, maWealth, cash, stock, sma):\r\n for d in range(sma-1, n_days):\r\n # buy if Stockprice > MA & if not bought yet\r\n if closePrices[d] > ma[d] and cash == 1:\r\n buyPrice = closePrices[d + 1]\r\n \r\n buy_data.append(buyPrice)\r\n trade_price.append(buyPrice)\r\n cash = 0\r\n stock = 1\r\n \r\n # sell if Stockprice < MA and if you have a stock to sell \r\n if closePrices[d] < ma[d] and stock == 1:\r\n sellPrice = closePrices[d + 1]\r\n \r\n cash = 1\r\n stock = 0\r\n sell_data.append(sellPrice)\r\n trade_price.append(sellPrice)\r\n maWealth = maWealth * (sellPrice / buyPrice)\r\n wealth.append(maWealth)\r\n\r\n#This line always hangs in my system, however this should give the desired result. \r\n#df2['Close'].apply(lambda x: signal(buyPrice, sellPrice, maWealth, cash, stock, sma))\r\n\r\nw = pd.DataFrame(wealth)\r\n\r\nplt.plot(w)\r\n\r\n\r\n### Multiple issues here. First, when a function is called a local namespace is created\r\n### So you won't be able to access trade_price, maWealth. Updates to wealth will not be visible outside\r\n### the function. Second, you've used the for loop. Using .apply would be the way to go.\r\n### Refer to the solutions provided.\r\n### Score 2/5 \r\n\r\n################################################################\r\n###Question 3\r\n\r\n# We Buy when Price > 10-month SMA\r\n# We Sell and move to cash when Price < 10-month SMA\r\n\r\nbuyPrice = 0.0\r\nsellPrice = 0.0\r\nmaWealth = 1.0\r\ncash = 1\r\nstock = 0\r\n#creating a list of different moving averages\r\nsma = [50,100,150,200]\r\nma=[[] for i in range(len(sma))]\r\nfor i in range(0,len(sma)):\r\n ma[i] = np.round(df2['Close'].rolling(window=sma[i], center=False).mean(), 2)\r\n \r\n \r\nn_days = len(df2['Close'])\r\n\r\nclosePrices = df2['Close']\r\n\r\nbuy_data = []\r\n\r\nsell_data = []\r\n\r\ntrade_price = []\r\n\r\nwealth = []\r\n\r\n#creating wealth and tradeprice list the number of sma periods\r\ntp=[[] for i in range(len(sma)+1)]\r\nw=[[] for i in range(len(sma)+1)]\r\n\r\n\r\n#running a for loop for all sma's\r\nfor n in range(0,len(sma)):\r\n \r\n \r\n buyPrice = 0.0\r\n sellPrice = 0.0\r\n maWealth = 1.0\r\n cash = 1\r\n stock = 0\r\n buy_data = []\r\n sell_data = []\r\n trade_price = []\r\n wealth = []\r\n \r\n for d in range(sma[n]-1, n_days):\r\n # buy if Stockprice > MA & if not bought yet\r\n if closePrices[d] > ma[n][d] and cash == 1:\r\n buyPrice = closePrices[d + 1]\r\n \r\n buy_data.append(buyPrice)\r\n trade_price.append(buyPrice)\r\n cash = 0\r\n stock = 1\r\n \r\n # sell if Stockprice < MA and if you have a stock to sell \r\n if closePrices[d] < ma[n][d] and stock == 1:\r\n sellPrice = closePrices[d + 1]\r\n cash = 1\r\n stock = 0\r\n sell_data.append(sellPrice)\r\n trade_price.append(sellPrice)\r\n maWealth = maWealth * (sellPrice / buyPrice)\r\n wealth.append(maWealth) \r\n w[n]= (wealth) \r\n tp[n] = trade_price\r\n \r\ndf2['Buy & Hold Returns'] = np.log(df2['Close'] / df2['Close'].shift(1))\r\n\r\n#printing returns for different moving averages\r\nprint(\"Cumulative returns, Buy and Hold\"+str(df2['Buy & Hold Returns'].sum())+\r\n \"\\nWealth at \"+str(sma[0])+\"MA \"+str(sum(w[0]))+\r\n \"\\nWealth at \"+str(sma[1])+\"MA \"+str(sum(w[1]))+\r\n \"\\nWealth at \"+str(sma[2])+\"MA \"+str(sum(w[2]))+\r\n \"\\nWealth at \"+str(sma[3])+\"MA \"+str(sum(w[3])))\r\n\r\n### Good. ###\r\n### Score 5/5 ###\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t \r\n################################################################\r\n###Question 4\r\n\r\n##### Strategy II: The Moving Average Crossover Strategy ######\r\n##### Close Price is used to do the calculations\r\n\r\nshortPeriod = 20\r\nlongPeriod = 40\r\n\r\ndf2['shortMA'] = df2['Close'].rolling(window=shortPeriod, center=False).mean()\r\ndf2['longMA'] = df2['Close'].rolling(window=longPeriod, center=False).mean()\r\n\r\n# WHY DOUBLE BRACKET\r\n### When you select multiple columns to plot graphs, you enclose it as a list ###\r\ndf2[['Close','shortMA','longMA']].plot(grid=False, linewidth=0.8) \r\n\r\ndf2['shortMA2'] = df2['Close'].rolling(window=shortPeriod, center=False).mean().shift(1)\r\ndf2['longMA2'] = df2['Close'].rolling(window=longPeriod, center=False).mean().shift(1)\r\n\r\n#Generating Signal\r\n\r\ndf2['Signal'] = np.where((df2['shortMA']>df2['longMA'])\r\n & (df2['shortMA2']df2['longMA2']), -1, df2['Signal'])\r\n\r\ndf2['Buy'] = df2.apply(lambda x: x['Close'] if x['shortMA'] > x['longMA'] \r\n and x['shortMA2'] < x['longMA2'] else 0, axis=1)\r\n\r\ndf2['Sell'] = df2.apply(lambda y: -y['Close'] if y['shortMA'] < y['longMA'] \r\n and y['shortMA2'] > y['longMA2'] else 0, axis=1)\r\n\r\n\r\ndf2['TP'] = df2['Buy'] + df2['Sell']\r\ndf2['TP']\r\ndf2['TP']=df2['TP'].replace(to_replace=0, method='ffill')\r\n\r\n\r\ndf2['Position'] = df2['Signal'].replace(to_replace=0, method= 'ffill')\r\n#Generating new Positions with NO SHORTING rule\r\ndf2['Position2'] = df2['Signal'].replace(to_replace=0, method= 'ffill')\r\n#replacing all shorting signals with null\r\ndf2['Position2'] = df2['Position2'].replace([-1],[0] )\r\n\r\nk = df2['Buy'].nonzero()\r\n\r\nlen(k[0]) # total number of trades\r\ndf2['Position'].plot(grid=True, linewidth=1)\r\n\r\ndf2['Buy & Hold Returns'] = np.log(df2['Close'] / df2['Close'].shift(1))\r\ndf2['Strategy Returns'] = df2['Buy & Hold Returns'] * df2['Position'].shift(1)\r\ndf2['No Short Strategy Returns'] = df2['Buy & Hold Returns'] * df2['Position2'].shift(1)\r\n\r\n#Plotting returns from multiple strategies\r\ndf2[['Buy & Hold Returns', 'Strategy Returns', 'No Short Strategy Returns']].cumsum().plot(grid=True, figsize=(9,5))\r\n\r\n### Correct. Score 5/5. Good.\r\n\r\n\r\n###############################################################\r\n#####Question 5\r\n\r\nstocks = [\"AXISBANK.NS\", \"BANKBARODA.NS\", \"BHEL.NS\",\"BPCL.NS\",\"BHARTIARTL.NS\"]\r\n\r\n\r\nend = datetime.datetime.now().date()\r\n\r\nstart = end - pd.Timedelta(days=365*5)\r\n\r\nf = web.get_data_yahoo(stocks, start, end)\r\n\r\n#Storing data and creating dataframes\r\ndf.to_pickle('f.pickle')\r\ndf_open = f.loc[\"Open\"].copy() \r\ndf_close = f.loc[\"Close\"].copy()\r\ndf_close = df_close.shift(1)\r\ndf_returns = df_close.divide(df_open, axis='index') - 1\r\n\r\n#Saving returns file\r\ndf_returns.to_csv(\"out.csv\")\r\n#dropping nan values\r\ndf_returns = df_returns.dropna()\r\ndf_returns = df_returns.applymap(float)\r\ndf_returns.loc['cumReturns'] = 0\r\n\r\n#Cumulative Returns added at the end of dataframe 'df_returns'\r\nfor i in range(len(df_returns.columns.values)):\r\n df_returns.loc[\"cumReturns\"][df_returns.columns.values[i]] = pd.Series(df_returns[df_returns.columns.values[i]].sum(), index = [df_returns.columns.values[i]])\r\n\r\n#defigning variables for hit ratio calculation\r\npos_count = 0\r\nneg_count = 0\r\ndf_returns.loc['hitRatio'] = 0\r\ndf_returns = df_returns.dropna()\r\ndf_returns = df_returns.applymap(float)\r\n\r\nfor i in range(len(df_returns.columns.values)):\r\n for j in range(len(df_returns)-1):\r\n if df_returns.iloc[j,i]>0:\r\n pos_count += 1\r\n if df_returns.iloc[j,i]<0:\r\n neg_count += 1\r\n#hit ratio added at the end of the dataframe returns\r\n df_returns.loc[\"hitRatio\"][df_returns.columns.values[i]] = pd.Series(pos_count/neg_count, index = [df_returns.columns.values[i]])\r\n pos_count = 0\r\n neg_count = 0\r\n\r\n#Creating list of the cumulative returns and hit ratio\r\ntemp1 = []\r\ntemp2 = []\r\nfor i in range(len(df_returns.columns.values)):\r\n temp1.append(df_returns.ix['cumReturns', i])\r\n temp2.append(df_returns.ix['hitRatio', i])\r\n\r\n#plotting the two graphs\r\nplt.plot(temp1)\r\nplt.plot(temp2)\r\n\r\n################################################################\r\n\r\n### Correct. Well done. Score 5/5\r\n\r\n###Question 6\r\n\r\n# We Buy when Price > 10-month SMA\r\n# We Sell and move to cash when Price < 10-month SMA\r\n\r\nbuyPrice = 0.0\r\nsellPrice = 0.0\r\nmaWealth = 1.0\r\ncash = 1\r\nstock = 0\r\nema = 20\r\n\r\nma = ta.EMA(np.array(df2['Close']), timeperiod = ema)\r\nma = np.array(ma)\r\nn_days = len(df2['Close'])\r\n\r\nclosePrices = df2['Close']\r\n\r\nbuy_data = []\r\n\r\nsell_data = []\r\n\r\ntrade_price = []\r\n\r\nwealth2 = []\r\n\r\nfor d in range(ema-1, n_days):\r\n # buy if Stockprice > MA & if not bought yet\r\n if closePrices[d] > ma[d] and cash == 1:\r\n buyPrice = closePrices[d + 1]\r\n \r\n buy_data.append(buyPrice)\r\n trade_price.append(buyPrice)\r\n cash = 0\r\n stock = 1\r\n \r\n # sell if Stockprice < MA and if you have a stock to sell \r\n if closePrices[d] < ma[d] and stock == 1:\r\n sellPrice = closePrices[d + 1]\r\n \r\n cash = 1\r\n stock = 0\r\n sell_data.append(sellPrice)\r\n trade_price.append(sellPrice)\r\n maWealth = maWealth * (sellPrice / buyPrice)\r\n wealth2.append(maWealth)\r\n\r\nw1 = pd.DataFrame(wealth2)\r\n#Plot for EMA, if the line in Question 2 works, wealth for SMA can be added in this chart as well.\r\nplt.plot(w1)\r\n\r\n\r\n### Same issues as Q1.\r\n### Score 3/5\r\n\r\n","sub_path":"SMA and ETF.py","file_name":"SMA and ETF.py","file_ext":"py","file_size_in_byte":10809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"98873871","text":"import os\nimport json\nfrom copy import deepcopy\nfrom mechanics import get_damage\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\n\nVERSION = 3\n_TYPE = 0\n\ndef main(config, name, ret_dist=False, sim_size=250, dur_dist=None):\n config[\"sim_size\"] = sim_size\n values = get_damage(config, ret_dist=ret_dist, dur_dist=dur_dist)\n print(f\" {name}={values[0]:6.1f}\")\n return values\n\ndef load_config(cfn):\n config_file = os.path.join(\"../config/\", cfn)\n with open(config_file, 'rt') as fid:\n config = json.load(fid)\n\n return config\n \ndef time_comparison():\n max_mages = 7\n do_ep = True\n \n etimes = np.array(list(range(25, 90, 5)) + list(range(90, 181, 15)))\n print(etimes)\n \n if do_ep:\n out_pyro = [np.array([0.0]) for dummy in range(max_mages)]\n out_fb = [np.array([0.0]) for dummy in range(max_mages)]\n out_scorch = [np.array([0.0]) for dummy in range(max_mages)]\n out2 = [np.array([0.0]) for dummy in range(max_mages)]\n \n sim_sizes = [0, 1000, 707, 577, 500, 447, 408, 378]\n scorches = [0, 6, 3, 2, 2, 2, 1, 1]\n \n for num_mages in range(3, max_mages + 1):\n encounter = \"template_pi_buffer\"\n config = load_config(encounter + \".json\")\n config[\"timing\"][\"delay\"] = 2.0\n config[\"rotation\"][\"initial\"][\"common\"] = [\"scorch\"]*scorches[num_mages]\n config[\"rotation\"][\"continuing\"][\"special\"] = {\n \"slot\": [num_mages - 1],\n \"value\": \"scorch_wep\"\n }\n \n config[\"stats\"][\"spell_power\"] = [785, 785] + [745 for aa in range(2, num_mages)]\n config[\"stats\"][\"crit_chance\"] = [0.15 for aa in range(num_mages)]\n config[\"stats\"][\"hit_chance\"] = [0.1 for aa in range(num_mages)]\n config[\"stats\"][\"intellect\"] = [302 for aa in range(num_mages)]\n \n config[\"stats\"][\"spell_power\"][-1] = 748\n config[\"stats\"][\"crit_chance\"][-1] = 0.18\n config[\"stats\"][\"intellect\"][-1] = 335\n \n config[\"buffs\"][\"raid\"] = [\n \"arcane_intellect\",\n \"improved_mark\",\n \"blessing_of_kings\"]\n config[\"buffs\"][\"consumes\"] = [\n \"greater_arcane_elixir\",\n \"elixir_of_greater_firepower\",\n \"flask_of_supreme_power\",\n \"blessed_wizard_oil\"]\n config[\"buffs\"][\"world\"] = [\n \"rallying_cry_of_the_dragonslayer\",\n \"spirit_of_zandalar\",\n \"dire_maul_tribute\",\n \"songflower_serenade\",\n \"sayges_dark_fortune_of_damage\"]\n config[\"buffs\"][\"racial\"] = [\"human\"]*num_mages\n config[\"configuration\"][\"num_mages\"] = num_mages\n config[\"configuration\"][\"target\"] = list(range(num_mages))\n \n config[\"configuration\"][\"sapp\"] = [0, 1, num_mages - 1]\n config[\"configuration\"][\"mqg\"] = list(range(2, num_mages - 1))\n config[\"configuration\"][\"pi\"] = [0, 1]\n\n config[\"configuration\"][\"name\"] = [f\"mage{idx + 1:d}\" for idx in range(num_mages)]\n \n if do_ep:\n osim_size = 1000.0*sim_sizes[num_mages]\n else:\n osim_size = 30.0*sim_sizes[num_mages]\n\n var = 3.0\n sim_size = int(osim_size*10/min(etimes)**0.5)\n config['timing']['duration'] = {\n \"mean\": max(etimes) + 5.0*var,\n \"var\": var,\n \"clip\": [0.0, 10000.0]}\n value_0 = main(config, f\" {num_mages:d} 0\", sim_size=sim_size, dur_dist=etimes)\n out2[num_mages - 1] = value_0\n if do_ep:\n config[\"stats\"][\"spell_power\"][0] += 30\n value_sp = main(config, f\"p{num_mages:d} sp\", sim_size=sim_size, dur_dist=etimes)\n config[\"stats\"][\"spell_power\"][0] -= 30\n config[\"stats\"][\"crit_chance\"][0] += 0.03\n value_cr = main(config, f\"p{num_mages:d} cr\", sim_size=sim_size, dur_dist=etimes)\n config[\"stats\"][\"spell_power\"][0] += 30\n config[\"stats\"][\"crit_chance\"][0] -= 0.03\n out_pyro[num_mages - 1] = 10.0*(value_cr - value_0)/(value_sp - value_0)\n\n if num_mages > 3:\n config[\"stats\"][\"spell_power\"][2] += 30\n value_sp = main(config, f\"f{num_mages:d} sp\", sim_size=sim_size, dur_dist=etimes)\n config[\"stats\"][\"spell_power\"][2] -= 30\n config[\"stats\"][\"crit_chance\"][2] += 0.03\n value_cr = main(config, f\"f{num_mages:d} cr\", sim_size=sim_size, dur_dist=etimes)\n config[\"stats\"][\"spell_power\"][2] += 30\n config[\"stats\"][\"crit_chance\"][2] -= 0.03\n out_fb[num_mages - 1] = 10.0*(value_cr - value_0)/(value_sp - value_0)\n\n\n config[\"stats\"][\"spell_power\"][-1] += 30\n value_sp = main(config, f\"s{num_mages:d} sp\", sim_size=sim_size, dur_dist=etimes)\n config[\"stats\"][\"spell_power\"][-1] -= 30\n config[\"stats\"][\"crit_chance\"][-1] += 0.03\n value_cr = main(config, f\"s{num_mages:d} cr\", sim_size=sim_size, dur_dist=etimes)\n out_scorch[num_mages - 1] = 10.0*(value_cr - value_0)/(value_sp - value_0)\n with open(\"savestate2.dat\", \"wb\") as fid:\n pickle.dump(out2, fid)\n if do_ep:\n pickle.dump(out_pyro, fid)\n pickle.dump(out_fb, fid)\n pickle.dump(out_scorch, fid)\n\n \n if do_ep:\n for type_st, out in [(\"pyro\", out_pyro), (\"fb\", out_fb), (\"scorch\", out_scorch)]:\n plt.close('all')\n plt.figure(figsize=(8.0, 5.5), dpi=200)\n #plt.title(f\"CE Crit Values (Shorter Encounters, WBs, No PI, Ignite Hold, Phase 6 Gear)\")\n for num_mages, ou in enumerate(out):\n if type_st == \"fb\" and num_mages + 1 <= 3:\n continue\n if not(ou.any()):\n continue\n #plt.plot(etimes, np.array(ou), label=config[\"configuration\"][\"name\"][index])\n label = f\"{num_mages + 1:d} mages\"\n if num_mages < 1:\n label = label[:-1]\n plt.plot(etimes,\n np.array(ou),\n label=label)\n plt.xlabel('Encounter Duration (seconds)')\n plt.ylabel('SP per 1% Crit')\n plt.grid()\n plt.xlim(0, 180)\n plt.legend()\n plt.savefig(f\"ce2_2pi_crit_{type_st:s}_{encounter:s}.png\")\n\n plt.close('all')\n plt.figure(figsize=(8.0, 5.5), dpi=200)\n #plt.title(f\"CE Crit Values (Shorter Encounters, WBs, No PI, Ignite Hold, Phase 6 Gear)\")\n for num_mages, ou in enumerate(out2):\n if not(ou.any()):\n continue\n #plt.plot(etimes, np.array(ou), label=config[\"configuration\"][\"name\"][index])\n label = f\"{num_mages + 1:d} mages\"\n if num_mages < 1:\n label = label[:-1]\n plt.plot(etimes,\n np.array(ou)/(num_mages + 1),\n label=label)\n plt.xlabel('Encounter Duration (seconds)')\n plt.ylabel('Damage per mage')\n plt.grid()\n plt.xlim(0, 180)\n plt.legend()\n plt.savefig(f\"ce2_2pi_{encounter:s}.png\")\n\nif __name__ == '__main__':\n time_comparison()\n ","sub_path":"src/ce_equiv_2pi.py","file_name":"ce_equiv_2pi.py","file_ext":"py","file_size_in_byte":7242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"43999901","text":"import playground, asyncio\nfrom playground.network.packet import PacketType\nfrom asyncio import *\nfrom packets import *\n\n\nclass IoTClientProtocol(asyncio.Protocol):\n initial = 0\n wtrespond = 1\n end = 2\n ERROR = 9\n def __init__(self):\n self.transport = None\n self.state = None\n self.RespondPacket = None\n self._deserializer = PacketType.Deserializer()\n\n def connection_made(self, transport):\n print(\"---Client connected!---\")\n self.transport = transport\n self.state = self.initial\n\n def data_received(self, data):\n print(\"---Client received data---\")\n self._deserializer.update(data)\n for pkt in self._deserializer.nextPackets():\n if isinstance(pkt, DeviceList):\n if self.state == self.initial:\n print(\"Client: Received a DeviceList\")\n self.RespondPacket = ModifyDevice()\n self.RespondPacket.ID = pkt.ID\n self.ModifyDevice()\n self.state = self.wtrespond\n else:\n print(\"state error\")\n self.state = self.ERROR\n elif isinstance(pkt, Respond):\n if self.state == self.wtrespond:\n print(\"Client: Received a respond message!\")\n if (pkt.respond == b\"Succeeded!\"):\n print(\"Congratulations! Operation Succeeded!\")\n elif (pkt.respond == b\"Failed!\"):\n print(\"Operation Failed!\")\n self.state = self.end\n else:\n self.state == self.ERROR\n print(\"Client State: {!r}\".format(self.state))\n else:\n print(\"received error packet\")\n self.state = self.end\n\n if self.state == self.end:\n self.transport.close()\n elif self.state == self.ERROR:\n self.transport.close()\n\n\n\n def ModifyDevice(self):\n print(\"Client State: {!r}\".format(self.state))\n if (self.RespondPacket.ID == 1001):\n self.RespondPacket.operation = b\"off\"\n elif (self.RespondPacket.ID == 1002):\n self.RespondPacket.operation = b\"on\"\n elif (self.RespondPacket.ID == 1003):\n self.RespondPacket.operation = b\"off\"\n else:\n self.RespondPacket.operation = b\"Can not identify device\"\n print(\"Client: Sent ModifyDevice packet ID:{}\".format(self.RespondPacket.ID) + \"\\n\")\n self.transport.write(self.RespondPacket.__serialize__())\n\n def GetDeviceList(self):\n print(\"Test start!\")\n print(\"Client State: {!r}\".format(self.state))\n self.RespondPacket = GetDeviceList()\n self.RespondPacket.category = \"lamp\"\n self.RespondPacket.number = 1001\n print(\"Client: Sent GetDeviceList packet ID:{}\".format(self.RespondPacket.number)+\"\\n\")\n self.transport.write(self.RespondPacket.__serialize__())\n\n def connection_lost(self, exc):\n self.transport = None\n print(\"IoT Client Connection Lost because {}\".format(exc))\n\n\nif __name__=='__main__':\n loop = get_event_loop()\n loop.set_debug(enabled=True)\n connect = playground.getConnector().create_playground_connection (lambda:IoTClientProtocol(), '20174.1.1.1', 5555)\n transport, client = loop.run_until_complete(connect)\n client.GetDeviceList()\n loop.run_forever()\n loop.close()","sub_path":"lab_1d/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"437661077","text":"'''\nCreated on Mar 28, 2014\n\n@author: SeungKoo\n@chapter: 7\n@contents: Web Development\n'''\n\n#! /usr/local/bin/python3\n\n#리눅스나 유닉스 환경에서 위의 선언은 필수적이다\n\nimport athletemodel\n\nthe_files = ['../example_code/hfpy_code/chapter6/james2.txt', \n\t\t\t'../example_code/hfpy_code/chapter6/sarah2.txt', \n\t\t\t'../example_code/hfpy_code/chapter6/julie2.txt', \n\t\t\t'../example_code/hfpy_code/chapter6/mikey2.txt']\n\n# 조회결과를 피클로 저장하고 각 정보를 가진 데이터 딕셔너리를 반환\ndata = athletemodel.put_to_store(the_files)\n\n# print (data)\n\nfor each_athlete in data:\n\tprint (data[each_athlete].name + ' ' + data[each_athlete].dob)\n\nprint ('============< data from pickle>============')\n\ndata_copy = athletemodel.get_from_store()\n\nfor each_athlete in data_copy:\n\tprint (data_copy[each_athlete].name + ' ' + data_copy[each_athlete].dob)\n\n","sub_path":"KOO/Python_01/HeadFirst/ch_07_01.py","file_name":"ch_07_01.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"286166984","text":"def main():\n # First line of input will be the number of cases\n cases = int(input())\n for i in range(1, cases + 1):\n # Each other line will be the number the needs to be checked\n number = int(input())\n # Check to see if the number is anything but 0\n if number:\n # Make a list with the numbers to find utilizing the indices as the numbers\n # Each index will be 0 if not found and 1 if found\n numbers_found = [0 for _ in range(0, 10)]\n # Keep track of the iterations through the while loop and the current number\n count = 0\n current_number = 0\n # There will be ten occurrences of 1 when all the numbers have been found\n while numbers_found.count(1) != 10:\n count += 1\n # On the first iteration through we want the actual number and after that we will set current number\n check_number = current_number and current_number or number\n result = str(check_number)\n # Using our check_number as a temporary variable, find all of the digits in it and set the value\n # in the list to 1\n while check_number:\n numbers_found[check_number % 10] = 1\n check_number = int(check_number/10)\n # Multiply the number by the iteration we are on plus one\n current_number = number * (count + 1)\n else:\n result = 'INSOMNIA'\n print('Case #{i}: {result}'.format(**locals()))\n\nif __name__ == '__main__':\n main()\n","sub_path":"google-code-jam-2016/counting_sheep.py","file_name":"counting_sheep.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"123139195","text":"# Tip calculator\nprint(\"Welcome to tip calculator\")\nbill_amount = float(input(\"What was the total bill? $\"))\ntip_percent = int(input(\"What percentage tip would you like to give? 10, 12, 15 ? \"))\nbill_with_tip = bill_amount * (1 + (tip_percent/100))\nno_of_people = int(input(\"How many people like to split the bill? \"))\nsplit_bill = float((bill_with_tip)/no_of_people)\n# print(split_bill)\nfinal_bill = round(split_bill,2)\nprint(\"Each person should pay: \", final_bill)\n\n\n","sub_path":"day2.3.py","file_name":"day2.3.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"389969723","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('projects', '0009_auto_20150617_2319'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='task',\n name='date_add',\n field=models.DateTimeField(auto_now_add=True, null=True),\n ),\n migrations.AddField(\n model_name='task',\n name='date_upd',\n field=models.DateTimeField(auto_now=True, null=True),\n ),\n migrations.AddField(\n model_name='task',\n name='user_add',\n field=models.ForeignKey(related_name='projects_task_created_by', blank=True, editable=False, to=settings.AUTH_USER_MODEL, null=True),\n ),\n migrations.AddField(\n model_name='task',\n name='user_upd',\n field=models.ForeignKey(related_name='projects_task_modified_by', blank=True, editable=False, to=settings.AUTH_USER_MODEL, null=True),\n ),\n ]\n","sub_path":"django_erp/projects/migrations/0010_auto_20150618_2339.py","file_name":"0010_auto_20150618_2339.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"388292112","text":"from django.conf.urls import include, url, patterns\r\nfrom django.conf.urls.static import static\r\nfrom django.conf import settings\r\n\r\nurlpatterns = [\r\n url(r'^$', 'music.views.home', name='home'),\r\n url(r'^music/$', 'music.views.music', name='music'),\r\n url(r'^videos/$', 'music.views.videos', name='videos'),\r\n url(r'^blog/$', 'music.views.blog', name='blog'),\r\n url(r'^tour/$', 'music.views.tour', name='tour'),\r\n url(r'^contacts/$', 'music.views.contacts', name='contacts'),\r\n url(r'^blog/(?P[-\\w]+)/$', 'music.views.show_news', name=\"news\"),\r\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"141988659","text":"import shutil\nimport glob\nimport os\nimport pathlib\nimport json\n\n\ndef copy_html_assets(assets_in, assets_out):\n all_dirs = [os.path.relpath(x[0], assets_in.as_posix())\n for x in os.walk(assets_in)]\n # Remove the top level directory itself\n all_dirs.pop(0)\n for dir_str in all_dirs:\n (assets_out / dir_str).mkdir(parents=True, exist_ok=True)\n stuff_to_glob = (assets_in / dir_str).as_posix() + \"/*\"\n for name in glob.glob(stuff_to_glob):\n filepath = pathlib.Path(name)\n if filepath.name == '.DS_Store':\n continue\n if filepath.is_file():\n if '/assets/js/excavation.js' in filepath.as_posix():\n # Minimize the very large JSON contained in the JS\n exc_js = filepath.open('r').read()\n exc_js = exc_js.replace(\"const excavation = \", \"\")\n new_js = json.loads(exc_js)\n new_js = \"const excavation = \" + json.dumps(new_js, separators=(\",\", \":\"))\n new_path = os.path.relpath(name, assets_in.as_posix())\n with open(pathlib.Path(assets_out / new_path), 'w') as f:\n f.write(new_js)\n unmin_js_path = os.path.relpath(name, assets_in.as_posix())\n unmin_js_path = (\n (assets_out / unmin_js_path).parent\n / \"excavation_unmin.js\"\n )\n shutil.copy(name, unmin_js_path)\n else:\n new_path = os.path.relpath(name, assets_in.as_posix())\n shutil.copy(name, assets_out / new_path)\n\n return\n\n\ndef copy_videos(videos_in, videos_out):\n if not videos_out.is_dir():\n videos_out.mkdir(parents=True, exist_ok=True)\n for filepath in videos_in.iterdir():\n shutil.copy(filepath, videos_out / filepath.name)\n\n\ndef copy_data(data_in, data_out):\n copy_html_assets(data_in, data_out)\n","sub_path":"src/generate_new_site/utilities/html_assets.py","file_name":"html_assets.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"146680552","text":"import numpy as np\nimport math\nfrom atomplot import plot\nfrom misc import include_atoms_gr, include_atoms_nt, grid_pq\n\n\ndef vector(n, m):\n \"\"\"\n A function used to find the coordinates of vector Ch.\n Input:\n n: number of n hops (type: integer)\n m: number of m hops (type: integer)\n Output:\n Ch: A numpy array holding the coordinates of vector Ch\n i.e. Ch.shape = (2,)\n \"\"\"\n vec = np.array([round(math.sqrt(3), 3) * n + round(math.sqrt(3) / 2, 3) * m, 0 - 1.5 * m])\n return vec\n\n\ndef normVector(vec):\n \"\"\"\n A function used to find the coordinates of the normalized Ch vector.\n Input:\n Ch: A numpy array holding the coordinates of vector Ch.\n Output:\n norm_vec: A numpy array holding the coordinates of normalized vector.\n i.e. norm_vec.shape = (2,)\n norm: Length of vector Ch (type: float)\n \"\"\"\n norm = round(math.sqrt(math.pow(vec[0],2) + math.pow(vec[1],2)), 3)\n norm_vec = np.array([round(vec[0] / norm, 3), round(vec[1] / norm, 3)])\n return norm_vec, norm\n\n\ndef normTvector(c_hat):\n \"\"\"\n A function used to find the coordinates of vector t_hat, perpendicular\n to c_hat. Dot product of c_hat and t_hat = 0.\n Input:\n c_hat: A numpy array holding the coordinates of normalized Ch vector.\n Output:\n t_hat: A numpy array holding the coordinates of normalized\n perpendicular vector t_hat\n i.e. t_hat.shape = (2,)\n \"\"\"\n t_hat = np.array([-1 * c_hat[1], c_hat[0]])\n return t_hat\n\n\ndef TVector(Ch, l):\n \"\"\"\n A function used to find the coordinates of vector T, perpendicular\n to Ch.\n Input:\n Ch: A numpy array holding the coordinates of vector Ch.\n l: Length of the perpendicular edge in units of carbon-carbon bond\n lengths (type: float).\n Output:\n T: A numpy array holding the coordinates of perpendicular vector T.\n i.e. T.shape = (2,)\n \"\"\"\n temp1 = normTvector(Ch)\n a = normVector(temp1)[1]\n temp2 = np.array([temp1[0] / a, temp1[1] / a])\n T = np.array([round(l*temp2[0], 3), round(l * temp2[1], 3)])\n return T\n\n\ndef pq(Ch, T):\n \"\"\"\n A function used to find the maximum and minimum values of p and q.\n Input:\n Ch: A numpy array holding the coordinates of vector Ch.\n T: A numpy array holding the coordinates of perpendicular vector T.\n Output:\n p: A numpy array holding the minimum and maximum value for p, i.e.\n p = np.array([p_min, p_max]), p_min, p_max are integers.\n q: A numpy array holding the minimum and maximum value for q, i.e.\n q = np.array([q_min, q_max]), q_min, q_max are integers.\n \"\"\"\n p_max = math.ceil((Ch[0] + T[0]) / (math.sqrt(3)/2))\n p_min = int(0)\n p = np.array([p_min, p_max])\n q = np.array([math.floor(Ch[1] / 1.5), math.ceil(T[1] / 1.5)])\n return p, q\n\n\ndef coordinates(pg, qg):\n \"\"\"\n A function used to return the coordinates of each atom.\n Input:\n p: A 2-d numpy array holding the integers used identify each atom \n along the x-direction.\n q: A 2-d numpy array holding the integers used identify each atom \n along the y-direction.\n Output:\n x: A 2-d numpy array holding the coordinates of each atom \n along the x-direction.\n y: A 2-d numpy array holding the coordinates of each atom \n along the y-direction.\n \"\"\"\n x_raw = [[] for list in pg]\n y_raw = [[] for list in qg]\n \n for a in range(len(pg)):\n for b in range(len(pg[a])):\n i = round(pg[a][b] * (math.sqrt(3) / 2), 3)\n x_raw[a].append(i)\n \n for j in range(len(qg)):\n for k in range(len(qg[j])):\n u = round(1.5*qg[j][k],3)\n if (pg[j][k] + qg[j][k]) % 2 != 0:\n u = u - (0.5*((qg[j][k] + pg[j][k]) % 2))\n u = round(u,3)\n y_raw[j].append(u)\n \n x = np.array(x_raw)\n y = np.array(y_raw)\n return x, y\n\n\ndef distance(x, y, c_hat):\n \"\"\"\n A function used to calculate the distance along Ch- and T- direction\n of each atom.\n Input:\n x: A 2-d numpy array holding the coordinates of each atom\n along the x-direction.\n y: A 2-d numpy array holding the coordinates of each atom\n along the y-direction.\n c_hat: A numpy array holding the coordinates of normalized Ch vector.\n Output:\n s: A 2-d numpy array holding the distance of each atom\n along the Ch-direction.\n t: A 2-d numpy array holding the distance of each atom\n along the T-direction.\n \"\"\"\n s_raw = [[] for list in x]\n t_raw = [[] for list in y]\n \n for a in range(len(x)):\n for b in range(len(x[a])):\n t_dot = round((-1 * c_hat[1] * x[a][b]) + (c_hat[0] * y[a][b]), 3)\n t_raw[a].append(t_dot)\n s_dot = round(c_hat[0] * x[a][b] + c_hat[1] * y[a][b], 3)\n s_raw[a].append(s_dot)\n \n t = np.array(t_raw)\n s = np.array(s_raw)\n return s, t\n\n\ndef Graphene(n, m, l):\n # Graphene determines the x, y and z coordinates\n # for a graphene sheet. This set of coordinates\n # represents a rectangular slice of a carbon sheet where\n # the lower left edge is represented by the vector\n # n*a1+m*a2, where a1 and a2 are vectors given in the\n # project description and n>=m are positive integers.\n # The integer len gives the length of the perpendicular edge\n # in units of carbon-carbon bond lengths.\n vec = vector(n, m)\n T = TVector(vec, l)\n p, q = pq(vec, T)\n pg, qg = grid_pq(p, q)\n x, y = coordinates(pg, qg)\n c_hat, arclen = normVector(vec)\n s, t = distance(x, y, c_hat)\n pos_gr = include_atoms_gr(x, y, s, t, arclen, l)\n tuberad = float(arclen / (2*(math.pi)))\n pos_nt = include_atoms_nt(pos_gr, c_hat, arclen, tuberad)\n return pos_gr, pos_nt\n\n\nif __name__ == \"__main__\": \n pos_gr, pos_nt = Graphene(6,6,6)\n plot(pos_gr)\n plot(pos_nt)\n \n\n","sub_path":"Project 4 - Constructing a Carbon Nanotube.py","file_name":"Project 4 - Constructing a Carbon Nanotube.py","file_ext":"py","file_size_in_byte":5983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"365646267","text":"'''\n依赖于bootstrap样式\n使用: pages = Pagination(all_depart.count(), request.GET.get('page', 1), per_num=10, page_disply=11)\n数据[page.start:page.end]\n前端展示 HTML page.page_html\n'''\n\nfrom django.utils.safestring import mark_safe\nclass Pagination:\n def __init__(self, total_count, page_num, per_num=10, page_disply=11):\n # 获取url中的页面数,如果不是指定数字类型,就赋值为第一页\n try:\n self.page_num = int(page_num)\n except Exception as e:\n self.page_num = 1\n\n self.total_count = total_count # 获取queryset对象中的数据数量\n self.per_num = per_num # 每页显示的数据条数\n self.page_disply = page_disply # 显示的总分页数\n self.half_per = page_disply // 2\n self.page_total_num, more = divmod(total_count, per_num) # 除法运算,返回两个数据,第一个为整除结果,第二个为余数\n\n # 如果有余数,页面数+1\n if more:\n self.page_total_num += 1\n\n @property # 添加装饰器,直接转化为静态属性去调用\n def start(self):\n return (self.page_num - 1) * self.per_num\n\n @property\n def end(self):\n return self.page_num * self.per_num\n\n @property\n def page_html(self):\n # 如果总页数小于要显示的页数,就显示全部分页号\n if self.page_total_num < self.page_disply:\n page_start = 1\n page_end = self.page_total_num\n\n # 如果总页数大于等于显示的固定页数,就自动向前后移动固定间隔的页码\n else:\n\n # 限制显示的负数页码\n if self.page_num <= self.half_per:\n page_start = 1\n page_end = self.page_disply\n\n # 限制超出页码\n elif self.page_num >= self.page_total_num - self.half_per:\n page_start = self.page_total_num - self.page_disply + 1\n page_end = self.page_total_num\n else:\n page_start = self.page_num - self.half_per\n page_end = self.page_num + self.half_per\n\n # 点击分页按钮的选中效果\n page_list = []\n\n # 添加向前翻页效果,在第一页时禁止向前翻页\n if self.page_num == 1:\n page_list.append(\n '
  • «
  • ')\n else:\n page_list.append(\n '
  • «
  • '.format(\n self.page_num - 1))\n\n for i in range(page_start, page_end + 1):\n if i == self.page_num: # 如果点击的分页正好是当前按钮,就添加选中效果\n page_list.append('
  • {}
  • '.format(i, i))\n else:\n page_list.append('
  • {}
  • '.format(i, i))\n\n # 添加向后翻页效果,在最后一页时,禁止向后翻页\n if self.page_num == self.page_total_num:\n page_list.append(\n '
  • »
  • ')\n else:\n page_list.append(\n '
  • »
  • '.format(\n self.page_num + 1))\n\n # 生成html页面,使用mark_safe后,前端就不需要使用{{ page|safe }}的方式,直接使用{{ page }}\n return mark_safe(''.join(page_list))\n","sub_path":"utils/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"21228544","text":"import os\nimport time\nimport csv\nimport random\n\nimport numpy as np\n\n# =================windows===========================\nload_file_list = \"D:\\Python_projects\\soundProcessing\\src/test_list_iden.txt\" # train_128_mfcc_for_veri.txt\nsave_file_list = \"D:\\Python_projects\\SoundProcessing\\src/test_pairs_for_veri.csv\"\n# =================linux===========================\n# load_file_list = \"/home/longfuhui/shengwenshibie/SoundProcessing/src/train_64_mfcc_for_veri.txt\" # train_128_mfcc_for_veri.txt\n# save_file_list = \"/home/longfuhui/shengwenshibie/SoundProcessing/src/train_64_pairs_for_veri.csv\"\nsave_list = []\nlist_file_length_1 = 897\n\n\n# 获取所有文件的路径、标签\niden_list = np.loadtxt(load_file_list, str,delimiter=\",\")\nlabels = np.array([int(i[1]) for i in iden_list])\nvoice_list = np.array([i[0] for i in iden_list])\ntotal_len = len(labels)\n\n\ndef write_csv(pre,last,lable):\n save_list.append([pre, last,lable])\n\n\n'''\nfirst 是下标\n'''\n\n\ndef create_pos_pairs(first):\n write_csv(voice_list[first], voice_list[first+1], 1)\n write_csv(voice_list[first], voice_list[first+2], 1)\n\n\ndef create_neg_pairs(first,list):\n write_csv(voice_list[first],voice_list[list[0]],0)\n write_csv(voice_list[first], voice_list[list[1]],0)\n\n\n# print(labels[0])\n# print(voice_list[0])\n\n\ndef gene_pairs():\n '''\n 生成训练对 和 标签\n :return: null\n '''\n '''\n 每条数据生成正反例 各 2 对\n 对正例,取其下面 2 条数据\n 对反例,随机 2 条\n '''\n\n\n '''\n 先全部遍历,找出每块的边界\n '''\n boundary = {}\n pre_lab = 0\n start = end = 0\n for i in range(total_len):\n this_lab = labels[i]\n # print(i,this_lab)\n if this_lab != pre_lab:\n end = i - 1\n boundary[pre_lab] = [start,end]\n pre_lab = this_lab\n start = i\n\n print(boundary)\n # print(boundary[0][1])\n\n\n '''\n 遍历每条数据,添加正反例\n '''\n block = 0\n test_end = boundary[block][1]\n jump = -1\n for i in range(total_len):\n if jump > 0:\n jump -= 1\n continue\n\n '''\n 生成 2 个正例,\n 如果当前 i + 2 > test_end,跳至下一个 block\n '''\n if i + 2 > test_end:\n block += 1\n if block > len(boundary) - 1:\n break\n test_end = boundary[block][1]\n jump = 1\n continue\n else:\n # print(\"=====================\")\n create_pos_pairs(i)\n\n\n '''\n 生成 2 个反例,\n 随机选取,不等于当前 lable 即可\n '''\n list = []\n while len(list) < 2:\n intt = random.randint(0,list_file_length_1)\n if labels[intt] != labels[i]:\n list.append(intt)\n create_neg_pairs(i,list)\n\n\n # '''\n # 生成 2 个正例,\n # 如果当前 i + 2 > test_end,跳至下一个 block\n # '''\n # if i+2 > test_end:\n # block += 1\n # if block > len(boundary) - 1:\n # break\n # test_end = boundary[block][1]\n # jump = 1\n # else:\n # # print(\"=====================\")\n # create_pos_pairs(i)\n\n '''\n 写入文件\n '''\n with open(save_file_list, 'a', newline='') as f:\n csv_writer = csv.writer(f,delimiter=' ')\n # 添加标题\n csv_head = ['lable','file1', 'file2']\n csv_writer.writerow(csv_head)\n # 添加内容\n for l in save_list:\n csv_content = [l[2],l[0], l[1]]\n csv_writer.writerow(csv_content)\n\n # 关闭文件\n f.close()\n\n\n\n\n\nif __name__ == '__main__':\n gene_pairs()\n\n","sub_path":"src/gene_test_pairs.py","file_name":"gene_test_pairs.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"569619861","text":"# script for plot of TUM type trajectory\n# change from camera frame to the mobile robot (m.r.) frame\n# TUM camera frame: (u, v, d) = (tx, ty, tz), qx, qy, qz, qw -- data[1~7], data[0] is timestamp\n# mobile frame: x = tz, y = -tx, z = - ty\n# quaternion from mobile frame to camera frame: (0.5, 0.5, -0.5, 0.5)\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d\n\nf = open(\"./Trajectory.txt\")\nfCur = open(\"./TrajectoryCur.txt\")\n\n# handle with tx, ty, tz, qx, qy, qz, qw data \nx = []; y = []; z = []; qx = []; qy = []; qz = []; qw = []\nxCur = []; yCur = []; zCur = []\n# calculate Z-Y-X Euler angle from m.r. quaternion\nalpha = []; beta = []; gamma = [];\nfor line in f:\n if line[0] == '#':\n continue\n data = line.split()\n x.append( float(data[3]) ) # tz\n y.append(-float(data[1]) ) #-tx\n z.append(-float(data[2]) ) #-ty\n \n qw.append(0.5 * ( float(data[4]) - float(data[5]) + float(data[6]) - float(data[7])) ) \n qx.append(0.5 * ( float(data[4]) + float(data[5]) - float(data[6]) - float(data[7])) )\n qy.append(0.5 * (-float(data[4]) + float(data[5]) + float(data[6]) - float(data[7])) )\n qz.append(0.5 * ( float(data[4]) + float(data[5]) + float(data[6]) + float(data[7])) )\n\n\n alpha.append(math.atan2(2*(qw[-1]*qz[-1]+qx[-1]*qy[-1]), 1-2*(qy[-1]*qy[-1]+qz[-1]*qz[-1])) )\n if 2*(qw[-1]*qy[-1]-qx[-1]*qz[-1]) > 1:\n beta.append(math.asin(1))\n else:\n beta.append(math.asin(2*(qw[-1]*qy[-1]-qx[-1]*qz[-1])) )\n \n gamma.append(math.atan2(2*(qw[-1]*qx[-1]+qy[-1]*qz[-1]), 1-2*(qx[-1]*qx[-1]+qy[-1]*qy[-1])) )\n \nfor line in fCur:\n if line[0] == '#':\n continue\n data = line.split()\n xCur.append( float(data[3]) ) # tz\n yCur.append(-float(data[1]) ) #-tx\n zCur.append(-float(data[2]) ) #-ty\n\n##for i in range(len(yaw)):\n## print yaw[i]\n\n# plot angle\nf = plt.figure()\nax1 = plt.subplot(311)\nax1.plot(alpha)\nax2 = plt.subplot(312)\nax2.plot(beta)\nax3 = plt.subplot(313)\nax3.plot(gamma)\nf.show()\n\n# plot quaternion\nfq = plt.figure()\nax1 = plt.subplot(411)\nax1.plot(qw)\nax2 = plt.subplot(412)\nax2.plot(qx)\nax3 = plt.subplot(413)\nax3.plot(qy)\nax4 = plt.subplot(414)\nax4.plot(qy)\nfq.show()\n\n# plot in 2d\nfig = plt.figure()\nplt.grid(True)\n\nh1 = min(min(x), min(z))\nh2 = max(max(x), max(z))\nv = [h1, h2, h1, h2]\nax1 = plt.subplot(211)\n##ax1 = fig.gca()\n##ax1.set_autoscale_on(False)\nax1.plot(x, y)\nax1.axis(v)\n\nh1 = min(min(xCur), min(zCur))\nh2 = max(max(xCur), max(zCur))\nv = [h1, h2, h1, h2]\nax2 = plt.subplot(212)\n##ax2 = fig.gca()\n##ax2.set_autoscale_on(False)\nax2.plot(x, y)\nax2.axis(v)\n\nfig.show()\n\n\n### plot in 3d\n##ax1 = plt.subplot(211, projection='3d')\n##ax1.plot(x, y, z)\n##ax2 = plt.subplot(212, projection='3d')\n##ax2.plot(xCur, yCur, zCur)\n##plt.show()\n","sub_path":"draw_trajectory.py","file_name":"draw_trajectory.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"484794659","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport os\n\nPROJECT_PATH = os.path.dirname(os.path.realpath(__file__))\nDICT_PATH = os.path.join(PROJECT_PATH, 'dict')\nDATA_PATH = os.path.join(PROJECT_PATH, 'data')\n\nIP = '192.168.3.180'\nPORT = '9999'\n\nGRAPH_URL = '192.168.3.180:7474'\nGRAPH_USER = 'neo4j'\nGRAPH_PWD = '12345678'","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"527022723","text":"# Extend an ar archive with an index for quick access of member files by name.\n\n# This index is sorted in alphabetical order (i.e. don't use it to read \n# sequentially) and also contains CRC32 values.\n\n# Format described in this file.\n\n# This is a really rough quick script.\n\n# BSAG: released to public domain; use freely.\n\n\n# Why ar?\n# - simple format - don't need an external lib\n# - can have files individually (un)commpressed - like a reverse tar-ball\n# (no point compressing things that are already compressed, like images)\n\n\n\n# The patched ar archive will contain the following files, in order:\n\n# \"/\" (optional) : for resolving long file names (if any)\n# \".index\" : the patched contents table\n# * : the rest of the files\n\n# The \".index\" file will always be the first or second file, depending on\n# if the ar archive contains the \"/\" special file.\n\n\n\n# File format - see https://en.wikipedia.org/wiki/Ar_(Unix)\n\n# File signature:\n\n# The 8 ASCII bytes \"!\\n\"\n\n# Then each file:\n\n# Offset | Size | Name | Format\n# ===========================================================\n# 0 | 16 | File identifier | ASCII string\n# 16 | 12 | File modification timestamp | Decimal string\n# 28 | 6 | Owner ID | Decimal string\n# 34 | 6 | Group ID | Decimal string\n# 40 | 8 | File mode | Octal string\n# 48 | 10 | File size in bytes | Decimal string\n# 5 | 2 | Ending characters | 0x60 0x0A\n# -----------------------------------------------------------\n# | 60 | Total size of member header\n\n# \"Each archive file member begins on an even byte boundary; a newline is\n# inserted between files if necessary. Nevertheless, the size given reflects\n# the actual size of the file exclusive of padding.\"\n\n# The patched contents table is a normal member header, followed by the\n# following binary data (this is our extension to the format):\n\n# A header:\n\n# Offset | Size | Name | Format\n# ===========================================================\n# 0 | 7 | Bytes: \".index\" 0x00 | Bytes\n# 7 | 1 | Version (always 0x01) | uint8\n# 8 | 4 | Number of files in index | uint32 (little endian)\n# 12 | 4 | Reserved, must be NUL bytes | 0x00 0x00 0x00 0x00\n# -----------------------------------------------------------\n# | 16 | Total size of index subheader\n\n\n# Then for each archived file, excluding \"/\" and excluding \".index\",\n# a variable-length record showing where to find the file in the archive,\n# sorted in alphabetical order of filename.\n\n# Offset | Size | Name | Format\n# ============================================================================\n# + 0 | 4 | Absolute offset in bytes of | uint32 (little endian)\n# | | the 60 byte member header that | (add 60 to get actual data)\n# | | this record refers to |\n# + 0 | 4 | Size in bytes of member file | uint32 (little endian)\n# + 8 | 4 | Checksum value (CRC32) | uint32 (little endian)\n# +12 | 2 | Length in bytes of the filename | uint16 (little endian)\n# +14 | s | Filename | ASCII string\n# +14 + s | 2 | Ending characters | 0x00 0x0A\n\n# Note that we abandon the text encoding here in favour of binary - the whole\n# table is designed to be copied directly into memory to be queried efficiently.\n\n# Size is given redundently to simplify client parsing code (no need to parse\n# member headers to read size)\n\n\n\nimport sys\nimport struct\nimport binascii\n\nARSIG = b\"!\\n\"\n\n\nclass Member:\n def __init__(self, offset, header, name, mtime, uid, gid, mode, size, ending):\n self.name = name.decode('ascii').strip()\n self.header = header\n self.mtime = mtime\n self.uid = uid\n self.gid = gid\n self.mode = mode\n self.size = int(size)\n self.offset = int(offset)\n\n if ending is None:\n ending = b'`\\n'\n\n if ending != b'`\\n':\n raise IOError(\"Invalid end of member marker\")\n\n if header is None:\n self.header = self.pack().encode('ascii')\n\n def pack(self):\n return \"%-16s%-12s%-6s%-6s%-8s%-10s%-2s\" % \\\n (self.name+\"/\", self.mtime, self.uid, self.gid, self.mode, str(self.size), \"`\\n\")\n\n def __repr__(self):\n return \"%8d %8d %32s\" % (self.size, self.offset, self.name)\n\n\ndef _read_sig(fp):\n sig = fp.read(len(ARSIG))\n if sig != ARSIG:\n raise IOError(\"Invalid signature: file is not an ar file.\")\n return sig\n\n\ndef _read_member(fp):\n # Advance to even offset\n if (fp.tell() % 2) == 1:\n fp.read(1)\n\n buf = fp.read(60)\n if len(buf) == 0:\n return None # EOF\n if len(buf) != 60:\n raise IOError(\"Unexpected end of file.\")\n\n result = struct.unpack('16s12s6s6s8s10s2s', buf)\n if result:\n offset = fp.tell()\n m = Member(offset, buf, *result)\n buf = fp.read(m.size)\n if len(buf) != m.size:\n raise IOError(\"Unexpected end of file\")\n\n return (m, buf)\n else:\n return None\n\n\ndef _write_member(dest, src, m, buf=None):\n # Advance to even offset\n if (dest.tell() % 2) == 1:\n dest.write(b\"\\n\")\n\n dest.write(m.header) \n if buf is None:\n src.seek(m.offset) \n buf = src.read(m.size)\n if len(buf) != m.size:\n raise IOError(\"Unexpected end of file\")\n dest.write(buf)\n\n\ndef _mkindex(src, members):\n\n# header\n# ===========================================================\n# 0 | 7 | Bytes: \".index\" 0x00 | Bytes\n# 7 | 1 | Version (always 0x01) | uint8\n# 8 | 4 | Number of files in index | uint32 (little endian)\n# 12 | 4 | Reserved, must be NUL bytes | 0x00 0x00 0x00 0x00\n# -----------------------------------------------------------\n# | 16 | Total size of index subheader\n\n yield b'.index\\x00\\x01' + \\\n struct.pack('= len(contents) - 1):\n raise IOError(\"Cannot resolve entry filename: out of bounds\")\n m.name = extract_terminated_string(contents[offset:])\n\n if m.name.endswith(\"/\"):\n m.name = m.name[0:-1]\n\n if (m.name == \".index\"):\n continue\n\n yield m\n\n\ndef indexable_member(member):\n if member.name == \"/\": return False\n if member.name == \".index\": return False\n return True\n\n\ndef usage():\n print(\"Usage:\")\n print(\" %s info ARCHIVE - list members of archive\" % sys.argv[0])\n print(\" %s extend ARCHIVE DEST - create new archive with index\" % sys.argv[0])\n sys.exit(-1)\n\n\n\nif len(sys.argv) < 3:\n usage()\n\n\ncmd = sys.argv[1]\narchive = sys.argv[2]\n\nif (cmd == \"info\") and (len(sys.argv) == 3):\n pass\nelif (cmd == \"extend\") and (len(sys.argv) == 4):\n dest_archive = sys.argv[3]\nelse:\n usage()\n\nif cmd == \"info\":\n with open(archive, 'rb') as fp:\n for m in _walk(fp):\n print(m)\n\nelif cmd == \"extend\":\n wrote_index = False\n\n with open(archive, 'rb') as src:\n with open(dest_archive, 'wb') as dest:\n\n members = list(_walk(src))\n src.seek(0)\n\n dest.write(ARSIG)\n for index, m in enumerate(members):\n\n if m.name == \"/\":\n if index != 0:\n raise IOError(\"Unexpected position for / special file\")\n _write_member(dest, src, m)\n\n if not wrote_index:\n wrote_index = True\n buf = b''.join(_mkindex(src, sorted(list(filter(indexable_member, members)),\n key=lambda x: x.name)))\n\n _write_member(dest, src,\n Member(60 + dest.tell(), None, b\".index\", \"\", \"\", \"\", \"100666\", len(buf), None)\n , buf)\n\n if m.name != \"/\":\n _write_member(dest, src, m)\n\nelse:\n usage()\n\n\n","sub_path":"arindex.py","file_name":"arindex.py","file_ext":"py","file_size_in_byte":9989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"264638107","text":"# pylint: disable=anomalous-backslash-in-string\n\n# 3rd-party\nimport requests\n\n\nclass TelegramBot:\n def __init__(self, token, user):\n self.base_url = f'https://api.telegram.org/bot{token}'\n self.user = user\n\n @property\n def _chart_up_emoji(self):\n return '\\U0001F4C8'\n\n @property\n def _chart_down_emoji(self):\n return '\\U0001F4C9'\n\n @property\n def _robot_emoji(self):\n return '\\U0001f916'\n\n @staticmethod\n def _sanitize(message):\n return str(message).replace('.', '\\.')\n\n def _send(self, message):\n res = requests.post(\n f'{self.base_url}/sendMessage',\n json={'parse_mode': 'MarkdownV2', 'chat_id': self.user, 'text': message},\n )\n\n if res.status_code != 200:\n raise Exception('(TelegramBot) Request failed. Got: {}'.format(res.content))\n\n return res.json()\n\n def notify_alert(self):\n message = (\n self._robot_emoji\n + ' __Notification from Stocks Stalker__ '\n + self._robot_emoji\n )\n\n return self._send(message)\n\n def notify_buy(self, tickers):\n message = self._chart_down_emoji + ' *TIME TO BUY*\\!\\n\\n'\n\n for ticker in tickers:\n message = '{} \\- `{}` \\(exp `{}`, now `{}`\\)\\n'.format(\n message,\n self._sanitize(ticker['code']),\n self._sanitize(ticker['expBuy']),\n self._sanitize(ticker['value']),\n )\n\n return self._send(message)\n\n def notify_sell(self, tickers):\n message = self._chart_up_emoji + ' *TIME TO SELL*\\!\\n\\n'\n\n for ticker in tickers:\n message = '{} \\- `{}` \\(exp `{}`, now `{}`\\)\\n'.format(\n message,\n self._sanitize(ticker['code']),\n self._sanitize(ticker['expSell']),\n self._sanitize(ticker['value']),\n )\n\n return self._send(message)\n","sub_path":"stalker/service/telegram.py","file_name":"telegram.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"365401275","text":"# 单词拆分\n# 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。\n\n# 说明:\n\n# 拆分时可以重复使用字典中的单词。\n# 你可以假设字典中没有重复的单词。\n# 示例 1:\n\n# 输入: s = \"leetcode\", wordDict = [\"leet\", \"code\"]\n# 输出: true\n# 解释: 返回 true 因为 \"leetcode\" 可以被拆分成 \"leet code\"。\n# 示例 2:\n\n# 输入: s = \"applepenapple\", wordDict = [\"apple\", \"pen\"]\n# 输出: true\n# 解释: 返回 true 因为 \"applepenapple\" 可以被拆分成 \"apple pen apple\"。\n# 注意你可以重复使用字典中的单词。\n# 示例 3:\n\n# 输入: s = \"catsandog\", wordDict = [\"cats\", \"dog\", \"sand\", \"and\", \"cat\"]\n# 输出: false\n\nclass Solution(object):\n def wordBreak(self, s, wordDict):\n \"\"\"\n :type s: str\n :type wordDict: List[str]\n :rtype: bool\n \"\"\"\n ret = False\n if len(s)==0:\n return ret\n\n wordlist = []\n i, j = 0, 0\n while(i<=j and j<=len(s)):\n if s[i:j] in wordDict:\n wordlist.append(s[i:j])\n i = j\n j = j + 1\n \n if j>len(s) and i validation loss = %6.8f, perplexity = %6.8f\" % (loss, np.exp(loss)))\n avg_valid_loss += loss / valid_reader.length\n\n print(\"at the end of epoch:\", epoch)\n print(\"train loss = %6.8f, perplexity = %6.8f\" % (avg_train_loss, np.exp(avg_train_loss)))\n print(\"validation loss = %6.8f, perplexity = %6.8f\" % (avg_valid_loss, np.exp(avg_valid_loss)))\n\n save_as = '%s/epoch%03d_%.4f.model' % (FLAGS.train_dir, epoch, avg_valid_loss)\n saver.save(session, save_as)\n print('Saved model', save_as)\n\n # write out summary events\n summary = tf.Summary(value=[\n tf.Summary.Value(tag=\"train_loss\", simple_value=avg_train_loss),\n tf.Summary.Value(tag=\"valid_loss\", simple_value=avg_valid_loss)\n ])\n summary_writer.add_summary(summary, step)\n\n # decide if need to decay learning rate\n if best_valid_loss is not None and np.exp(avg_valid_loss) > np.exp(best_valid_loss) - FLAGS.decay_when:\n print('validation perplexity did not improve enough, decay learning rate')\n current_learning_rate = session.run(train_model.learning_rate)\n print('learning rate was:', current_learning_rate)\n current_learning_rate *= FLAGS.learning_rate_decay\n if current_learning_rate < 1.e-5:\n print('learning rate too small - stopping now')\n break\n\n session.run(train_model.learning_rate.assign(current_learning_rate))\n print('new learning rate is:', current_learning_rate)\n else:\n best_valid_loss = avg_valid_loss\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"train_sentence_encoder.py","file_name":"train_sentence_encoder.py","file_ext":"py","file_size_in_byte":14444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"504779469","text":"#!/usr/bin/env python3\n\n#******************************************************************************\n# treeline.py, the main program file\n#\n# TreeLine, an information storage program\n# Copyright (C) 2015, Douglas W. Bell\n#\n# This is free software; you can redistribute it and/or modify it under the\n# terms of the GNU General Public License, either Version 2 or any later\n# version. This program is distributed in the hope that it will be useful,\n# but WITTHOUT ANY WARRANTY. See the included LICENSE file for details.\n#******************************************************************************\n\n__progname__ = 'TreeLine'\n__version__ = '2.0.2a'\n__author__ = 'Doug Bell'\n\ndocPath = '/usr/local/share/doc/treeline' # modified by install script\niconPath = '/usr/local/share/icons/treeline' # modified by install script\ntemplatePath = '/usr/local/share/treeline/templates' # modified by install script\nsamplePath = '/usr/local/share/doc/treeline/samples' # modified by install script\ntranslationPath = 'translations'\n\n\nimport sys\nimport os.path\nimport argparse\nimport locale\nimport builtins\nfrom PyQt4 import QtCore, QtGui\n\n\ndef loadTranslator(fileName, app):\n \"\"\"Load and install qt translator, return True if sucessful.\n\n Arguments:\n fileName -- the translator file to load\n app -- the main QApplication\n \"\"\"\n translator = QtCore.QTranslator(app)\n modPath = os.path.abspath(sys.path[0])\n if modPath.endswith('.zip'): # for py2exe\n modPath = os.path.dirname(modPath)\n path = os.path.join(modPath, translationPath)\n result = translator.load(fileName, path)\n if not result:\n path = os.path.join(modPath, '..', translationPath)\n result = translator.load(fileName, path)\n if not result:\n path = os.path.join(modPath, '..', 'i18n', translationPath)\n result = translator.load(fileName, path)\n if result:\n QtCore.QCoreApplication.installTranslator(translator)\n return True\n else:\n print('Warning: translation file \"{0}\" could not be loaded'.\n format(fileName))\n return False\n\ndef setupTranslator(app, lang=''):\n \"\"\"Set language, load translators and setup translator functions.\n\n Return the language setting\n Arguments:\n app -- the main QApplication\n lang -- language setting from the command line\n \"\"\"\n try:\n locale.setlocale(locale.LC_ALL, '')\n except locale.Error:\n pass\n if not lang:\n lang = os.environ.get('LC_MESSAGES', '')\n if not lang:\n lang = os.environ.get('LANG', '')\n if not lang:\n try:\n lang = locale.getdefaultlocale()[0]\n except ValueError:\n pass\n if not lang:\n lang = ''\n numTranslators = 0\n if lang and lang[:2] not in ['C', 'en']:\n numTranslators += loadTranslator('qt_{0}'.format(lang), app)\n numTranslators += loadTranslator('treeline_{0}'.format(lang),\n app)\n\n def translate(text, comment=''):\n \"\"\"Translation function, sets context to calling module's filename.\n\n Arguments:\n text -- the text to be translated\n comment -- a comment used only as a guide for translators\n \"\"\"\n try:\n frame = sys._getframe(1)\n fileName = frame.f_code.co_filename\n finally:\n del frame\n context = os.path.basename(os.path.splitext(fileName)[0])\n return QtCore.QCoreApplication.translate(context, text, comment)\n\n def markNoTranslate(text, comment=''):\n \"\"\"Dummy translation function, only used to mark text.\n\n Arguments:\n text -- the text to be translated\n comment -- a comment used only as a guide for translators\n \"\"\"\n return text\n\n if numTranslators:\n builtins._ = translate\n else:\n builtins._ = markNoTranslate\n builtins.N_ = markNoTranslate\n return lang\n\n\ndef main():\n \"\"\"Main event loop function for TreeLine\n \"\"\"\n app = QtGui.QApplication(sys.argv)\n parser = argparse.ArgumentParser()\n parser.add_argument('--lang', help='language code for GUI translation')\n parser.add_argument('fileList', nargs='*', metavar='filename',\n help='input filename(s) to load')\n args = parser.parse_args()\n # must setup translator before any treeline module imports\n lang = setupTranslator(app, args.lang)\n import globalref\n globalref.lang = lang\n globalref.localTextEncoding = locale.getpreferredencoding()\n\n import treemaincontrol\n treeMainControl = treemaincontrol.TreeMainControl(args.fileList)\n app.exec_()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"TreeLine/source/treeline.py","file_name":"treeline.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"575715707","text":"# IMPORTING NECESSARY LIBRARIES\nfrom flask import Flask, render_template, request\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\nimport numpy as np\nimport os\n\n# LOADING THE MODEL\nmodel = load_model('model/model.h5')\n\n# WRITING THE FUNCTION\ndef predict_catordog(model, inputimage):\n test_image = load_img(inputimage, target_size=(200,200))\n test_image = img_to_array(test_image)/255\n test_image = np.expand_dims(test_image, axis=0)\n\n result = model.predict(test_image).round(3)\n\n\n prediction = np.argmax(result)\n\n if prediction == 0:\n message = \"The image uploaded is of a cat\"\n else:\n message = \"The image uploaded is of a dog\"\n\n return message\n\n# CREATING FLASK INSTANCE\napp = Flask(__name__)\n\n# CREATING ENDPOINTS\n@app.route('/', methods = ['GET','POST'])\ndef home():\n return render_template('index.html')\n\n@app.route('/predict', methods = ['GET','POST'])\ndef predict():\n if request.method == 'POST':\n file = request.files['uploadedfile']\n filename = file.filename\n filepath = os.path.join('static/userUploaded', filename)\n file.save(filepath)\n final = predict_catordog(model,inputimage=filepath)\n return render_template('prediction.html',user_image= filepath, finaloutput = final)\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"162990380","text":"from menu import *\n\n\n\nwindow = sf.RenderWindow(sf.VideoMode(640, 480), \"pySFML Window\")\nview = sf.View()\nview.reset(sf.Rectangle((100, 100), (640, 480)))\nwindow.view = view\n\nmenu = Menu(window)\nmenu.Start()\nwhile window.is_open:\n\twindow.clear()\n\tmenu.DrawFrame()\n\twindow.display()","sub_path":"testMenu.py","file_name":"testMenu.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"160659354","text":"# Import Dependencies \nfrom flask import Flask, render_template, redirect, url_for\nimport pymongo\nimport os\n\n# Create MongoDB connection; Create database and collection if it does not exist.\nconn = 'mongodb://localhost:27017'\nclient = pymongo.MongoClient(conn)\ndb = client[\"marsDB\"]\ncollection = db[\"mars\"]\n\n# Create an instance of Flask app\napp = Flask(__name__)\n\n@app.route(\"/scrape\")\ndef import_scrape():\n # Import scrape_mars python file that will web scrapping using beautiful soup and return the data in dictionary.\n import scrape_mars\n if len(db.list_collection_names()) != 0:\n db.mars.drop()\n collection.insert_one(scrape_mars.scrape())\n # return \"Data was successfully scrapped.\"\n return redirect(url_for('show_scraped_data'))\n\n\n@app.route(\"/\")\ndef show_scraped_data():\n # Query the Mongo database and pass the mars data into an HTML template to display the data.\n mars_dic = None\n if len(db.list_collection_names()) == 0:\n return render_template(\"scrape.html\")\n else:\n for field in collection.find():\n mars_dic = field\n break\n return render_template(\"index.html\", dic=mars_dic)\n\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"587616468","text":"import os\n\nfrom setuptools import setup, find_packages\n\n\nif __name__ == '__main__':\n HERE = os.path.abspath(os.path.dirname(__file__))\n\n with open(os.path.join(HERE, 'README.md')) as f:\n README = f.read()\n\n with open(os.path.join(HERE, 'requirements.txt')) as f:\n REQUIREMENTS = [s.strip().replace('-', '_') for s in f.readlines()]\n\n setup(name='pybiz',\n version='1.0',\n description='PyBiz',\n long_description=README,\n install_requires=REQUIREMENTS,\n packages=find_packages(),\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"49056647","text":"#Aidan Walk\r\n#ASTR 260-001\r\n#21 April 2021, 17.00\r\n#HW11 PDE's\r\n\r\n#Problem 1, part b\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport numba\r\nimport time\r\n\r\nclass box:\r\n '''potential box to be inserted into metal square'''\r\n def __init__(self, length, width, positionX=None, positionY=None, charge=None):\r\n self.length = length #in cm, associated with x\r\n self.width = width #in cm, associated with y\r\n self.positionX = positionX #X position of top left corner of box\r\n self.positionY = positionY #y position of top left corner of box\r\n self.charge = charge #+/- 1\r\n \r\ndef insertBox(array, rho=None, boxes=None):\r\n '''inserts the potential box into an array\r\n positionX and positionX+width,\r\n positionY and positionY+length (of box) must be within bounds of array\r\n boxes = list of boxes to insert into array'''\r\n for box in boxes:\r\n xnaught, xfinal = box.positionX, box.positionX + box.width\r\n ynaught, yfinal = box.positionY, box.positionY + box.length\r\n \r\n #input charged box into array\r\n for i in range(xnaught, xfinal):\r\n for j in range(ynaught, yfinal):\r\n array[j,i] = rho*box.charge #index goes as j,i b/c row=y, column=x\r\n \r\n return array\r\n\r\n@numba.jit(nopython = True)\r\ndef iterate(phi):\r\n gain = 0.00001\r\n \r\n phiPrime = np.zeros(phi.shape)\r\n for i in range(gridsize+1):\r\n for j in range(gridsize+1):\r\n #if i or j is boundary, keep values the same\r\n if i==0 or i==gridsize or j==0 or j==gridsize or np.abs(phi[i,j])==rho:\r\n phiPrime[i,j] = phi[i,j]\r\n else:\r\n phiPrime[i,j] = ( ((1+gain)/4)*(phi[i+1, j] + phi[i-1, j] + \\\r\n phi[i, j+1] + phi[i, j-1] + \\\r\n gridSpacing**2/4.0*rho)) - \\\r\n gain*phi[i,j]\r\n \r\n return phiPrime\r\n\r\nif __name__ == \"__main__\":\r\n gridsize = 100 #n x n grid across box, in cm\r\n target = 1e-6 #target accuracy, in volts\r\n \r\n #charge density\r\n gridSpacing = 0.01 #cm in a m\r\n rho = 1 #coulomb/m**2\r\n \r\n \r\n #box characteristics \r\n width = length = 20 #cm\r\n positiveBox = box(length, width, \r\n positionX = gridsize-length-20, \r\n positionY = 20+1, \r\n charge = 1)\r\n negativeBox = box(length, width, \r\n positionX = 20+1, \r\n positionY = gridsize-width-20, \r\n charge = -1) \r\n boxes = [positiveBox, negativeBox]\r\n \r\n \r\n #initial metal box\r\n metalBox = np.zeros((gridsize+1, gridsize+1))\r\n #insert potential boxes into metal box\r\n metalBox = insertBox(metalBox, rho=rho, boxes=boxes)\r\n\r\n phiprime = np.zeros(metalBox.shape)\r\n\r\n max_diff = 1.0\r\n iteration = 0\r\n \r\n print('Calculating potential via Gauss-Seidel Method to an accuracy of', target, 'volts...')\r\n start_time = time.time()\r\n while max_diff > target:\r\n #calculate new values of potential\r\n phiprime = iterate(metalBox)\r\n \r\n max_diff = np.max(abs(metalBox-phiprime))\r\n metalBox, phiprime = phiprime, metalBox\r\n #print('iteration:', iteration, 'Difference', max_diff)\r\n iteration=iteration+1\r\n end_time = time.time() #stop time\r\n print('--- Calculation duration: %s seconds ---' % (end_time - start_time))\r\n print('Value of potential at middle of box:', metalBox[int(gridsize/2), int(gridsize/2)])\r\n \r\n plt.imshow(metalBox, cmap='Greys')\r\n plt.savefig('AidanWalk_HW11_1b_Plot.png', dpi=300)\r\n print(\"Plot saved as 'AidanWalk_HW11_1b_Plot.png'\")\r\n","sub_path":"AidanWalk_HW11_1b.py","file_name":"AidanWalk_HW11_1b.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"378095154","text":"def cmap(mapCen, mapData):\n mapResults = []\n numFeatures = len(mapData[0])\n ##for each data piece\n for dataToMap in mapData:\n eucDists = []\n ##iterate through each centroid\n for cen in mapCen:\n ##find the Squared Euclidean Distance to the data piece\n SED = 0\n for feature in range(numFeatures):\n dif = cen[feature] - dataToMap[feature]\n SED = SED + (dif * dif)\n eucDists.append(SED)\n ##record the centroid with the shortest distance\n mapResults.append(eucDists.index(min(eucDists)))\n return(mapResults)\n\ndef sortDataToCluster(dataToSort, dataIndicies, k):\n clusteredData = []\n ##set up empty results array\n for cluster in range(k):\n clusteredData.append([])\n ##dataIndicies[d] returns the centroid ID of the data stored in dataToSrt[d]\n for d in range(len(dataToSort)):\n clusteredData[dataIndicies[d]].append(dataToSort[d])\n return(clusteredData)\n\nif __name__ == '__main__':\n import dispy, socket, time\n import numpy as np\n import matplotlib.pyplot as plt\n \n ##fetch the IP address of the client\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"10.0.0.2\", 80)) ##doesn't matter if 8.8.8.8 can't be reached\n \n ##read in data from text file, split into lines and turned into floats\n f = open(\"data.txt\",\"r\")\n data = [[float(num) for num in line.split()] for line in f.readlines()]\n f.close()\n\n numdata = len(data) ##length of dataset\n features = len(data[0]) ##length of a single data piece\n\n ##set k\n k = 7\n \n ##choose random centroids from available data\n centroidID = np.random.permutation(numdata)\n centroids = np.empty((k,features))\n for i in range(k):\n centroids[i] = data[centroidID[i]]\n \n ##repeat cycle x number of times to train centroids\n numtrials = 10\n numNodes = 32 ##usually total number of core on network, maybe 2 times the number if feeling generous)\n numtrialtaken = 0\n \n for trialNum in range(numtrials):\n ## reset cluster for fresh use\n cluster = dispy.JobCluster(cmap,ip_addr=s.getsockname()[0], nodes=['10.0.0.3','10.0.0.4','10.0.0.5','10.0.0.6'])\n \n ##split each data piece into its own job\n numJobs = numNodes\n results = []\n jobData = np.array_split(data,numJobs)\n starts = []\n ends = []\n jobs = []\n \n ##new method writing direct into job list, however, it doesnt allow for adding a jobID to the job\n #jobs = [cluster.submit(centroids,jobData[i]) for i in range(numJobs)]\n\n for i in range(numJobs):\n ##schedule execution of 'cmap' on a node (running 'dispynode')\n ##with parameters (centroids of classes, batch of data to be classified)\n starts.append(time.time_ns())\n job = cluster.submit(centroids,jobData[i])\n job.id = i \n jobs.append(job)\n\n for job in jobs:\n n = job() ##get job results\n ends.append(time.time_ns())\n ##.append would create a sublist. Dereferencing arrays when combine prevents this\n if n is not None:\n results = [*results, *n]\n print('Executed cmap job %s in %s seconds' % (job.id, job.end_time - job.start_time))\n cluster.print_status()\n ##MUST be called before new cluster defined\n cluster.close()\n \n for i in range(len(starts)):\n print('Job %s completed in real time of %s' %(i, ((ends[i] - starts[i])/1000000000)))\n\n ##sort data into clusters. This can be done as simple assignment into a list so parallelizing this would be worthless\n clusteredData = sortDataToCluster(data,results,k)\n ##clusteredData[class][data][feature]\n \n ##setup empty results\n results = []\n \n ##do feature averaging client side. Doing it server side results in speedup < 1 due to network latency\n ##for each cluster\n for i in range(k):\n numDiC = len(clusteredData[i])\n ##for each feature in chosen cluster\n for j in range(features):\n featureSum = 0\n featureAvg = 0\n ##collect each value of chosen feature from data in cluster\n for m in range(numDiC):\n featureSum = featureSum + clusteredData[i][m][j]\n ##if no data in cluster, use centroid instead \n if (featureSum == 0):\n featureAvg = centroids[i][j]\n else:\n featureAvg = featureSum/numDiC\n ##store result\n results.append(featureAvg)\n \n ##rebuild centroids from results\n newCentroids = centroids\n for i in range(k):\n for j in range(features):\n newCentroids[i][j] = results[(features*i) + j]\n ##check to see if centroids have changed\n compare = centroids == newCentroids\n if compare.all():\n ##if so stop classifying\n numtrialtaken = trialNum\n trialNum = numtrials - 1 ##exit the loop\n else:\n ##if not keep classifying\n centroids = newCentroids\n \n ##display results for 2D data in 7 or fewer clusters\n if ((k <= 7) and (features == 2)):\n colors = ['blue','green','red','yellow','orange','brown','purple']\n centroidsx = []\n centroidsy = []\n ##plot each cluster\n for a in range(k):\n tempX = []\n tempY = []\n for d in clusteredData[a]:\n tempX.append(d[0])\n tempY.append(d[1])\n lbl = 'class ' + str(a)\n plt.scatter(tempX, tempY, label = lbl, color = colors[a], marker = '*')\n ##plot centroids\n for c in range(k):\n plt.scatter(centroids[c][0], centroids[c][1], color = 'black', marker = '.', s = 50)\n ##plot graph labels\n plt.xlabel('Feature 1')\n plt.ylabel('Feature 2')\n titlestr = 'Classification of data after ' + str(numtrialtaken) + ' k-means trials'\n plt.title(titlestr)\n plt.legend()\n \n ##show figure\n plt.show()\n","sub_path":"k-means-training.py","file_name":"k-means-training.py","file_ext":"py","file_size_in_byte":6297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"449975951","text":"## The purpose of this scraper is solely created for educational testing only and it is by no mean for commercial activities.\n\nfrom lxml import html\nfrom datetime import datetime as dt\nimport requests, re, time, schedule, pandas as pd, numpy as np\n\ndef extract():\n ## Script Processing Timestamp\n print('Processing Time: ', dt.fromtimestamp(time.time()).strftime('%H:%M'))\n \n ## Web Request to extract HTML format\n webpage = requests.get('https://www.asx.com.au/asx/statistics/indexInfo.do')\n tree = html.fromstring(webpage.content)\n \n ## HTML transformation in filtering unneeded texts\n quote = tree.xpath('//td[@nowrap =\"nowrap\"]/text()')\n quote = [re.sub(r'[^0-9]', '', x) for x in quote]\n quote = [x for x in quote if x]\n \n ## Further Data Preprocessing\n c = [float(a)/10 for a in quote[1::2]]\n close = (list(c))[1::2]\n d = [float(b)/10 for b in quote[0::2]]\n last = (list(d))[0::2]\n \n ## Data Engineering (Changes)\n chg = [(b-a)/a for a,b in zip(close, last)]\n \n ## Lists Merging\n overall = last + close + chg\n \n ## Dataframe Creation\n df = (pd.DataFrame(data = [overall]).astype(float))\n df['GMT10'] = dt.today().strftime('%Y-%m-%d-%H:%M')\n \n ## Loading new data every 5 minutes in csv format\n with open('ASX.csv', 'a') as f:\n df.to_csv(f, header = False)\n\nschedule.every(5).minutes.do(extract)\nwhile True:\n schedule.run_pending()\n time.sleep(5)\n\n","sub_path":"scrapping.py","file_name":"scrapping.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"411479957","text":"import turtle\nfrom math import *\n\na = float(input('a=')) # angle in radians\nv = float(input('v=')) # m/s\nh = float(input('h=')) # metres\ng = 9.8 # m/s\nx2 = (v * cos(a))*(((v * sin(a))/g) + sqrt((2 / g) * (h + ((v ** 2)*sin(a))/(2 * g))))\nprint('точка у яку влучить снаряд: ', x2)\n\nfor i in range(0, x2):\n y = i * math.tan(a) - (g * i * i) / (2 * v * v * math.cos(a) * math.cos(a)) + h\n turtle.up()\n turtle.setpost(i,yh)\n turtle.down(i,y)\n turtle.circle(1)\n","sub_path":"tokill/6666666.py","file_name":"6666666.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"74514064","text":"'''\nThis code is a python version of genome for testing and developing\nAuthor: Jingxuan\nInput format:\n - Trajectory format : 5250120B145F5EBD398592804B58C452D82034;103.8630833,1.334861111,2016-10-10 09:00:00,1,525-1-52-10842;103.8630833,1.334861111,2016-10-10 10:00:00,1,525-1-52-10842;\n'''\nfrom update import Update\nfrom utils.time_common import zdt_to_dt\n\nclass Trajectory:\n def __init__(self):\n pass\n\n def form_trajectory_from(self, lbs):\n \"\"\"\n form Trajectory object from raw lbs format\n :param lbs: list of lbs record\n :return: trajectory object\n \"\"\"\n self.imsi = lbs[0].data['imsi']\n lbs = sorted(lbs, key=lambda x: x.data['timestamp'])\n self.updates = list(map(lambda x: Update(\"{0},{1},{2},1,{3}\".format(x.data['lon'], x.data['lat'], x.data['timestamp'], x.data['cgi'])), lbs))\n\n def from_string(self, str):\n \"\"\"\n convert trajectory from string to object\n :param str: trajectory in string format\n :return: trajectory object\n \"\"\"\n fields = str.strip().split(\";\")\n self.imsi = fields[0]\n self.updates = [Update(i) for i in fields[1:]]\n\n def merge_trajectory(self, other):\n \"\"\"\n merge updates for trajectories having same imsi\n :param other: other trajectory\n :return: updated update list\n \"\"\"\n if self.imsi != other.imsi:\n ValueError(\"two trajectory has different imsi\")\n else:\n self.updates = sorted(self.updates + other.updates, key=lambda x: x.timestamp)\n\n def filter_by_time(self, start_time, end_time=\"\", interpolation=True):\n \"\"\"\n filter updates in trajectory by given period\n :param start_time: start time in string in format \"%Y-%m-%d %H:%M:%S\"\n :param end_time: end time in string in format \"%Y-%m-%d %H:%M:%S\"\n :return: updated update list\n \"\"\"\n if end_time:\n updates = [i for i in self.updates if start_time <= i.timestamp <= end_time]\n if not interpolation:\n updates = [i for i in self.updates if i.cell_type!=\"10\"]\n else:\n updates = [i for i in self.updates if start_time <= i.timestamp]\n if not interpolation:\n updates = [i for i in self.updates if i.cell_type!=\"10\"]\n\n new_tr = Trajectory()\n new_tr.updates = updates\n return new_tr\n\n def map_to_local_timestamp(self, target_tz=\"Australia/Sydney\"):\n updates = []\n for i in self.updates:\n i.timestamp = zdt_to_dt(i.timestamp, target_tz=target_tz)\n updates.append(i)\n self.updates = updates\n\n def correct_location(self, dic):\n \"\"\"\n correct the location for the cells in given dic\n :param dic: dict of (cell and location)\n :return:\n \"\"\"\n new_updates = []\n for i in self.updates:\n cell = i.cell\n if cell in dic:\n lat = dic[cell][0]\n lon = dic[cell][1]\n new_updates.append(Update(\"{0},{1},{2},{3},{4}\".format(str(lon), str(lat), i.timestamp, i.cell_type, i.cell)))\n else:\n new_updates.append(i)\n self.updates = new_updates\n\n def __str__(self):\n return \"%s;%s\"%(self.imsi, \";\".join([i.__str__() for i in self.updates]))\n\n def __iter__(self):\n for i in self.updates:\n yield i\n","sub_path":"package/jx_analysis_python/genome/trajectory.py","file_name":"trajectory.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"76663899","text":"# https://www.codechef.com/problems/BUY1GET1\n\nimport math\n\ndef count_jewels(s):\n\tseen = {}\n\n\tfor c in s.strip():\n\t\tif c in seen:\n\t\t\tseen[c] += 1\n\t\telse:\n\t\t\tseen[c] = 1\n\n\treturn seen\n\ndef calculate_min_price(seen):\n\tcost = 0\n\n\tfor v in seen.values():\n\t\tcost += math.ceil(v / 2)\n\n\treturn cost\n\ndef solve():\n\tcases = int(input())\n\n\twhile cases > 0:\n\t\ts = input()\n\t\tjewels = count_jewels(s)\n\t\tprint(calculate_min_price(jewels))\n\t\tcases -= 1\n\nsolve()\n","sub_path":"codechef/easy/buy1_get1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"251848169","text":"file = open(\"ELECTION.txt\",\"r\")\nline = file.read()\ndap = 0 #votes for DAP\npjp = 0 #Votes for PJP\nntp = 0 #Votes for NTP\nvoid = 0 #Number of voided votes\ntotal = 0 #total number of votes cast\nline = line.split()\nfor i in line:\n if i == \"A\":\n ntp += 1\n elif i == \"B\":\n dap += 1\n elif i == \"C\":\n pjp += 1\n elif i == \"V\":\n void += 1\n total += 1\n\nparty = {ntp:\"NTP\",dap:\"DAP\",pjp:\"PJP\",void:\"Void\"} #Dictionary of the votes and party names\nvotes = [ntp,dap,pjp,void] #Array of number of votes to be sorted \nvotes.sort() #Sort the list in order\nhighest = party.get(votes[3]) #name of party with largest number of votes\n\nprint(\"Results for the Electoral Division of Putrajaya\")\nfor i in votes[::-1]: #Read the list from the back\n print(party.get(i),end=\"\\t\") #Print the party name \n i = i/total*100 #Convert number of votes to percentage\n i = round(i,1) #round i to 1 decimal place\n i = str(i)+\"%\" #add a percentage sign\n print(i)\nprint(\"Winner is\",highest)\n\n","sub_path":"Papers/C2 BT2 2017/Task 1.1.py","file_name":"Task 1.1.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"41654246","text":"import numpy as np\nfrom itertools import product\nimport gym\nfrom tqdm import trange\nfrom joblib import Parallel, delayed\n\ndef gridsearch(agent_class, parameters, trials, n_episodes, max_episode_length=np.inf):\n\t\"\"\" Parameters should a dictionary of the form of the form:\n\t\t{\n\t\t\t\"bin_counts\": List of iterables, each iterable contains possible bin values for respective observation element,\n\t\t\t\"epsilon_time_constant\": iterable of possible epsilon_time_constant values,\n\t\t\t\"lr_time_constant\": iterable of possible lr_time_constant values,\n\t\t}\n\t\"\"\"\n\n\t# Grid individual parameters\n\tgridded_bins = product(*parameters[\"bin_counts\"])\n\tgridded_epsilons = product(parameters[\"epsilon_time_constant\"])\n\tgridded_lr_time_constant = product(parameters[\"lr_time_constant\"])\n\n\t# Grid all of the parameters\n\tgrid = [x for x in product(gridded_bins, gridded_epsilons, gridded_lr_time_constant)]\n\n\t# Construct nice dictionary to pass to evaluate_parameters\n\tfor i in range(len(grid)):\n\t\tgrid[i] = {\n\t\t\t\"bin_counts\": grid[i][0],\n\t\t\t\"epsilon_time_constant\": grid[i][1][0], # Unpack 1 element tuple\n\t\t\t\"lr_time_constant\": grid[i][2][0], # Unpack 1 element tuple\n\t\t}\n\n\tprint(f\"Running gridsearch over {len(grid)} parameter configurations...\")\n\tresults = Parallel(n_jobs=-1, backend=\"multiprocessing\", verbose=True)(\n\t\tdelayed(evaluate_parameters)(agent_class, params, trials, n_episodes, max_episode_length) for params in grid\n\t)\n\n\tfor i in range(len(results)):\n\t\tresults[i] = (grid[i], results[i])\n\n\treturn results\n\ndef evaluate_parameters(agent_class, parameters, trials, n_episodes, max_episode_length=np.inf):\n\t\"\"\" Evaluates a single set of parameters. Returns the WMA of each trial \"\"\"\n\n\tperformance = []\n\tfor _ in range(trials):\n\t\tagent = agent_class(**parameters)\n\n\t\ttrial_rewards = []\n\t\tfor _ in range(n_episodes):\n\t\t\treward = agent.train_episode(visualize=False, max_steps=max_episode_length)\n\t\t\ttrial_rewards.append(reward)\n\n\t\tperformance.append(np.average(trial_rewards))\n\t\t# performance.append(calc_wma_reverse(trial_rewards))\n\n\treturn performance\n\ndef calc_wma_reverse(vals):\n\t\"\"\" Calculates a weighted moving average of vals, higher weights to first elements.\n\t\tThus higher wma's will be assigned to faster-converging models.\n\t\"\"\"\n\n\treturn np.dot(vals, np.arange(len(vals), 0, -1)) / (len(vals) * (len(vals) + 1) / 2)","sub_path":"utils/gridsearch.py","file_name":"gridsearch.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"51221911","text":"from keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy\n# seed of reproductibilty, este es random. se deberia sacar mediante formula.\nseed = 7\nnumpy.random.seed(seed)\n# cargando el dataset de pima-indians\ndataset = numpy.loadtxt(\"pima-indians-diabetes.csv\", delimiter=\",\")\nprint(\"DATASET ORIGINAL\")\nprint(dataset)\n\n# Dividir el dataset en variables input(x) y output(y)\nX = dataset[:,0:8]\n#Corte del array: [row inicial:rowfinal, datoinicial:datofinal]\nY = dataset[:,8]\nprint(\"VALORES DE X\")\nprint(X)\nprint(\"VALORES DE Y\")\nprint(Y)\n\n# Crear el modelo\nmodel = Sequential()\nmodel.add(Dense(12, input_dim=8, init='uniform', activation='relu'))\nmodel.add(Dense(8, init='uniform', activation='relu'))\nmodel.add(Dense(1, init='uniform', activation='sigmoid'))\n# Configurar Aprendizaje del modelo\nmodel.compile(loss='binary_crossentropy' , optimizer='adam', metrics=['accuracy'])\n# Fit model\nmodel.fit(X, Y, nb_epoch=15, batch_size=5) \n#epoch: Entrenamientos\n#batch_size: Cantidad de Muestras\n\n# Evaluar el modelo\nscores = model.evaluate(X, Y)\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\nprint(X)\nZ=numpy.array([[0,89,66,23,94,28.1,0.167,21]])\n#Predicciones del Dataset, para comparar con el original Y\n#predicciones = model.predict(X, batch_size=5, verbose=0)\n#print(predicciones)\nprint(\"PREDICCION DE PRUEBA\")\nprediccion_prueba=model.predict(Z, batch_size=5, verbose=0)\nprint(prediccion_prueba)\n","sub_path":"1-diabetes/prediccionNN.py","file_name":"prediccionNN.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"275361158","text":"# import the necessary packages\nfrom skimage.segmentation import slic\nfrom skimage.segmentation import mark_boundaries\nfrom skimage.util import img_as_float\nfrom skimage import io\nimport matplotlib.pyplot as plt\nimport numpy as np\n# import cv2\nfrom matplotlib import pyplot as plt\nimport pickle\n\ndef removeText(img, ocrResults):\n for ocr in ocrResults:\n bbox = ocr[0]\n xMin = int(bbox[0][0])\n yMin = int(bbox[0][1])\n xMax = int(bbox[2][0])\n yMax = int(bbox[2][1])\n value = img[yMax][xMax]\n\n for x in range(xMin,xMax):\n for y in range(yMin,yMax):\n img[y][x] = value\n\n return img\n\ndef main():\n # read detection results from pickle file\n detectResultName = r'C:\\Users\\jiali\\Desktop\\MapElementDetection\\code\\postProcessingDetection\\detectResultsOrigin.pickle'\n with open(detectResultName, 'rb') as fDetectResults:\n detectResults = pickle.load(fDetectResults)\n\n # read ocr results from pickle file\n ocrResultName = r'C:\\Users\\jiali\\Desktop\\MapElementDetection\\code\\postProcessingDetection\\ocrBoundsListOrigin.pickle'\n with open(ocrResultName, 'rb') as fOCRResults:\n ocrResults = pickle.load(fOCRResults)\n\n path = r'C:\\Users\\jiali\\Desktop\\MapElementDetection\\dataCollection\\USStateChoro\\originalSize'\n\n # img1Name = '1_i7aR525CtXLHOPbarZt5kg.png'\n # img1Name = '7.7886413.jpg'\n # img1Name = '22.Map.jpg'\n img1Name = '8.9781412956970-p406-1.jpg'\n # read images and remove texts on the images\n img1 = io.imread(path + '\\\\' + img1Name) # Image1 to be matched\n ocrImg1 = [ocr[1:] for ocr in ocrResults if ocr[0]==img1Name][0]\n img1Proc = removeText(img1,ocrImg1)\n\n image = img_as_float(img1Proc)\n # loop over the number of segments\n\n # apply SLIC and extract (approximately) the supplied number\n # of segments\n numSegments = 300\n segments = slic(image, n_segments = numSegments, sigma = 5)\n # show the output of SLIC\n fig = plt.figure(\"Superpixels -- %d segments\" % (numSegments))\n ax = fig.add_subplot(1, 1, 1)\n bounds = mark_boundaries(image, segments)\n ax.imshow(bounds)\n plt.axis(\"off\")\n # show the plots\n plt.show()\n\nif __name__ == \"__main__\": main()","sub_path":"code/state identification/superpixelSegmentation.py","file_name":"superpixelSegmentation.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"474037886","text":"def operationTotal(theGen, probXover, probMut, elitism, selectionMethod):\n tempFitVector = popFit(theGen);\n theStrongF = 0;\n \n if (elitism == 1):\n theStrongF = max(tempFitVector);\n theStrongP = tempFitVector.index(theStrongF)\n theStrong = theGen[theStrongP];\n \n if (selectionMethod == 1):\n theGen = selectRoulette(theGen);\n else:\n theGen = tournamentSelect(theGen);\n \n theGen = crossover(theGen, probXover);\n theGen = mutation(theGen, probMut, theStrongF, tempFitVector);\n \n if (elitism == 1):\n tempFitVector = popFit(theGen);\n theWeakF = min(tempFitVector);\n theWeakP = tempFitVector.index(theWeakF);\n theGen[theWeakP] = theStrong;\n \n if (theWeakF < theStrongF):\n theGen[theWeakP] = theStrong\n \n return theGen;\n\n\ndef evolution(rowNum, probXover, probMut, elitism, selectionMethod):\n \n # initialize\n population = genPopulation(rowNum)\n fitVector = popFit(population)\n best = max(fitVector)\n bestInd = population[fitVector.index(best)]\n \n countConverge = 0;\n genCount = 1;\n limit = 60;\n \n while True:\n population = operationTotal(population, probXover, probMut, elitism, selectionMethod)\n fitVector = popFit(population);\n genCount += 1;\n \n if (max(fitVector) > best):\n best = max(fitVector);\n bestInd = population[fitVector.index(best)]\n \n print(best)\n print(bestInd)\n else:\n countConverge -= 1\n \n limit -= 1;\n \n if (countConverge == 15):\n break;\n if (limit == 0):\n break;\n \n bestInd.append(best)\n \n return bestInd;","sub_path":"Shauffe 6/GA/operation.py","file_name":"operation.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"477918209","text":"\"\"\"Index analyzer plugin for Yeti indicators.\"\"\"\nfrom __future__ import unicode_literals\n\nfrom flask import current_app\nimport requests\n\nfrom timesketch.lib.analyzers import interface\nfrom timesketch.lib.analyzers import manager\nfrom timesketch.lib import emojis\n\n\ndef build_query_for_indicators(indicators):\n \"\"\"Builds an Elasticsearch query for Yeti indicator patterns.\n\n Prepends and appends .* to the regex to be able to search within a field.\n\n Returns:\n The resulting ES query string.\n \"\"\"\n query = []\n for domain in indicators:\n query.append('domain:/.*{0:s}.*/'.format(domain['pattern']))\n return ' OR '.join(query)\n\n\nclass YetiIndicators(interface.BaseSketchAnalyzer):\n \"\"\"Index analyzer for Yeti threat intel indicators.\"\"\"\n\n NAME = 'yetiindicators'\n DEPENDENCIES = frozenset(['domain'])\n\n def __init__(self, index_name, sketch_id):\n \"\"\"Initialize the Index Analyzer.\n\n Args:\n index_name: Elasticsearch index name\n \"\"\"\n super(YetiIndicators, self).__init__(index_name, sketch_id)\n self.intel = {}\n self.yeti_api_root = current_app.config.get('YETI_API_ROOT')\n self.yeti_api_key = current_app.config.get('YETI_API_KEY')\n self.yeti_indicator_labels = current_app.config.get(\n 'YETI_INDICATOR_LABELS', [])\n\n def get_bad_domain_indicators(self, entity_id):\n \"\"\"Retrieves a list of indicators associated to a given entity.\n\n Args:\n entity_id (str): STIX ID of the entity to get associated inticators\n from. (typically an Intrusion Set)\n\n Returns:\n A list of JSON objects describing a Yeti Indicator.\n \"\"\"\n results = requests.post(\n self.yeti_api_root + '/entities/{0:s}/neighbors/'.format(entity_id),\n headers={'X-Yeti-API': self.yeti_api_key},\n )\n if results.status_code != 200:\n return []\n domain_indicators = []\n for neighbor in results.json().get('vertices', {}).values():\n if neighbor['type'] == 'x-regex' and \\\n set(self.yeti_indicator_labels) <= set(neighbor['labels']):\n domain_indicators.append(neighbor)\n\n return domain_indicators\n\n def get_intrusion_sets(self):\n \"\"\"Populates the intel attribute with data from Yeti.\n\n Retrieved intel consists of Intrusion sets and associated Indicators.\n \"\"\"\n results = requests.post(\n self.yeti_api_root + '/entities/filter/',\n json={'name': '', 'type': 'intrusion-set'},\n headers={'X-Yeti-API': self.yeti_api_key},\n )\n if results.status_code != 200:\n return\n self.intel = {item['id']: item for item in results.json()}\n for _id in self.intel:\n self.intel[_id]['indicators'] = self.get_bad_domain_indicators(_id)\n\n def run(self):\n \"\"\"Entry point for the analyzer.\n\n Returns:\n String with summary of the analyzer result\n \"\"\"\n if not self.yeti_api_root or not self.yeti_api_key:\n return 'No Yeti configuration settings found, aborting.'\n\n self.get_intrusion_sets()\n actors_found = []\n for intrusion_set in self.intel.values():\n if not intrusion_set['indicators']:\n continue\n\n found = False\n\n for indicator in intrusion_set['indicators']:\n query = build_query_for_indicators([indicator])\n\n events = self.event_stream(query_string=query,\n return_fields=[])\n\n name = intrusion_set['name']\n for event in events:\n found = True\n event.add_emojis([emojis.get_emoji('SKULL')])\n event.add_tags([name])\n event.commit()\n event.add_comment(\n 'Indicator \"{0:s}\" found for actor \"{1:s}\"'.format(\n indicator['name'], name))\n\n if found:\n actors_found.append(name)\n self.sketch.add_view(\n 'Domain activity for actor {0:s}'.format(name),\n self.NAME,\n query_string=query)\n\n if actors_found:\n return '{0:d} actors were found! [{1:s}]'.format(\n len(actors_found), ', '.join(actors_found))\n return 'No indicators were found in the timeline.'\n\n\nmanager.AnalysisManager.register_analyzer(YetiIndicators)\n","sub_path":"timesketch/lib/analyzers/yetiindicators.py","file_name":"yetiindicators.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"431299986","text":"#!/usr/bin/env python3\n\nfrom random import shuffle\n\ndevs = [\n 'Keith',\n 'Paul', \n 'Amir', \n 'Daniel',\n 'Tao',\n 'Arash']\n\nanalysts = [\n 'Ramesh', \n 'Vandhana', \n 'Jina', \n 'Pratima',\n 'Yan']\n\nshuffle(devs)\nshuffle(analysts)\n\nwhile devs and analysts:\n dev = devs.pop()\n analyst = analysts.pop()\n\n print(f\"{dev} {analyst}\")\n\nif devs or analysts:\n byes = ','.join(devs + analysts)\n print(\"~~~~~~\")\n print(f\"Bye: {byes}.\")\n","sub_path":"office_hours_dev_analyst.py","file_name":"office_hours_dev_analyst.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"449382728","text":"import pykd\nimport os\nimport time\nimport shutil\nimport sys\nimport datetime\nfrom subprocess import Popen,call\nimport traceback\n\ndef log(log_str):\n with open(\"p.log\",\"at\") as log:\n log.write(log_str)\n\ndef sleep():\n time.sleep(200)\n\ne=pykd.dbgCommand\ninput_dir=os.path.join(os.getcwd(),\"input\")\ncrash_dir=os.path.join(os.getcwd(),\"crashes\")\nif not os.path.exists(input_dir):\n log(\"ERROR:input dir not exists\")\n os._exit(0)\nif not os.path.exists(crash_dir):\n os.makedirs(crash_dir)\n\n\ndef save_sample(who_find):\n try:\n log( \"\\n\"+str(who_find)+\" FIND VULNERABILITY!!!\"+\"#\"*64+datetime.datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S\"))\n except:\n traceback.print_exc()\n\n sample_file=sys.argv[1]\n try:\n Popen(args=[\"python\", \"mycopy.py\",os.path.join(input_dir, sample_file),os.path.join(crash_dir, sample_file)],shell=True)\n except:\n traceback.print_exc()\n\n try:\n shutil.copyfile(os.path.join(input_dir, sample_file), os.path.join(crash_dir, sample_file))\n except:\n traceback.print_exc()\n shutil.copyfile(os.path.join(input_dir, sample_file), os.path.join(crash_dir, sample_file))\n\n try:\n logf=open(os.path.join(crash_dir,\"log_\"+sample_file+\".txt\"),\"wt\")\n logf.write(\"*\"*40+\".lastevent\"+\"*\"*40+\"\\n\"*2)\n logf.write(e(\".lastevent\")+\"\\n\"*4)\n logf.write(\"*\"*40+\"r\"+\"*\"*40+\"\\n\"*2)\n logf.write(e(\"r\")+\"\\n\"*4)\n logf.write(\"*\"*40+\"u \"+\"*\"*40+\"\\n\"*2)\n logf.write(e(\"u\")+\"\\n\"*4)\n logf.write(\"*\"*40+\"ub\"+\"*\"*40+\"\\n\"*2)\n logf.write(e(\"ub eip\")+\"\\n\"*4)\n logf.write(\"*\"*40+\"callstack\"+\"*\"*40+\"\\n\"*2)\n logf.write(e(\"kv\")+\"\\n\"*4)\n logf.write(\"*\" * 40 + \"lm\" + \"*\" * 40 + \"\\n\" * 2)\n logf.write(e(\"lm\") + \"\\n\" * 4)\n logf.close()\n except:\n traceback.print_exc()\n log( \"ERROE:crashlog create error!\")\n sleep()\n\nwhile True:\n try:\n res_g=e(\"sxd cpr;sxd ld;sxd ct;sxd et;g\")\n event=e(\".lastevent\")\n kstr=e(\"k L2\")\n rstr=e(\"r\")\n if (kstr.find(\"verifier!VerifierStopMessage\") >= 0):\n save_sample(\"M\")\n if event.find(\"WOW64 breakpoint\") > 0 or event.find(\"Break instruction exception\") > 0 or event.find(\"Exit process\") > 0 or rstr.find(\"ntdll!KiFastSystemCallRet\") > 0:\n continue\n save_sample(\"I\")\n except:\n pass","sub_path":"p.py","file_name":"p.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"175778151","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('contactmanager', '0003_auto_20150721_1910'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='contactinformation',\n name='contact',\n ),\n migrations.AddField(\n model_name='contactlist',\n name='email',\n field=models.EmailField(default=b'null', max_length=254),\n ),\n migrations.AddField(\n model_name='contactlist',\n name='notes',\n field=models.TextField(default=b''),\n ),\n migrations.AddField(\n model_name='contactlist',\n name='phone_number',\n field=models.CharField(default=b'', max_length=12),\n ),\n migrations.DeleteModel(\n name='ContactInformation',\n ),\n ]\n","sub_path":"cmanagersite/contactmanager/migrations/0004_auto_20150721_2009.py","file_name":"0004_auto_20150721_2009.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"9922041","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.layers import Input, LSTM, Dense, SimpleRNN, GRU\nfrom keras.models import Model\nfrom keras import optimizers\n\n\ndf = pd.read_csv('./ILURN.csv', usecols=[1])\ndat = df.values\n\n# Since LSTM can be sensitive to the scale, we normalize the data\n# with MinMaxScaler here.\nsc = MinMaxScaler(feature_range=(0, 1))\ndat = sc.fit_transform(dat)\n\n# Then, split the data into train and test data. Since this is\n# time series data, we should not mix our data when we split.\ntrain_size = int(0.7 * len(dat))\ntrain, test = dat[:train_size], dat[train_size:]\n\n# The following lag_function returns the data with +lag time.\n# Hence, lag here is negative, in a sense.\ndef lag_function(data, lag):\n data_lag = []\n for i in range(len(data) - lag):\n data_lag.append(data[i + lag])\n return np.array(data_lag)\n\n\n# The following create_date returns the all lagged data within the\n# given timestep. It returns two lists: lagged data and target.\ndef create_data(data, timestep):\n target = data[:-timestep]\n for i in range(1, timestep + 1):\n if i == 1:\n data_lag = lag_function(data, i)[:len(target)]\n else:\n data_lag = np.hstack((data_lag, lag_function(data, i)[:len(target)]))\n return data_lag, target\n\n# We will work with timestep = 3. Hence, three lagged explanatory variables\n# for each y.\ntimestep = 3\n\ntrain_X, train_Y = create_data(train, timestep)\ntest_X, test_Y = create_data(test, timestep)\n\n# Dimension of the input for a RNN model: [sample_size, timestep, number of feature]\ntrain_X = np.reshape(train_X, (train_X.shape[0], timestep, 1))\ntest_X = np.reshape(test_X, (test_X.shape[0], timestep, 1))\n\n\n# The following functions build the RNN models with keras and compile them.\n# We use same parameters: 32 units, tanh activation, glorot initializers, etc...\ndef RNN_build(timestep):\n inputs = Input(shape=(timestep, 1))\n h1 = SimpleRNN(units=32)(inputs)\n out = Dense(1)(h1)\n model = Model(inputs=inputs, outputs=out)\n model.compile(optimizer=optimizers.Adam(), loss='mean_squared_error')\n return model\n\n\ndef LSTM_build(timestep):\n inputs = Input(shape=(timestep, 1))\n h1 = LSTM(units=32)(inputs)\n out = Dense(1)(h1)\n model = Model(inputs=inputs, outputs=out)\n model.compile(optimizer=optimizers.Adam(), loss='mean_squared_error')\n return model\n\n\ndef GRU_build(timestep):\n inputs = Input(shape=(timestep, 1))\n h1 = GRU(units=32)(inputs)\n out = Dense(1)(h1)\n model = Model(inputs=inputs, outputs=out)\n model.compile(optimizer=optimizers.Adam(), loss='mean_squared_error')\n return model\n\n\n# epochs=50, batch_size=1, given the small size of sample.\nRNN_model, LSTM_model, GRU_model = RNN_build(timestep), LSTM_build(timestep), GRU_build(timestep)\n\n# We compare three models defined above. They all seem to do quite well.\n# I will stick to the GRU model.\nfor mod in [RNN_model, LSTM_model, GRU_model]:\n mod.fit(train_X, train_Y, epochs=50, batch_size=1, verbose=False)\n predict_train = mod.predict(train_X)\n predict_test = mod.predict(test_X)\n print(f'mean_squared_loss for train: {mean_squared_error(train_Y, predict_train)} '\n f'for test: {mean_squared_error(test_Y, predict_test)}'\n )\n\n# Inverse transform back to the original scale.\npredict_train, train_Y = sc.inverse_transform(predict_train), sc.inverse_transform(train_Y)\npredict_test, test_Y = sc.inverse_transform(predict_test), sc.inverse_transform(test_Y)\ndat = sc.inverse_transform(dat)\n\n# concatenate the data and missing bits due to the lagged component with nan.\npredict_data = np.concatenate((\n np.concatenate((predict_train, np.repeat(np.nan, 3)[:, np.newaxis])),\n np.concatenate((predict_test, np.repeat(np.nan, 3)[:, np.newaxis]))\n ))\n\n\n# GRU seems to fit both the train and test data well. The following lines produce\n# figure1.png. \nplt.plot(dat, label='data')\nplt.plot(predict_data, label='prediction')\nplt.vlines(x=train_X.shape[0] + 1.5, ymin=0, ymax=15, colors='red', ls='dashed')\nplt.legend()\nplt.text(s='Train', x=train_X.shape[0] - 50, y=13, size='large')\nplt.text(s='Test', x=train_X.shape[0] + 40, y=13, size='large')\nplt.show()\n","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"501383933","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nfrom app import create_app, db\nfrom app.models import tables, Config\nfrom app.utils import _\nfrom flask_script import Manager, Shell\n\napp = create_app(os.getenv('FLASK_CONFIG') or 'default')\nmanager = Manager(app)\n\n# Global variables to jinja2 environment\napp.jinja_env.globals['_'] = _\n#app.jinja_env.filters['split'] = split\n\n\ndef make_shell_context():\n '''定义向Shell导入的对象'''\n return dict(app=app, db=db)\nmanager.add_command(\"shell\", Shell(make_context=make_shell_context))\n\n\n@manager.command\ndef test():\n '''Run the unit tests'''\n import unittest\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)\n\n\n@manager.command\ndef init_db():\n '''Initial database'''\n db.connect()\n\n print('Creating tables ...')\n db.create_tables(tables)\n print('Tables have been created.')\n\n print('Writing default configurations ...')\n Config.create(name='site_name', value=app.config['DEFAULT_SITE_NAME'])\n Config.create(name='site_url', value=app.config['DEFAULT_SITE_URL'])\n Config.create(name='count_topic', value=app.config['DEFAULT_TOPICS_PER_PAGE'])\n Config.create(name='count_post', value=app.config['DEFAULT_POSTS_PER_PAGE'])\n Config.create(name='count_list_item', value=app.config['DEFAULT_LIST_ITEM_PER_PAGE'])\n# Config.create(name='count_subpost', value=app.config['DEFAULT_SUBPOSTS_PER_PAGE'])\n print('Default configurations have been written into database.')\n\n db.close()\n\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"121955728","text":"import numpy\nimport numba\nimport transitleastsquares.tls_constants as tls_constants\n\n\n@numba.jit(fastmath=True, parallel=False, nopython=True)\ndef fold(time, period, T0):\n \"\"\"Normal phase folding\"\"\"\n return (time - T0) / period - numpy.floor((time - T0) / period)\n\n\n@numba.jit(fastmath=True, parallel=False, nopython=True)\ndef foldfast(time, period):\n \"\"\"Fast phase folding with T0=0 hardcoded\"\"\"\n return time / period - numpy.floor(time / period)\n\n\n@numba.jit(fastmath=True, parallel=False, nopython=True)\ndef get_edge_effect_correction(flux, patched_data, dy, inverse_squared_patched_dy):\n regular = numpy.sum(((1 - flux) ** 2) * 1 / dy ** 2)\n patched = numpy.sum(((1 - patched_data) ** 2) * inverse_squared_patched_dy)\n return patched - regular\n\n\n@numba.jit(fastmath=True, parallel=False, nopython=True)\ndef get_lowest_residuals_in_this_duration(\n mean,\n transit_depth_min,\n patched_data_arr,\n duration,\n signal,\n inverse_squared_patched_dy_arr,\n overshoot,\n ootr,\n summed_edge_effect_correction,\n chosen_transit_row,\n datapoints,\n T0_fit_margin,\n):\n\n # if nothing is fit, we fit a straight line: signal=1. Then, at dy=1,\n # the squared sum of residuals equals the number of datapoints\n summed_residual_in_rows = datapoints\n best_row = 0\n best_depth = 0\n\n xth_point = 1\n if T0_fit_margin > 0 and duration > T0_fit_margin:\n T0_fit_margin = 1 / T0_fit_margin\n xth_point = int(duration / T0_fit_margin)\n if xth_point < 1:\n xth_point = 1\n\n for i in range(len(mean)):\n if (mean[i] > transit_depth_min) and (i % xth_point == 0):\n data = patched_data_arr[i : i + duration]\n dy = inverse_squared_patched_dy_arr[i : i + duration]\n target_depth = mean[i] * overshoot\n scale = tls_constants.SIGNAL_DEPTH / target_depth\n reverse_scale = 1 / scale # speed: one division now, many mults later\n\n # Scale model and calculate residuals\n intransit_residual = 0\n for j in range(len(signal)):\n sigi = (1 - signal[j]) * reverse_scale\n intransit_residual += ((data[j] - (1 - sigi)) ** 2) * dy[j]\n\n current_stat = intransit_residual + ootr[i] - summed_edge_effect_correction\n\n if current_stat < summed_residual_in_rows:\n summed_residual_in_rows = current_stat\n best_row = chosen_transit_row\n best_depth = 1 - target_depth\n\n return summed_residual_in_rows, best_row, best_depth\n\n# ootr_efficient out_of_transit_residuals\n@numba.jit(fastmath=True, parallel=False, nopython=True)\ndef out_of_transit_residuals(data, width_signal, dy):\n chi2 = numpy.zeros(len(data) - width_signal + 1)\n fullsum = numpy.sum(((1 - data) ** 2) * dy)\n window = numpy.sum(((1 - data[:width_signal]) ** 2) * dy[:width_signal])\n chi2[0] = fullsum - window\n for i in range(1, len(data) - width_signal + 1):\n becomes_visible = i - 1\n becomes_invisible = i - 1 + width_signal\n add_visible_left = (1 - data[becomes_visible]) ** 2 * dy[becomes_visible]\n remove_invisible_right = (1 - data[becomes_invisible]) ** 2 * dy[\n becomes_invisible\n ]\n chi2[i] = chi2[i - 1] + add_visible_left - remove_invisible_right\n return chi2\n","sub_path":"transitleastsquares/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"257530752","text":"from pylab import *\nimport tables\n\ndef getMeshGrid(grid):\n xl, yl = grid._v_attrs.vsLowerBounds\n xu, yu = grid._v_attrs.vsUpperBounds\n nx, ny = grid._v_attrs.vsNumCells\n dx = (xu-xl)/nx\n dy = (yu-yl)/ny\n X = linspace(xl+0.5*dx, xu-0.5*dx, nx)\n Y = linspace(yl+0.5*dy, yu-0.5*dy, ny)\n\n return meshgrid(X, Y)\n\ndef mkFig(fh, XX, YY, dat, nm):\n tm = fh.root.timeData._v_attrs.vsTime\n Valf = 0.1\n Lx = 4*pi*5.0\n tmAlf = tm/(Lx/Valf)\n \n f = figure(1)\n pcolormesh(XX, YY, dat.transpose())\n axis('image')\n colorbar()\n title(\"T = %.4g\" % tmAlf)\n \n savefig(nm)\n close()\n\nfor i in range(51):\n print (\"Working on %d ..\" % i)\n fh = tables.openFile(\"../s426/s426-is-coal_q_%d.h5\" % i)\n q = fh.root.StructGridField\n X, Y = getMeshGrid(fh.root.StructGrid)\n mkFig(fh, X, Y, q[:,:,3], 's426-Jze-%05d.png' % i)\n fh.close()\n","sub_path":"source/sims/s426/mkmov.py","file_name":"mkmov.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"571034348","text":"# -*- coding: utf-8 -*-\n\nclass ClassificadorECG():\n \n def __init__(self, sinalECG):\n self.sinalECG = sinalECG\n\n \n def classificador_ecg(self): \n import pickle\n\n lda = pickle.load(open('dadosECG//lda_ecg.sav', 'rb'))\n \n # Classificador\n nb_ecg = pickle.load(open('dadosECG//nb_ecg.sav', 'rb'))\n\n novo_registro = lda.transform(self.sinalECG)\n resultados = nb_ecg.predict(novo_registro)\n return resultados","sub_path":"Classificador/classificadorECG.py","file_name":"classificadorECG.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"228244433","text":"from urllib.request import urlopen\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport os\r\n\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\r\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\r\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\r\n 'Accept-Encoding': 'none',\r\n 'Accept-Language': 'en-US,en;q=0.8',\r\n 'Connection': 'keep-alive'}\r\n\r\nos.mkdir('res')\r\nwith open('res/7funsList.csv', 'w', encoding='utf-8') as f:\r\n f.write('Cuisine,Ingredients,Image,Url\\n')\r\n\r\npage = 1\r\nfor i in range(1, 3171):\r\n allPagesUrl = 'https://www.7funs.com/recipes/%s'%page\r\n resAll = requests.get(allPagesUrl, headers=headers)\r\n soupAll = BeautifulSoup(resAll.text, 'html.parser')\r\n try:\r\n cuisineName = soupAll.select('div[class=\"top_toole\"] span')[0].text\r\n ingredientList = soupAll.select('div[class=\"Rbox\"] ul p')\r\n ingredientName = ''\r\n for j in ingredientList:\r\n ingredientName += '{%s}'%j.text if (j.text != '食料:' and j.text != '調味料:') else ''\r\n imageUrl = soupAll.select('div[class=\"photo DBox_xx\"] img')[0]['src']\r\n imageUrl = imageUrl if imageUrl != '' else 'none'\r\n print(cuisineName)\r\n print(ingredientName)\r\n print(imageUrl)\r\n with open('res/7funsList.csv', 'a', encoding='utf-8') as f:\r\n f.write('%s,%s,%s,%s\\n'%(cuisineName.replace(',',';'), ingredientName.replace(',',';'), imageUrl, allPagesUrl))\r\n print('-')\r\n except:\r\n print('', end='')\r\n page += 1","sub_path":"funs7/funs7.py","file_name":"funs7.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"120518875","text":"# Assignment 4 attempt\n# Based on below\n# Interactive Visuazliations Part II\n# Update graphics in Hover\n\n# Group the data by borough, species, health, steward\n# Variables\n# boroname = {Manhattan, Staten Island, Brooklyn, Queens, Bronx}\n# spc_common ... long list\n# health = {Good, Fair, Poor, NaN}\n# steward = {None, 1or2, 3or4, 4orMore, NaN}\n\n# Question 1: What proportion of trees are in good, fair, or poor health according to the ‘health’ variable?\n\n# Run this app with `python app.py` and\n# visit http://127.0.0.1:8050/ in your web browser.\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.express as px\nfrom dash.dependencies import Output, Input\nimport pandas as pd\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n# Server variable needed for Heroku app\n# Comment this line out when running dash app locally\nserver = app.server\n\n# Query for list of Borough Names\nsoql_url_boros = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' + \\\n '$select=distinct(boroname)')\n\ndf_boros = pd.read_json(soql_url_boros)\ndf_boros = df_boros.sort_values('boroname_1', ascending=True)\n\n\n# Query for list of Tree Names\nsoql_url_trees = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' + \\\n '$select=distinct(spc_common)')\n\ndf_trees = pd.read_json(soql_url_trees)\n\ndf_trees['spc_common_1'].fillna(value='Species Missing', inplace=True)\ndf_trees = df_trees.sort_values('spc_common_1', ascending=True)\n\n# Query for initial dataset based on American beech and Bronx\nsoql_url = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' +\\\n '$select=boroname,spc_common, health, steward, count(tree_id)' +\\\n '&$where=spc_common=\\'American beech\\' and boroname=\\'Bronx\\'' +\\\n '&$group=boroname,spc_common, health, steward').replace(' ', '%20')\ndf = pd.read_json(soql_url)\n\n# Set indicators for the boroughs\nindicators_boros = df_boros['boroname_1']\n\n# Set indicators for the trees\nindicators_trees = df_trees['spc_common_1']\n\napp.layout = html.Div([\n html.H1(children='Assignment 4'),\n html.H3(children='Author: Philip Tanofsky'),\n html.H5(children='DATA 608, Fall 2020'),\n html.H5(children='October 18, 2020'),\n html.Div([\n\n html.Div([\n html.H6(children='Select a Borough'),\n dcc.Dropdown(\n id='boro-selection-dd',\n options=[{'label': i, 'value': i} for i in indicators_boros],\n value='Bronx',\n clearable=False\n )\n ],\n style={'width': '49%', 'display': 'inline-block'}),\n\n html.Div([\n html.H6(children='Select a Tree Species'),\n dcc.Dropdown(\n id='tree-selection-dd',\n options=[{'label': i, 'value': i} for i in indicators_trees],\n value='American beech',\n clearable=False\n )\n ], style={'width': '49%', 'float': 'right', 'display': 'inline-block'})\n ], style={\n 'borderBottom': 'thin lightgrey solid',\n 'backgroundColor': 'rgb(250, 250, 250)',\n 'padding': '10px 5px'\n }),\n\n html.Div([\n html.H3(children='Question 1'),\n html.Div(children='''\n What proportion of trees are in good, fair, or poor health according to the ‘health’ variable?\n '''),\n html.Div([\n dcc.Graph(\n id='tree-health-graph'\n )\n ], style={'width': '49%', 'display': 'inline-block', 'padding': '0 20'}),\n ]),\n\n html.Div([\n html.H3(children='Question 2'),\n html.Div(children='''\n Are stewards having an impact on the health of trees?\n '''),\n html.Div([\n dcc.Graph(\n id='tree-health-steward-graph'\n )\n ], style={'width': '90%', 'display': 'inline-block', 'padding': '0 20'}),\n ])\n])\n\n@app.callback(\n Output('tree-health-graph', 'figure'),\n Output('tree-health-steward-graph', 'figure'),\n [Input('boro-selection-dd', 'value'),\n Input('tree-selection-dd', 'value')])\ndef update_health_graph(boro_name, tree_name):\n\n soql_url = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' +\\\n '$select=boroname,spc_common, health, steward, count(tree_id)' +\\\n '&$where=spc_common=\\'' + tree_name + '\\'' +\\\n ' and boroname=\\'' + boro_name + '\\'' +\\\n '&$group=boroname,spc_common, health, steward').replace(' ', '%20')\n dff = pd.read_json(soql_url)\n\n # Rename count column to cleaner name\n dff.rename({'count_tree_id': 'Count'}, axis=1, inplace=True)\n dff.rename({'steward': 'Steward'}, axis=1, inplace=True)\n\n # Calculate total trees\n total_trees = dff['Count'].sum()\n\n fig1 = px.bar(dff, x=dff['health'], y=dff['Count'] / total_trees * 100)\n fig1.update_traces(hovertemplate =\n 'Steward: %{text}'+\n '
    Health: %{x}
    '+\n 'Count Pct: %{y}
    ',\n text=dff['Steward'])\n\n fig1.update_xaxes(title='Health')\n fig1.update_yaxes(title='Percentage')\n fig1.update_layout(margin={'l': 40, 'b': 40, 't': 10, 'r': 0},\n xaxis={'categoryorder':'array', 'categoryarray':['Good','Fair','Poor']})\n\n fig2 = px.bar(dff, x=\"health\", y=\"Count\", barmode=\"group\",\n facet_col=\"Steward\",\n category_orders={\"Steward\": [\"None\", \"1or2\", \"3or4\", \"4orMore\"]})\n fig2.update_xaxes(title='Health')\n fig2.update_yaxes(title='Count')\n fig2.update_layout(xaxis={'categoryorder':'array', 'categoryarray':['Good','Fair','Poor']})\n\n return fig1, fig2\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"mod4_h/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"245744889","text":"\nimport pygame\nimport cv2\nimport numpy\n#from pygame.locals import *\n\npygame.init()\nwidth = 1920\nheight = 1080\nscreen = pygame.display.set_mode ( (width, height), pygame.RESIZABLE)\n\nf = open(\"out.raw\", \"rb\")\n\ndone = False\nwhile not done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n if event.type == pygame.VIDEORESIZE:\n surface = pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE)\n width = event.w\n height = event.h\n\n raw_image = f.read(1920 * 1080 * 3)\n image = numpy.fromstring(raw_image, dtype='uint8')\n frame = image.reshape((1080,1920,3))\n\n #img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n img = frame\n #if (ret == False):\n # break\n #display_image = cv2.resize(img, (width, height))\n\n screen.blit(pygame.image.frombuffer(img.tostring(), img.shape[1::-1], \"RGB\"), (0,0))\n\n pygame.display.flip()","sub_path":"server-controller/tests/raw_video_test.py","file_name":"raw_video_test.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"454528546","text":"# find the maximum and minimum\n# values without using the \"max\"\n# and \"min\" functions\n\ndata = [3,4,77,1,34,7]\n\nmin_val = data[0]\nmax_val = data[0]\n\n# normally do this:\n# print(min(data))\n# print(max(data))\n\nfor x in data:\n if x < min_val:\n min_val = x\n if x > max_val:\n max_val = x\n\nprint(min_val)\nprint(max_val)\n\n# Output:\n# 1\n# 77\n","sub_path":"code/199.py","file_name":"199.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"165541351","text":"import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(nrows=2, ncols=5, sharex=True, sharey=True,)\nax = ax.flatten()\nfor i in range(10):\n img = X_train[y_train == i][0].reshape(28, 28)\n ax[i].imshow(img, cmap='Greys', interpolation='nearest')\n\nax[0].set_xticks([])\nax[0].set_yticks([])\nplt.tight_layout()\n# plt.savefig('./figures/mnist_all.png', dpi=300)\nplt.show()\n","sub_path":"first_digit.py","file_name":"first_digit.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"354850815","text":"from django import template\nfrom django.conf import settings\n\nregister = template.Library()\n\n####################################################################\n# Tag to get value code description\n# Usage : {% value_code_description 'VALUE-SET-CODE' value_code %}\n# value_code is a variable\nclass ValueDescriptionNode(template.Node):\n\n def __init__(self, value_set_code, value_code):\n self.value_set_code = value_set_code\n # Value code is expected to be a variable\n self.value_code = template.Variable(value_code)\n\n def render(self, context):\n from infra.objects.value_set import get_value_description\n value_code = self.value_code.resolve(context)\n return get_value_description(self.value_set_code, value_code)\n \n@register.tag\ndef value_code_description(parser, token):\n\n token_list = token.split_contents()\n # We expect 3 elements : tag_name, value_set_code, value_code\n if len(token_list) != 3:\n raise template.TemplateSyntaxError((\"value_code_description tag expects exactly 2 params\"))\n if not (token_list[1][0] == token_list[1][-1] and token_list[1][0] in ('\"', \"'\")):\n raise template.TemplateSyntaxError((\"value_set_code must be enclosed in quotes\"))\n else:\n return ValueDescriptionNode(token_list[1][1:-1], token_list[2])\n\n####################################################################\n# Tag to get a Selection's Entity Name\n# Usage : {% selection_entity_name selection_log_id %}\n# selection_log_id is a variable\nclass SelectionEntityNode(template.Node):\n\n def __init__(self, selection_log_id):\n # Selection Log Id is expected to be a variable\n self.selection_log_id = template.Variable(selection_log_id)\n\n def render(self, context):\n\n from infra.models import SelectionLog\n from infra.objects.selection_log import get_selection_entity\n\n selection_log_id = self.selection_log_id.resolve(context)\n try:\n sel_log = SelectionLog.objects.get(pk=selection_log_id)\n return get_selection_entity(sel_log)\n except SelectionLog.DoesNotExist:\n return ''\n \n@register.tag\ndef selection_entity_name(parser, token):\n\n token_list = token.split_contents()\n # We expect 2 elements : tag_name, selection_log_id\n if len(token_list) != 2:\n raise template.TemplateSyntaxError((\"selection_entity_name tag expects selection_log_id\"))\n else:\n return SelectionEntityNode(token_list[1])\n\n####################################################################\n# Tag to get the app/model for a Model instance\n# Usage: {% get_app_slash_model model_instance %}\nclass AppSlashModelNode(template.Node):\n\n def __init__(self, app_model):\n # Model is expected to be a variable\n self.app_model = template.Variable(app_model)\n\n def render(self, context):\n from bin.helpers import get_app_dot_model\n app_model = self.app_model.resolve(context)\n return get_app_dot_model(app_model).replace('.', '/')\n\n@register.tag\ndef get_app_slash_model(parser, token):\n\n token_list = token.split_contents()\n # We expect 2 elements : tag_name, model\n if len(token_list) != 2:\n raise template.TemplateSyntaxError((\"get_app_slash_model tag expects model\"))\n else:\n return AppSlashModelNode(token_list[1])\n\n####################################################################\n# Tag to print attributes of an object, very useful in debugging\n# objects in templates.\n# Usage: {% list_attributes object_name %}\nclass ListAttributeNode(template.Node):\n\n def __init__(self, object_name):\n # Object Name is expected to be a variable\n self.object_name = template.Variable(object_name)\n\n def render(self, context):\n object_name = self.object_name.resolve(context)\n return dir(object_name)\n \n@register.tag\ndef list_attributes(parser, token):\n\n token_list = token.split_contents()\n # We expect 2 elements : tag_name, object_name\n if len(token_list) != 2:\n raise template.TemplateSyntaxError((\"list_attributes tag expects object_name\"))\n else:\n return ListAttributeNode(token_list[1])\n\n####################################################################\n# Tag to get the set a variable with a literal value or context variable.\n# Usage: {% set_var var1 = 22 %} or {% set_var var2 = ctx_var %}\n# Then you can use it using {{var1}} or {% if var1 == 22 %}\n# Code borrowed from http://www.soyoucode.com/2011/set-variable-django-template\nclass SetVarNode(template.Node):\n\n def __init__(self, var_name, var_value):\n # Value is expected to be a scalar value\n self.var_name = var_name\n self.var_value = var_value\n\n def render(self, context):\n try:\n value = template.Variable(self.var_value).resolve(context)\n except template.VariableDoesNotExist:\n value = \"\"\n context[self.var_name] = value\n return u\"\"\n\n@register.tag\ndef set_var(parser, token):\n\n token_list = token.split_contents()\n # We expect 4 elements : tag_name, var_name, = sign and value\n if len(token_list) != 4:\n raise template.TemplateSyntaxError((\"set_var tag expects var = value\"))\n elif token_list[2] != '=':\n raise template.TemplateSyntaxError((\"Equal sign (=) expected after variable, not %(token)s\" % {'token': token_list[2]}))\n else:\n return SetVarNode(token_list[1], token_list[3])\n\n####################################################################\n# Used in tabs to detect whether a formset is inline or is a normal\n# collapsed fieldset. (from YC)\ndef is_inline(value):\n # Depends on how django admin names the inline!\n if value.find('_set') >= 0:\n return True\n else:\n return False \nregister.filter('is_inline', is_inline)\n\n####################################################################\n# Generate an valid id , based on the fieldset.name , used in fieldset.html\n# (from YC)\ndef to_id(value):\n if value:\n return 'fs_' + value.lower().replace(' ','_')\n else:\n return 'fs_default'\nregister.filter('to_id', to_id)\n####################################################################\n# specifically used for formsets. basically check if the same string \n# after removing -group suffix'. (From YC)\ndef is_same(value, arg):\n return value == arg.replace('-group','')\nregister.filter('is_same', is_same)\n####################################################################\n# Checks if it is a defined tab in tabs_list, both normal fieldsets \n# or inline_formsets. (from YC)\ndef is_tab(value, arg):\n arg = arg or 'None'\n value = value or []\n if arg.find('_set') >= 0:\n res = (arg + '-group') in value \n else:\n res = arg in value\n return res\nregister.filter('is_tab', is_tab)\n","sub_path":"infra/templatetags/infra_tags.py","file_name":"infra_tags.py","file_ext":"py","file_size_in_byte":6824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"560903982","text":"#!/usr/bin/env python\n\nimport unittest\nimport sys\nfrom mock import MagicMock\n\nfrom tire_pressure_monitoring import Alarm, Sensor\n\nLOW_PRESSURE_THRESHOLD = 17.0\nHIGH_PRESSURE_THRESHOLD = 21.0\n\n# See http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html\nEPSILON = HIGH_PRESSURE_THRESHOLD * sys.float_info.epsilon\n\nclass SensorTest(unittest.TestCase):\n\n def test_float_psi_value(self):\n sensor = Sensor()\n psi_value = sensor.pop_next_pressure_psi_value()\n self.assertTrue(isinstance(psi_value, float))\n\nclass AlarmTest(unittest.TestCase):\n\n def create_sensor(self, next_psi_values):\n sensor = MagicMock(spec=Sensor)\n sensor.pop_next_pressure_psi_value.side_effect = next_psi_values\n return sensor\n\n def create_alarm(self, next_psi_values):\n alarm = Alarm(\n self.create_sensor(next_psi_values),\n LOW_PRESSURE_THRESHOLD,\n HIGH_PRESSURE_THRESHOLD)\n return alarm\n\n def create_checked_alarm(self, next_psi_values):\n alarm = self.create_alarm(next_psi_values)\n alarm.check()\n return alarm\n\n def test_default_alarm_state(self):\n alarm = self.create_alarm([ LOW_PRESSURE_THRESHOLD ])\n self.assertFalse(alarm.is_alarm_on)\n\n def test_low_pressure_threshold(self):\n alarm = self.create_checked_alarm([ LOW_PRESSURE_THRESHOLD ])\n self.assertFalse(alarm.is_alarm_on)\n\n def test_high_pressure_threshold(self):\n alarm = self.create_checked_alarm([ HIGH_PRESSURE_THRESHOLD ])\n self.assertFalse(alarm.is_alarm_on)\n\n def test_less_than_low_pressure_threshold(self):\n alarm = self.create_checked_alarm(\n [ LOW_PRESSURE_THRESHOLD - EPSILON ])\n self.assertTrue(alarm.is_alarm_on)\n\n def test_greater_than_high_pressure_threshold(self):\n alarm = self.create_checked_alarm(\n [ HIGH_PRESSURE_THRESHOLD + EPSILON ])\n self.assertTrue(alarm.is_alarm_on)\n\n def test_alarm_stays_on_after_returning_to_normal(self):\n alarm = self.create_alarm([\n HIGH_PRESSURE_THRESHOLD + EPSILON,\n HIGH_PRESSURE_THRESHOLD\n ])\n alarm.check()\n self.assertTrue(alarm.is_alarm_on)\n alarm.check()\n self.assertTrue(alarm.is_alarm_on)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"TDDMicroExercises.YoursSolutions/imedwei/TirePressureMonitoringSystem/test_tire_pressure_monitoring.py","file_name":"test_tire_pressure_monitoring.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"208544617","text":"## Jewels and Stones\n\n# Example 1:\n# Input: jewels = \"aA\", stones = \"aAAbbbb\"\n# Output: 3\n\n# Example 2:\n# Input: jewels = \"z\", stones = \"ZZ\"\n# Output: 0\n\nfrom collections import Counter\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n temp=Counter()\n for x in stones:\n temp[x]+=1\n # print(temp)\n result=0\n for k,v in temp.items():\n if k in jewels:\n result+=v\n \n return result","sub_path":"Leetcode/HashTable/p1136.py","file_name":"p1136.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"491451507","text":"#!/usr/bin/env python\n\n\"\"\"staticjinja\n\nUsage:\n staticjinja build [options]\n staticjinja watch [options]\n staticjinja -h | --help\n staticjinja --version\n\nCommands:\n build Render the site\n watch Render the site, and re-render on changes to \n\nOptions:\n --srcpath= Directory in which to build from [default: ./templates]\n --outpath= Directory in which to build to [default: ./]\n --static= Directory(s) within containing static files\n -h --help Show this screen.\n --version Show version.\n\"\"\"\nimport os\nimport sys\n\nfrom docopt import docopt\n\nfrom .staticjinja import Site\nfrom staticjinja import __version__\n\n\ndef render(args):\n \"\"\"\n Render a site.\n\n :param args:\n A map from command-line options to their values. For example:\n\n {\n '--help': False,\n '--outpath': './',\n '--srcpath': './templates',\n '--static': None,\n '--version': False,\n 'build': True,\n 'watch': False\n }\n \"\"\"\n\n def resolve(path):\n if not os.path.isabs(path):\n path = os.path.join(os.getcwd(), path)\n return os.path.normpath(path)\n\n srcpath = resolve(args[\"--srcpath\"])\n if not os.path.isdir(srcpath):\n print(\"The templates directory '{}' is invalid.\".format(srcpath))\n sys.exit(1)\n\n outpath = resolve(args[\"--outpath\"])\n\n staticdirs = args[\"--static\"]\n staticpaths = None\n if staticdirs:\n staticpaths = staticdirs.split(\",\")\n for path in staticpaths:\n path = os.path.join(srcpath, path)\n if not os.path.isdir(path):\n print(\"The static files directory '{}' is invalid.\".format(path))\n sys.exit(1)\n\n site = Site.make_site(searchpath=srcpath, outpath=outpath, staticpaths=staticpaths)\n site.render(use_reloader=args[\"watch\"])\n\n\ndef main(argv=None):\n if argv is None:\n argv = sys.argv[1:]\n render(docopt(__doc__, argv=argv, version=__version__))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"staticjinja/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"300576381","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 30 19:01:24 2019\n\n@author: 10541\n\"\"\"\nimport time\nsample_text = \"thanga than working with vini sample truck girl green love\"\n\nsample_dict = {\"thanga \":\"thangarajan\",\"vini\":\"ammu\"}\nstart_time = time.time()\n#for k in range(10000):\n# temp_text = None\n# for i in sample_dict.keys():\n# print(i,sample_dict.get(i))\n# temp_text = sample_text.replace(i,sample_dict.get(i))\n# sample_text = temp_text\ndict_keys = list(sample_dict.keys())\nfor i in range(1000000):\n for word in sample_text.split(' '):\n if word in dict_keys:\n sample_text = sample_text.replace(word, sample_dict.get(word))\nend_time = time.time()\nprint(sample_text)\nprint(end_time-start_time)\n\nimport pandas as pd\ndf =pd.read_csv('no_header.csv',header=None)\nfor _,row in df.iterrows():\n print(row[0])\n \nprint(lower('SAM'))\nprint('SAM'.lower())\n","sub_path":"fast_match_replace_text.py","file_name":"fast_match_replace_text.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"649978262","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\na = 0.25\nb = 0.75\njumlah_titik = 300\n\n# buat dua list yang masih kosong\nx_point = []\ny_point = []\n\nfor i in range(jumlah_titik):\n x = np.random.normal(0.0,0.4)\n y = a*x + b + np.random.normal(0.0,0.1)\n x_point.append([x])\n y_point.append([y])\n\nplt.plot(x_point,y_point,'o',label='Random Data')\nplt.legend()\nplt.show()\n","sub_path":"contoh/tf-grad-decent.py","file_name":"tf-grad-decent.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"561328733","text":"import win32com.client\nfrom pywintypes import Time as pyTime\nfrom time import gmtime\n\n#scopeName = \"ASCOM.Celestron.Telescope\"\n\nx = win32com.client.Dispatch(\"ASCOM.Utilities.Chooser\")\nx.DeviceType = \"Telescope\"\nd = x.Choose(None)\nprint( d )\ntel = win32com.client.Dispatch(d)\n\ntel.Connected = True\n#tel.Tracking = True\nprint(tel.SiteLatitude)\nprint(tel.SiteLongitude)\nprint(tel.UTCDate)\n\ntel.UTCDate = pyTime(gmtime())\nprint(tel.UTCDate)\n\n#tel.SlewToCoordinates(12.34, 86.7)\n#tel.Connected = False","sub_path":"scope.py","file_name":"scope.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"281467006","text":"import shutil \nimport os\n\n\n\"\"\"\n从测试集中4660个文件夹(细类别)下分出44个大类别\n\"\"\"\ntxt_dir = open(\"/home/lichen/deepfashion/data/CategoryAndAttribute/Anno/list_category_img.txt\").read().splitlines()\ntest_dir = \"/home/lichen/deepfashion/dataset/categary/train/\"\nimg_path_list = []\n\ndef txt_classification():\n \n for img_data in os.listdir(test_dir):\n img_data_path = test_dir + img_data\n for single_img in os.listdir(img_data_path):\n single_img_path = img_data +\"/\"+ single_img\n global img_path\n img_path_list.append(single_img_path)\n \n print(\"开始拷贝!!\")\n for img_list in txt_dir:\n #把字符串变成列表\n img = [i.replace(' ','') for i in img_list.split(\" \") if i != '']\n #从路径中获取文件名\n img_path,img_name = os.path.split(img[0])\n img_path = img_path.split('/')[1]\n path_name = img_path +'/'+ img_name\n if path_name in img_path_list:\n #原始测试集4660个文件夹\n srcfile = test_dir +\"/\"+ path_name\n #分类测试集44个文件夹\n dstfile = \"/home/lichen/deepfashion/dataset/categary/svm/train/\" + img[1]\n\n if not os.path.isdir(dstfile):\n os.makedirs(dstfile)\n shutil.copyfile(srcfile,dstfile+\"/\"+img_path+\"_\"+img_name)\n else:\n shutil.copyfile(srcfile,dstfile+\"/\"+img_path+\"_\"+img_name)\n\ntxt_classification()\n\n\n","sub_path":"tools/categary/data_move.py","file_name":"data_move.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"290321544","text":"from flask import Flask, \\\n render_template, \\\n request, redirect, \\\n url_for, flash, \\\n jsonify\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Restaurant, MenuItem\n\napp = Flask(__name__)\n\nengine = create_engine('sqlite:///restaurantmenu.db')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\n\n\n@app.route('/')\ndef defaultRestaurantMenu():\n session = DBSession()\n restaurant = session.query(Restaurant).first()\n items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)\n return render_template('menu.html', restaurant_id=restaurant.id, name=restaurant.name, items=items)\n\n\n@app.route('/restaurants//')\ndef restaurantMenu(restaurant_id):\n # Base.metadata.bind = engine\n #\n # DBSession = sessionmaker(bind=engine)\n session = DBSession()\n\n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).first()\n items = session.query(MenuItem).filter_by(restaurant_id=restaurant_id)\n return render_template('menu.html', restaurant_id=restaurant_id, name=restaurant.name, items=items)\n\n@app.route('/restaurants//new', methods=['GET', 'POST'])\ndef newMenuItem(restaurant_id):\n # Base.metadata.bind = engine\n #\n # DBSession = sessionmaker(bind=engine)\n # session = DBSession()\n session = DBSession()\n\n if request.method == 'POST':\n newItem = MenuItem(name=request.form['name'], description=request.form[\n 'description'], price=request.form['price'], course=request.form['course'], restaurant_id=restaurant_id)\n session.add(newItem)\n session.commit()\n return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))\n else:\n return render_template('newmenuitem.html', restaurant_id=restaurant_id)\n\n\n@app.route('/restaurants///edit',\n methods=['GET', 'POST'])\ndef editMenuItem(restaurant_id, menu_id):\n # Base.metadata.bind = engine\n #\n # DBSession = sessionmaker(bind=engine)\n session = DBSession()\n\n # print(menu_id)\n edited = session.query(MenuItem).filter_by(id=menu_id).one()\n # print(edited.name)\n if request.method == 'POST':\n if request.form['name']:\n edited.name = request.form['name']\n session.add(edited)\n session.commit()\n flash(\"Edited menu item\")\n return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))\n else:\n # USE THE RENDER_TEMPLATE FUNCTION BELOW TO SEE THE VARIABLES YOU\n # SHOULD USE IN YOUR EDITMENUITEM TEMPLATE\n return render_template(\n 'editmenuitem.html', restaurant_id=restaurant_id, menu_id=menu_id, item=edited)\n\n\n@app.route('/restaurant///delete/',\n methods=['GET', 'POST'])\ndef deleteMenuItem(restaurant_id, menu_id):\n # Base.metadata.bind = engine\n #\n # DBSession = sessionmaker(bind=engine)\n session = DBSession()\n\n edited = session.query(MenuItem).filter_by(id=menu_id).one()\n if request.method == \"POST\":\n if edited:\n session.delete(edited)\n session.commit()\n flash(\"Deleted menu item\")\n return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))\n\n else:\n return render_template(\"deletemenuitem.html\", restaurant_id=restaurant_id, menu_id=menu_id, item=edited)\n\n\n\n\n@app.route('/restaurants//menu/JSON')\ndef restaurantMenuJSON(restaurant_id):\n session = DBSession()\n\n # restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n items = session.query(MenuItem).filter_by(restaurant_id = restaurant_id).all()\n return jsonify(MenuItems=[i.serialize for i in items])\n\n@app.route('/restaurants//menu//JSON')\ndef menuItemJSON(restaurant_id, menu_id):\n session = DBSession()\n # items = session.query(Restaurant).filter_by(restaurant_id=restaurant_id).all()\n # return jsonify(MenuItem=items[menu_id].serialize())\n items = session.query(MenuItem).filter_by(id = menu_id).one()\n return jsonify(MenuItem=items.serialize)\n\n\nif __name__ == '__main__':\n app.secret_key = 'super_secret_key'\n app.debug = True\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"flask_server.py","file_name":"flask_server.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"526929681","text":"#!/usr/bin/env python\n\n# Copyright (c) 2016, Diligent Droids\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# \n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# \n# * Neither the name of hlpr_kinesthetic_teaching nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# Author: Andrea Thomaz, athomaz@diligentdroids.com\n\nimport rospy\nimport tf \nimport time\nfrom geometry_msgs.msg import Pose, Point, Quaternion\nfrom sensor_msgs.msg import JointState\n\n\ndef eef_pose_pub():\n rospy.init_node('eef_publisher')\n rospy.loginfo(\"Publishing right EEF gripper location\")\n listener = tf.TransformListener()\n pub = rospy.Publisher('eef_pose', Pose, queue_size=10)\n\n DEFAULT_LINK = '/right_ee_link'\n DEFAULT_RATE = 100\n\n # Pull from param server the hz and EEF link\n eef_link = rospy.get_param(\"~eef_link\", DEFAULT_LINK)\n publish_rate = rospy.get_param(\"~eef_rate\", DEFAULT_RATE)\n\n rate = rospy.Rate(publish_rate)\n while not rospy.is_shutdown():\n try: \n trans, rot = listener.lookupTransform('/base_link', eef_link, rospy.Time(0))\n except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n continue\n msg = Pose()\n msg.position = Point()\n msg.position.x, msg.position.y, msg.position.z = trans[0], trans[1], trans[2]\n msg.orientation = Quaternion() \n msg.orientation.x, msg.orientation.y, msg.orientation.z, msg.orientation.w = rot[0], rot[1], rot[2], rot[3]\n pub.publish(msg)\n rate.sleep()\n\nif __name__ =='__main__':\n try:\n eef_pose_pub()\n except rospy.ROSInterruptException:\n pass\n\n\n\n","sub_path":"hlpr_record_demonstration/src/hlpr_record_demonstration/eef_publisher.py","file_name":"eef_publisher.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"241609124","text":"# from helium import *\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nurl= 'https://www.ema.europa.eu/en/medicines/ema_group_types/ema_medicine'\r\npage = requests.get(url)\r\n\r\n# browser = start_chrome(url)\r\n\r\n# if Text('I accept cookies').exists():\r\n# click(\"I accept cookies\")\r\n\r\n# while Text('LOAD MORE').exists():\r\n# click('LOAD MORE')\r\n# time.sleep(4)\r\n# if not Text('LOAD MORE').exists(): break\r\n\r\n\r\nepar_name_list = BeautifulSoup.find(class_ ='ema-listings view-content-solr ecl-u-pt-m')\r\nepar_name_list_items = epar_name_list.find_all('a')\r\n\r\n# Create a BeautifulSoup object\r\nsoup = BeautifulSoup(page.text, 'html.parser')\r\n\r\ndef get_data(url):\r\n r = requests.get(url)\r\n data = dict(r.json())\r\n return data\r\n\r\ndef parse(data): \r\n # Pull all titles and descriptions\r\n for epar_name in epar_name_list_items:\r\n title = epar_name.find(class_='ecl-list-item__title ecl-heading').text.strip()\r\n link = \"https://www.ema.europa.eu\" + epar_name.get('href')\r\n description = epar_name.find(class_='ema-u-color-grey-2 ecl-u-mb-s').text.strip()\r\n myepar = {\r\n 'title': title,\r\n 'link': link,\r\n 'description': description\r\n }\r\n return myepar\r\n\r\ndef output(results):\r\n myepar.to_csv('epars.csv', index=False) \r\n return\r\n\r\nresults = []\r\ndata = get_data(url)\r\nresults(parse(data))\r\noutput(results)\r\n\r\n","sub_path":"epars.py","file_name":"epars.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"169022220","text":"#!/usr/bin/python3\n\n##Author: Jeff Radabaugh\n##Version: 1.0\n##Date: 02-24-2017\n\n#Import Section\nimport time\nimport os\nimport sys\nfrom shutil import copyfile\nfrom pathlib import Path\nfrom configparser import ConfigParser\nimport smtplib\nimport email\nfrom email import encoders\nfrom email.message import Message\nfrom email.mime.audio import MIMEAudio\nfrom email.mime.base import MIMEBase\nfrom email.mime.image import MIMEImage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nimport Adafruit_DHT\nimport RPi.GPIO as GPIO\nimport subprocess\nimport re\n\n#Variable Declaration\n#THconfig = ConfigParser()\n#THconfig.read(\"/opt/TEMP-HUMIDITY/CONFIG/TempHumidity.config\")\n\n\n\ndef GetTempHumidity(Type,Pin,):\n\tsensor = Type\n\tpin = Pin\n\t\n\tif sensor == \"2302\":\n\t\tsensor = Adafruit_DHT.AM2302\n\n\t# Try to grab a sensor reading. Use the read_retry method which will retry up\n\t# to 15 times to get a sensor reading (waiting 2 seconds between each retry).\n\thumidity, temperature = Adafruit_DHT.read_retry(sensor, pin)\n\t# Un-comment the line below to convert the temperature to Fahrenheit.\n\ttemperature = temperature * 9/5.0 + 32\n\t# Note that sometimes you won't get a reading and\n\t# the results will be null (because Linux can't\n\t# guarantee the timing of calls to read the sensor).\n\t# If this happens try again!\n\tif humidity is not None and temperature is not None:\n\t\treturn(temperature,humidity)\n\telse:\n\t\tprint('Failed to get reading. Try again!')\n\t\tsys.exit(1)\n\ndef SendMail(ToAddress,Subject,Body,USERNAME,PASSWORD):\n\tMAILTO = ToAddress\n\tMAILFROM = \"High Tunnel\"\n\tmsg = MIMEText(Body)\n\tmsg['Subject'] = Subject\n\tmsg['From'] = MAILFROM\n\tmsg['To'] = \", \".join(MAILTO)\n\n\tserver = smtplib.SMTP('smtp.gmail.com:587')\n\tserver.ehlo_or_helo_if_needed()\n\tserver.starttls()\n\tserver.ehlo_or_helo_if_needed()\n\tserver.login(USERNAME,PASSWORD)\n\tserver.sendmail(USERNAME, MAILTO, msg.as_string())\n\tserver.quit()\n\ndef SendMailAttachment(ToAddress,FromAddress,Subject,text,USERNAME,PASSWORD,files=[]):\n\tMAILTO = ToAddress\n\tMAILFROM = FromAddress\n\tassert type(files)==list\n\tmsg = MIMEMultipart()\n\tmsg['From'] = USERNAME\n\tmsg['To'] = \", \".join(MAILTO)\n\tmsg['Date'] = formatdate(localtime=True)\n\tmsg['Subject'] = Subject\n\tmsg.attach( MIMEText(text) )\n\n\tfor f in files or []:\n\t\twith open(f, \"rb\") as fil:\n\t\t\tpart = MIMEApplication(fil.read(),Name=basename(f))\n\t\t\tpart['Content-Disposition'] = 'attachment; filename=\"%s\"' % basename(f)\n\t\t\tmsg.attach(part)\n\n\tserver = smtplib.SMTP('smtp.gmail.com:587')\n\tserver.ehlo_or_helo_if_needed()\n\tserver.starttls()\n\tserver.ehlo_or_helo_if_needed()\n\tserver.login(USERNAME,PASSWORD)\n\tserver.sendmail(USERNAME, MAILTO, msg.as_string())\n\tserver.quit()\n\ndef FindThisProcess(process_name):\n\tps = subprocess.Popen(\"ps -eaf|grep -v grep |grep \"+process_name, shell=True, stdout=subprocess.PIPE)\n\toutput = ps.stdout.read()\n\tps.stdout.close()\n\tps.wait()\n\treturn output\n\ndef IsRunning(process_name):\n\tToutput = FindThisProcess( process_name )\n\toutput = \"%s\" % (Toutput)\n\tif re.search(process_name, output) is None:\n\t\treturn False\n\telse:\n\t\treturn True\n\n\n\n\n\n\n\t\n\n\n\n","sub_path":"opt/PYTHON_LIBRARIES/Farm.py","file_name":"Farm.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"260435496","text":"# Copyright 2014 OpenCore LLC\n#\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 implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport json\nimport logging\nfrom flask import Flask, request\nfrom ferry.install import Installer\nfrom ferry.docker.manager import DockerManager\nfrom ferry.docker.docker import DockerInstance\n\n# Initialize Flask\napp = Flask(__name__)\n\n# Initialize the storage driver\ninstaller = Installer()\ndocker = DockerManager()\n\n\"\"\"\nFetch the current information for a particular filesystem. \n\"\"\"\n@app.route('/storage', methods=['GET'])\ndef query_storage():\n status = AllocationResponse()\n status.uuid = request.args['uuid']\n status.status = status.NOT_EXISTS\n\n # Get the time the storage cluster was created, \n # along with basic usage information. \n info = storage.query_storage(status.uuid)\n if info != None:\n status.status = info\n\n # Return the JSON reply.\n return status.json()\n\n\n\"\"\"\nFetch the current docker version\n\"\"\"\n@app.route('/version', methods=['GET'])\ndef get_version():\n return docker.version()\n\n\"\"\"\nAllocate the backend from a snapshot. \n\"\"\"\ndef _allocate_backend_from_snapshot(payload):\n snapshot_uuid = payload['_file']\n backends = docker.fetch_snapshot_backend(snapshot_uuid)\n\n if backends:\n return _allocate_backend(payload = None,\n backends = backends)\n\n\"\"\"\nAllocate the backend from a deployment. \n\"\"\"\ndef _allocate_backend_from_deploy(payload, params=None):\n app_uuid = payload['_file']\n backends = docker.fetch_deployed_backend(app_uuid, params)\n \n if backends:\n return _allocate_backend(payload = None,\n backends = backends)\n\n\"\"\"\nAllocate the backend from a stopped service. \n\"\"\"\ndef _allocate_backend_from_stopped(payload):\n app_uuid = payload['_file']\n backends = docker.fetch_stopped_backend(app_uuid)\n \n if backends:\n return _allocate_backend(payload = None,\n backends = backends,\n uuid = app_uuid)\n\ndef _fetch_num_instances(instance_arg, instance_type, options=None):\n reply = {}\n try:\n num_instances = int(instance_arg)\n reply['num'] = num_instances\n except ValueError:\n # This was not an integer, check if it was a string.\n # First remove any extra white spaces.\n instance_arg = instance_arg.replace(\" \",\"\")\n if instance_arg[0] == '>':\n if instance_arg[1] == '=':\n min_instances = int(instance_arg[2])\n else:\n min_instances = int(instance_arg[1]) + 1\n\n if options and instance_type in options:\n num_instances = int(options[instance_type])\n if num_instances < min_instances:\n reply['num'] = min_instances\n else:\n reply['num'] = num_instances\n else:\n reply['query'] = { 'id' : instance_type,\n 'text' : 'Number of instances for %s' % instance_type }\n return reply\n\ndef _allocate_compute(computes, storage_uuid, options=None):\n \"\"\"\n Allocate a new compute backend. This method assumes that every\n compute backend already has a specific instance count associated\n with it. After creating the compute backend, it sends back a list\n of all UUIDs that were created in the process. \n \"\"\"\n uuids = []\n compute_plan = []\n for c in computes:\n compute_type = c['personality']\n reply = _fetch_num_instances(c['instances'], compute_type, options)\n num_instances = reply['num']\n c['instances'] = num_instances\n args = {}\n if 'args' in c:\n args = c['args']\n\n layers = []\n if 'layers' in c:\n layers = c['layers']\n\n compute_uuid, compute_containers = docker.allocate_compute(compute_type = compute_type,\n storage_uuid = storage_uuid, \n args = args, \n num_instances = num_instances,\n layers = layers)\n compute_plan.append( { 'uuid' : compute_uuid,\n 'containers' : compute_containers,\n 'type' : compute_type, \n 'start' : 'start' } )\n uuids.append( compute_uuid )\n return uuids, compute_plan\n\ndef _query_backend_params(backends, options=None):\n \"\"\"\n Helps allocate a storage/compute backend. It must first determine though if\n there are any missing value parameters. If there are, it sends back a\n list of questions to the client to get those values. The client then\n has to resubmit the request. \n \"\"\"\n all_queries = []\n for b in backends:\n backend_type = b['personality']\n query = _fetch_num_instances(b['instances'], backend_type, options)\n if 'query' in query:\n all_queries.append(query)\n return all_queries\n\ndef _restart_compute(computes):\n uuids = []\n compute_plan = []\n for c in computes:\n service_uuid = c['uuid']\n compute_type = c['type']\n\n # Transform the containers into proper container objects.\n compute_containers = c['containers']\n containers = [DockerInstance(j) for j in compute_containers] \n\n uuids.append(service_uuid)\n compute_plan.append( { 'uuid' : service_uuid,\n 'containers' : containers,\n 'type' : compute_type, \n 'start' : 'restart' } )\n docker.restart_containers(service_uuid, containers)\n return uuids, compute_plan\n\n\"\"\"\nAllocate a brand new backend\n\"\"\"\ndef _allocate_backend(payload,\n backends=None,\n replace=False,\n uuid=None):\n iparams = None\n if not backends:\n # The 'iparams' specifies the number of instances to use\n # for the various stack components. It is optional since\n # the application stack may already specify these values. \n if 'iparams' in payload:\n iparams = payload['iparams']\n \n # We should find the backend information in the payload. \n if 'backend' in payload:\n backends = payload['backend']\n else:\n backends = []\n\n # This is the reply we send back. The 'status' denotes whether\n # everything was created/started fine. The UUIDs are a list of \n # tuples (storage, compute) IDs. The 'backends' just keeps track of\n # the backends we used for allocation purposes. \n backend_info = { 'status' : 'ok', \n 'uuids' : [],\n 'backend' : backends }\n storage_plan = []\n compute_plan = []\n compute_uuids = []\n\n # First we need to check if either the storage or the compute \n # have unspecified number of instances. If so, we'll need to abort\n # the creating the backend, and send a query. \n if not uuid:\n all_questions = []\n for b in backends:\n storage = b['storage']\n storage_params = _query_backend_params([storage], iparams)\n compute_params = []\n if 'compute' in b:\n compute_params = _query_backend_params(b['compute'], iparams)\n all_questions = storage_params + compute_params + all_questions\n\n # Looks like there are unfilled parameters. Send back a list of\n # questions for the user to fill out. \n if len(all_questions) > 0:\n backend_info['status'] = 'query'\n backend_info['query'] = all_questions\n return backend_info, None\n \n # Go ahead and create the actual backend stack. If the user has passed in\n # an existing backend UUID, that means we should restart that backend. Otherwise\n # we create a fresh backend. \n for b in backends:\n storage = b['storage']\n if not uuid:\n args = None\n if 'args' in storage:\n args = storage['args']\n storage_type = storage['personality']\n reply = _fetch_num_instances(storage['instances'], storage_type, iparams)\n num_instances = reply['num']\n storage['instances'] = num_instances\n layers = []\n if 'layers' in storage:\n layers = storage['layers']\n\n storage_uuid, storage_containers = docker.allocate_storage(storage_type = storage_type, \n num_instances = num_instances,\n layers = layers,\n args = args,\n replace = replace)\n storage_plan.append( { 'uuid' : storage_uuid,\n 'containers' : storage_containers,\n 'type' : storage_type, \n 'start' : 'start' } )\n else:\n storage_uuid = storage['uuid']\n storage_type = storage['type']\n storage_containers = storage['containers']\n\n # Transform the containers into proper container objects.\n containers = [DockerInstance(j) for j in storage_containers]\n storage_plan.append( { 'uuid' : storage_uuid,\n 'containers' : containers,\n 'type' : storage_type, \n 'start' : 'restart' } )\n docker.restart_containers(storage_uuid, containers)\n \n # Now allocate the compute backend. The compute is optional so\n # we should check if it even exists first. \n compute_uuid = []\n if 'compute' in b:\n if not uuid:\n compute_uuid, plan = _allocate_compute(b['compute'], storage_uuid, iparams)\n compute_uuids += compute_uuid\n compute_plan += plan\n else:\n compute_uuid, plan = _restart_compute(b['compute'])\n compute_uuids += compute_uuid\n compute_plan += plan\n\n backend_info['uuids'].append( {'storage':storage_uuid,\n 'compute':compute_uuid} )\n return backend_info, { 'storage' : storage_plan,\n 'compute' : compute_plan }\n\ndef _allocate_connectors(payload, backend_info):\n connector_info = []\n connector_plan = []\n if 'connectors' in payload:\n connectors = payload['connectors']\n for c in connectors:\n # Check number of instances.\n num_instances = 1\n if 'instances' in c:\n num_instances = int(c['instances'])\n\n # Check if this connector type has already been pulled\n # into the local index. If not, manually pull it. \n connector_type = c['personality']\n logging.warning(\"allocating %d instances of %s\" % (num_instances, connector_type))\n if not installer._check_and_pull_image(connector_type):\n # We could not fetch this connetor. Instead of \n # finishing, just return an error.\n return False, connector_info, None\n\n for i in range(num_instances):\n # Connector names are created by the user \n # to help identify particular instances. \n if 'name' in c:\n connector_name = c['name']\n if num_instances > 1:\n connector_name = connector_name + \"-\" + str(i)\n else:\n connector_name = None\n\n # Arguments are optional parameters defined by\n # the user and passed to the connectors.\n if 'args' in c:\n args = c['args']\n else:\n args = {}\n\n # The user can choose to expose ports on the connectors. \n if 'ports' in c:\n ports = c['ports']\n else:\n ports = []\n\n # Now allocate the connector. \n uuid, containers = docker.allocate_connector(connector_type = connector_type,\n backend = backend_info, \n name = connector_name, \n args = args,\n ports = ports)\n connector_plan.append( { 'uuid' : uuid,\n 'containers' : containers,\n 'type' : connector_type, \n 'start' : 'start' } )\n connector_info.append(uuid)\n return True, connector_info, connector_plan\n\n\"\"\"\nAllocate the connectors from a snapshot. \n\"\"\"\ndef _allocate_connectors_from_snapshot(payload, backend_info):\n snapshot_uuid = payload['_file']\n return docker.allocate_snapshot_connectors(snapshot_uuid,\n backend_info)\n\n\"\"\"\nAllocate the connectors from a deployment. \n\"\"\"\ndef _allocate_connectors_from_deploy(payload, backend_info, params=None):\n app_uuid = payload['_file']\n return docker.allocate_deployed_connectors(app_uuid,\n backend_info,\n params)\n\n\"\"\"\nAllocate the connectors from a stopped application. \n\"\"\"\ndef _allocate_connectors_from_stopped(payload, backend_info, params=None):\n app_uuid = payload['_file']\n return docker.allocate_stopped_connectors(app_uuid,\n backend_info,\n params)\n\ndef _register_ip_addresses(backend_plan, connector_plan):\n \"\"\"\n Helper function to register the hostname/IP addresses\n of all the containers. \n \"\"\"\n ips = []\n for s in backend_plan['storage']:\n for c in s['containers']:\n if isinstance(c, dict):\n ips.append( [c['internal_ip'], c['hostname']] )\n else:\n ips.append( [c.internal_ip, c.host_name] )\n for s in backend_plan['compute']:\n for c in s['containers']:\n if isinstance(c, dict):\n ips.append( [c['internal_ip'], c['hostname']] )\n else:\n ips.append( [c.internal_ip, c.host_name] )\n for s in connector_plan:\n for c in s['containers']:\n # This is slightly awkward. It is because when starting\n # a new stack, we get proper \"container\" objects. However,\n # when restarting we get dictionary descriptions. Should just\n # fix at the restart level! \n if isinstance(c, dict):\n ips.append( [c['internal_ip'], c['hostname']] )\n else:\n ips.append( [c.internal_ip, c.host_name] )\n docker._transfer_ip(ips)\n\ndef _start_all_services(backend_plan, connector_plan):\n \"\"\"\n Helper function to start both the backend and\n frontend. Depending on the plan, this will either\n do a fresh start or a restart on an existing cluster. \n \"\"\"\n\n # Make sure that all the hosts have the current set\n # of IP addresses. \n _register_ip_addresses(backend_plan, connector_plan)\n\n # Now we need to start/restart all the services. \n for s in backend_plan['storage']:\n if s['start'] == 'start':\n docker.start_service(s['uuid'], \n s['containers'])\n else:\n docker._restart_service(s['uuid'], s['containers'], s['type'])\n\n for c in backend_plan['compute']:\n if c['start'] == 'start':\n docker.start_service(c['uuid'], c['containers'])\n else:\n docker._restart_service(c['uuid'], c['containers'], c['type'])\n\n # The connectors can optionally output msgs for the user.\n # Collect them so that we can display them later. \n all_output = {}\n for c in connector_plan:\n if c['start'] == 'start':\n output = docker.start_service(c['uuid'], c['containers'])\n all_output = dict(all_output.items() + output.items())\n else:\n output = docker._restart_connectors(c['uuid'], c['containers'], c['backend'])\n all_output = dict(all_output.items() + output.items())\n return all_output\n\ndef _allocate_new(payload):\n \"\"\"\n Helper function to allocate and start a new stack. \n \"\"\"\n reply = {}\n backend_info, backend_plan = _allocate_backend(payload, replace=True)\n reply['status'] = backend_info['status']\n if backend_info['status'] == 'ok':\n success, connector_info, connector_plan = _allocate_connectors(payload, backend_info['uuids'])\n\n if success:\n output = _start_all_services(backend_plan, connector_plan)\n uuid = docker.register_stack(backend_info, connector_info, payload['_file'])\n reply['text'] = str(uuid)\n reply['msgs'] = output\n else:\n # One or more connectors was not instantiated properly. \n docker.cancel_stack(backend_info, connector_info)\n reply['status'] = 'failed'\n else:\n reply['questions'] = backend_info['query']\n\n return json.dumps(reply)\n\ndef _allocate_stopped(payload):\n \"\"\"\n Helper function to allocate and start a stopped stack. \n \"\"\"\n base = docker.get_base_image(payload['_file'])\n backend_info, backend_plan = _allocate_backend_from_stopped(payload)\n if backend_info['status'] == 'ok':\n connector_info, connector_plan = _allocate_connectors_from_stopped(payload, backend_info['uuids'])\n output = _start_all_services(backend_plan, connector_plan) \n uuid = docker.register_stack(backends = backend_info,\n connectors = connector_info,\n base = base,\n uuid = payload['_file'])\n return json.dumps({'status' : 'ok',\n 'text' : str(uuid),\n 'msgs' : output})\n else:\n return json.dumps({'status' : 'failed'})\n\ndef _allocate_snapshot(payload):\n \"\"\"\n Helper function to allocate and start a snapshot.\n \"\"\"\n backend_info, backend_plan = _allocate_backend_from_snapshot(payload)\n if backend_info['status'] == 'ok':\n connector_info, connector_plan = _allocate_connectors_from_snapshot(payload, \n backend_info['uuids'])\n output = _start_all_services(backend_plan, connector_plan)\n uuid = docker.register_stack(backend_info, connector_info, payload['_file'])\n return json.dumps({'status' : 'ok',\n 'text' : str(uuid),\n 'msgs' : output })\n else:\n return json.dumps({'status' : 'failed'})\n\ndef _allocate_deployed(payload, params=None):\n \"\"\"\n Helper function to allocate and start a deployed application. \n \"\"\"\n backend_info, backend_plan = _allocate_backend_from_deploy(payload, params)\n if backend_info['status'] == 'ok':\n connector_info, connector_plan = _allocate_connectors_from_deploy(payload, \n backend_info['uuids'],\n params)\n output = _start_all_services(backend_plan, connector_plan)\n uuid = docker.register_stack(backend_info, connector_info, payload['_file'])\n return json.dumps({'status' : 'ok',\n 'text' : str(uuid),\n 'msgs' : output })\n\n\n@app.route('/login', methods=['POST'])\ndef login_registry():\n \"\"\"\n Login to a remote registry. \n \"\"\"\n if docker.login_registry():\n return \"success\"\n else:\n return \"fail\"\n\n@app.route('/image', methods=['POST'])\ndef push_image():\n \"\"\"\n Push a local image to a remote registry. \n \"\"\"\n image = request.form['image']\n if 'server' in request.form:\n registry = request.form['server']\n else:\n registry = None\n if docker.push_image(image, registry):\n return \"success\"\n else:\n return \"fail\"\n\n@app.route('/image', methods=['GET'])\ndef pull_image():\n \"\"\"\n Pull a remote image to the local registry. \n \"\"\"\n image = request.args['image']\n if docker.pull_image(image):\n return \"success\"\n else:\n return \"fail\"\n \n@app.route('/create', methods=['POST'])\ndef allocate_stack():\n \"\"\"\n Create some new storage infrastructure\n \"\"\"\n payload = json.loads(request.form['payload'])\n mode = request.form['mode']\n conf = request.form['conf']\n params = docker._get_deploy_params(mode, conf)\n\n # Check whether the user wants to start from fresh or\n # start with a snapshot.\n if docker.is_stopped(payload['_file']):\n return _allocate_stopped(payload)\n elif docker.is_snapshot(payload['_file']):\n return _allocate_snapshot(payload)\n elif docker.is_deployed(payload['_file'], params):\n return _allocate_deployed(payload, params)\n elif '_file_path' in payload:\n return _allocate_new(payload)\n else:\n return \"Could not start \" + payload['_file']\n\n@app.route('/deployed', methods=['GET'])\ndef query_deployed():\n \"\"\"\n Query the deployed applications.\n \"\"\"\n mode = request.args['mode']\n conf = request.args['conf']\n params = docker._get_deploy_params(mode, conf)\n\n return docker.query_deployed(params)\n\n@app.route('/query', methods=['GET'])\ndef query_stacks():\n \"\"\"\n Query the stacks.\n \"\"\"\n if 'constraints' in request.args:\n constraints = json.loads(request.args['constraints'])\n return docker.query_stacks(constraints)\n else:\n return docker.query_stacks()\n\n@app.route('/snapshots', methods=['GET'])\ndef snapshots():\n \"\"\"\n Query the snapshots\n \"\"\"\n return docker.query_snapshots()\n\n@app.route('/apps', methods=['GET'])\ndef apps():\n \"\"\"\n Get list of installed applications.\n \"\"\"\n return docker.query_applications()\n\n@app.route('/stack', methods=['GET'])\ndef inspect():\n \"\"\"\n Inspect a particular stack.\n \"\"\"\n uuid = request.args['uuid']\n if docker.is_running(uuid) or docker.is_stopped(uuid):\n return docker.inspect_stack(uuid)\n elif docker.is_installed(uuid):\n return docker.inspect_installed(uuid)\n\n\"\"\"\nCopy over logs\n\"\"\"\n@app.route('/logs', methods=['GET'])\ndef logs():\n stack_uuid = request.args['uuid']\n to_dir = request.args['dir']\n return docker.copy_logs(stack_uuid, to_dir)\n\n\"\"\"\n\"\"\"\n@app.route('/deploy', methods=['POST'])\ndef deploy_stack():\n stack_uuid = request.form['uuid']\n mode = request.form['mode']\n conf = request.form['conf']\n\n # Deploy the stack and check if we need to\n # automatically start the stack as well. \n params = docker._get_deploy_params(mode, conf)\n if docker.deploy_stack(stack_uuid, params):\n _allocate_deployed( { '_file' : stack_uuid } )\n\n\"\"\"\nManage the stacks.\n\"\"\"\n@app.route('/manage/stack', methods=['POST'])\ndef manage_stack():\n stack_uuid = request.form['uuid']\n stack_action = request.form['action']\n reply = docker.manage_stack(stack_uuid, stack_action)\n\n # Format the message to make more sense.\n if reply['status']:\n return reply['msg'] + ' ' + reply['uuid']\n else:\n return reply['msg']\n","sub_path":"ferry/http/httpapi.py","file_name":"httpapi.py","file_ext":"py","file_size_in_byte":24386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"163709604","text":"# import\nimport string\n\n# define\nJACKAPI = { \"Sys\": ['halt', 'error', 'wait'],\n \"Memory\": ['peek', 'poke', 'alloc', 'deAlloc'],\n \"Keyboard\": ['keyPressed', 'readChar', 'readLine', 'readInt'], \n \"Screen\": ['clearScreen', 'setColor', 'drawPixel', 'drawLine', 'drawRectangle', 'drawCircle'],\n \"Output\": ['moveCursor', 'printChar', 'printString', 'printInt', 'println', 'backSpace'],\n \"Array\": ['new', 'dispose'],\n \"String\": ['new', 'dispose', 'length', 'charAt', 'setCharAt', 'appendChar', 'eraseLastChar',\n 'intValue', 'setInt', 'doubleQuote', 'backSpace', 'newLine'],\n \"Math\": ['multiply', 'divide', 'min', 'max', 'sqrt']}\n\n# classes \n# a class for a symbol table\nclass table:\n def __init__(self, scope, className):\n self.vars = {}\n self.className = className\n if scope == 0:\n self.vars = { \"field\": [], \"static\": []}\n else:\n self.vars = { \"argument\": [], \"local\": [] }\n\n # adds a name to the symbol table\n def add(self, name, type, kind):\n if kind == 'method':\n name = 'this'\n type = self.className\n kind = 'argument'\n elif kind == 'var':\n kind = 'local' \n self.vars[kind] = self.vars.get(kind, []) + [(name, type)]\n\n# a class to handle tables and scope nesting\nclass tables:\n def __init__(self, className=''):\n self.tables = []\n self.className = className\n\n # opens a scope level\n def open(self):\n self.tables = [table(len(self.tables), self.className)] + self.tables\n\n # closes a scope level\n def close(self):\n self.tables = self.tables[1:]\n\n # adds a variable to the current scope level\n def add(self, name, type, kind):\n self.tables[0].add(name, type, kind)\n\n # get number of class vars\n def getClassVars(self):\n sum = 0\n for _,value in self.tables[-1].vars.items():\n sum += len(value)\n return sum\n\n # get number of current sub vars\n def getSubVars(self):\n return len(self.tables[0].vars['local'])\n\n # look up symbol and return vm equivalent\n def getSymbol(self, name):\n for tab in self.tables:\n for key, values in tab.vars.items():\n index = 0\n for v in values:\n if name == v[0]:\n if key == 'argument':\n return ('argument '+str(index))\n elif key == 'local':\n return ('local '+str(index))\n elif key == 'static':\n return ('static '+str(index))\n elif key == 'field':\n return ('this '+str(index))\n index += 1\n for key, values in JACKAPI.items():\n if name == key:\n return 'OS'\n if name == self.className:\n return 'className'\n\n # takes a name and returns the type of the name\n def getType(self, name):\n for tab in self.tables:\n for _, values in tab.vars.items():\n for v in values:\n if name == v[0]:\n return v[1]\n\n return name\n","sub_path":"bin/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"412980487","text":"# coding: utf-8\n\"\"\"\"\"\"\nfrom __future__ import (print_function, division, absolute_import,\n unicode_literals)\nimport math\nimport numpy as np\nfrom simple_w_imager.kernels import (exp_taper, generate_w_kernel)\nfrom simple_w_imager.utils import (plot_image, plot_cimage, plot_line,\n plot_semilogy)\n\n\ndef main():\n \"\"\".\"\"\"\n im_size = 4096 # Image size in pixels along each dim of the image.\n fov = 4.0 # Image FoV in degrees\n num_w = 16 # Number of w plane kernels to generate\n\n w_max = 15000 # Maximum w value in wavelengths\n w_min = 0 # Minimum w value in wavelengths\n w_mid = 0.5 * (w_min + w_max)\n w_rms = w_mid * 0.5\n max_uvw = 1.05 * w_max * (w_rms / w_mid)\n w_scale = (num_w - 1)**2 / max_uvw\n\n # Loop over w values in sqrt(w) space and evaluate kernels.\n kernels = []\n for i in range(num_w):\n w = i**2 / w_scale\n c_uv, support = generate_w_kernel(w, im_size, fov, max_size=2048,\n over_sample=4, padded=False,\n cut_level=1e-3)\n print(i, w, support)\n kernels.append(dict(kernel=c_uv, support=support))\n plot_cimage(kernels[i]['kernel'],\n title='w = {}, support = {}'.format(w, support))\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"473878957","text":"\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy import interpolate\r\n\r\ndata = pd.read_excel(\"stress_strain_2.xls\")\r\ndata_numpy = data.to_numpy()\r\n\r\nCoordpairs_fem_y = []\r\nCoordpairs_fem_u = []\r\nCoordpairs_exp_y = []\r\nCoordpairs_exp_u = []\r\n\r\nfor i in range(1, len(data_numpy[:,3])):\r\n coord = [data_numpy[i,3],data_numpy[i,5]]\r\n Coordpairs_fem_y.append(coord)\r\n\r\n coord = [data_numpy[i,4],data_numpy[i,6]]\r\n Coordpairs_fem_u.append(coord)\r\n \r\n coord = [data_numpy[i,8],data_numpy[i,10]]\r\n Coordpairs_exp_y.append(coord)\r\n \r\n coord = [data_numpy[i,9],data_numpy[i,11]]\r\n Coordpairs_exp_u.append(coord)\r\n\r\nPolyfit_fem=[]\r\nPolyfit_exp=[]\r\n\r\nfor i in range(len(Coordpairs_fem_y)):\r\n y=[0, Coordpairs_fem_y[i][0], Coordpairs_fem_u[i][0]]\r\n x=[0, Coordpairs_fem_y[i][1], Coordpairs_fem_u[i][1]]\r\n f = interpolate.interp1d(x, y,kind='linear')\r\n \r\n # t, c, k = interpolate.splrep(x, y, s=0, k=1)\r\n \r\n xnew = np.arange(0, x[2], .00001)\r\n ynew = f(xnew) \r\n plt.plot(x, y, 'o', xnew, ynew, '--')\r\n \r\n # spline = interpolate.BSpline(t,c,k, extrapolate = False)\r\n # plt.plot(xnew, spline(xnew), 'r')\r\n\r\n\r\n yy=[0, Coordpairs_exp_y[i][0], Coordpairs_exp_u[i][0]]\r\n xx=[0, Coordpairs_exp_y[i][1], Coordpairs_exp_u[i][1]]\r\n \r\n g = interpolate.interp1d(xx, yy,kind='linear')\r\n \r\n xxnew = np.arange(0, x[2], .00001)\r\n yynew = g(xxnew) \r\n plt.plot(xx, yy, 'o', xxnew, yynew, ':')\r\n \r\n \r\nplt.show()\r\n \r\n","sub_path":"ss.py","file_name":"ss.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"107784895","text":"# Given an infix expression with parentheses, \n# balanced_paren will return True or False if\n# the amount of parenthesis are balanced. This\n# solution was made WITHOUT a stack implementation.\n# Ex. \"((2+2)+2)\" -> True : Balanced\n# \"(3*3))\" -> False : Not Balanced\n# \"((2+1))\" -> False : Not Balanced\n\ndef balanced_paren(exp):\n open_count = 0\n close_count = 0\n \n for char in exp:\n if char == '(': open_count += 1\n if char == ')': close_count += 1\n \n if open_count == close_count: return True\n else: return False\n\nexp1 = \"((2+2)+2)\"\nexp2 = \"(3*3))\"\nexp3 = \"((2)\"\n\nprint(\"%s: %r\" % (exp1, balanced_paren(exp1)))\nprint(\"%s: %r\" % (exp2, balanced_paren(exp2)))\nprint(\"%s: %r\" % (exp3, balanced_paren(exp3)))","sub_path":"balanced_paren_1.py","file_name":"balanced_paren_1.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"44046470","text":"#!/usr/bin/env python3\nimport yaml\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import request\n\nimport santa\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n if request.method == \"POST\":\n s = santa.secret_santa(\n yaml.load(request.form[\"participants\"]),\n yaml.load(request.form[\"exclusions\"]),\n request.form[\"from\"],\n request.form[\"subject\"],\n request.form[\"content\"],\n True,\n )\n print(s)\n return render_template(\"index.html\", sent=s)\n else:\n return render_template(\"index.html\")\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"392912870","text":"import datetime as dt\nfrom futures_utils import build_contract, get_contract_specs, get_mkt_times\nfrom interactive_brokers.ib_utils import create_ib_futures_contract\n\nclass FuturesContract(object):\n def __init__(self, base_symbol, exp_year=None, exp_month=None, continuous=False):\n self.base_symbol = base_symbol\n self.symbol = build_contract(base_symbol, exp_year, exp_month)\n self.exp_year = exp_year if exp_year is not None else dt.datetime.now().year\n self.exp_month = exp_month if exp_month is not None else dt.datetime.now().month\n\n specs = get_contract_specs(self.base_symbol)\n self.name = specs['Name']\n self.exchange = specs['Exchange']\n self.tick_value = float(specs['Tick Value'])\n self.contract_size = specs['Contract Size']\n self.active = specs['Active']\n self.deliver_months = specs['Delivery Months']\n self.units = specs['Units']\n self.currency = specs['Currency']\n self.trading_times = specs['Trading Times']\n self.min_tick_value = (specs['Minimum Tick Value'])\n self.full_point_value = float(specs['Full Point Value'])\n self.terminal_point_value = float(specs['Terminal Point Value'])\n\n self.contract_multiplier = self.full_point_value*self.terminal_point_value\n\n self.mkt_open, self.mkt_close = get_mkt_times(self.trading_times)\n self.ib_contract = create_ib_futures_contract(self.base_symbol,\n exp_month=self.exp_month,\n exp_year=self.exp_year,\n exchange=self.exchange,\n currency=self.currency)\n\n\n\n","sub_path":"trading/futures_contract.py","file_name":"futures_contract.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"507150594","text":"# -*- coding: utf-8 -*-\n\nimport util.log_util\nfrom util import csvdb\n\n\"\"\"\ncorrel.product_list의 상품을 입력하는 역할을 수행하는 모듈.\nblg_product_list.csv의 데이터를 읽어서 DB에 입력해줍니다.\n새로운 상품을 추가하고자 한다면 blg_product_list.csv파일에 최신 버전을 담은 후\n실행하면 됩니다.\n\"\"\"\nif __name__ == '__main__':\n #DB to csv product_list data \n #DBToCsv_ProductListData(CSV_FILE_NAME, HEADER_LIST)\n \n LOG_FILE_NAME = 'log.txt'\n util.log_util.InitLogging(file_name=LOG_FILE_NAME)\n \n # Constant values\n CSV_FILE_NAME = 'product_list.csv'\n HEADER_DICT = {\"Ticker\":[0, type('')],\n \"BaseCurncy\":[1, type('')],\n \"Description\":[2, type('')],\n \"AmountPerOnePoint\":[3, type(0)],\n \"TickSize\":[4, type(0)],\n \"Type\":[5, type('')],\n }\n \n DSN = 'correl'\n TABLE_NAME = 'product_list'\n \n csvdb.CsvToDB(CSV_FILE_NAME, HEADER_DICT, DSN, TABLE_NAME)\n ","sub_path":"kb_codes/sandbox/python/market_boy/src/tool/blg_data/product_list_main.py","file_name":"product_list_main.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"639029404","text":"import numpy\nimport sys\n\nval1='1001'\nif (len(sys.argv)>1):\n val1=sys.argv[1]\n\ndef encode(m, g):\n en = numpy.dot(m, g)%2\n return en\n\ndef decode(m, h):\n dec = numpy.dot(h, m)%2\n return dec\n\ndef flipbit(enc,bitpos):\n\n if (enc[bitpos]==1):\n enc[bitpos]=0\n else:\n enc[bitpos]=1\n return enc\n\t\ndef hamming(inp):\n g = numpy.array([\n [1, 1, 1, 0, 0, 0, 0],\n [1, 0, 0, 1, 1, 0, 0],\n [0, 1 ,0 ,1 ,0 ,1 ,0],\n [1, 1, 0, 1, 0, 0, 1]])\n \n h = numpy.array([\n [ 0, 0, 0, 1, 1, 1, 1],\n [0 ,1 ,1 ,0 ,0 ,1 ,1],\n [ 1,0, 1, 0,1, 0, 1],])\n \n inp = inp[:4]\n\n enc = encode(inp, g)\n\n dec = decode(enc, h)\n print (\"Input \\t\\tCoded (1 error) \\tError Position\")\n print (inp,\"\\t\",enc,\"\\t\",dec)\n\n print (\"----------------------\")\n print (\"Single Errors:\")\n print (\"Input \\t\\tCoded (1 error) \\tError Position\")\n for i in range (0,7):\n enc = encode(inp, g)\n enc1=flipbit(enc,i)\n dec = decode(enc1, h)\n print (inp,\"\\t\",enc1,\"\\t\",dec)\n\ninp = numpy.fromstring(val1,'u1')- ord('0')\n \nhamming(inp)\n","sub_path":"1-Y-2-S/TPI-Hamming-his-matrices.py","file_name":"TPI-Hamming-his-matrices.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"492662372","text":"\"\"\"\n============================\nAuthor:柠檬班-木森\nTime:2019/10/24\nE-mail:3247119728@qq.com\nCompany:湖南零檬信息技术有限公司\n============================\n\"\"\"\nimport time\nimport unittest\nfrom mylogger import log\nfrom register import register\nfrom read_excle import ReadExcle\nfrom py23_16day.project_V1.ddt import ddt, data\n\n\"\"\"\nddt:能够实现数据驱动:通过用例数据,自动生成测试用例\n自动遍历用例数据,去生成测试用例,\n\n没遍历出来一条用例的数据,会当成一个参数,传到生成的用例中去\n\n\n\"\"\"\n\n@ddt\nclass RegisterTestCase(unittest.TestCase):\n excle = ReadExcle(\"cases.xlsx\", 'register')\n cases = excle.read_data_obj()\n\n @data(*cases)\n def test_register(self, case):\n\n # 第一步 准备用例数据\n # 获取用例的行号\n row = case.case_id + 1\n # 获取预期结果\n excepted = eval(case.excepted)\n # 获取用例入参\n data = eval(case.data)\n\n # 第二步: 调用功能函数,获取实际结果\n res = register(*data)\n\n # 第三步:比对预期结果和实际结果\n try:\n self.assertEqual(excepted, res)\n except AssertionError as e:\n log.info(\"用例:{},执行未通过\".format(case.title))\n self.excle.write_data(row=row, column=5, value=\"未通过\")\n log.error(e)\n raise e\n else:\n log.info(\"用例:{},执行通过\".format(case.title))\n self.excle.write_data(row=row, column=5, value=\"通过\")\n","sub_path":"python_basic_content/py23_16day/project_V1/test_cases.py","file_name":"test_cases.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"228697366","text":"import os\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Extract results to latex writings\")\n\nparser.add_argument('--results', type=str, help='results file')\nparser.add_argument('--output', type=str, help='output results file')\n\nargs = parser.parse_args()\n\np_results = args.results\np_output = args.output\n\noutput_values = []\n\nevery_default = 20\n\nwith open(p_results, 'r') as f:\n\n lines = f.readlines()\n\n header = lines[0].replace(';\\n', '').split(';')\n del lines[0]\n\n data_lines = [ l.replace(';\\n', '').split(';') for l in lines ]\n\n # extract params here\n for line in data_lines:\n\n output_line = []\n model_name = line[0]\n\n sequence_size = int(model_name.split('seq')[1].split('_')[0])\n \n if 'every' in model_name:\n w_size, h_size, sv_begin, sv_end = list(map(int, model_name.split('seq')[0].split('_')[-6:-2]))\n else:\n w_size, h_size, sv_begin, sv_end = list(map(int, model_name.split('seq')[0].split('_')[-5:-1]))\n\n\n bnorm = False\n if '_norm_' in model_name:\n bnorm = True\n\n snorm = False\n if '_seqnorm_' in model_name:\n snorm = True\n\n if 'every' in model_name:\n every_param = int([ d for d in model_name.split('_') if 'every' in d ][0].replace('every','')) * every_default\n else:\n every_param = every_default\n\n\n output_line.append(sequence_size)\n output_line.append((200 / w_size) * (200 / h_size))\n\n if sv_begin == 0:\n h_svd = \"$H_{SVD}$\"\n else:\n h_svd = \"$H'_{SVD}$\"\n\n output_line.append(h_svd)\n output_line.append(model_name.split('bsize')[-1])\n output_line.append(bnorm)\n output_line.append(snorm)\n output_line.append(every_param)\n # 1, 3, 4, 6\n output_line.append(float(line[1]))\n output_line.append(float(line[3]))\n output_line.append(float(line[4]))\n output_line.append(float(line[6]))\n\n output_values.append(output_line)\n\n\noutput_f = open(p_output, 'w')\n\noutput_f.write('\\\\begin{tabular}{|r|r|c|c|c|c|c|r|r|r|r|} \\n')\noutput_f.write('\\t\\hline \\n')\noutput_f.write('\\t\\\\textbf{$k$} & \\\\textbf{$m$} & \\\\textbf{$F$} & \\\\textbf{$b_s$} & \\\\textbf{$bnorm$} & \\\\textbf{$snorm$} & \\\\textbf{$n$ step} & \\\\textbf{Acc Train} & \\\\textbf{Acc Test} & \\\\textbf{AUC Train} & \\\\textbf{AUC Test} \\\\\\\\ \\n')\noutput_f.write('\\t\\hline \\n')\n\noutput_values = sorted(output_values, key=lambda l:l[-1], reverse=True)\n\n# for each data\nfor v in output_values[:20]:\n output_f.write('\\t{0} & {1} & {2} & {3} & {4} & {5} & {6} & {7:.2f} \\\\% & {8:.2f} \\\\% & {9:.2f} \\\\% & {10:.2f} \\\\% \\\\\\\\ \\n' \\\n .format(v[0], int(v[1]), v[2], int(v[3]), int(v[4]), int(v[5]), int(v[6]), v[7] * 100, v[8] * 100, v[9] * 100, v[10] * 100))\n\noutput_f.write('\\t\\hline \\n')\noutput_f.write('\\end{tabular} \\n')\n","sub_path":"extraction/extract_results.py","file_name":"extract_results.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"80962714","text":"##################################################\n# Functions for reading the outputs of the\n# ba-thesis scripts\n#\n# author: Gregor Sturm (gregor.sturm@cs.tum.edu)\n##################################################\n\nfrom Bio import SeqIO\nimport collections\n\ndef read_precursor_results(inputfile):\n \"\"\"read the outputs of reads-to-stemloop.py, returns a list with records\"\"\"\n\n opened = False\n if not hasattr(inputfile, 'read'):\n opened = True\n inputfile = open(inputfile, 'r')\n\n results = []\n i = 0\n for line in inputfile.readlines():\n line = line.strip()\n if line[0] == \"#\":\n continue\n if i%4 == 0:\n tmpName = line[1:].lower()\n if i%4 == 1:\n tmpSeq = line.split(\"\\t\")\n if i%4 == 2:\n tmpStart = line.split(\"\\t\")\n if i%4 == 3:\n tmpEnd = line.split(\"\\t\")\n results.append({\"seq\": tmpSeq, \"start\": tmpStart, \"end\": tmpEnd, \"name\": tmpName})\n i += 1\n\n if opened:\n inputfile.close()\n\n return results\n\ndef read_to_dict(inputfile):\n \"\"\"reads the file line by line into a dictionary such that\n it can be checked in constant time, whether a specific\n line is in the file.\n\n dict.get(line) == None\n\n Args:\n inputfile: can either be a file or a pathname.\"\"\"\n\n opened = False\n if not hasattr(inputfile, 'read'):\n opened = True\n inputfile = open(inputfile, 'r')\n\n dict = {}\n for line in inputfile:\n line = line.strip().lower()\n dict[line] = True\n\n if opened:\n inputfile.close()\n\n return dict\n\ndef read_fasta_to_dict(inputfile):\n \"\"\"reads a fasta file into a dictionary, such that\n dict[header] = sequence\n\n Args:\n inputfile: can either be a file or a pathname\"\"\"\n\n dict = collections.OrderedDict()\n for record in SeqIO.parse(inputfile, \"fasta\"):\n dict[str(record.id).lower()] = str(record.seq)\n\n return dict\n\n\n\n","sub_path":"read_results.py","file_name":"read_results.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"632956716","text":"import pandas as pd\nfrom pandas_profiling import ProfileReport\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.seasonal import seasonal_decompose as sdecomp\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom sklearn.linear_model import Ridge\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_squared_error\nfrom itertools import product\nimport xgboost as xgb\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import ShuffleSplit\nfrom pmdarima.arima import auto_arima\nimport warnings\n\n# ОТРИСОВКА ВРЕМЕННОГО РЯДА\ndef ShowPlot(data, message):\n fig = plt.figure(figsize = (19, 8), num = message)\n d = plt.plot(data[:], color = 'purple', label = \"data\") # ОТРИСОВАВ ТОЛЬКО ПЕРВЫЕ 200 ЗНАЧЕНИЙ, МОЖНО УВИЕТЬ НАЛИЧИЕ СЕЗОНН0СТИ; ПРИМЕРНЫЙ РАЗМЕР СЕЗОНА - 75, начниая с 0-ГО ЗНАЧЕНИЯ\n plt.legend()\n plt.grid(linewidth = 1)\n plt.title(message, fontsize = 'xx-large')\n plt.show()\n '''\n fig = sdecomp(data, model = \"additive\", freq = 75).plot()\n plt.show()\n '''\n\n# СЧИТАЕМ ДАННЫЕ ИЗ ФАЙЛА В DataFrame\ndef GetData(FileName):\n input_file = open(FileName, \"r\")\n input_data = [int(line) for line in input_file]\n input_file.close()\n dframe = pd.DataFrame(input_data, index = range(len(input_data)), columns = ['data'])\n dframe.to_csv(\"task1.csv\")\n return dframe\n\n# НАХОЖДЕНИЕ НАИЛУЧШИХ ПАРАМЕТРОВ ДЛЯ ARIMA\ndef ArimaBSTParams(data, logfile):\n data = data.astype('float')\n data = data.to_numpy()\n ShowPlot(data, \"Исходный временной ряд\")\n ShowPlot(data[ : 75], \"Сезонная часть ряда\")\n\n tmp_data = data[ : ]\n adf_stat, adf_crit_val = adfuller(tmp_data, regression = 'c')[0], adfuller(tmp_data, regression = 'c')[4][\"5%\"]\n int_degree = 0\n while adf_stat >= adf_crit_val:\n print(\"\\n\", adf_stat, adf_crit_val)\n tmp_data = np.diff(tmp_data)\n adf_stat, adf_crit_val = adfuller(tmp_data, regression = 'c')[0], adfuller(tmp_data, regression = 'c')[4][\"5%\"]\n int_degree += 1\n print(\"Порядок интегрированности временного ряда равен:\", int_degree)\n\n tmp_data_seasonal = data[ : 75]\n adf_stat, adf_crit_val = adfuller(tmp_data_seasonal, regression = 'c')[0], adfuller(tmp_data_seasonal, regression = 'c')[4][\"5%\"]\n int_degree_seasonal = 0\n while adf_stat >= adf_crit_val:\n print(\"\\n\", adf_stat, adf_crit_val)\n tmp_data_seasonal = np.diff(tmp_data_seasonal)\n adf_stat, adf_crit_val = adfuller(tmp_data_seasonal, regression = 'c')[0], adfuller(tmp_data_seasonal, regression = 'c')[4][\"5%\"]\n int_degree += 1\n print(\"Порядок интегрированности сезонной части временного ряда равен:\", int_degree_seasonal)\n\n fig = plt.figure(figsize = (8, 8), num = 'Графики ACF и PACF')\n ax = []\n ax.append(fig.add_subplot(2, 1, 1))\n plot_acf(tmp_data, ax = ax[0])\n ax.append(fig.add_subplot(2, 1, 2))\n plot_pacf(tmp_data, ax = ax[1])\n plt.show()\n\n fig = plt.figure(figsize = (8, 8), num = 'Графики ACF и PACF')\n ax = []\n ax.append(fig.add_subplot(2, 1, 1))\n plot_acf(tmp_data_seasonal, ax = ax[0])\n ax.append(fig.add_subplot(2, 1, 2))\n plot_pacf(tmp_data_seasonal, ax = ax[1])\n plt.show()\n\n arima_params = auto_arima(y = data, start_p = 0, start_q = 0, start_Q = 0, start_P = 0, max_order = 10, m = 75, seasonal = False, out_of_sample_size = 100)\n print(arima_params.summary())\n\n forecast = []\n for i, days in enumerate([1, 3, 10]):\n prediction = arima_params.predict(days)\n forecast.append(prediction)\n logfile.write(f\"\\nПрогноз с помощью auto_arima на {days} шагов вперед: \")\n for num in forecast[i]:\n logfile.write(str(num) + \" \")\n logfile.write(\"\\n\")\n print(f\"Прогноз с помощью auto_arima на {days} шагов вперед:\", forecast[i])\n return forecast\n\n '''\n fig = plt.figure(figsize = (16, 8), num = 'Реальные данные + прогноз')\n dates = np.arange(75 + 3)\n plt.plot(dates[ : 75], data[ : 75], color = 'blue', label = 'real')\n plt.plot(dates[75 : ], forecast, color = 'purple', label = 'predicted')\n plt.legend()\n plt.title('Реальные данные + прогноз', fontsize = 'xx-large')\n plt.show()\n '''\n\n# ПРОГНОЗИРОВАНИЕ ВРЕМЕННОГО РЯДА С ПОМОЩЬЮ ARIMA\ndef ArimaPrediction(data):\n data = data.astype('float')\n data = data.to_numpy()\n data = np.diff(data)\n #ShowPlot(data, \"Исходный ряд после дифференцирования\")\n print(data.shape)\n warnings.simplefilter('ignore')\n data_len = len(data)\n split = int(data_len*0.8) # РАЗБИВАЕМ РЯД НА ОБУЧАЮЩУЮ И ТЕСТИРУЮУЩУЮ ВЫБОРКИ\n data_train = data[ : split]\n data_test = data[split : ]\n adf_stat, adf_crit_val = adfuller(data, regression = 'c')[0], adfuller(data, regression = 'c')[4][\"5%\"]\n int_degree = 1\n while adf_stat >= adf_crit_val:\n print(\"\\n\", adf_stat, adf_crit_val)\n data = np.diff(data)\n adf_stat, adf_crit_val = adfuller(data, regression = 'c')[0], adfuller(data, regression = 'c')[4][\"5%\"]\n int_degree += 1\n print(\"Порядок интегрированности временного ряда равен:\", int_degree)\n # НАЙДЕМ ПО ГРАФИКУ КОЭФФИЦИЕНТЫ p И q ДЛЯ МОДЕЛИ ARIMA\n fig = plt.figure(figsize = (8, 8), num = 'Графики ACF и PACF')\n ax = []\n ax.append(fig.add_subplot(2, 1, 1))\n plot_acf(data, ax = ax[0])\n ax.append(fig.add_subplot(2, 1, 2))\n plot_pacf(data, ax = ax[1])\n plt.show()\n print(\"В ходе тестирования выяснил, что параметры ACF и PACF 2 и 0 соотвественно\")\n acf_coef = int(input(\"Введите коэффициент ACF: \")) # MA составляющая временного ряда, параметр \"q\"\n pacf_coef = int(input(\"Введите коэффициент PACF: \")) # AR составляющая временного ряда, параметр \"p\"\n parameters = product(range(pacf_coef + 1), range(acf_coef + 1))\n parameters_list = list(parameters)\n model_score = model_score_best = q_best = p_best = 0 # БУДЕМ ИСПОЛЬЗОВАТЬ МЕТРИКУ R^2 (можно и MSE), ТАК КАК МЕТРИКА АКАИКЕ ПРИ ТАКИХ p И q НЕ ОБЯЗАТЕЛЬНА\n forecasted_best = list(np.zeros(len(data_test)))\n for params in parameters_list:\n print(\"\\nТестируется ARIMA (%d,%d,%d)\" % (params[0], int_degree, params[1]))\n forecasted = []\n for iter in range(len(data_test)):\n model = ARIMA(data_train, order = (params[0], int_degree, params[1]))\n model_fit = model.fit(disp = 0)\n forecast_step = model_fit.forecast()[0]\n forecasted.append(forecast_step)\n data_train = np.append(data_train, data_test[iter])\n #print(len(forecasted))\n #forecasted = np.array(forecasted)\n model_score = r2_score(data_test, forecasted)\n print(\"Её метрика:\", model_score)\n if model_score > model_score_best:\n model_score_best = model_score\n p_best = params[0]\n q_best = params[1]\n forecasted_best = forecasted\n print(\"Наилучшая модель по метрике R_2 это ARIMA(%d,%d,%d) с результатом %f\" % (p_best, int_degree, q_best, model_score_best))\n fig = plt.figure(figsize = (8, 5), num = 'Прогоноз VS Тест')\n plt.plot(data_test, color = 'orange', label = 'Тест')\n plt.plot(forecasted_best, color = 'purple', label = 'Прогноз')\n plt.legend()\n plt.grid(linewidth = 1)\n plt.title('Прогоноз VS Тест', fontsize = 'xx-large')\n plt.show()\n model = ARIMA(data, order = (p_best, int_degree, q_best))\n model_fit = model.fit(disp = 0)\n forecast = []\n for i in [1, 3, 10]:\n forecast.append(model_fit.forecast(i)[0])\n for i, days in enumerate([1, 3, 10]):\n print(f\"Прогноз с помощью ARIMA на {days} шагов вперед\", forecast[i])\n return forecast\n\n# ЗДЕСЬ РЕАЛИЗОВАН МОЙ СОБСТВЕННЫЙ АЛГОРИТМ ПРОГНОЗОВ\ndef MyPrediction(data, logfile):\n forecast_range = [1, 3, 10]\n data = data.to_numpy()\n period_lenght = 75 # ДЛИНА СЕЗОНА\n pos = data.shape[0] % period_lenght # ЗДЕСЬ МЫ ПОЛУЧАЕМ ПОЗИЦИЮ ВНУТРИ ПЕРИОДА, НА КОТОРУЮ НУЖНО ДЕЛАТЬ ПРОГНОЗ\n forecast = []\n a = 0.85 # КОЭФФИЦИЕНТ В ЭКСПОНЕНЦИАЛЬНОМ СГЛАЖИВАНИИ\n for ranges in forecast_range:\n sub_forecast = []\n for fr in range(ranges):\n prev = data[pos + fr : : period_lenght] # ЗДЕСЬ МЫ СОСТАВЛЯЕМ СПИСОК ИЗ ПРЕДЫДУЩИХ ЗНАЧЕНИЙ НА ПОЗИЦИИ pos ВНУТРИ ПЕРИОДА\n prev = np.array(prev)\n tmp_forecast = [prev[0]]\n for i in range(len(prev)):\n tmp_forecast.append((a*prev[i] + (1 - a)*prev[i - 1]))\n sub_forecast.append(a*tmp_forecast[len(tmp_forecast) - 1] + (1- a)*tmp_forecast[len(tmp_forecast) - 2])\n forecast.append(sub_forecast)\n for i, days in enumerate([1, 3, 10]):\n logfile.write(f\"\\nПрогноз своим методом на {days} шагов вперед: \")\n for num in forecast[i]:\n logfile.write(str(num) + \" \")\n logfile.write(\"\\n\")\n print(f\"Прогноз своим методом на {days} шагов вперед\", forecast[i])\n return forecast\n\n# ЗДЕСЬ РЕАЛИЗОВАН ПРОГНОЗ С ПОМОЩЬЮ АЛГОРИТМА XBGoost Regressor\ndef XGBPrediction(data, logfile):\n data = data.to_numpy()\n period = 75\n pos = data.shape[0] % period\n forecast = []\n X = []\n y = []\n for i in range(data.shape[0] - period):\n X.append(data[i : i + period])\n y.append(data[i + period])\n X.append(data[data.shape[0] - period : data.shape[0]])\n data_x = np.array(X) # ПОСЛЕДНЯЯ СТРОКА - ПРИЗНАКИ ДЛЯ ПРОГНОЗА\n data_y = np.array(y)\n xgb_model = xgb.XGBRegressor(learning_rate = 0.001, verbosity = 0, nthread = -1, random_state = 0)\n cv_gen = ShuffleSplit(n_splits = 9, test_size = 0.7, random_state = 0)\n xgb_gs = GridSearchCV(\n xgb_model,\n {\n 'n_estimators': [75],\n 'max_depth': [3, 5],\n 'booster': ['gbtree', 'gblinear'],\n 'gamma': np.linspace(0.00005, 0.0001, num = 5),\n 'reg_alpha': np.linspace(0.0001, 0.001, num = 3),\n 'reg_lambda': np.linspace(0.0001, 0.001, num = 3)\n },\n scoring = 'r2',\n n_jobs = -1,\n cv = 5\n )\n xgb_gs.fit(data_x[ : -1], data_y)\n print(xgb_gs.best_params_)\n print(\"r2 score\",xgb_gs.best_score_)\n prediction = xgb_gs.best_estimator_.predict(data_x[-1 : ])\n forecast.append(prediction)\n for i, days in enumerate([1]):\n logfile.write(f\"\\nПрогноз с помощью XGBoost на {days} шагов вперед: \")\n for num in forecast[i]:\n logfile.write(str(num) + \" \")\n logfile.write(\"\\n\")\n print(f\"Прогноз с помощью XGBoost на {days} шагов вперед\", forecast[i])\n return forecast\n\n# ЗДЕСЬ РЕАЛИЗОВАН ПРОГНОЗ С ПОМОЩЬЮ БИБЛИОТЕКИ SKLearn\ndef SKLearnPrediction(data, logfile):\n data = data.to_numpy()\n period = 75\n pos = data.shape[0] % period\n forecast = []\n X = []\n y = []\n for i in range(int(data.shape[0] / period)):\n X.append(data[i*period : i*period + pos])\n y.append(data[i*period + pos])\n X.append(data[(int(data.shape[0] / period))*period : (int(data.shape[0] / period))*period + pos])\n data_x = np.array(X) # ПОСЛЕДНЯЯ СТРОКА - ПРИЗНАКИ ДЛЯ ПРОГНОЗА\n data_y = np.array(y)\n model = Ridge(copy_X = True, random_state = 0)\n cv_gen = ShuffleSplit(n_splits = 9, test_size = 0.7, random_state = 0)\n model_gs = GridSearchCV(\n model,\n {\n 'alpha' : np.linspace(0.1, 2.0, num = 10),\n 'fit_intercept' : [True, False],\n 'normalize' : [True, False],\n 'tol' : np.linspace(0.00001, 0.0001, num = 5),\n 'solver' : ['auto', 'svd', 'cholesky', 'lsqr', 'sparce_cg', 'sag', 'saga']\n },\n scoring = 'r2',\n n_jobs = -1,\n cv = 5\n )\n model_gs.fit(data_x[ : -1], data_y)\n print(model_gs.best_params_)\n print(\"r2 score:\", model_gs.best_score_)\n prediction = model_gs.best_estimator_.predict(data_x[-1 : ])\n #print(\"Прогноз с помощью SKLearn Ridge:\", prediction)\n forecast.append(prediction)\n for i, days in enumerate([1]):\n logfile.write(f\"\\nПрогноз с помощью SKLearn на {days} шагов вперед: \")\n for num in forecast[i]:\n logfile.write(str(num) + \" \")\n logfile.write(\"\\n\")\n print(f\"Прогноз с помощью SKLearn на {days} шагов вперед\", forecast[i])\n return forecast\n\n\n\n\n# M A I N\ndf = GetData(\"task1.txt\")\n#df = pd.read_csv(\"task1.csv\", index_col = 0)\n#ShowPlot(df['data'], \"Исходные данные\")\nprint(df.describe())\nprofile = ProfileReport(df, title=\"Data\")\nprofile.to_file(\"task1.html\")\n# ПОСМОТРЕТЬ ОТЧЕТ МОЖНО ОТКРЫВ ДАННЫЙ .html ФАЙЛ\n\nreport = open(\"task1_report.txt\", \"w\")\n\nArimaBSTParams(df['data'], report)\n\nMyPrediction(df['data'], report)\n\nXGBPrediction(df['data'], report)\n\nSKLearnPrediction(df['data'], report)\n\nreport.close()\n","sub_path":"Svyaznoy/Task1/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":14482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"92642766","text":"import tensorflow as tf\nfrom read_utils import TextConverter\nfrom model import CharRNN\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nfrom IPython import embed\n\nFLAGS = tf.flags.FLAGS\n\ntf.flags.DEFINE_integer('lstm_size', 128, 'size of hidden state of lstm')\ntf.flags.DEFINE_integer('num_layers', 3, 'number of lstm layers')\ntf.flags.DEFINE_boolean('use_embedding', True, 'whether to use embedding')\ntf.flags.DEFINE_integer('embedding_size', 128, 'size of embedding')\ntf.flags.DEFINE_string('converter_path', 'model/0/converter.pkl', 'model/name/converter.pkl')#gai1\ntf.flags.DEFINE_string('checkpoint_path', 'model/0', 'checkpoint path')#gai2\ntf.flags.DEFINE_string('start_string', '大街', 'use this string to start generating')\ntf.flags.DEFINE_integer('max_length', 500, 'max length to generate')\n\n\ndef main(_,catalog, word):\n checkpoint_path='model/%d'%(catalog)\n FLAGS.start_string = FLAGS.start_string.encode('utf-8').decode('utf-8')\n converter = TextConverter(filename=FLAGS.converter_path)\n if os.path.isdir(FLAGS.checkpoint_path):\n FLAGS.checkpoint_path =\\\n tf.train.latest_checkpoint(FLAGS.checkpoint_path)\n\n model = CharRNN(converter.vocab_size, sampling=True,\n lstm_size=FLAGS.lstm_size, num_layers=FLAGS.num_layers,\n use_embedding=FLAGS.use_embedding,\n embedding_size=FLAGS.embedding_size)\n\n model.load(FLAGS.checkpoint_path)\n\n start = converter.text_to_arr(FLAGS.start_string)\n arr = model.sample(FLAGS.max_length, start, converter.vocab_size)\n print(converter.arr_to_text(arr))\n\n\ndef write_song(catalog=0, word=''):\n song_script = open('sample.txt', encoding='utf-8').read().split('\\n')\n return song_script\n\n\nif __name__ == '__main__':\n tf.app.run()\n # write_song()\n","sub_path":"BibuyingData/CharRNN/sample1.py","file_name":"sample1.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"344864428","text":"\nfrom datetime import datetime\nfrom sqlalchemy import Column, Integer, DateTime, ForeignKey\nfrom flaskblog import db, login_manager\nfrom flask_login import UserMixin\n\n@login_manager.user_loader\ndef load_user(user_id):\n\treturn User.query.get(int(user_id))\n\n# @login_manager.user_loader\n# def load_user(customer_id):\n# \treturn Tailor.query.get(int(customer_id))\n\n# from __main__ import db\n\nclass User(db.Model, UserMixin):\n\t# __tablename__ = 'user'\n\tid = db.Column(db.Integer, primary_key=True)\n\tfirstname = db.Column(db.String(20), unique=False, nullable=False )\n\tlastname = db.Column(db.String(20), unique=False, nullable=False )\n\tusername = db.Column(db.String(20), unique=False, nullable=False )\n\tshop_name = db.Column(db.String(20), unique=False, nullable=True)\n\tnumber = db.Column(db.Integer, unique=False, nullable=False )\n\taddress = db.Column(db.String(20), unique=False, nullable=False )\n\timagefile = db.Column(db.String(20), nullable=True, default='default.jpg')\n\tpassword = db.Column(db.String(60), nullable=False)\n\tuser_type = db.Column(db.Integer, nullable=False, default = 0)\n\t# skill_type = db.Column(db.Integer, nullable=False , default = 0)\n\tis_embroidery = db.Column(db.Integer, default=0)\n\tis_partywear = db.Column(db.Integer, default=0)\n\tis_dailywear = db.Column(db.Integer, default=0)\n\tis_modestwear = db.Column(db.Integer, default=0)\n\n\tdef __repr__(self):\n\t\treturn f\"User('{self.firstname}', '{self.lastname}', '{self.username}')\"\n\n\tdef is_active(self):\n\t \"\"\"True, as all users are active.\"\"\"\n\t return True\n\n\tdef get_id(self):\n\t \"\"\"Return the email address to satisfy Flask-Login's requirements.\"\"\"\n\t return self.id\n\n\tdef is_authenticated(self):\n\t \"\"\"Return True if the user is authenticated.\"\"\"\n\t return True\n\n\tdef is_anonymous(self):\n\t \"\"\"False, as anonymous users aren't supported.\"\"\"\n\t return False\n\n\n\n\n\n\n\nclass Collection(db.Model):\n\t# __tablename__ = 'collection'\n\tid = db.Column(db.Integer, primary_key=True)\n\t# tname = db.Column(db.String(20), db.ForeignKey('User.username'),nullable=False )\n\n\tprice = db.Column(db.String(20), nullable=False )\n\ttitle = db.Column(db.String(20), nullable=False )\n\tis_embroidery = db.Column(db.Integer, default=0) \n\tis_partywear = db.Column(db.Integer, default=0)\n\tis_dailywear = db.Column(db.Integer, default=0)\n\tis_modestwear = db.Column(db.Integer, default=0)\n\tfabric = db.Column(db.Text, nullable=False )\n\tcategory = db.Column(db.Integer, nullable=False, default = 0)\n\tcreated_at = db.Column(db.DateTime, default=datetime.now().strftime(\"%B%d,%Y %I:%M%p\"))\n\tupdated_at =db.Column(db.DateTime,nullable=True)\n\t# date_posted = db.Column(db.DateTime,nullable=False,default= datetime(int(year), int(month), 1))\n\t# create_at_info = db.Column(datetime,now().strftime(\"%B%d,%Y %I:%M%p\"))\n\tproduct_image = db.Column(db.String(20), nullable=False, default='default.jpg')\n\tdescription = db.Column(db.String(50), nullable=False)\n\tuser_id = db.Column(db.Integer, db.ForeignKey('user.id'))\n\tuser = db.relationship('User')#, backref=db.backref('collection', lazy=True))\n\n\n\tdef __repr__(self):\n\t\treturn f\"Collection('{self.price}','{self.description}', '{self.title}')\"\n\n\n\tdef get_id(self):\n\t \"\"\"Return the email address to satisfy Flask-Login's requirements.\"\"\"\n\t return self.id\n\n\tdef is_authenticated(self):\n\t \"\"\"Return True if the user is authenticated.\"\"\"\n\t return self.authenticated\n\n\n","sub_path":"flaskblog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"109318112","text":"import numpy as np\nfrom verification_tools import calc_limits\n\nconfigs = [{'aperture':'ch1','disperser':'short'},\n {'aperture':'ch1','disperser':'medium'},\n {'aperture':'ch1','disperser':'long'},\n {'aperture':'ch2','disperser':'short'},\n {'aperture':'ch2','disperser':'medium'},\n {'aperture':'ch2','disperser':'long'},\n {'aperture':'ch3','disperser':'short'},\n {'aperture':'ch3','disperser':'medium'},\n {'aperture':'ch3','disperser':'long'},\n {'aperture':'ch4','disperser':'short'},\n {'aperture':'ch4','disperser':'medium'},\n {'aperture':'ch4','disperser':'long'}]\napertures = 1.22*0.42*np.array([5.3,6.1,7.2,8.2,9.4,10.6,12.5,14.5,16.5,19.3,22.7,26.1])/10.\nidt_fluxes = np.array([0.05,0.043,0.046,0.045,0.051,0.060,0.098,0.084,0.136,0.54,1.2,2.9])\n\nobsmode = {\n 'instrument': 'miri',\n 'mode': 'mrs',\n 'filter': None,\n 'aperture': 'ch1',\n 'disperser': 'short'\n }\nexp_config = {\n 'subarray': 'full',\n 'readout_pattern': 'fastr1',\n 'ngroup': 99,\n 'nint': 36,\n 'nexp': 1\n }\nstrategy = {\n 'target_xy': [0.0, 0.0],\n 'method': 'ifunodoffscene',\n 'aperture_size': 1.1,\n 'dithers': [{'x':0,'y':0},{'x':50,'y':0}],\n \"units\": \"arcsec\"\n }\n\noutputs_regular, outputs_one = calc_limits.calc_limits(configs,apertures,idt_fluxes,obsmode=obsmode,scanfac=150,skyfacs=1.05,\n exp_config=exp_config,strategy=strategy,background='minzodi12')\n\nnp.savez('../../outputs/miri_mrs_sensitivity.npz',\n wavelengths=outputs_regular['wavelengths'], sns=outputs_regular['sns'], lim_fluxes=outputs_regular['lim_fluxes'],\n sat_limits=outputs_regular['sat_limits'], configs=outputs_regular['configs'], line_limits=outputs_regular['line_limits'])\n\nnp.savez('../../outputs/miri_mrs_sensitivity_one.npz',\n wavelengths=outputs_one['wavelengths'], sns=outputs_one['sns'], lim_fluxes=outputs_one['lim_fluxes'],\n sat_limits=outputs_one['sat_limits'], configs=outputs_one['configs'], line_limits=outputs_one['line_limits'])\n","sub_path":"tests/miri/miri_sensitivity_mrs.py","file_name":"miri_sensitivity_mrs.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"22738496","text":"#!/usr/local/bin/python3\n\n# Create a function to parse the BLAST file and find match quality\ndef find_percent_match(line):\n # Split using tab delimiter first\n split_one = line.split('\\t')\n \n # Capture pident and turn into number instead of string\n pident = float(split_one[2])\n \n # Split using | as delimeter\n split_two = line.split('|')\n \n # Capture transcript ID and SP ID\n trans_ID = split_two[0]\n SP_ID = split_two[4]\n \n # Remove version number from SP ID by splitting and capturing before the period\n SP_ID = SP_ID.split('.')[0] \n \n # Initialize match_report variable\n match_report = \"\"\n \n # Determine match quality using percent identity, and create report \n if pident == (100 or 100.00):\n match_report = (trans_ID + \" is a perfect match for \" + SP_ID) \n \n elif 75 < pident <100:\n match_report = (trans_ID + \" is a good match for \" + SP_ID)\n \n elif 50 < pident < 75:\n match_report = (trans_ID + \" is a fair match for \" + SP_ID)\n \n else:\n match_report = (trans_ID + \" is a bad match for \" + SP_ID)\n \n return (match_report, pident) \n \n# Open a BLAST file for reading\nblast_file = '/scratch/RNASeq/blastp.outfmt6'\nblast_open = open(blast_file)\nblast = blast_open.readlines()\n\n# Open a file to print output\noutput = open(\"blast_analysis.txt\", \"w\")\n\n# Use the function on each line of the file, to parse and check for match quality\nfor line in blast:\n \n match = find_percent_match(line)\n \n # Save the returned variables from the function\n match_report = match[0]\n pident = match[1]\n \n # Print each report on match quality along with the percent identity to the file\n tab = \"\\t\"\n output.write(tab.join([match_report, str(pident)]) + \"\\n\")\n\noutput.close()\nblast_open.close()","sub_path":"Module07/analyze_blast.py","file_name":"analyze_blast.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"77268607","text":"from flask import Flask, request\nfrom player import Player\nfrom team_manager import TeamManager\nfrom staff import Staff\nimport json\n\napp = Flask(__name__)\n\nCANUCKS_DB = 'canucks.sqlite'\ncanucks = TeamManager(CANUCKS_DB)\n\n\n@app.route('/team_manager/employee', methods=['POST'])\ndef add_member():\n \"\"\"adds employee object based on type and assigns object an ID number\"\"\"\n content = request.json\n try:\n if content['type'] == 'staff':\n staff = Staff(content['first_name'], content['last_name'], content['date_of_birth'],\n content['position'], content['hire_date'], content['previous_team'], content['type'])\n id = canucks.add(staff)\n elif content['type'] == 'player':\n player = Player(content['first_name'], content['last_name'], content['date_of_birth'],\n content['position'], float(content['height']), float(content['weight']), int(content['player_number']),\n content['shoot'], content['type'])\n\n id = canucks.add(player)\n else:\n raise ValueError\n\n response = app.response_class(\n response=str(id),\n status=200\n )\n\n except:\n response = app.response_class(\n response=\"Input invalid\",\n status=400\n )\n return response\n\n\n@app.route('/team_manager/employee/', methods=['PUT'])\ndef update_member(id):\n \"\"\"updates employee object based on their ID\"\"\"\n content = request.json\n try:\n if id <= 0:\n response = app.response_class(\n status=400\n )\n return response\n if content['type'] == 'staff':\n team_member = Staff(content['first_name'], content['last_name'], content['date_of_birth'],\n content['position'], content['hire_date'], content['previous_team'], content['type'])\n elif content['type'] == 'player':\n team_member = Player(content['first_name'], content['last_name'], content['date_of_birth'],\n content['position'], float(content['height']), float(content['weight']),\n int(content['player_number']),\n content['shoot'], content['type'])\n else:\n raise ValueError\n team_member.id = id\n canucks.update(team_member)\n response = app.response_class(\n response=\"OK\",\n status=200\n )\n except ValueError as e:\n status_code = 400\n if str(e) == \"Team Member does not exist\":\n status_code = 404\n response = app.response_class(\n response=str(e),\n status=status_code\n )\n return response\n\n\n@app.route('/team_manager/employee/', methods=['DELETE'])\ndef delete_member(id):\n \"\"\"deletes employee object based on their ID\"\"\"\n if id <= 0:\n response = app.response_class(\n status=400\n )\n return response\n try:\n canucks.delete(id)\n response = app.response_class(\n status=200\n )\n except ValueError as e:\n status_code = 400\n if str(e) == \"Team Member does not exist\":\n status_code = 404\n response = app.response_class(\n response=str(e),\n status=status_code\n )\n\n return response\n\n\n@app.route('/team_manager/employee/', methods=['GET'])\ndef get(id):\n \"\"\"returns employee object based on their ID\"\"\"\n try:\n if canucks.get(id) is None:\n response = app.response_class(\n response=\"Team Member does not exist\",\n status=404\n )\n else:\n team_member = canucks.get(id)\n response =app.response_class(\n response=json.dumps(team_member.to_dict()),\n mimetype='application/json',\n status=200\n )\n except:\n response = app.response_class(\n response=\"invalid input\",\n status=400\n )\n return response\n\n\n@app.route('/team_manager/employee/all', methods=['GET'])\ndef get_all():\n \"\"\"returns all employee objects\"\"\"\n response = app.response_class(\n status=200,\n response=json.dumps([team_member.to_dict() for team_member in canucks.get_all()]),\n mimetype='application/json'\n )\n return response\n\n\n@app.route('/team_manager/employee/all/', methods=['GET'])\ndef get_all_by_type(type):\n \"\"\"returns employee object under staff or player type\"\"\"\n try:\n if type == 'staff' or type == 'player':\n response = app.response_class(\n status=200,\n response=json.dumps([team_member.to_dict() for team_member in canucks.get_all_by_type(type)]),\n mimetype='application/json'\n )\n else:\n raise ValueError\n except ValueError:\n response = app.response_class(\n status=400,\n response=\"Type is invalid\"\n )\n return response\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"team_manager_api.py","file_name":"team_manager_api.py","file_ext":"py","file_size_in_byte":5109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"448910703","text":"# Fonksiyonlar program içerisinde oluşturulan kod parçacıklarıdır.\n# Bu parçacıklar ile belirli işlemler tanımlayıp, daha sonra\n# istediğimiz yerde bu fonksiyonu çağırabiliyoruz.\ndef sistem_bilgisi():\n import sys\n print(\"\\nSistemde kurulu python'un: \")\n print(\"\\nSürüm numarası: \", sys.version_info.major)\n print(\"Alt sürüm numarası: \", sys.version_info.minor)\n print(\"Minik sürüm numarası: \", sys.version_info.micro)\n print(\"\\nİşletim sisteminin adı: \", sys.platform, \"\\n\")\n\nsistem_bilgisi()\n\n# Sınırsız sayıda parametre alabilen fonksiyon tanımlama\ndef fonksiyon(*args):\n print(args)\n\n# Verilen çıktıdan anlaşılacağı üzere bir demet elde ediyoruz.\n# Demet metotları ile çıktımızı manipule edebiliriz.\nfonksiyon(1, 2, 3, 4, 5)\n\n# Yine sınırsız sayıda İSİMLİ parametre üretebiliriz.\ndef isimli(**kwargs):\n print(kwargs)\n\nisimli(isim=\"Onur\", soyisim=\"Yıldırım\", yas=\"26\", dil=\"Türkçe\")\n\n# print() fonksiyonunun kullamını genişletelim.\ndef bas(*args, start='', **kwargs):\n for i in args:\n print(start+i, **kwargs)\n\n# *args sayesinde kullanıcıya istediği kadar parametre girişi\n# yapabilmesini sağlıyoruz. daha sonra start parametresini\n# tanımladık. Default değeri boş karakter dizisi, yani kullanıcı\n# bir şey tanımlamaz ise çıktı da herhangi bir değişiklik olmayacak\n# **kwargs ise print() fonksiyonunun hali hazırda sahip olduğu\n# sep, flush gibi parametreleri kullanabilmemizi sağlıyor.\nbas('One', 'Two', 'Three', start=\"#.\")\n\n# İleri Düzey Fonksiyonlar\n# lambda, fonksiyon tanımlamaya yarayan bir kod parçasıdır.\nfonk = lambda parametre1, parametre2: parametre1 + parametre2\nprint(fonk(2,5))\n\n# lambda, fonksiyon tanımlayamayacağımız yerlerde kullanımı\n# bakımından oldukça bakımlıdır. sorted() fonksiyonunun key\n# parametresi bizden bir fonksiyon tanımlamamızı ister ama biz\n# print() içerisinde fonksiyon tanımlayamayız. Örnek olarak:\nharfler = \"abcçdefgğhıijklmnoöprsştuüvyz\"\nçevrim = {i: harfler.index(i) for i in harfler}\n\nisimler = [\"ahmet\", \"ışık\", \"ismail\", \"çiğdem\", \"can\", \"şule\"]\n\nprint(sorted(isimler, key=lambda x:çevrim.get(x[0])))\n\n# Bir sayının çift olup olmadığına lambda ile bakalım\nsayi = lambda sayı: sayı%2 == 0\nprint(sayi(100), sayi(99))\n\n# Bir liste içindeki tüm sayıların karesini lambda ile bulalım\nsayılar = [1, 2, 4, 7, 8]\nprint(*map(lambda sayı: sayı**2, sayılar))\n\n# Kısaca lambda fonksiyonu şu şekilde açıklanabilir:\n# lambda x: x + 10\n# Yukarıdaki kod parçacığının anlamı: 'x' adlı bir parametre alan\n# bir lambda fonksiyonu tanımla. Bu fonksiyon, 'x parametresine 10\n# sayısını eklesin.\n# Tabi bu fonksiyon birden fazla parametre alabilir.\nbirleştirici = lambda ifade, birleştiren: birleştiren.join(ifade.split())\nprint(birleştirici('Istanbul Büyükşehir Belediyesi', '-'))\n\n# lambda fonksiyonları arayüz oluştururken çok işimize yarayacak.\nimport tkinter\nimport tkinter.ttk as ttk\n\npen = tkinter.Tk()\nbtn = ttk.Button(text='merhaba', command=lambda: print('merhaba'))\nbtn.pack(padx=20, pady=20)\n\npen.mainloop()\n\n# Recursive fonksiyonlar kendi kendini çağırabilen fonksiyonlardır.\ndef azalt(kelime):\n if len(kelime) < 1:\n return kelime\n else:\n print(kelime)\n return azalt(kelime[1:])\nprint(azalt('anlamadıklarım'))\n\ndef sayaç(sayı, sınır):\n print(sayı)\n if sayı == sınır:\n return 'bitti!'\n else:\n return sayaç(sayı+1, sınır)\nprint(sayaç(0, 100))\n\n# İç içe geçmiş listeleri tek elemanlı bir listeye çevireceğiz\nliste = [1, 2, 4, [2, 5, 2, 3], [1, 2, [3, 4, 5, 6]]]\n\ndef düz_liste_yap(liste):\n if not isinstance(liste, list):\n return [liste]\n elif not liste:\n return []\n else:\n return düz_liste_yap(liste[0]) + düz_liste_yap(liste[1:])\n\nprint(düz_liste_yap(liste))\n","sub_path":"Python3_Basic/fonksiyonlar.py","file_name":"fonksiyonlar.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"426892973","text":"import math\n\ndef mean(alist):\n mean = sum(alist) / len(alist)\n return mean\n\ndef standardDev(alist):\n theMean = mean(alist) \n sum = 0\n for item in alist:\n difference = item - theMean\n diffsq = difference ** 2\n sum = sum + diffsq\n \n sdev = math.sqrt(sum/(len(alist)-1))\n return sdev\n\ndef correlation(xlist, ylist):\n xbar = mean(xlist)\n ybar = mean(ylist)\n xstd = standardDev(xlist)\n ystd = standardDev(ylist)\n num = 0.0\n for i in range(len(xlist)):\n num = num + (xlist[i]-xbar) * (ylist[i]-ybar)\n corr = num / ((len(xlist)-1) * xstd * ystd) \n return corr\n\ndef stockCorrelate():\n url1 = open('aapl2.csv')\n url2 = open('amzn2.csv')\n t1Data = url1.readlines()\n t2Data = url2.readlines() \n \n t1Data = [line[0:-1].split(',') for line in t1Data[1:] ] \n # list of rows as lists, i.e. one row is a list of strings\n # print('list of two lists', t1Data[0:2])\n t2Data = [line[0:-1].split(',') for line in t2Data[1:] ] \n \n t1Close = []\n t2Close = []\n for i in range(min(len(t1Data), len(t2Data))): \n if t1Data[i][0] == t2Data[i][0]:\n t1Close.append(float(t1Data[i][4]))#share price, at opening or closing?\n t2Close.append(float(t2Data[i][4])) \n\n return correlation(t1Close, t2Close)\n\n\nimport turtle\n\ndef plotPts(): \n# # add your code here to plot the data\n\n url1 = open('aapl2.csv')\n url2 = open('amzn2.csv')\n t1Data = url1.readlines()\n t2Data = url2.readlines() \n \n t1Data = [line[0:-1].split(',') for line in t1Data[1:] ] \n # list of rows as lists, i.e. one row is a list of strings\n # print('list of two lists', t1Data[0:2])\n t2Data = [line[0:-1].split(',') for line in t2Data[1:] ] \n \n t1Close = []\n t2Close = []\n for i in range(min(len(t1Data), len(t2Data))): \n if t1Data[i][0] == t2Data[i][0]:\n t1Close.append(float(t1Data[i][4]))#share price, at opening or closing?\n t2Close.append(float(t2Data[i][4]))\n \n drawPlot= turtle.Scren()\n drawPlot.setworldcoordinates(100,100, 1200, 1200)\n t =turtle.Turtle()\n print( t1Close[0:8])\n print(len(t1Close))\n for i in range(1, len(t1Close)):\n t.up()\n t.goto(t1Close[i], t2Close[i])\n t.down()\n t.dot()\n drawPlot.exitonclick()\n turtle.done()\n \n \n \n# main program starts here\ncorrResult = stockCorrelate()\nprint( corrResult)\n\n","sub_path":"CH5/dataInternetFromFile.py","file_name":"dataInternetFromFile.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"295726811","text":"from flask import Flask\nfrom flask_restful import Api, Resource, reqparse\n\napp = Flask(__name__)\napi = Api(app)\n\nvisitors = [\n {\n \"name\": \"Nicholas\",\n \"date\": \"22/10/2018\",\n \"reason\": \"coffee machine maintenance\"\n },\n {\n \"name\": \"Elvin\",\n \"date\": \"21/10/2018\",\n \"reason\": \"HR training\"\n },\n {\n \"name\": \"Jass\",\n \"date\": \"23/10/2018\",\n \"reason\": \"ER Dr, she came to check on Mr Lewis who was not feeling well\"\n }\n]\n\n\nclass Visitor(Resource):\n def get(self, name):\n for visitor in visitors:\n if name == visitor[\"name\"]:\n return visitor, 200\n return \"Visitor not found\", 404\n\n def post(self, name):\n parser = reqparse.RequestParser()\n parser.add_argument(\"date\")\n parser.add_argument(\"reason\")\n args = parser.parse_args()\n\n for visitor in visitors:\n if name == visitor[\"name\"]:\n return \"Visitor with name {} already exists\".format(name), 400\n\n visitor = {\n \"name\": name,\n \"date\": args[\"date\"],\n \"reason\": args[\"reason\"]\n }\n visitors.append(visitor)\n return visitor, 201\n\n def put(self, name):\n parser = reqparse.RequestParser()\n parser.add_argument(\"date\")\n parser.add_argument(\"reason\")\n args = parser.parse_args()\n\n for visitor in visitors:\n if name == visitor[\"name\"]:\n visitor[\"date\"] = args[\"date\"]\n visitor[\"reason\"] = args[\"reason\"]\n return visitor, 200\n\n visitor = {\n \"name\": name,\n \"date\": args[\"date\"],\n \"reason\": args[\"reason\"]\n }\n visitors.append(visitor)\n return visitor, 201\n\n def delete(self, name):\n global visitors\n visitors = [visitor for visitor in visitors if visitor[\"name\"] != name]\n return \"{} is deleted.\".format(name), 200\n\n\napi.add_resource(Visitor, \"/v1/visitor/\")\n\n\nclass Report(Resource):\n def get(self):\n return visitors, 200\n\n\napi.add_resource(Report, \"/v1/report\")\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"318596749","text":"\"\"\"\nCIS-15 project 9\nEmanuel Navarro\n\"\"\"\nimport random \nimport sys\nscript, madlib=sys.argv\n\ndef pick_random_door(doors):\n my_number = random.randrange(0, doors)\n door=my_number\n return door\n\n# sets the bounds for highest and lowest values allowed\ndef get_integer(lowest, highest):\n while True: \n try:\n num = int(input(f'Enter the number of turns: '))\n if lowest <= num <= highest:\n return num \n else:\n True\n except:\n True\ndef montys_choice(car,choice1,doors):\n possible_door=[]\n \n for i in range(doors):\n possible_door.append(i)\n \n possible_door.remove(car)\n if car!=choice1:\n possible_door.remove(choice1)\n else:\n \n possible_door.remove(1234%(len(possible_door)))\n return possible_door \n\ndef has_won(car,choice1,choice2):\n if car==choice1 and choice2==False:\n return True\n elif car == choice1 and choice2==True:\n return False \n elif car != choice1 and choice2==True:\n return True\n elif car!=choice1 and choice2==False:\n return False\n else:\n False\n \n \n\n\ndef main() :\n won=0.0\n switch=0.0\n stay=0.0\n staywin= float (0.0)\n switchwin= float (0.0)\n lost=0.0\n mrt=0.0\n percent= float (100)\n doors=int(madlib)\n \n \n while True: \n try:\n \n \n Turns= get_integer(0, 100000)\n for car in range(Turns):\n \n car = pick_random_door(doors)\n choice1 = random.randrange(1, doors)\n monty = montys_choice(car, choice1,doors)\n choice2 = random.choice([True, False])\n #Adds plus one to counter switch\n if choice2:\n switch+=1\n #Adds plus one top counter stay \n else:\n stay+=1\n #adds up how many times you switch win and switch stay\n x=has_won(car, choice1, choice2)\n if x:\n if choice2:\n switchwin+=1\n else:\n staywin+=1\n \n \n #print(\"Switch and won: \",switchwin)\n #print(\"Stayed and won: \",staywin)\n #This is where we calculate how many wins per switch \n print(\"Switching wins\", switchwin/float (switch)*percent,\"% of the time\")\n #This is where w calculate how many wins per stay\n print(\"Staying wins\",staywin/float (stay)*percent,\"% of the time\")\n return\n \n except:\n True\n\n \n \nif __name__ == '__main__' :\n main() ","sub_path":"week11/project9_xc.py","file_name":"project9_xc.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"98797934","text":"import time\nfrom abc import abstractmethod\nfrom abc import abstractproperty\n\nfrom . import exceptions\nfrom . import project_config\nfrom . import version\nfrom .helpers import enums\n\n\nclass Event(object):\n \"\"\" Representation of an event which can be sent to the Optimizely logging endpoint. \"\"\"\n\n def __init__(self, url, params, http_verb=None, headers=None):\n self.url = url\n self.params = params\n self.http_verb = http_verb or 'GET'\n self.headers = headers\n\n\nclass BaseEventBuilder(object):\n \"\"\" Base class which encapsulates methods to build events for tracking impressions and conversions. \"\"\"\n\n def __init__(self, config, bucketer):\n self.config = config\n self.bucketer = bucketer\n self.params = {}\n\n @abstractproperty\n class EventParams(object):\n pass\n\n def _add_project_id(self):\n \"\"\" Add project ID to the event. \"\"\"\n\n self.params[self.EventParams.PROJECT_ID] = self.config.get_project_id()\n\n def _add_account_id(self):\n \"\"\" Add account ID to the event. \"\"\"\n\n self.params[self.EventParams.ACCOUNT_ID] = self.config.get_account_id()\n\n def _add_user_id(self, user_id):\n \"\"\" Add user ID to the event. \"\"\"\n\n self.params[self.EventParams.END_USER_ID] = user_id\n\n @abstractmethod\n def _add_attributes(self, attributes):\n \"\"\" Add attribute(s) information to the event.\n\n Args:\n attributes: Dict representing user attributes and values which need to be recorded.\n \"\"\"\n pass\n\n @abstractmethod\n def _add_source(self):\n \"\"\" Add source information to the event. \"\"\"\n pass\n\n @abstractmethod\n def _add_time(self):\n \"\"\" Add time information to the event. \"\"\"\n pass\n\n def _add_common_params(self, user_id, attributes):\n \"\"\" Add params which are used same in both conversion and impression events.\n\n Args:\n user_id: ID for user.\n attributes: Dict representing user attributes and values which need to be recorded.\n \"\"\"\n\n self._add_project_id()\n self._add_account_id()\n self._add_user_id(user_id)\n self._add_attributes(attributes)\n self._add_source()\n self._add_time()\n\n\nclass EventBuilderV1(BaseEventBuilder):\n \"\"\" Class which encapsulates methods to build events for tracking\n impressions and conversions using the old endpoint. \"\"\"\n\n # Attribute mapping format\n ATTRIBUTE_PARAM_FORMAT = '{segment_prefix}{segment_id}'\n # Experiment mapping format\n EXPERIMENT_PARAM_FORMAT = '{experiment_prefix}{experiment_id}'\n # Event API format\n OFFLINE_API_PATH = 'https://{project_id}.log.optimizely.com/event'\n\n\n class EventParams(object):\n ACCOUNT_ID = 'd'\n PROJECT_ID = 'a'\n EXPERIMENT_PREFIX = 'x'\n GOAL_ID = 'g'\n GOAL_NAME = 'n'\n END_USER_ID = 'u'\n EVENT_VALUE = 'v'\n SEGMENT_PREFIX = 's'\n SOURCE = 'src'\n TIME = 'time'\n\n def _add_attributes(self, attributes):\n \"\"\" Add attribute(s) information to the event.\n\n Args:\n attributes: Dict representing user attributes and values which need to be recorded.\n \"\"\"\n\n if not attributes:\n return\n\n for attribute_key in attributes.keys():\n attribute_value = attributes.get(attribute_key)\n # Omit falsy attribute values\n if attribute_value:\n attribute = self.config.get_attribute(attribute_key)\n if attribute:\n self.params[self.ATTRIBUTE_PARAM_FORMAT.format(\n segment_prefix=self.EventParams.SEGMENT_PREFIX, segment_id=attribute.segmentId)] = attribute_value\n\n def _add_source(self):\n \"\"\" Add source information to the event. \"\"\"\n\n self.params[self.EventParams.SOURCE] = 'python-sdk-{version}'.format(version=version.__version__)\n\n def _add_time(self):\n \"\"\" Add time information to the event. \"\"\"\n\n self.params[self.EventParams.TIME] = int(time.time())\n\n def _add_impression_goal(self, experiment):\n \"\"\" Add impression goal information to the event.\n\n Args:\n experiment: Object representing experiment being activated.\n \"\"\"\n\n # For tracking impressions, goal ID is set equal to experiment ID of experiment being activated\n self.params[self.EventParams.GOAL_ID] = experiment.id\n self.params[self.EventParams.GOAL_NAME] = 'visitor-event'\n\n def _add_experiment(self, experiment, variation_id):\n \"\"\" Add experiment to variation mapping to the impression event.\n\n Args:\n experiment: Object representing experiment being activated.\n variation_id: ID for variation which would be presented to user.\n \"\"\"\n\n self.params[self.EXPERIMENT_PARAM_FORMAT.format(experiment_prefix=self.EventParams.EXPERIMENT_PREFIX,\n experiment_id=experiment.id)] = variation_id\n\n def _add_experiment_variation_params(self, user_id, valid_experiments):\n \"\"\" Maps experiment and corresponding variation as parameters to be used in the event tracking call.\n\n Args:\n user_id: ID for user.\n valid_experiments: List of tuples representing valid experiments for the event.\n \"\"\"\n\n for experiment in valid_experiments:\n variation = self.bucketer.bucket(experiment, user_id)\n if variation:\n self.params[self.EXPERIMENT_PARAM_FORMAT.format(experiment_prefix=self.EventParams.EXPERIMENT_PREFIX,\n experiment_id=experiment.id)] = variation.id\n\n def _add_conversion_goal(self, event_key, event_value):\n \"\"\" Add conversion goal information to the event.\n\n Args:\n event_key: Event key representing the event which needs to be recorded.\n event_value: Value associated with the event. Can be used to represent revenue in cents.\n \"\"\"\n\n event = self.config.get_event(event_key)\n\n if not event:\n return\n\n event_ids = event.id\n\n if event_value:\n event_ids = '{goal_id},{revenue_goal_id}'.format(goal_id=event.id,\n revenue_goal_id=self.config.get_revenue_goal().id)\n self.params[self.EventParams.EVENT_VALUE] = event_value\n\n self.params[self.EventParams.GOAL_ID] = event_ids\n self.params[self.EventParams.GOAL_NAME] = event_key\n\n def create_impression_event(self, experiment, variation_id, user_id, attributes):\n \"\"\" Create impression Event to be sent to the logging endpoint.\n\n Args:\n experiment: Object representing experiment for which impression needs to be recorded.\n variation_id: ID for variation which would be presented to user.\n user_id: ID for user.\n attributes: Dict representing user attributes and values which need to be recorded.\n\n Returns:\n Event object encapsulating the impression event.\n \"\"\"\n\n self.params = {}\n self._add_common_params(user_id, attributes)\n self._add_impression_goal(experiment)\n self._add_experiment(experiment, variation_id)\n return Event(self.OFFLINE_API_PATH.format(project_id=self.params[self.EventParams.PROJECT_ID]),\n self.params)\n\n def create_conversion_event(self, event_key, user_id, attributes, event_value, valid_experiments):\n \"\"\" Create conversion Event to be sent to the logging endpoint.\n\n Args:\n event_key: Event key representing the event which needs to be recorded.\n user_id: ID for user.\n event_value: Value associated with the event. Can be used to represent revenue in cents.\n valid_experiments: List of tuples representing valid experiments for the event.\n\n Returns:\n Event object encapsulating the conversion event.\n \"\"\"\n\n self.params = {}\n self._add_common_params(user_id, attributes)\n self._add_conversion_goal(event_key, event_value)\n self._add_experiment_variation_params(user_id, valid_experiments)\n return Event(self.OFFLINE_API_PATH.format(project_id=self.params[self.EventParams.PROJECT_ID]),\n self.params)\n\n\nclass EventBuilderV2(BaseEventBuilder):\n \"\"\" Class which encapsulates methods to build events for tracking \n impressions and conversions using the new endpoints. \"\"\"\n\n IMPRESSION_ENDPOINT = 'https://p13nlog.dz.optimizely.com/log/decision'\n CONVERSION_ENDPOINT = 'https://p13nlog.dz.optimizely.com/log/event'\n HTTP_VERB = 'POST'\n HTTP_HEADERS = {'Content-Type': 'application/json'}\n EVENT_VALUE_METRIC = 'revenue'\n\n class EventParams(object):\n ACCOUNT_ID = 'accountId'\n PROJECT_ID = 'projectId'\n LAYER_ID = 'layerId'\n EXPERIMENT_ID = 'experimentId'\n VARIATION_ID = 'variationId'\n END_USER_ID = 'visitorId'\n EVENT_ID = 'eventEntityId'\n EVENT_NAME = 'eventName'\n EVENT_METRICS = 'eventMetrics'\n EVENT_FEATURES = 'eventFeatures'\n USER_FEATURES = 'userFeatures'\n DECISION = 'decision'\n LAYER_STATES = 'layerStates'\n TIME = 'timestamp'\n SOURCE_SDK_TYPE = 'clientEngine'\n SOURCE_SDK_VERSION = 'clientVersion'\n ACTION_TRIGGERED = 'actionTriggered'\n IS_GLOBAL_HOLDBACK = 'isGlobalHoldback'\n IS_LAYER_HOLDBACK = 'isLayerHoldback'\n\n def _add_attributes(self, attributes):\n \"\"\" Add attribute(s) information to the event.\n\n Args:\n attributes: Dict representing user attributes and values which need to be recorded.\n \"\"\"\n\n self.params[self.EventParams.USER_FEATURES] = []\n if not attributes:\n return\n\n for attribute_key in attributes.keys():\n attribute_value = attributes.get(attribute_key)\n # Omit falsy attribute values\n if attribute_value:\n attribute = self.config.get_attribute(attribute_key)\n if attribute:\n self.params[self.EventParams.USER_FEATURES].append({\n 'id': attribute.id,\n 'name': attribute_key,\n 'type': 'custom',\n 'value': attribute_value,\n 'shouldIndex': True\n })\n\n def _add_source(self):\n \"\"\" Add source information to the event. \"\"\"\n\n self.params[self.EventParams.SOURCE_SDK_TYPE] = 'python-sdk'\n self.params[self.EventParams.SOURCE_SDK_VERSION] = version.__version__\n\n def _add_time(self):\n \"\"\" Add time information to the event. \"\"\"\n\n self.params[self.EventParams.TIME] = int(round(time.time() * 1000))\n\n def _add_required_params_for_impression(self, experiment, variation_id):\n \"\"\" Add parameters that are required for the impression event to register.\n\n Args:\n experiment: Experiment for which impression needs to be recorded.\n variation_id: ID for variation which would be presented to user.\n \"\"\"\n\n self.params[self.EventParams.IS_GLOBAL_HOLDBACK] = False\n self.params[self.EventParams.LAYER_ID] = experiment.layerId\n self.params[self.EventParams.DECISION] = {\n self.EventParams.EXPERIMENT_ID: experiment.id,\n self.EventParams.VARIATION_ID: variation_id,\n self.EventParams.IS_LAYER_HOLDBACK: False\n }\n\n def _add_required_params_for_conversion(self, event_key, user_id, event_value, valid_experiments):\n \"\"\" Add parameters that are required for the conversion event to register.\n\n Args:\n event_key: Key representing the event which needs to be recorded.\n user_id: ID for user.\n event_value: Value associated with the event. Can be used to represent revenue in cents.\n valid_experiments: List of tuples representing valid experiments for the event.\n \"\"\"\n\n self.params[self.EventParams.IS_GLOBAL_HOLDBACK] = False\n self.params[self.EventParams.EVENT_FEATURES] = []\n self.params[self.EventParams.EVENT_METRICS] = []\n\n if event_value:\n self.params[self.EventParams.EVENT_METRICS] = [{\n 'name': self.EVENT_VALUE_METRIC,\n 'value': event_value\n }]\n\n self.params[self.EventParams.LAYER_STATES] = []\n for experiment in valid_experiments:\n variation = self.bucketer.bucket(experiment, user_id)\n if variation:\n self.params[self.EventParams.LAYER_STATES].append({\n self.EventParams.LAYER_ID: experiment.layerId,\n self.EventParams.ACTION_TRIGGERED: True,\n self.EventParams.DECISION: {\n self.EventParams.EXPERIMENT_ID: experiment.id,\n self.EventParams.VARIATION_ID: variation.id,\n self.EventParams.IS_LAYER_HOLDBACK: False\n }\n })\n\n self.params[self.EventParams.EVENT_ID] = self.config.get_event(event_key).id\n self.params[self.EventParams.EVENT_NAME] = event_key\n\n def create_impression_event(self, experiment, variation_id, user_id, attributes):\n \"\"\" Create impression Event to be sent to the logging endpoint.\n\n Args:\n experiment: Experiment for which impression needs to be recorded.\n variation_id: ID for variation which would be presented to user.\n user_id: ID for user.\n attributes: Dict representing user attributes and values which need to be recorded.\n\n Returns:\n Event object encapsulating the impression event.\n \"\"\"\n\n self.params = {}\n self._add_common_params(user_id, attributes)\n self._add_required_params_for_impression(experiment, variation_id)\n return Event(self.IMPRESSION_ENDPOINT,\n self.params,\n http_verb=self.HTTP_VERB,\n headers=self.HTTP_HEADERS)\n\n def create_conversion_event(self, event_key, user_id, attributes, event_value, valid_experiments):\n \"\"\" Create conversion Event to be sent to the logging endpoint.\n\n Args:\n event_key: Key representing the event which needs to be recorded.\n user_id: ID for user.\n event_value: Value associated with the event. Can be used to represent revenue in cents.\n valid_experiments: List of tuples representing valid experiments for the event.\n attributes: Dict representing user attributes and values.\n\n Returns:\n Event object encapsulating the conversion event.\n \"\"\"\n\n self.params = {}\n self._add_common_params(user_id, attributes)\n self._add_required_params_for_conversion(event_key, user_id, event_value, valid_experiments)\n return Event(self.CONVERSION_ENDPOINT,\n self.params,\n http_verb=self.HTTP_VERB,\n headers=self.HTTP_HEADERS)\n\n\ndef get_event_builder(config, bucketer):\n \"\"\" Helper method to get appropriate EventBuilder class based on the version of the datafile.\n\n Args:\n config: Object representing the project's configuration.\n bucketer: Object representing the bucketer.\n\n Returns:\n Event builder based on the version of the datafile.\n\n Raises:\n Exception if provided datafile has unsupported version.\n \"\"\"\n\n config_version = config.get_version()\n if config_version == project_config.V1_CONFIG_VERSION:\n return EventBuilderV1(config, bucketer)\n if config_version == project_config.V2_CONFIG_VERSION:\n return EventBuilderV2(config, bucketer)\n\n raise exceptions.InvalidInputException(enums.Errors.UNSUPPORTED_DATAFILE_VERSION)\n","sub_path":"optimizely/event_builder.py","file_name":"event_builder.py","file_ext":"py","file_size_in_byte":14590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"154769183","text":"import argparse\n\nparser = argparse.ArgumentParser(description='Run simulation for nora w 3d layers')\nparser.add_argument('t', metavar='threads', type=int,\n default=1,\n help='number of nest threads')\nparser.add_argument('n', metavar='nn',\n default=3000,\n help='desired number of neurons')\n\nargs = parser.parse_args()\n\n\n# Quality of graphics\ndpi_n = 120\n\nnumber_of_threads = args.t\n\n# Number of neurons\nNN = args.n\n\n# T - simulation time | dt - simulation pause step\nT = 1000.\ndt = 10.\n\n# Neurons number for spike detector\nN_detect = 100\n\n# Neurons number for multimeter\nN_volt = 3\n\n# Generator delay\npg_delay = 10.\n\n# Synapse weights\nw_Glu = 3.\nw_GABA = -w_Glu * 2\nw_ACh = 8.\nw_NA_ex = 13.\nw_NA_in = -w_NA_ex\nw_DA_ex = 13.\nw_DA_in = -w_DA_ex\n\n\n# Minimal number of neurons\nNN_minimal = 10\n\n# Additional settings\nnoradrenaline_flag = True # noradrenaline modulation flag\ndopamine_flag = True # dopamine modulation flag\ngenerator_flag = True\ncreate_images = True\n\nMaxSynapses = 4000 # max synapses\n\nBOUND = 0.2 # outer bound of rectangular 3d layer\nR = .25 # radius of connectivity sphere of a neuron\n\n","sub_path":"src dopanora/simulation_params.py","file_name":"simulation_params.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"119514371","text":"from django.contrib import admin\nfrom financeiro.models.titulo import Titulo, Recibo\n\n# Register your models here.\nclass TituloAdmin(admin.ModelAdmin):\n\n readonly_fields = ['usuario_cadastrou']\n def save_model(self,request, obj, form, change):\n obj.usuario_cadastrou = request.user\n obj.save()\nadmin.site.register(Titulo, TituloAdmin)\nadmin.site.register(Recibo)\n","sub_path":"financeiro/admin/titulo.py","file_name":"titulo.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"111008088","text":"from quchem_ibm.IBM_experiment_functions import *\nimport pickle\nimport os\nimport argparse\n\n\ndef main(method_name):\n molecule_name='LiH'\n ## Load input data\n base_dir = os.getcwd()\n data_dir = os.path.join(base_dir, 'Input_data')\n input_file = os.path.join(data_dir, 'LiH_bravyi_kitaev_12_qubit_experiment_time=2020Sep21-132537266776.pickle')\n with open(input_file, 'rb') as handle:\n input_data = pickle.load(handle)\n\n ## Get IBM account\n my_provider = load_IBM_provider()\n # IBM_backend = Get_IBM_backends(my_provider, show_least_busy=False)\n IBM_backend = 'ibmq_qasm_simulator'\n\n # LCM(102,630)=10710\n\n # (10710*475)/630 = 1326\n # (10710*78)/102 = 8190\n shot_list=[8190 for _ in range (10)]\n # shot_list=[1326 for _ in range (10)]\n\n run_experiment_exp_loop_QASM(molecule_name,\n method_name,\n my_provider,\n IBM_backend,\n input_data,\n shot_list,\n optimization_level=3)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"method\", type=str, help=\"VQE method (standard_VQE, LCU, seq_rot_VQE\")\n # parser.add_argument(\"IBMQ_backend\", type=str, help=\"name of IBMQ backend device\")\n # parser.add_argument(\"n_shots\", type=int, help=\"number of circuit shots\")\n args = parser.parse_args()\n\n main(args.method)","sub_path":"old_projects/quchem_ibm/Experiments/LiH_12_qubit_exp.py","file_name":"LiH_12_qubit_exp.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"287280683","text":"from __future__ import absolute_import, unicode_literals, division, print_function\n\nfrom . import model_base\nfrom . import wcs\n\n\n__all__ = ['RampFitOutputModel']\n\n\nclass RampFitOutputModel(model_base.DataModel, wcs.HasFitsWcs):\n \"\"\"\n A data model for the optional output of the ramp fitting step.\n \"\"\"\n schema_url = \"rampfitoutput.schema.json\"\n\n def __init__(self, init=None,\n slope=None,\n sigslope=None,\n yint=None,\n sigyint=None,\n pedestal=None,\n weights=None,\n crmag=None,\n **kwargs):\n super(RampFitOutputModel, self).__init__(init=init, **kwargs)\n\n if slope is not None:\n self.slope = slope\n\n if sigslope is not None:\n self.sigslope = sigslope\n\n if yint is not None:\n self.yint = yint\n\n if sigyint is not None:\n self.sigyint = sigyint\n\n if pedestal is not None:\n self.pedestal = pedestal\n\n if weights is not None:\n self.weights = weights\n\n if crmag is not None:\n self.crmag = crmag\n\n","sub_path":"jwst_lib/models/rampfitoutput.py","file_name":"rampfitoutput.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"36788159","text":"from django.urls import path\nfrom . import views\n\napp_name = 'groups'\n\nurlpatterns = [\n path('', views.ListGroups.as_view(), name='all'),\n path('new/', views.CreateGroup.as_view(), name='create'),\n path('posts/in//', views.SingleGroup.as_view(), name='single'),\n path('join//', views.JoinGroup.as_view(), name='join'),\n path('leave//', views.LeaveGroup.as_view(), name='leave'),\n\n]\n\n# if this doesn't work try setting it to \n# I think because the 'slug' is already a slug I\n# don't have to specify to turn it into one but\n# I could be wrong\n","sub_path":"social_project/social/groups/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"354498887","text":"# Function:\r\n# 1. Write a class to represent an Item - each item has name, price and quantity.\r\n# Include a method to calculate total price. Test your class by creating few Item objects.\r\n# 2. Write a class to represent a complex number.\r\n# Complex numbers can be written in the form of a+bi where a and b are real numbers and i is the solution of i^2=-1\r\n#\r\n# Add methods to add and subtract complex numbers - to add/subtract complex numbers you add/subtract\r\n# the corresponding real and imaginary parts.\r\n#\r\n# For example, adding 1+2i and 2+3i will result in 3+5i\r\n# Compiler used: PyCharm\r\n\r\n# Functions/Classes\r\n\r\nclass Items:\r\n\r\n def __init__(self, name, price, quantity): # Initialise the variables.\r\n self.name = name\r\n self.price = price\r\n self.quantity = quantity\r\n\r\n def __info__(self):\r\n return self.name, self.price, self.quantity,\r\n\r\n\r\ndef Stock(new_cart): # Function to add an item to the parameters defined in the class.\r\n # This way the user can add their own items during run-time\r\n name_ = input(\"Please enter the item name.\\n\")\r\n price_ = input(\"Please enter the item price.\\n\")\r\n quantity_ = input(\"Please enter the item quantity.\\n\")\r\n\r\n new_item = Items(name_, price_, quantity_)\r\n print(new_item.name, \"Has been added to your basket.\\n\")\r\n\r\n quantity_ = int(quantity_)\r\n price_ = int(price_)\r\n cart = price_ * quantity_\r\n new_cart = (new_cart + cart)\r\n print(\"Your basket is: €\", new_cart)\r\n\r\n# Main function\r\ndef main():\r\n new_cart = 0\r\n\r\n # Menu to choice which function you want\r\n print(\"1. Add items to the class.\\n\")\r\n print(\"2. View you cart.\\n\")\r\n\r\n while 1:\r\n choice = input(\"\\nPlease enter the number that corresponds to what option you want:\\n\")\r\n choice = int(choice) # making the variable an int\r\n\r\n if choice == 1:\r\n # Call function\r\n Stock(new_cart)\r\n\r\n # elif choice == 2:\r\n\r\n else:\r\n print(\"Invalid input\\n\")\r\n\r\nmain()\r\n","sub_path":"Python/Overloading.py","file_name":"Overloading.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"649533781","text":"import os\nfrom flask import Flask\nfrom datetime import date\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n name = \"Ferko\"\n if \"MY_NAME\" in os.environ:\n name = os.environ[\"MY_NAME\"]\n return \"

    Hello There {}!

    \".format(name)\n\n@app.route(\"/date\")\ndef date():\n today = date.today()\n return \"

    {}

    \".format(today.strftime(\"%d.%m.%Y\"))\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"pages_migrated_example/zkt/cvicenia/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"614654285","text":"import subprocess\nimport leather\nimport filteroperations\nfrom dataimport import *\nimport warnings\n\nwarnings.simplefilter('ignore', PendingDeprecationWarning)\nfrom pymongo import MongoClient\n\ntry:\n import readline\nexcept ImportError:\n # readline not available\n pass\n\nSTANDARD_FILL_COLOR = '#4169e1'\n\n\ndef create_bar_chart_favorite_opponents(tupel_list, driver_id):\n chart = leather.Chart('Favorite opponents of driver ' + driver_id)\n chart.add_x_axis(name='Opponent id')\n chart.add_y_axis(name='Races driven')\n chart.add_columns(data=tupel_list, fill_color=STANDARD_FILL_COLOR)\n return chart\n\n\ndef create_line_chart(cursor, attribute_name, title, x_axis_name, y_axis_name):\n # colleting data for the line-chart\n data = []\n i = 0\n for doc in cursor:\n data.append(str(doc[attribute_name]))\n i += 1\n\n chart = leather.Chart(title=title)\n chart.add_x_scale(0, i)\n chart.add_x_axis(name=x_axis_name)\n chart.add_y_axis(name=y_axis_name)\n chart.add_line(data)\n\n\ndef create_bar_chart(cursor, attribute_name1, attribute_name2, title):\n # collecting data for the bar chart\n data = []\n for doc in cursor:\n data.append((doc[attribute_name2], str(doc[attribute_name1])))\n\n # create the graph to display\n chart = leather.Chart(title=title)\n chart.add_x_axis(name=attribute_name2)\n chart.add_y_axis(name=attribute_name1)\n chart.add_bars(data=data, fill_color=STANDARD_FILL_COLOR)\n return chart\n\n\ndef create_simple_bar_chart(data, title, x_axis_name, y_axis_name):\n chart = leather.Chart(title=title)\n chart.add_x_axis(name=x_axis_name)\n chart.add_y_axis(name=y_axis_name)\n chart.add_bars(data=data, fill_color=STANDARD_FILL_COLOR)\n return chart\n\n\ndef create_simple_line_chart(data, title, x_axis_name, y_axis_name):\n chart = leather.Chart(title=title)\n chart.add_x_axis(name=x_axis_name)\n chart.add_y_axis(name=y_axis_name)\n chart.add_line(data=data, stroke_color=STANDARD_FILL_COLOR)\n return chart\n\n\ndef draw_bar_chart_with_attributes(cursor, filename, attribute1, attribute2, title):\n chart = create_bar_chart(cursor, attribute1, attribute2, title)\n # Save the graph to the results folder\n chart.to_svg('/results/' + filename + '.svg')\n\n\ndef combine_charts_to_grid(list_of_charts):\n grid = leather.Grid()\n grid.add_many(list_of_charts)\n return grid\n\n\ndef draw_grid(grid, filename):\n grid.to_svg('/results/' + filename + '.svg')\n\n\ndef collect_and_draw_important_data_per_id(driver_id, database):\n fav_op_data = filteroperations.preferred_opponent_by_driver_id(driver_id, database)\n favorite_opponent_column_chart = create_bar_chart_favorite_opponents(fav_op_data, driver_id)\n\n proportion_data = filteroperations.proportions_of_races_by_driver_id(driver_id, database)\n proportion_bar_chart = create_simple_bar_chart(proportion_data, 'Proportions of the tracked races', 'amount', '')\n\n bets_data = filteroperations.money_bets_over_timer_by_driver_id(driver_id=driver_id, database=database)\n bets_line_chart = create_simple_line_chart(bets_data, 'Trend of bets', 'race-ID', 'amount in €')\n\n grid_data = [favorite_opponent_column_chart, proportion_bar_chart, bets_line_chart]\n grid = combine_charts_to_grid(grid_data)\n draw_grid(grid, 'detailed_charts_' + driver_id)\n\n\ndef draw_drivers_by_wl_ratio(database):\n cursor = filteroperations.drivers_by_win_loss_ratio(database)\n draw_bar_chart_with_attributes(cursor, 'best_drivers_by_wl_ratio', '_id', 'win_loss_ratio',\n 'Best drivers by win loss ratio')\n\n\ndef draw_drivers_by_races_finished(database):\n cursor = filteroperations.drivers_by_finished_races(database)\n draw_bar_chart_with_attributes(cursor, 'best_drivers_by_races_finished', '_id', 'races_finished',\n 'Drivers by races finished')\n\n\ndef draw_drivers_by_decline_ratio(database):\n cursor = filteroperations.drivers_by_declined_races(database)\n draw_bar_chart_with_attributes(cursor, 'drivers_by_decline_ratio', '_id', 'decline_ratio',\n 'Drivers by decline ratio')\n\n\ndef draw_drivers_by_retire_ratio(database):\n cursor = filteroperations.drivers_by_retired_races(database)\n draw_bar_chart_with_attributes(cursor, 'drivers_by_retire_ratio', '_id', 'retire_ratio', 'Drivers by retire ratio')\n\n\ndef draw_drivers_by_earned_money(database):\n cursor = filteroperations.drivers_by_money_earned(database)\n draw_bar_chart_with_attributes(cursor, 'drivers_by_money_earned', '_id', 'money_earned', 'Drivers by money earned')\n\n\ndef draw_drivers_by_lost_money(database):\n cursor = filteroperations.drivers_by_money_lost(database)\n draw_bar_chart_with_attributes(cursor, 'drivers_by_money_lost', '_id', 'money_earned', 'Drivers by money lost')\n\n\ndef draw_drivers_by_deny_ratio(database):\n cursor = filteroperations.drivers_by_denied_races(database)\n draw_bar_chart_with_attributes(cursor, 'drivers_by_deny_ratio', '_id', 'deny_ratio', 'Drivers by deny ratio')\n\n\ndef draw_tracks_by_appearance(database):\n cursor = filteroperations.preferred_tracks_by_appearances(database)\n draw_bar_chart_with_attributes(cursor, 'tracks_by_appearance', '_id', 'count',\n 'Tracks by appearance over all races')\n\n\ndef evaluate_command(string_command):\n # checking for built-in methods\n if string_command == \"help\":\n print(\"The following commands are supported:\\n\"\n \"1) 'help': shows this help-page\\n\"\n \"2) 'drivers by win loss ratio': Creates a chart of the top ten drivers ordered by their win loss \"\n \"ratio with \"\n \"more than ten races driven\\n\"\n \"3) 'drivers by races finished': Creates a chart of the top ten (experienced) drivers by races \"\n \"finished.\\n \"\n \"4) 'drivers by decline ratio': Creates a chart of the top ten drivers by decline ratio.\\n\"\n \"5) 'drivers by retire ratio': Creates a chart of the top ten drivers by retire ratio.\\n\"\n \"6) 'drivers by money earned': Creates a chart of the top ten richest drivers.\\n\"\n \"7) 'drivers by money lost': Creates a chart of the top ten poorest drivers.\\n\"\n \"8) 'drivers by deny ratio': Creates a chart of the top ten drivers by deny ratio.\\n\"\n \"9) 'tracks by appearance': Creates a chart of the top ten most driven tracks. \\n\"\n \"10) 'driver details ' Creates a collection of charts for a specific driver. The driver-ID \"\n \"must be between 1 and 9999\\n\")\n elif string_command == \"drivers by win loss ratio\":\n draw_drivers_by_wl_ratio(db)\n elif string_command == \"drivers by races finished\":\n draw_drivers_by_races_finished(db)\n elif string_command == \"drivers by decline ratio\":\n draw_drivers_by_decline_ratio(db)\n elif string_command == \"drivers by retire ratio\":\n draw_drivers_by_retire_ratio(db)\n elif string_command == \"drivers by money earned\":\n draw_drivers_by_earned_money(db)\n elif string_command == \"drivers by money lost\":\n draw_drivers_by_lost_money(db)\n elif string_command == \"drivers by deny ratio\":\n draw_drivers_by_deny_ratio(db)\n elif string_command == \"tracks by appearance\":\n draw_tracks_by_appearance(db)\n elif \"driver details\" in string_command:\n driver_id_list = [int(s) for s in string_command.split() if s.isdigit()]\n try:\n driver_id = str(driver_id_list[0])\n collect_and_draw_important_data_per_id(driver_id, db)\n except IndexError:\n print(\"Please enter a valid driver-ID. \\n\")\n elif string_command == \"shutdown\":\n # Shutting down the loop!\n return False\n else:\n print(\n \"Sorry, the command could not be resolved. Be aware of upper-case and lower-case letters and try again.\\n\")\n\n return True\n\n\nprint(\"\\nWelcome to innobi, your way to go for the innotec code competition of july 2017! \"\n \"Please wait while the csv data is imported. \"\n \"After that you can inspect some interesting details of the data.\")\n# launch mongodb server\nsubprocess.Popen(['mongod', '--fork', '--logpath', '/results/mongod.log'], stdout=subprocess.DEVNULL)\nclient = MongoClient()\ndb = client.innobi\n# start import\nimport_csv_data(db)\n# start interactive shell\nworking = True\nprint(\"Hello! Please enter a command. Type 'help' to access the help-page and show possible commands.\\n\")\nwhile working:\n inputstring = input(\"$ \")\n working = evaluate_command(inputstring)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"612055758","text":"from flask import Flask, request, render_template, redirect, url_for\nfrom geopy.geocoders import Bing\nfrom geopy.exc import GeocoderTimedOut\nimport re\nimport urllib\nfrom bs4 import BeautifulSoup\n\n\npatterns = [\" st\", \"street\", \"ave\", \"avenue\", \"plz\", \"ctr\", \"park\", \"pl\", \" plaza \", \"way\", \"grn\", \"sq\", \"ln\", \"dr\",\n \"ct\", \"oval\", \"vlg\", \"blvd\", \"boulevard\", \" ter\", \"pkwy\", \"rd\", \"row\", \"hwy\", \"americas\", \"broadway\", '69th']\n \n \nold = ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', 'B9', 'C0', 'C1', 'C2', 'C3', 'C4',\n 'C5', 'C6', 'C7', 'C8', 'C9', 'D0', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'E1', 'E3', 'E4', 'E6',\n 'E7', 'E9', 'F1', 'F2', 'F4', 'F5', 'F8', 'F9', 'G0', 'G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'H1',\n 'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I9', 'J1', 'J2', 'J3',\n 'J4', 'J5', 'J6', 'J7', 'J8', 'J9', 'K1', 'K2', 'K3', 'K4', 'K5', 'K6', 'K7', 'K9', 'L1', 'L2', 'L3', 'L8', 'L9',\n 'M1', 'M2', 'M3', 'M4', 'M9', 'N1', 'N2', 'N3', 'N4', 'N9', 'O1', 'O2', 'O3', 'O4', 'O5', 'O6', 'O7', 'O8', 'O9',\n 'P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9', 'Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'R0',\n 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'RA', 'RB', 'RG', 'RH', 'RK', 'RP', 'RR', 'RS', 'RT', 'RW',\n 'S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S9', 'T1', 'T2', 'T9', 'U0', 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8',\n 'U9', 'V0', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8',\n 'W9', 'Y1', 'Y2', 'Y3', 'Y4', 'Y5', 'Y6', 'Y7', 'Y8', 'Y9', 'Z0', 'Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6', 'Z7', 'Z8',\n 'Z9']\n\nnew = ['R2', 'R2', 'R2', 'R2', 'R2', 'R2', 'R2', 'R2', 'R2', 'R2', 'R2', 'R2', 'R2', 'R2', 'LAC', 'MAC', 'LAC', 'LAC',\n 'ROS', 'R2', 'LAC', 'LAC', 'LAC', 'R2', 'LAC', 'LAC', 'MAC', 'MAC', 'MAC', 'MAC', 'MAC', 'MAC', 'MAC', 'MAC',\n 'ROS', 'ROS', 'ROS', 'GOV', 'ROS', 'ROS', 'ROS', 'ROS', 'ROS', 'ROS', 'ROS', 'ROS', 'R2', 'ROS', 'ROS', 'ROS',\n 'ROS', 'ROS', 'ROS', 'ROS', 'ROS', 'ROS', 'HOT', 'HOT', 'HOT', 'HOT', 'HOT', 'LAC', 'LAC', 'LAC', 'HOT', 'HOS',\n 'HOS', 'HOS', 'HOS', 'HOS', 'HOS', 'HOS', 'HOS', 'ROS', 'ROS', 'ROS', 'ROS', 'MALL', 'ROS', 'ROS', 'ROS', 'SCH',\n 'ROS', 'SOB', 'SOB', 'ROS', 'ROS', 'MALL', 'ROS', 'SOB', 'ACME', 'MAC', 'MAC', 'MAC', 'MAC', 'SCH', 'SCH', 'SCH',\n 'HOS', 'HOS', 'HOS', 'HOS', 'HOS', 'MALL', 'HOS', 'MOB', 'OBME', 'OBME', 'OBME', 'MOB', 'OBME', 'MOB', 'MOB',\n 'MOB', 'MALL', 'ROS', 'ROS', 'SCH', 'ROS', 'SCH', 'SCH', 'SCH', 'MIS', 'ROS', 'MIS', 'MIS', 'MIS', 'MALL',\n 'MALL', 'MALL', 'MALL', 'MALL', 'MAC', 'LAC', 'LAC', 'LAC', 'MAC', 'MAC', 'LAC', 'LAC', 'LAC', 'LAC', 'SCH',\n 'ROS', 'ROS', 'ROS', 'ROS', 'ROS', 'MAC', 'ROS', 'ROS', 'ROS', 'ROS', 'ROS', 'ROS', 'LAC', 'LAC', 'LAC', 'ROS',\n 'HOS', 'ROS', 'ROS', 'ROS', 'MIS', 'ROS', 'ROS', 'ROS', 'ROS', 'MIS', 'ROS', 'MIS', 'ROS', 'R2', 'R2', 'R2',\n 'R2', 'ROS', 'SCH', 'HOS', 'ROS', 'GOV', 'MIS', 'SCH', 'SCH', 'SCH', 'SCH', 'SCH', 'SCH', 'SCH', 'SCH', 'SCH',\n 'GOV', 'GOV', 'GOV', 'GOV', 'GOV', 'GOV', 'GOV', 'GOV', 'GOV', 'SCH', 'SCH', 'MIS', 'ROS', 'GOV', 'GOV', 'MIS',\n 'MIS', 'MIS', 'MIS'] \n \n \ngeolocator = Bing(\n 'vadrPcGdNLSX5bPNL7tw~ySbwhthllg7rNA4VSJ-O4g~Ag28cbu9Slxp5Sh_AsBDuQ9WypPuEhl9pHVPCAkiPf4A9FgCBf3l0KyQTKKsLCHw')\n\napp = Flask(__name__)\n\n\n@app.route(\"/app\")\ndef index():\n return \"\"\"
    \n \"Smiley\n

    Address Cleaning/Geocoding Tool


    \n
    \n

    \n

    Paste addresses into input box (1 address per line).

    \n

    After hitting submit, do not refresh the page. The page will reload when the\n software finishes.

    \n \n \n \n

    Created by: Harrison Leggio - Questions? Email Me

    \n \n
    \"\"\"\n \n \n@app.route(\"/app1\")\ndef index1():\n return \"\"\"
    \n \"Smiley\n

    Stop Rate Allowance Code Generator


    \n
    \n

    \n

    Paste addresses into input box (1 address per line).

    \n

    After hitting submit, do not refresh the page. The page will reload when the\n software finishes.

    \n \n \n \n

    Created by: Harrison Leggio - Questions? Email Me

    \n \n
    \"\"\"\n \n@app.route('/', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != 'zyp' or request.form['password'] != 'zyp':\n error = 'Invalid Credentials. Please try again.'\n else:\n return redirect(url_for('select'))\n return render_template('login.html', error=error)\n \n@app.route('/select')\ndef select():\n return \"\"\"
    \n \n \"Smiley\n


    \n
    \n \n
    \n\"\"\"\n\n@app.route('/results', methods=['POST'])\ndef process():\n choice = request.form['Item_1']\n if choice == 'Cleaning Tool':\n return redirect(url_for('index'))\n else:\n return redirect(url_for('index1'))\n \n\n\n@app.route(\"/clean\", methods=['POST'])\ndef dothing():\n addresses = request.form['addresses']\n return cleanAddress(addresses)\n \n@app.route(\"/building\", methods=['POST'])\ndef dothing1():\n addresses = request.form['addresses']\n return getBuilding(addresses)\n\n\ndef cleanAddress(addresses):\n addresses = addresses.split('\\n')\n cleaned = []\n success = 0\n fail = 0\n cleaned.append('
    \"Smiley

    ')\n\n for address in addresses:\n\n address = address.lower()\n address = re.sub('[^A-Za-z0-9]+', ' ', address).lstrip()\n \n if 'one' in address:\n address = address.replace('one', '1')\n if 'two' in address:\n address = address.replace('two', '2')\n if 'three' in address:\n address = address.replace('three', '3')\n if 'four' in address:\n address = address.replace('four', '4')\n if 'five' in address:\n address = address.replace('five', '5')\n if 'eight' in address:\n address = address.replace('eight', '8')\n if 'nine' in address:\n address = address.replace('nine', '9')\n if 'fith' in address:\n address = address.replace('fith', 'fifth')\n if 'aveneu' in address:\n address = address.replace('aveneu', 'avenue')\n if 'united states of america' in address:\n address = address.replace('united states of america', '')\n #print (address)\n \n i = 0\n for char in address:\n if char.isdigit():\n address = address[i:]\n break\n i += 1\n \n #print (address)\n \n if 'plz' in address:\n address = address.replace('plz', 'plaza ', 1)\n if 'hstreet' in address:\n address = address.replace('hstreet', 'h street')\n if 'dstreet' in address:\n address = address.replace('dstreet', 'd street')\n if 'hst' in address:\n address = address.replace('hst', 'h st')\n if 'dst' in address:\n address = address.replace('dst', 'd st')\n if 'have' in address:\n address = address.replace('have', 'h ave')\n if 'dave' in address:\n address = address.replace('dave', 'd ave')\n if 'havenue' in address:\n address = address.replace('havenue', 'h avenue')\n if 'davenue' in address:\n address = address.replace('davenue', 'd avenue')\n\n \n #print address\n \n regex = r'(.*)(' + '|'.join(patterns) + r')(.*)'\n address = re.sub(regex, r'\\1\\2', address).lstrip() + \" nyc\"\n \n \"\"\"for pattern in patterns:\n location = address.find(pattern)\n if location >= 0:\n address = address[:location + len(pattern)] + ' nyc'\n break\"\"\"\n print (address)\n \n \n\n try:\n \n clean = geolocator.geocode(address)\n x = clean.address\n address, city, zipcode, country = x.split(\",\")\n address = address.lower()\n if 'first' in address:\n address = address.replace('first', '1st')\n if 'second' in address:\n address = address.replace('second', '2nd')\n if 'third' in address:\n address = address.replace('third', '3rd')\n if 'fourth' in address:\n address = address.replace('fourth', '4th')\n if 'fifth' in address:\n address = address.replace('fifth', '5th')\n if ' sixth a' in address:\n address = address.replace('ave', '')\n address = address.replace('avenue', '')\n address = address.replace(' sixth', ' avenue of the americas')\n if ' 6th a' in address:\n address = address.replace('ave', '')\n address = address.replace('avenue', '')\n address = address.replace(' 6th', ' avenue of the americas')\n if 'seventh' in address:\n address = address.replace('seventh', '7th')\n if 'fashion' in address:\n address = address.replace('fashion', '7th')\n if 'eighth' in address:\n address = address.replace('eighth', '8th')\n if 'ninth' in address:\n address = address.replace('ninth', '9th')\n if 'tenth' in address:\n address = address.replace('tenth', '10th')\n if 'eleventh' in address:\n address = address.replace('eleventh', '11th')\n \n zipcode = zipcode[3:]\n cleaned.append((str(address) + \", \" + str(zipcode.lstrip()) +\n \", \" + str(clean.latitude) + \", \" + str(clean.longitude)) + '
    ')\n success += 1\n except AttributeError:\n cleaned.append('Can not be cleaned
    ')\n fail += 1\n except ValueError:\n cleaned.append('Can not be cleaned
    ')\n fail += 1\n except GeocoderTimedOut as e:\n cleaned.append('Can not be cleaned
    ')\n fail += 1\n \n total = success + fail\n percent = float(success) / float(total) * 100\n percent = round(percent, 2)\n cleaned.append('
    Accuracy: ' + str(percent) + ' %')\n cleaned.append('

    ')\n\n return \"\\n\".join(cleaned)\n \n \ndef getBuilding(addresses):\n addresses = addresses.split('\\n')\n types = []\n success = 0\n fail = 0\n types.append('
    \"Smiley

    ')\n\n for address in addresses:\n\n num, name = address.split(\" \", 1)\n newName = name.replace(\" \", \"+\")\n num = num.rstrip()\n newName = newName.rstrip()\n link = \"http://a810-bisweb.nyc.gov/bisweb/PropertyProfileOverviewServlet?boro=1&houseno=\" + (\n num) + \"&street=\" + (newName) + \"&go2=+GO+&requestid=0\"\n\n r = urllib.urlopen(link).read()\n soup = BeautifulSoup(r, \"html.parser\")\n try:\n classification = (soup.find(\"b\", text=\"Department of Finance Building Classification:\").find_next(\"td\").text)\n code = classification[:2]\n if code in old:\n pos = old.index(code)\n types.append(new[pos] + '
    ')\n success += 1\n else:\n types.append(\"Not found
    \")\n fail += 1\n except AttributeError:\n types.append('Not found
    ')\n fail += 1\n total = success + fail\n percent = float(success) / float(total) * 100\n percent = round(percent, 2)\n types.append('
    Accuracy: ' + str(percent) + ' %') \n types.append('

    ')\n return \"\\n\".join(types)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, host='0.0.0.0')\n \n","sub_path":"Rerouting/JointTools.py","file_name":"JointTools.py","file_ext":"py","file_size_in_byte":13414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"339189653","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files.\n\"\"\"\nimport csv\n\nfrom enum import auto, Enum\n\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\"\"\"\nTASK 3:\n(080) is the area code for fixed line telephones in Bangalore.\nFixed line numbers include parentheses, so Bangalore numbers\nhave the form (080)xxxxxxx.)\n\nPart A: Find all of the area codes and mobile prefixes called by people\nin Bangalore.\n - Fixed lines start with an area code enclosed in brackets. The area\n codes vary in length but always begin with 0.\n - Mobile numbers have no parentheses, but have a space in the middle\n of the number to help readability. The prefix of a mobile number\n is its first four digits, and they always start with 7, 8 or 9.\n - Telemarketers' numbers have no parentheses or space, but they start\n with the area code 140.\n\nPrint the answer as part of a message:\n\"The numbers called by people in Bangalore have codes:\"\n \nThe list of codes should be print out one per line in lexicographic order with no duplicates.\n\nPart B: What percentage of calls from fixed lines in Bangalore are made\nto fixed lines also in Bangalore? In other words, of all the calls made\nfrom a number starting with \"(080)\", what percentage of these calls\nwere made to a number also starting with \"(080)\"?\n\nPrint the answer as a part of a message::\n\" percent of calls from fixed lines in Bangalore are calls\nto other fixed lines in Bangalore.\"\nThe percentage should have 2 decimal digits\n\"\"\"\n\n\nclass PhoneType(Enum):\n Fixed = auto()\n Mobile = auto()\n Marketer = auto()\n\n\nfixed_prefix = '('\nbangalore_code = '080'\nmarketer_prefix = '140'\n\n\ndef parse_fixed_line(phone_number):\n return phone_number.split(')')[0][1:]\n\n\ndef classify_and_fetch_code(phone_number):\n if phone_number[0] == fixed_prefix:\n fixed_code = parse_fixed_line(phone_number)\n return PhoneType.Fixed, fixed_code\n elif phone_number[0:3] == marketer_prefix:\n return PhoneType.Marketer, marketer_prefix\n else:\n return PhoneType.Mobile, phone_number[0:4]\n\ncalls_from_bangalore = 0\ncalls_from_bangalore_to_bangalore = 0\ncodes_called_from_bangalore = set()\n\n\ndef is_bangalore(phone_type, code):\n return (phone_type == PhoneType.Fixed) and (code == bangalore_code)\n\n\nfor call in calls:\n caller = call[0]\n receiver = call[1]\n caller_type, caller_code = classify_and_fetch_code(caller)\n receiver_type, receiver_code = classify_and_fetch_code(receiver)\n if is_bangalore(caller_type, caller_code):\n calls_from_bangalore += 1\n codes_called_from_bangalore.add(receiver_code)\n if is_bangalore(receiver_type, receiver_code):\n calls_from_bangalore_to_bangalore += 1\n\nassert parse_fixed_line('(6788) 478-2444') == '6788'\nassert parse_fixed_line('(6) 478-2444') == '6'\n\nprint(\"The numbers called by people in Bangalore have codes:\")\nfor code in sorted(list(codes_called_from_bangalore)):\n print(code)\n\npercentage = calls_from_bangalore_to_bangalore / calls_from_bangalore * 100\nprint(f\"{percentage:4.4} percent of calls from fixed lines in Bangalore are calls \"\n f\"to other fixed lines in Bangalore.\")\n","sub_path":"Task3.py","file_name":"Task3.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"323557133","text":"import matplotlib.pyplot as plt\nfrom numpy.linalg import norm\nimport numpy as np\nfrom numpy import pi\nfrom scipy import interpolate,integrate\nfrom scipy.optimize import curve_fit\nfrom scipy.special import erf\nfrom scipy.optimize import anderson\nfrom scipy.optimize import root\nfrom pandas import read_csv\n\ndf = read_csv('imp_15a.dat', sep ='\\s+', header = None).T\n# df = read_csv('test.csv', sep =',', header = None).T\n\nt0 = df.iloc[0].values*1e-9\npulse0 = df.iloc[1].values\npulse = pulse0\nt = t0\n\nNmax = np.argmax(pulse)\nPulse = np.log(pulse[Nmax:])\nT = t[Nmax:]\nline = lambda t,alpha,b: -alpha*t + b \n\npopt = curve_fit(line, \n xdata=T,\n ydata=Pulse,\n p0=[2e6,0],\n )[0]\n\nplt.plot(T,Pulse)\nplt.plot(T,line(T,popt[0],popt[1]))\nalpha = popt[0] # 2096503.7683083578\nb = popt[1]\n\nc = 299792458\nR = 6370e3\ntheta = np.deg2rad(1.5)\ngamma = 2*np.sin(theta/2)**2/np.log(2)\n\n\nprint(alpha) # 2095703 Почти идеально\nice = lambda t, A, tau,sigma_l: A * (1 + erf( (t-tau)/sigma_l ))\npopt = curve_fit(ice, \n xdata=t[0:Nmax],\n ydata=pulse[0:Nmax]*2,\n p0=[(max(pulse) - min(pulse))/2,5e-11,6e-9],\n )[0]\nplt.figure()\nA = popt[0]\ntau = popt[1]\nsigma_l = popt[2]\n# plt.plot(t,ice(t,popt[0],popt[1],popt[2]))\n# plt.plot(t,pulse*2)\nice0 = A * np.exp(-alpha*(t-tau/2))* (1 + erf( (t-tau)/sigma_l ))\n# plt.plot(t, ice(t))\n# plt.show()\n\nN0max = np.argmax(ice0)\n\n# # # #############################################################\n# arg = np.max(np.argwhere(pulse < 0.01*np.max(pulse)))\n# left_edge = arg\n# for i in range(2,arg):\n# line = lambda t,T: T \n# popt = curve_fit(line, \n# xdata=t[0:i],\n# ydata=pulse[0:i],\n# p0=[0],\n# )[0]\n# if np.linalg.norm(pulse[0:i] - line(t[0:i],popt[0])) > 0.01:\n# left_edge = i\n# break\n\n# sigma_l = (t[Nmax] - t[left_edge])/3.5\n# print(sigma_l)\n\n\n\n\n# # ice = lambda t, A, tau,sigma_l: A * np.exp(-alpha*(t-tau/2))* (1 + erf( (t-tau)/sigma_l ))\n# # popt = curve_fit(ice, \n# # xdata=t[0:Nmax],\n# # ydata=pulse[0:Nmax]/max(pulse)*2,\n# # p0=[1,0,1e-8],\n# # )[0]\n# # plt.figure()\n# # print(popt)\n# # plt.plot(t,ice(t,popt[0],popt[1],popt[2]))\n# # plt.plot(t[:Nmax],pulse[:Nmax]/max(pulse)*2)\n# # plt.show()\n\n# # ########################## оптимизация по амплитуде\n# A = 1\n# sigma_c = sigma_l / np.sqrt(2)\n# tau = alpha * sigma_c**2\n# print('tau= ', tau)\n# print('sigma_l= ', sigma_l)\n\nbrown = lambda t,A,alpha,sigma: A*np.exp(-alpha*(t - alpha/2 * sigma**2))*(1 + erf( (t - alpha*sigma**2)/(2**0.5*sigma))) \nice = lambda t, A,alpha,tau,sigma_l: A * np.exp(-alpha*(t-tau/2)) * (1 + erf((t-tau)/sigma_l))\n\n\nt_true = t - t[Nmax] + t[N0max]\npopt = curve_fit(ice, \n xdata=t_true,\n ydata=pulse,\n p0=[A,alpha,tau,sigma_l],\n )[0]\n\n\n\n\n\nplt.figure(3)\nplt.plot(t,pulse)\n# y = brown(t, 1, alpha,sigma_c)\n# plt.plot(t,y)\ny = ice(t_true,popt[0],popt[1],popt[2],popt[3])\nplt.plot(t, y)\nplt.show()\n\n\n\n","sub_path":"project/rad_test.py","file_name":"rad_test.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"252186069","text":"from netgan.netgan import *\r\nimport tensorflow as tf\r\nfrom netgan import utils\r\nimport scipy.sparse as sp\r\nimport scipy\r\nimport numpy as np\r\nfrom sklearn.metrics import roc_auc_score, average_precision_score\r\nfrom scipy.sparse import (spdiags, SparseEfficiencyWarning, csc_matrix,csr_matrix, isspmatrix, dok_matrix, lil_matrix, bsr_matrix)\r\nfrom tqdm import tqdm\r\nimport time\r\nimport igraph as ig\r\nimport argparse\r\nimport warnings\r\nimport os\r\n\r\nprint(\"==================================================================================\")\r\nwarnings.filterwarnings(module='sklearn*', action='ignore', category=DeprecationWarning)\r\nwarnings.filterwarnings(module='numpy*', action='ignore', category=DeprecationWarning)\r\nwarnings.simplefilter('ignore', SparseEfficiencyWarning)\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--dir_name', type=str, default='', help='experiment dir name')\r\nopt = parser.parse_args()\r\nK = 50\r\nSMALLER_K = 45\r\n\r\n# =====================================\r\n# read facebook_combined social network\r\n# =====================================\r\nif os.path.exists(\"matrix/1youtube_SN.npz\"):\r\n print(\"*** loading dataset matrix ***\")\r\n youtube_SN = scipy.sparse.load_npz('matrix/youtube_SN.npz')\r\n _N = youtube_SN.shape[0]\r\n\r\nelse:\r\n data = np.loadtxt(\"OurData/facebook_combined.txt\")\r\n file = open(\"OurData/facebook_group.txt\")\r\n print(\"data shape: \", data.shape)\r\n\r\n\r\n G = ig.Graph()\r\n G.add_vertices(4039)\r\n edge_list = []\r\n weight_list = []\r\n\r\n for i in tqdm(range(data.shape[0])):\r\n n1 = int(data[i, 0])\r\n n2 = int(data[i, 1])\r\n # n1 and n2 are both in node_dict\r\n if (n1, n2) not in edge_list and (n2,n1) not in edge_list and n1!=n2:\r\n edge_list.append((n1, n2))\r\n weight_list.append(1.0)\r\n\r\n G.add_edges(edge_list)\r\n G.es['weight'] = weight_list\r\n\r\n\r\n youtube_SN = sp.csr_matrix(G.get_adjacency().data)\r\n youtube_SN = youtube_SN + youtube_SN.T\r\n youtube_SN[youtube_SN > 1] = 1\r\n span_N = youtube_SN.shape[0]\r\n lcc = utils.largest_connected_components(youtube_SN)\r\n # youtube_SN = youtube_SN[lcc,:][:,lcc]\r\n _N = youtube_SN.shape[0]\r\n _E = youtube_SN.sum()/2\r\n\r\n print(\"N: \", _N, \"// E: \", _E)\r\n\r\n # scipy.sparse.save_npz('matrix/youtube_SN.npz', youtube_SN)\r\n\r\n\r\nval_share = 0.15\r\ntest_share = 0.00\r\nseed = 481516234\r\ntrain_ones, val_ones, val_zeros, test_ones, test_zeros = utils.train_val_test_split_adjacency(\r\n\tyoutube_SN, val_share, test_share, seed, undirected=True, connected=True, asserts=True)\r\n\r\n\r\n# train_graph = sp.coo_matrix((np.ones(len(train_ones)),(train_ones[:,0], train_ones[:,1]))).tocsr()\r\ntrain_graph = youtube_SN\r\nassert (train_graph.toarray() == train_graph.toarray().T).all()\r\n\r\n# ======================================\r\n# Prepare the ground community\r\n# ======================================\r\nfile = open(\"OurData/facebook_group.txt\")\r\nlines = file.readlines()\r\nfile.close()\r\nnode_list = []\r\n\r\nfor i in range(193): # use top K communitys nodes\r\n lines[i] = lines[i].replace(\"\\n\", \"\").split(\"\\t\")\r\n lines[i] = lines[i][1:]\r\n node_list.append(lines[i])\r\n\r\nground_truth_community = np.zeros((train_graph.shape[0]))\r\nfor i in range(len(node_list)):\r\n for j in range(len(node_list[i])):\r\n ground_truth_community[int(node_list[i][j])] = i\r\n\r\n\r\nprint()\r\nprint()\r\nprint()\r\nprint()\r\nprint()\r\n\r\n\r\n# ===========================\r\n# fb train graph processing\r\n# ===========================\r\nwhile True:\r\n gra = train_graph.toarray()\r\n _N = gra.shape[0]\r\n print(\"############# Youtube social network #############\")\r\n print(\"*** train_graph shape: \", gra.shape)\r\n print(\"*** train graph edges: \", gra.sum())\r\n print(\"==================================================================================\")\r\n\r\n rw_len = 40\r\n batch_size = 16\r\n fb_walker = utils.RandomWalker(train_graph, rw_len, p=10, q=1, batch_size=batch_size)\r\n rws = fb_walker.walk().__next__()\r\n a = utils.score_matrix_from_random_walks(rws, _N).tocsr().toarray()\r\n a[a>1] = 1\r\n print(\"*** sample rw as train_graph shape: \", a.shape)\r\n print(\"*** sample rw as train_graph edges: \", a.sum())\r\n print(\"==================================================================================\")\r\n # input()\r\n\r\n break\r\n\r\n\r\n# # Source code setting\r\n# netgan = NetGAN(_N, rw_len, walk_generator= walker.walk, gpu_id=0, use_gumbel=True, disc_iters=3,\r\n# W_down_discriminator_size=128, W_down_generator_size=128,\r\n# l2_penalty_generator=1e-7, l2_penalty_discriminator=5e-5,\r\n# generator_layers=[40], discriminator_layers=[30], temp_start=5, learning_rate=0.0003)\r\n\r\n# # Coustom setting\r\n# netgan = NetGAN(_N, rw_len, \r\n# walk_generator_1=fb_walker.walk, privacy_walk_generator_1=None, \r\n# walk_generator_2=None, privacy_walk_generator_2=None, \r\n# walk_generator_3=None, privacy_walk_generator_3=None, \r\n# gpu_id=1, use_gumbel=True, disc_iters=3, noise_dim=rw_len,\r\n# W_down_discriminator_size=1024, W_down_generator_size=1024, batch_size=batch_size,\r\n# l2_penalty_generator=1e-7, l2_penalty_discriminator=5e-5,\r\n# generator_layers=[60], discriminator_layers=[60], temp_start=5, learning_rate=0.0003,\r\n# dir_name=opt.dir_name, legacy_generator=False, every_temperature=2000)\r\n\r\n\r\n# Paper setting\r\nnetgan = NetGAN(_N, rw_len, \r\n walk_generator_1=fb_walker.walk, privacy_walk_generator_1=None, \r\n walk_generator_2=None, privacy_walk_generator_2=None, \r\n walk_generator_3=None, privacy_walk_generator_3=None, \r\n gpu_id=2, use_gumbel=True, disc_iters=5, noise_dim=rw_len,\r\n W_down_discriminator_size=32, W_down_generator_size=64, batch_size=batch_size,\r\n l2_penalty_generator=1e-7, l2_penalty_discriminator=5e-5,\r\n generator_layers=[40], discriminator_layers=[30], temp_start=5, learning_rate=0.0003,\r\n dir_name=opt.dir_name, legacy_generator=False, every_temperature=500)\r\n\r\n\r\n\r\n\r\nstopping_criterion = \"val\"\r\n\r\nassert stopping_criterion in [\"val\", \"eo\"], \"Please set the desired stopping criterion.\"\r\n\r\nif stopping_criterion == \"val\": # use val criterion for early stopping\r\n stopping = None\r\nelif stopping_criterion == \"eo\": #use eo criterion for early stopping\r\n stopping = 0.5 # set the target edge overlap here\r\n\r\n#================\r\n# Train the model\r\n#================\r\n# eval_every = 58000\r\n# plot_every = 58000\r\n# eval_every = 9999\r\n# plot_every = 9999\r\neval_every = 2000\r\nplot_every = 2000\r\n# eval_every = 500\r\n# plot_every = 500\r\n# eval_every = 20\r\n# plot_every = 20\r\n\r\n# ===================================\r\n# Hyperparameter configurition\r\n# ===================================\r\n\r\n\r\n\r\n\r\n# log_dict = netgan.train(A_orig=_A_obs, val_ones=val_ones, val_zeros=val_zeros, stopping=stopping,\r\n# eval_every=eval_every, plot_every=plot_every, max_patience=20, max_iters=200000)\r\nlog_dict = netgan.train(A_orig=train_graph, val_ones=val_ones, val_zeros=val_zeros, stopping=stopping,\r\n eval_every=eval_every, plot_every=plot_every, max_patience=20, max_iters=25000,\r\n model_name=opt.dir_name, continue_training=False, K=K, SMALLER_K=SMALLER_K, evaluate=False\r\n , label=ground_truth_community)\r\n\r\nprint(log_dict.keys())","sub_path":"GSGAN/version4.5-fb/test_demo.py","file_name":"test_demo.py","file_ext":"py","file_size_in_byte":7511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"295531816","text":"import json\n\nimport soundcloud\n\nfrom .settings import soundcloud_settings\nfrom .post_to_reddit import init_post\n\n\ndef init_detection():\n client_id = soundcloud_settings.get('client_id')\n client_secret = soundcloud_settings.get('client_secret')\n redirect_uri = soundcloud_settings.get('redirect_uri')\n\n # create client object with app credentials\n client = soundcloud.Client(client_id=client_id,\n client_secret=client_secret,\n redirect_uri=redirect_uri)\n\n with open('data/tracks.json') as data_file:\n saved_tracks = json.load(data_file)\n\n artists = [\n {\n 'name': 'kanyewest',\n 'user_id': '174006135'\n },\n {\n 'name': 'octobersveryown',\n 'user_id': '1078461'\n },\n {\n 'name': 'lilb',\n 'user_id': '109965622'\n },\n {\n 'name': 'theweeknd',\n 'user_id': '3274725'\n },\n {\n 'name': 'macklemore',\n 'user_id': '557633'\n },\n {\n 'name': 'logic',\n 'user_id': '56873359'\n },\n\t{\n\t 'name': 'hiphopnewtracks',\n\t 'user_id': '183201121'\n\t}\n ]\n\n for artist in artists:\n new_track = client.get('/users/{}/tracks'.format(artist.get('user_id')), limit=1)[0]\n\n if str(new_track.id) not in saved_tracks['data']:\n print('Detected new track:')\n print(new_track.user.get('username') + ' - ' + new_track.title)\n save_new_track(new_track, saved_tracks)\n\n\ndef save_new_track(track, saved_tracks):\n new_track_dict = {'artist': track.user.get('username'), 'title': track.title}\n saved_tracks['data'][track.id] = new_track_dict\n username = track.user.get('username')\n\n title = '[FRESH] '\n if username != 'hiphopnewtracks':\n title += username\n title += ' - '\n title += track.title\n\n\n print('Saving new track to the database')\n with open('data/tracks.json', 'w') as data_file:\n json.dump(saved_tracks, data_file)\n\n new_track_data = {\n 'title': title,\n 'url': track.permalink_url\n }\n\n init_post(new_track_data)\n","sub_path":"libs/detect_changes.py","file_name":"detect_changes.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"249347561","text":"DEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n ('Angel Medrano', 'asmedrano@gmail.com'),\n )\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'SOMEDB', # Or path to database file if using sqlite3.\n 'USER': 'SOMEUSER', # Not used with sqlite3.\n 'PASSWORD': 'P455w0rd', # 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\nSTATIC_ROOT = '/path/to/static/'\nSTATIC_URL = 'http://yweb/static/'\n\nMEDIA_URL = STATIC_URL + \"media/\"\n\nXS_SHARING_ALLOWED_ORIGINS = \"http://127.0.0.1:8888\"\nSRC_FILE_STORAGE_PATH = '/tmp' #defaults to temp\nADDITIONAL_APPS = ()\nADDITIONAL_MIDDLEWARE_CLASSES=()\n\n","sub_path":"spoonmachine/local_settings.example.py","file_name":"local_settings.example.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"186973200","text":"import unittest\n\nfrom main.helpers.file import file_read_helper\n\n\nclass TestFileReadHelperMethods(unittest.TestCase):\n def test_get_dict_reader(self):\n header1, header2 = \"mac.vendor.part\", \"vendor\"\n value1, value2 = \"3c:d9:2b\", \"Hewlett Packard\"\n\n csv_file = '{},{}\\n{},\"{}\"'.format(header1, header2, value1, value2).splitlines()\n dict_reader = file_read_helper.get_csv_dict_reader(csv_file)\n\n field_names = [header1, header2]\n self.assertEqual(dict_reader.fieldnames, field_names)\n\n for row in dict_reader:\n self.assertEqual(row[header1], value1)\n self.assertEqual(row[header2], value2)\n\n def test_is_header(self):\n line_dict = {\n 0: True,\n 1: False\n }\n for key in line_dict:\n self.assertEqual(file_read_helper.is_header(key), line_dict[key])\n\n\nif __name__ == \"__main__\":\n suite = unittest.TestLoader().loadTestsFromTestCase(TestFileReadHelperMethods)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"backend/bin/test/test_helpers/test_file_helpers/test_file_read_helper.py","file_name":"test_file_read_helper.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"437976580","text":"from common import *\nimport pygame as p\nimport chess\nimport chess.pgn\nimport chess.svg\nimport time\n\n\n#board = chess.Board()\npgn = open(\"mygame.pgn\")\ngame = chess.pgn.read_game(pgn)\nboard = game.board()\n\n\np.init()\n\nscreen = p.display.set_mode((WIDTH, HEIGHT))\nscreen.fill(p.Color(\"white\"))\nclock = p.time.Clock()\nrunning = True\n#while running:\nfor move in game.mainline_moves():\n clock.tick(MAX_FPS)\n drawboard(screen)\n drawpieces(screen,board)\n board.push(move)\n p.display.flip()\n time.sleep(1)","sub_path":"movetrainer.py","file_name":"movetrainer.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"113081024","text":"# task_3.py\n# Задача к главе 2, под номером 3\n# Напишите проrрамму «Щедрый посетитель», в окно которой пользователь сможет ввести сумму счета за обед\n# в ресторане. Программа должна выводить два значения: чаевые из расчета 15 и\n# 20 % от указанной суммы.\n# pkuzmichev 15.04.2016\n\ninvoice_amount = int(input(\"Введите сумму счёта за обед: \"))\n\nfifteen_percent = invoice_amount / 100 * 15 # тут получаем 15 процентов от суммы\nprint(\"\\nЧаевые (15 процентов от суммы):\", fifteen_percent)\n\ntwenty_percent = invoice_amount / 100 * 20\nprint(\"\\nЧаевые (20 процентов от суммы):\", twenty_percent)\n\ninput(\"\\n\\nНажмите Enter, чтобы выйти.\")","sub_path":"chapter_2/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"284380488","text":"import flask\nfrom flask import Response, request, jsonify\nimport re, os\nimport json, xmltodict\n\n# local_modules\n\n# Modules for web technologies scanning\nfrom whatweb_tool import getDataFromWhatWeb\nfrom webtech_tool import getDataFromWebTech\n\n# Modules for subdomains scanning\nfrom sublist3r_tool import getDataFromSublist3r\n\n# Modules for directories/files scanning\nfrom gobuster_tool import getDirsFromGobuster, getFilesFromGobuster\n\n# Modules for domain information \nfrom whois_tool import getDataFromWhois\n\n# Modules which related to DNS\nfrom dig_tool import getDataFromDig\n\n# Modules for Server scanning\nfrom nmap_tool import getDataFromNmap\n\n# Modules for WAF scanning\nfrom wafw00f_tool import getDataFromWafw00f\n\n# Modules for CMS scanning\nfrom wpscan_tool import getDataFromWpscan\nfrom droopescan_tool import getDataFromDroopescan\nfrom joomscan_tool.joomscan_tool import getDataFromJoomscan\n# from joomscan_tool.parseHTML import getJsonData\n\n# Modules for Exploit DB\nfrom searchsploit_tool import getDataFromSearchsploit\n\n# Modules Web scanning with Nikto \nfrom nikto_tool import getDataFromNikto\n\napp = flask.Flask(__name__)\napp.config[\"DEBUG\"] = True\n\n# Web technologies scanning\n@app.route('/api/v1/enumeration/whatweb', methods=['GET'])\ndef whatweb_api():\n if 'url' in request.args:\n #Get cookie if it is defined\n try:\n cookie = request.args['cookie']\n except:\n cookie = None\n \n results = getDataFromWhatWeb(request.args['url'], cookie)\n\n contents = {}\n contents['technologies'] = []\n\n if (results):\n\n with open('whatweb_results.xml', 'r') as f:\n data = xmltodict.parse(f.read())\n \n # In case wrong URL or nothing return\n if (data['log'] == None):\n return jsonify(contents)\n else:\n\n # Delete key:value which un-needed\n try:\n # In case having many targets\n for i in range(0, len(data['log']['target'])):\n contents['technologies'] = contents['technologies'] + data['log']['target'][i]['plugin']\n\n # Remove duplicate technologies\n res_list = []\n for i in range(len(contents['technologies'])):\n if contents['technologies'][i] not in contents['technologies'][i + 1:]:\n res_list.append(contents['technologies'][i])\n \n # Assign res_list back again to contents\n contents['technologies'] = res_list\n return jsonify(contents)\n\n except: \n # In case having only one target\n contents['technologies'] = data['log']['target']['plugin']\n return jsonify(contents)\n else:\n return jsonify(contents)\n else:\n return jsonify('Define url parameter')\n\n@app.route('/api/v1/enumeration/webtech', methods=['GET'])\ndef webtech_api():\n if 'url' in request.args:\n # Check if URL has http|https\n rightFormat = re.search(\"^(http|https)://\", request.args['url'])\n\n contents = {}\n contents['technologies'] = []\n\n if (rightFormat):\n results = getDataFromWebTech(request.args['url'])\n if (results != \"Connection Error\"):\n contents['technologies'] = results.pop('tech')\n return jsonify(contents)\n else:\n return jsonify(contents)\n else:\n return jsonify(\"Please add 'http' or 'https' to url parameter\")\n else:\n return jsonify(\"Define url parameter\")\n\n\n# Subdomains scanning\n@app.route('/api/v1/enumeration/sublist3r', methods=['GET'])\ndef sublist3r_api():\n if 'url' in request.args:\n\n results = {}\n results['subdomains'] = []\n\n subdomains = getDataFromSublist3r(request.args['url'])\n\n if (len(subdomains) != 0) :\n results = {}\n results['subdomains'] = list(subdomains)\n return jsonify(results)\n else:\n return jsonify(results)\n else:\n return jsonify('Define url parameter')\n\n\n# Directories/files scanning\n@app.route('/api/v1/enumeration/gobuster', methods=['GET'])\ndef gobuster_api():\n\n\n #Check whether requests have url parameter\n if 'url' in request.args:\n \n #Check whether url parameter in right format\n rightFormat = re.search(\"^(http|https)://\", request.args['url'])\n\n #Get cookie if it is defined\n try:\n cookie = request.args['cookie']\n except:\n cookie = \"\"\n\n if (rightFormat):\n results_dirs = getDirsFromGobuster(request.args['url'], cookie)\n results_files = getFilesFromGobuster(request.args['url'], cookie)\n\n results = {}\n results['files'] = []\n results['directories'] = []\n\n if (results_dirs == 'wrong URL' and results_files == 'wrong URL'):\n return jsonify(results)\n\n else:\n if (results_dirs != 'wrong URL'):\n data = []\n directories = results_dirs.decode('UTF-8').strip().split('\\n\\r')\n for directory in directories:\n data.append(directory.strip())\n results['directories'] = data\n\n if (results_files != 'wrong URL'):\n data = []\n files = results_files.decode('UTF-8').strip().split('\\n\\r')\n for file in files:\n data.append(file.strip()) \n results['files'] = data\n\n return jsonify(results)\n else:\n return jsonify(\"Please add 'http' or 'https' to url parameter\")\n else:\n return jsonify('Define url parameter')\n\n\n# Domain information\n@app.route('/api/v1/enumeration/whois', methods=['GET'])\ndef whois_api():\n if 'url' in request.args:\n info = getDataFromWhois(request.args['url'])\n return jsonify(info)\n else:\n return jsonify('Define url parameter')\n\n\n# DNS information\n@app.route('/api/v1/enumeration/dig', methods=['GET'])\ndef dig_api():\n\n if 'url' in request.args:\n\n contents = getDataFromDig(request.args['url'])\n return jsonify(contents)\n\n else:\n return jsonify('Please fill in a specific url')\n\n\n# Server information\n@app.route('/api/v1/enumeration/nmap', methods=['GET'])\ndef nmap_api():\n if 'url' in request.args:\n results = getDataFromNmap(request.args['url'])\n\n contents = \"\"\n\n if (results != \"Can not get data from nmap\"):\n with open('nmap_results.txt','r') as f:\n # Load to dictionary again for post-processing\n contents = f.read() \n\n return contents\n else:\n return contents\n else:\n return jsonify('Define url parameter')\n\n\n# WAF scanning\n@app.route('/api/v1/enumeration/wafw00f', methods=['GET'])\ndef wafw00f_api():\n if 'url' in request.args:\n results = getDataFromWafw00f(request.args['url'])\n\n contents = {}\n contents['wafs'] = []\n\n if (results):\n with open('wafw00f.json','r') as f:\n tmp = json.loads(f.read())\n contents['wafs'] = tmp\n return jsonify(contents)\n else:\n return jsonify(contents)\n else:\n return jsonify('Define url parameter') \n\n\n# CMS scanning\n@app.route('/api/v1/enumeration/wpscan', methods=['GET'])\ndef wpscan_api():\n if 'url' in request.args:\n\n #Check whether url parameter in right format\n rightFormat = re.search(\"^(http|https)://\", request.args['url'])\n\n contents = {}\n \n if (rightFormat):\n\n #Get cookie if it is defined\n try:\n cookie = request.args['cookie']\n except:\n cookie = None\n\n results = getDataFromWpscan(request.args['url'], cookie)\n\n if (results):\n with open('wpscan.json', 'r') as f:\n contents = json.loads(f.read())\n return jsonify(contents)\n else:\n return jsonify(contents)\n else:\n return jsonify(\"Please add 'http' or 'https' to url parameter\")\n else:\n return jsonify('Define url paramter')\n\n@app.route('/api/v1/enumeration/droopescan', methods=['GET'])\ndef droopescan_api():\n if 'url' in request.args:\n\n results = getDataFromDroopescan(request.args['url'])\n \n contents = {}\n\n if (results != \"Can not get data from droopescan\"):\n try:\n contents = results.decode('utf-8')\n return jsonify(json.loads(contents))\n except:\n return jsonify({})\n else:\n return jsonify(contents)\n else:\n return jsonify('Define url paramter')\n\n@app.route('/api/v1/enumeration/joomscan', methods=['GET'])\ndef joomscan_api():\n if 'url' in request.args:\n\n results = getDataFromJoomscan(request.args['url'])\n\n contents = \"\"\n\n if (results):\n\n # Get path of reports\n path = '/root/python_tool/joomscan/reports/'\n reportFolder = os.listdir(path)[0]\n reportPath = os.path.join(path, reportFolder)\n\n # Read contents in report with extension is txt\n for reportFile in os.listdir(reportPath):\n if re.search(\"(.txt)$\", reportFile):\n\n with open(os.path.join(reportPath, reportFile), 'r') as f:\n contents = f.read()\n return contents\n else:\n return contents\n \n else:\n return jsonify('Define url paramter')\n\n\n# Search exploit from ExploitDB\n@app.route('/api/v1/enumeration/searchsploit', methods=['GET'])\ndef searchsploit_api():\n\n path = 'https://www.exploit-db.com/raw/'\n\n if 'pattern' in request.args:\n results = getDataFromSearchsploit(request.args['pattern'])\n contents = {}\n contents['RESULTS_EXPLOIT'] = []\n\n if (results):\n with open('searchsploit_results.json', 'r') as f:\n contents = json.loads(f.read())\n\n # Delete un-needed elements\n contents.pop('SEARCH')\n contents.pop('DB_PATH_EXPLOIT')\n contents.pop('DB_PATH_SHELLCODE')\n contents.pop('RESULTS_SHELLCODE')\n \n for i in range(0, len(contents['RESULTS_EXPLOIT'])):\n edb_id = contents['RESULTS_EXPLOIT'][i]['EDB-ID']\n contents['RESULTS_EXPLOIT'][i].pop('EDB-ID')\n contents['RESULTS_EXPLOIT'][i].pop('Path')\n contents['RESULTS_EXPLOIT'][i]['URL'] = path + edb_id\n\n return jsonify(contents)\n else:\n return jsonify(jsonify)\n else:\n return jsonify('Define url paramter')\n \n# Web scanning with Nikto \n@app.route('/api/v1/enumeration/nikto', methods=['GET']) \ndef nikto_api():\n if 'url' in request.args:\n rightFormat = re.search(\"^(http|https)://\", request.args['url'])\n\n contents = {}\n\n if (rightFormat):\n results = getDataFromNikto(request.args['url'])\n if (results):\n with open('nikto_results.json', 'r') as f:\n contents = json.loads(f.read()[::-1].replace(',','',2)[::-1])\n return jsonify(contents)\n else:\n return jsonify(contents)\n else:\n return jsonify(\"Please add 'http' or 'https' to url parameter\")\n else:\n return jsonify('Define url paramter')\n\napp.run(host='0.0.0.0', port=5000)\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":11929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"587194159","text":"##############\n## Logimage ##\n##############\n\nB = 0 # Case blanche\nN = 1 # Case noire\ninconnu = 2 # Case inconnue\n\nfrom copy import deepcopy \nimport numpy\nimport pylab\n\n\n##############################################\n##Programme principal : solveur de logimage ##\n##############################################\n\ndef resolution_logimage(L,C):\n \"\"\"Résoud le logimage dont la liste des contraintes sur les lignes\n est donnée dans L et la liste des contraintes sur les colonnes dans\n C.\"\"\"\n\n # Mesure de la taille du logimage\n n = taille(L,C)\n \n # Création des possibilités\n poss_lignes = possibilite_ligne(L,n)\n poss_colonnes = possibilite_colonne(C,n)\n T = creation_tableau_reponse(n) # Tableau initial rempli de 2 \n \n Image = backtrack(T,poss_lignes,poss_colonnes, L, C)\n\n print(Image[0]) # Image[0] est un booléen. Image[0] vaut True si\n # et seulement si il exite une solution au\n # logimage.\n\n if not Image[0]:\n return ('erreur')\n\n # Image[1] est le logimage complété \n return pylab.imshow(Image[1], cmap= 'gray_r', interpolation = 'nearest')\n\n\n#########################\n## Analyse du logimage ##\n#########################\n\n## Détermination de la taille du logimage :\n\ndef taille(L,C):\n \"\"\"Détermine la taille de la grille à remplir, \n et fait les ajustements nécéssaires à la résolution \n de logimages rectangulaires.\"\"\"\n nc = len(C)\n nl = len(L)\n if nc == nl:\n n = nc\n elif nc > nl: \n n = nc\n for i in range(nc-nl):\n L.append([0])\n else :\n n = nl\n for i in range (nl-nc):\n C.append([0])\n return n\n\n## Création d'une liste de possibilités\n\ndef possibilite(Indice,n):\n \"\"\"La fonction prend en arguments la liste des indices (contraintes)\n et la dimension de la ligne/colonne et renvoie une liste de listes\n de toutes les possibilités. On procède par récursivité.\n\n \"\"\"\n # Indice: liste d'indices de la ligne ou de la colonne\n # n: nombre de cases à remplir\n\n l = []\t# l: toutes les listes de solutions\n \n # Cas 1 : On a déjà travaillé sur toutes les cases, \n # le programme s'arrête. \n if n == 0: \n return [l] \n \n # Cas 2 : Quand on a déjà rentré toutes les cases noires\n # on complète les cases restantes en blanc.\n if len(Indice) == 0: \n return [[B]*n]\n \n # Cas 3 : On travaille sur le dernier indice à part \n if len(Indice) == 1: \n case_blanche = n - Indice[0]\n for k in range(case_blanche+1):\n l.append([B]*k + [N]*Indice[0] + [B]*(n-k-Indice[0])) \n # On place la (ou les) case(s) noire(s) dans toutes les \n # positions possibles et on complète avec les blanches. \n return l \n \n cases_imposees = sum(Indice) + len(Indice) - 1 \n # Correspond à l'ensemble des cases à colorier (noires) \n # et aux cases blanches imposées entre les noires\n cases_libres = n-cases_imposees\n \n # Cas 4 : Si on n'a pas de cases libres on crée l'unique possibilté\n if cases_libres == 0: \n a = [] \n for j in range(len(Indice)-1):\n a = a+[N]*Indice[j]+[B]\n a = a + [N]*Indice[-1]\n return [a]\n \n # Si toutes les conditions d'arrêt sont non vérifiées, \n # on rentre dans la boucle de récursivité.\n for i in range(cases_libres+1): \n m = n-(i+1+Indice[0])\t# Cases restantes après chaque boucle \n for p in possibilite(Indice[1:],m): \n l.append([B]*i+[N]*Indice[0]+[B]+ p) \n # On place les premières cases noires avec leur case \n # blanche imposée, et on répète la même opération \n # pour tous les indices.\n \n return l\n \n \n## Création des listes (pour les lignes et colonnes) \n## de toutes les possibilités pour le logimage.\n\n\ndef possibilite_ligne(L,n): # n = nombre de lignes, L = liste d'indices pour la ligne \n \"\"\"Crée la liste des possibilités pour chaque ligne. Chaque\n possibilité prend la forme d'une liste. Celles-ci sont elles-mêmes\n dans une liste pour une ligne donnée, et les liste obtenues pour\n chaque ligne sont elles mêmes stockées dans un tableau.\"\"\"\n\n poss_lignes = []\n for k in range (n):\n poss_lignes.append(possibilite(L[k],n))\n return poss_lignes\n \n\ndef possibilite_colonne(C,n): # n = nombre de colonnes, C = liste d'indices pour la colonne \n \"\"\"Crée la liste des possibilités pour chaque colonne. Chaque\n possibilité prend la forme d'une liste. Celles-csi sont elles-mêmes\n dans une liste pour une colonne donnée, et les liste obtenues pour\n chaque colonne sont elles mêmes stockées dans un tableau.\"\"\"\n\n poss_colonnes = []\n for k in range(n):\n poss_colonnes.append(possibilite(C[k],n))\n return poss_colonnes\n\n\n###################################\n## Remplissage du tableau réponse##\n###################################\n\ndef creation_tableau_reponse(n) :\n return inconnu*numpy.ones((n,n))\n \n##remplir les cases certaines dans le tableau réponse\n\ndef remplissage_cases_certaines(tableau_reponse, poss_lignes, poss_colonnes,n):\n \"\"\"Compare toutes les possibilités pour une même ligne \n et remplit le tableau si on trouve une case sûre, noire ou blanche.\"\"\"\n modif = False \t# Variable-drapeau qui permet de sortir de la boucle \n\t\t\t\t\t# finale si on n'a plus de modifications\n \n # On prend les différentes possibilités pour une même ligne\n for i in range (len(poss_lignes)):\n p = len (poss_lignes[i])\n for j in range(n):\n # On somme tous les éléments d'indice j des possibilités \n # pour une ligne donnée : \n # si on trouve p, il n'y a que des 1 donc la case est noire,\n # si on trouve 0, la case est blanche, \n # sinon, elle n'est pas certaine et on ne fait rien.\n S = sum(poss_lignes[i][k][j] for k in range (p))\n if S == p and tableau_reponse[i][j] == inconnu:\n tableau_reponse [i][j] = N \n modif = True\n \n elif S == 0 and tableau_reponse[i][j] == inconnu:\n tableau_reponse [i][j] = B\n modif = True\n \n # On répète l'opération sur les colonnes\n for j in range(len(poss_colonnes)) :\n p = len (poss_colonnes[j])\n for i in range(n):\n S = sum(poss_colonnes[j][k][i] for k in range (p))\n if S == p and tableau_reponse[i][j] == inconnu:\n tableau_reponse[i][j] = N\n modif = True\n \n elif S == 0 and tableau_reponse[i][j] == inconnu:\n tableau_reponse[i][j] = B\n modif = True\n \n return modif \n \n \n## Éliminer les listes de possibilités devenues fausses après un premier\n## remplissage\n \ndef elimination_possibilites(tableau_reponse, poss_lignes, \n\t\t\t poss_colonnes, n):\n \"\"\"On parcourt le tableau, si une case donnée est certaine, toutes\n les listes de possibilités ne possédant pas cette case sont\n éliminées.\"\"\"\n\n for i in range(n): \n for j in range(n): \n if tableau_reponse[i][j] != inconnu : \n\t\t# On ne traite pas les cases non sûres (inconnu)\n \n # On regarde toutes les lignes qui contiennent \n # la case considérée.\n Linter = [] # Liste intermédiaire qui va contenir \n # les possibilités conservées.\n for L in poss_lignes[i]: # L: toutes les possibilités \n\t\t # pour la ligne d'indice i.\n if L[j] == tableau_reponse[i][j]:\n Linter.append(L)\n poss_lignes[i] = deepcopy(Linter)\n \n # On répète la même opération avec les colonnes\n Linter = []\n for C in poss_colonnes[j]:\n if C[i] == tableau_reponse[i][j] :\n Linter.append(C)\n poss_colonnes[j] = deepcopy(Linter)\n \n \n##Vérification\n\ndef verif_ligne(tableau, indice, contraintes):\n \"\"\"Vérifie si une ligne du tableau est bien correctement complétée.\"\"\"\n j = 0\n n = len(tableau)\n for c in contraintes:\n nb_noirs = 0\n while j < n and tableau[indice][j] == B:\n j += 1 # On avance jusqu'à la prochaine séquence de noirs\n while j < n and tableau[indice][j] == N:\n nb_noirs += 1\n j += 1 # On compte le nombre de noirs de la séquence\n if nb_noirs != c or (j < n and tableau[indice][j] != B):\n return False # On vérifie qu'il est bon et que la séquence\n # de noirs est en bout de ligne ou suivie\n # d'un blanc.\n while j < n:\n if tableau[indice][j] == N:\n return False\n j += 1\n return True\n\ndef verif_colonne(tableau, indice, contraintes):\n \"\"\"Vérifie si une colonne du tableau est bien correctement complétée.\"\"\"\n i = 0\n n = len(tableau)\n for c in contraintes:\n nb_noirs = 0\n while i < n and tableau[i][indice] == B:\n i += 1 # On avance jusqu'à la prochaine séquence de noirs\n while i < n and tableau[i][indice] == N:\n nb_noirs += 1\n i += 1 # On compte le nombre de noirs de la séquence\n if nb_noirs != c or (i < n and tableau[i][indice] != B):\n return False\n while i < n:\n if tableau[i][indice] == N:\n return False # On vérifie qu'il est bon et que la séquence\n # de noirs est en bout de colonne ou suivie\n # d'un blanc.\n i += 1\n return True\n\ndef verif_logimage(tableau, L, C):\n \"\"\"Vérifie si le logimage est correctement complété.\"\"\"\n n = len(tableau)\n for i in range(n):\n if not verif_ligne(tableau, i, L[i]):\n return False\n if not verif_colonne(tableau, i, C[i]):\n return False\n return True\n\n\n##Backtracking\n\ndef meilleur_essai(L):\n \"\"\"Renvoie la plus petite liste de possibilités possédant au \n moins 2 possibilités.\"\"\"\n lignes_incertaines = [(i,len(L[i])) \\\n\t\t\t for i in range(len(L)) if len(L[i])!=1]\n # Recherche du minimum\n indice, minimum = lignes_incertaines[0]\n for i,m in lignes_incertaines:\n if m < minimum:\n indice, minimum = i, m\n return indice \n \n\ndef est_fini(tableau_reponse, n):\n \"\"\"Vérifie si le logimage est résolu.\"\"\"\n for i in range(n):\n for j in range(n):\n if tableau_reponse[i][j] == inconnu:\n return False\n return True\n\n\ndef erreur(poss_lignes, poss_colonnes, n):\n \"\"\"Détecte si une ligne donnée n'a plus de possibilité\"\"\"\n for i in range(n):\n if len(poss_lignes[i]) == 0:\n print(\"ligne\")\n print(\"i=\",i)\n return True\n if len(poss_colonnes[i]) == 0:\n print(\"i=\",i)\n return True\n return False\n\n\ndef backtrack(tableau_reponse, poss_lignes, poss_colonnes, L, C) :\n \"\"\"Construit le logimage à partir de la liste des possibilités de\n ligne et de colonnes. Si un choix est nécessaire, une méthode de\n backtracking permet d'explorer les différents choix et de retourner\n une solution correcte.\"\"\"\n\n # Le résultat prend la forme d'un couple constitué d'un booléen\n # représentant la validité de la solution et du tableau complété.\n n = taille(poss_lignes, poss_colonnes)\n er = erreur(poss_lignes, poss_colonnes, n)\n \n changement = True\n \n while not er and changement :\n changement = remplissage_cases_certaines(tableau_reponse, \n\t\t\t\t\t\t poss_lignes, poss_colonnes, n)\n elimination_possibilites(tableau_reponse, poss_lignes, \n\t\t\t\t poss_colonnes,n)\n er = erreur(poss_lignes, poss_colonnes, n)\n \n if est_fini(tableau_reponse, n):\n print(tableau_reponse)\n if verif_logimage(tableau_reponse, L, C):\n return (True, tableau_reponse)\n else:\n return (False, tableau_reponse)\n \n elif not er:\n print('backtrack')\n rang_essais = meilleur_essai(poss_lignes)\n essais = poss_lignes[rang_essais]\n for es in essais:\n print('r=',rang_essais)\n print('es =',es)\n t = deepcopy(tableau_reponse)\n l = deepcopy(poss_lignes)\n c = deepcopy(poss_colonnes)\n l[rang_essais] = [es]\n\n remplissage_cases_certaines(t, l, c, n)\n elimination_possibilites(t, l, c, n)\n \n print(\"t=\",t)\n b = backtrack(t, l, c, L, C)\n if b[0]:\n return b\n return (False, tableau_reponse) \n \n#########################\n## Logimage à résoudre ##\n#########################\n\n# Indices du logimage \nC1=[[2],[1,1,1],[2,1],[1,1,1],[2]]\nL1=[[3],[1],[1,1],[1,1],[5]]\n\n#Truc à pattes\nC2 = [[1],[5],[1,2],[3],[2]]\nL2 = [[3],[1,1],[4],[3],[1,1]]\n\n#Chateau\nC3 = [[3],[1,9],[6,7],[4,4,2,1],[6,4,1],[1,1,9],[6,3],[2,1,5],[2,9],[2,1,2,5],[12],[1,1,4,1],[9,2,1],[15],[1,3]]\nL3 =[[1,2],[3,1,4],[5,3,2],[3,2,2,2],[1,3,1,4],[3,5,2],[6,1,1,2],[1,1,6,2],[15],[3,2,2,2,2],[15],[13],[2,2,3,1],[2,1,2,1],[5,5]]\n\n#Abeille\nC4 = [[5,3],[8,4,1,1],[9,9],[9,4,1,2],[13],[5,4],[17],[9,4,4],[8,5,1],[5,6,2],[6,4],[2,2,8,1],[4,6,2],[7,4],[2,2,6,1],[3,7,2,2],[6,5],[6],[5,2,2],[3,6]]\nL4 = [[2,3,1,1],[4,5,2,2],[4,5,1,1],[4,5,1,2],[4,5,2,1],[4,5,1,4],[3,3,7],[4,3,9],[3,2,11],[2,1,10],[4,9],[15],[14,1],[12,1,2],[5,1,1,2,2,1],[1,1,1,2,2,1,1],[4,2,2,1,1,1],[1,1,1,1,1,1,1],[4,1,1,4,2],[3,2,2,1,1]]\n\n#Tests (à ne pas utiliser car ne marchent pas)\nC5=[[1,1,1,1,5],[1,1,1,1,5],[1,1,1,1,5],[1,1,1,1,3],[1,1,1,1,3],[1,1,1,1,1],[1,1,1,1,2,1],[1,1,1,1,5,1,2],[1,1,1,1,7,1,2],[1,1,1,1,11,2],[1,1,1,1,12,3],[6,13,5],[2,13,5],[2,15,6],[4,24],[29],[29],[2,25],[11,12],[4,3,10],[2,6,9],[6,8],[2,6],[2,5],[3,4],[2,4],[4],[2],[1],[1]]\nL5 =[[12,3],[1,5],[17,1],[10],[12,8],[1,5],[11,7],[8],[10],[12],[14],[12,2],[12,2],[12,2],[11,3],[12,4],[11,3],[3,12,3],[5,14,2],[30],[5,14],[3,12],[12],[10],[9],[9],[7],[7],[6],[5],[6],[6]]\n\nC6 = [[3],[1,9],[6,7],[3,4,2,1],[6,4,1],[1,1,9],[6,3],[2,1,5],[2,9],[2,1,2,5],[12],[1,1,4,1],[9,2,1],[15],[1,3]]\nL6 =[[2],[3,1,4],[5,3,2],[3,2,2,2],[1,3,1,4],[3,5,2],[6,1,1,2],[1,1,6,2],[15],[3,2,2,2,2],[15],[13],[2,2,3,1],[2,1,2,1],[5,5]]\n\n#pégase\nLpegase =[[11],[11],[10],[9,1],[8,3],[8,5],[7,7],[7,9],[5,5,2],[9],[13],[16],[2,14],[2,14],[3,14],[2,15],[2,4,5],[3,4,3],[2,5,1,1],[2,2,1,1],[1,2,2,1],[1,2,2],[1,1],[2,2],[2,2]]\nCpegase =[[1,2],[1,5],[2,6],[2,4],[3,1],[3,5,6],[4,10,2],[6,9,1],[8,11],[9,12],[9,6,3],[15,2],[15,1],[14],[5,7],[8],[10],[11],[12,1],[6,6],[4,2,1],[5,5],[3],[3],[2]]\n\n\n#Totoro\nLtotoro=[[3,3],[3,3],[4,4],[4,4],[11],[13],[2,5,2],[1,1,3,1,1],[3,2,2,3],[15],[15],[6,6],[4,3,4],[3,3],[3,2,2,3],[2,2],[2,2],[3,3],[2,2],[3,3]]\nCtotoro=[[7],[12],[10,3],[7,5,1],[6,3,1],[6,1,3,1],[5,3],[7,1],[4,2,1],[7,1],[5,3],[6,1,3,1],[6,3,1],[7,5,1],[10,3],[12],[7]]\n \n#backtrack\nL=[[2,1,1],[1,1],[2],[1,1,1,1],[1,1,1,1,1,1],[1,1,1,1],[2,1,1,1],[1,3,1],[1,1,1,1],[2,1,1,1,3],[1,1,1,1],[1,3,1],[1,1,1,1],[1,1],[1,9]]\nC=[[9],[1,1,1,1],[1],[1,1,1,1],[6,3],[1,1],[1,1,1],[1,1,1,1,1],[1,1,6,1],[1,1,1,2],[1,1],[1,1,1],[1,9],[1,1],[1]]\n\n#Nouveau Backtraking \nLb=[[1,1],[1,3,1],[1],[2,2],[3,2],[3,1,1],[1,1,1],[1,2,2],[1,3,1],[1,1,2,2]]\nCb=[[2,1,3],[1,1],[1,1,2,2],[1,1,1],[1,1,1,1],[4,1,1],[1,2,1],[1,1,1],[1,1,1,1],[1,1,1]]\n\n#3eme essai\nLg = [[1],[2,1],[],[2,1],[2,1],[1,1,1],[1,1,1],[1,1],[1,1,1,1],[1,1,1,1]]\nCg = [[1,1,2],[1],[1,1,2,2],[1],[1,1,1],[2],[2,1],[1,1],[1,1],[1,1]]\n\nLmarylin = [[9],[7,1],[5,2,2],[4,2,4,10],[3,1,7,4],[2,2,4,2],[2,4,3,2],[2,4,2,3],[1,3,2,2,3],[1,2,4,2],[1,2,1],[1,1,1],[1,1,6,8],[3,3,3,2],[2,3,2,1],[1,1,7,7,1],[2,1,2,1,2,2],[3,3,6,7,1],[5,6,1,1,8],[8,1,1,1,5],[3,1,1,1,1],[1,3,1],[1,7,1],[3,3,4,1],[2,3,2,2,1,1],[2,5,1,2],[3,2,2,1,3,4,1],[4,2,2,1,10,1],[1,3,3,1,3,3,2],[2,6,1,8,1],[3,3,2,6,2],[4,4,4,3,1],[14,7],[12,2,2,5],[12,9,5]]\n\n#Marylin Monroe\nCmarylin = [[13,14],[8,2,5,6],[5,3,2,3,5],[4,2,1,3,4],[3,3,1,2,2,3],[2,2,1,4,2,3],[2,5,2,1,2,3],[1,10,4,2,3,3],[1,5,2,7,5,3],[3,2,4,1,3,4],[3,1,2,3,2,5],[6,1,1,3,11],[2,2,1,1,2,2],[1,1,2,1,3,2,2],[3,1,4,1,4,2],[4,2,3,1,5,1],[6,6,1,2,3,1],[3,1,2,1,3,1],[2,2,2,3,1],[1,6,1,2,3,1],[2,4,5,1],[1,3,1,4,1],[1,2,1,2,1,2,2],[1,2,1,2,2],[1,1,1,4,2],[2,1,1,3,4],[3,1,2,2,5],[6,1,1,3,3,3],[3,4,2,3,4,3],[3,9,1,4,4]]\n\n#Crabe\nLcrabe = [[1],[2],[3],[4,2,2],[6,4],[3,3],[6,2],[2,2],[2,1,1,2],[4,2,2,2],[1,2,1,4,2],[1,1,9,4],[14,2,2],[2,12,2,1],[2,1,10,2,3],[1,15,1],[2,11,4,1],[2,14,3],[1,2,15,1],[1,2,9,2,2,1],[1,3,3],[1,1],[1,1],[1]]\n\nCcrabe = [[2,3],[1,2,2],[2,2,2,5],[2,1,2,3],[2,1,1,1],[2,2,4],[3,10],[6,8],[4,11],[2,1,9],[2,1,1,10],[2,1,12],[1,12],[1,1,11],[2,9],[3,2,10],[11,1,1,3],[7,1,1,1,2],[2,1,1,1],[1,1,1,2],[1,1,2,2,1],[2,2,2,3],[3,2,2],[1]]\n\n \n##Appel automatique de la fonction\nresolution_logimage(Lg,Cg)\npylab.show()\n\n","sub_path":"Logigi.py","file_name":"Logigi.py","file_ext":"py","file_size_in_byte":17283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"185004814","text":"from django.shortcuts import render, get_object_or_404\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom django.urls import reverse\r\n\r\nfrom .models import Product\r\nfrom django.template import loader, RequestContext\r\n\r\nimport json\r\nfrom django.http import JsonResponse\r\n\r\n# Create your views here.\r\ndef index(request):\r\n # Get all 5 latest questions from the database\r\n latest_products = Product.objects.order_by('-pub_date')[:5]\r\n\r\n # Get needed template\r\n # template = loader.get_template('polls/index.html')\r\n\r\n # To parse variables to an html file\r\n context = {\r\n 'latest_products': latest_products,\r\n }\r\n\r\n # Render the page by request, page, and which variables to parse\r\n return render(request, 'products/index.html', context)\r\n\r\n # To return html file as a response by request\r\n # return HttpResponse(template.render(context, request))\r\n\r\ndef validate_category(request):\r\n selected = request.GET.get('category_id', None)\r\n\r\n file = open('categories.json')\r\n json_string = file.read()\r\n file.close()\r\n data = json.loads(json_string)\r\n MY_CHOICES = ()\r\n MY_SECOND_CHOICES = ()\r\n\r\n print(selected)\r\n\r\n for categories in data['categories']:\r\n for category in categories['category']:\r\n MY_CHOICES += (category['categorie_id'], category['name']),\r\n print('ID: ' + category['categorie_id'] + ' - Name: ' + category['name'])\r\n if category['categorie_id'] == selected:\r\n for child in category['children']:\r\n MY_SECOND_CHOICES += (child['categorie_id'], child['name']),\r\n print(child)\r\n\r\n data = {\r\n 'children': MY_SECOND_CHOICES\r\n }\r\n\r\n return JsonResponse(data)\r\n","sub_path":"test/apps/products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"548957936","text":"import grpc\nimport image_pb2_grpc\nimport image_pb2\nfrom concurrent import futures\nimport cv2\nfrom main import detect, image_utils, firebase\nimport base64\nimport uuid\nimport time\nimport queue\n\nFRAME_PER_PROCESS = 10\nRESIZE_FACTOR = 4\n\nlabels_path = \"..\\yolo-custom\\obj.names\"\nweights_path = \"..\\yolo-custom\\yolov4-tiny-custom_final_mask.weights\"\nconfig_path = \"..\\yolo-custom\\yolov4-tiny-custom-mask.cfg\"\ndetect = detect.FaceRecognition(weights_path, config_path, labels_path)\nfirebase_object = firebase.FireBase(\n '..\\..\\strangerdetection-firebase-adminsdk-ndswy-371433d43f.json',\n 'strangerdetection.appspot.com')\n\ndetect.set_encodings(firebase_object.get_all_encoding_value())\n\n\n\n\ndef process_frame(frame):\n small_frame = cv2.resize(frame, (0, 0), fx=1/RESIZE_FACTOR, fy=1/RESIZE_FACTOR)\n result, face_encodings = detect.process_image(small_frame)\n return result, face_encodings\n\n\ndef draw_frame(frame, detect_info):\n for result in detect_info:\n (top, right, bottom, left) = result['face_location']\n match = result['match']\n # Scale back up face locations since the frame we detected\n top *= RESIZE_FACTOR\n right *= RESIZE_FACTOR\n bottom *= RESIZE_FACTOR\n left *= RESIZE_FACTOR\n # Draw a box around the face\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 label = \"Known\" if match else \"Unknown\"\n cv2.putText(frame, label, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n return frame\n\n\nclass ProcessImageService(image_pb2_grpc.ProcessImageServicer):\n def __init__(self, pool):\n super(ProcessImageService, self).__init__()\n self.pool = pool\n\n def ProcessImage(self, request, context):\n video_capture = cv2.VideoCapture(0)\n if not video_capture.isOpened():\n print(\"Cannot open camera\")\n exit()\n i = 0\n while True:\n ret, frame = video_capture.read()\n if i % FRAME_PER_PROCESS == 0:\n result, face_encodings = process_frame(frame)\n i += 1\n frame = draw_frame(frame, result)\n small_frame = cv2.resize(frame, (0, 0), fx=1/RESIZE_FACTOR, fy=1/RESIZE_FACTOR)\n encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]\n success, code = cv2.imencode('.jpg', small_frame, encode_param)\n base64_string = str(base64.b64encode(code))[2:-1]\n yield image_pb2.ProcessImageReply(image=base64_string, result=str(result))\n\n def CreateEncoding(self, request, context):\n user_email = request.user_email\n image_base64_string = request.image\n image_array = image_utils.parse_b64_string_to_image_array(image_base64_string)\n encoding = detect.get_encoding(image_array)\n image_name = str(uuid.uuid4()) + '.png'\n encoding_data = {'encoding': encoding.tolist(),\n 'user_email': user_email,\n 'image_name': image_name}\n firebase_object.upload_image(image_name, image_array)\n firebase_object.create_encoding(encoding_data)\n return image_pb2.CreateEncodingReply(encoding=encoding, user_email=user_email, image_name=image_name)\n\n def DeleteEncoding(self, request, context):\n image_name = request.image_name\n encodings = firebase_object.delete_encoding_by_image_name(image_name)\n for encoding in encodings:\n detect.remove_encoding(encoding)\n return image_pb2.DeleteEncodingReply(count=len(encodings))\n\n\ndef serve():\n pool = futures.ThreadPoolExecutor(max_workers=16)\n servicer = ProcessImageService(pool)\n server = grpc.server(pool)\n server.add_insecure_port('[::]:50052')\n image_pb2_grpc.add_ProcessImageServicer_to_server(\n servicer=servicer, server=server\n )\n server.start()\n server.wait_for_termination()\n\n\nif __name__ == '__main__':\n # detect.set_encodings(firebase_object.get_all_encoding_value())\n # print(firebase_object.get_image_access_url(\"214c9708-b8e3-4238-bde0-a9aaccb29d30.png\"))\n serve()\n","sub_path":"grpc_test/grpc_server.py","file_name":"grpc_server.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"172317180","text":"from django.conf.urls import patterns, include, url\nfrom .views import *\n\nurlpatterns = patterns('frame_game.views',\n #url(r'frame/(?P\\d+)/$', 'one_frame', name='OneFrame'),\n url(r'^pl_list/$', players_list, name='Players_list'),\n url(r'^pl_profile/(?P\\d+)/$', plr_profile, name='Players_profile'),\n url(r'^$', home, name='Home_fg'),\n url(r'^play/$', game, name='Play'),\n\n\n\n)\n\n","sub_path":"frame_game/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"112523481","text":"import numpy as np\nfrom sklearn.cluster import MeanShift, estimate_bandwidth\nfrom sklearn.decomposition import PCA\nfrom a_lib import *\n\n\n# Get Data\nDataID = 'a01'\n\necg, sqrs125, wavedet_ = get_ecg_sqrs125_wavedet(DataID, 5)\nQRS = wavedet_\nfeatures_list, _ = get_feature(QRS, ecg)\n\n#根据IntervalSum去除时间异常,根据Height去除高度异常\noutlier_list = []\nfor idx, val in enumerate(features_list):\n outlier_list.append([sum(val), val[0], val[1:]])\n# IntervalSum 排序\noutlier_list.sort()\nmargin = int(len(outlier_list)/1000)\noutlier_list = outlier_list[margin: -margin]\n# Height 排序\noutlier_list.sort(key=lambda x:x[1])\nmargin = int(len(outlier_list)/1000)\noutlier_list = outlier_list[margin: -margin]\n\nnew_features_list = []\nfor val in outlier_list:\n new_features_list.append([val[1], val[2][0], val[2][1]])\n\n#\n\n\n#算出坐标\nnew_features_list = np.array(new_features_list)\nX = new_features_list[:,1]*10\nY = new_features_list[:,2]*10\nZ = new_features_list[:,0]\n\n\n# 绘制散点图\nfig = plt.figure()\nax = Axes3D(fig)\nm_sactter = ax.scatter(X, Y, Z, c=Z, cmap=plt.get_cmap('rainbow'), s=1)\nfig.colorbar(m_sactter, shrink=0.5)\nax.set_xlim(0, 1.1*X.max())\nax.set_ylim(0, 1.1*Y.max())\nax.set_zlim(1.1*Z.min(), 1.1*Z.max())\n# ax.plot(Y, Z, 'k.', zdir='x', zs=1.1*X.max())\n# ax.plot(X, Z, 'k.', zdir='y', zs=1.1*Y.max())\n# ax.plot(X, Y, 'k.', zdir='z', zs=1.1*Z.min())\n\n\n# ax.legend(loc='best')\n \nax.set_zlabel('Z')\nax.set_ylabel('Y')\nax.set_xlabel('X')\nax.view_init(90, 270)\n# ax.view_init(30, 270-45)\n# ax.view_init(30, 45)\n\nplt.show()\n\npass","sub_path":"preprocessing_PT/simply_visual_Poincaré_Height.py","file_name":"simply_visual_Poincaré_Height.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"645574459","text":"# Copyright (c) 2013, Myme and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\n\ndef execute(filters=None):\n\tcolumns, data = [], []\n\t\n\tcolumns = []\n\tselect_field = \"\"\n\tgroup_clause = \"\"\n\torder_clause = \"\"\n\tleft_join = \"\"\n\tif filters.get(\"group_by\") == \"Customer\" :\n\t\tcolumns = [\"Customer:Link/Customer:100\",\"Item Code:Link/Item:100\",\"Colour:Data:100\",\"Qty Pending Order:Float:150\",\"Qty Sisa di Pending Order:Float:200\",\n\t\t\t\"Qty Teralokasi:Float:150\"]\n\t\tselect_field = \" po.`customer`,por.`item_code_roll`,por.`colour`,por.`roll_qty`,por.`qty_sisa`,por.`qty_dialokasi` \"\n\t\torder_clause = \" ORDER BY po.`customer` \"\n\telif filters.get(\"group_by\") == \"Item\" :\n\t\tcolumns = [\"Item Code:Link/Item:100\",\"Colour:Data:100\",\"Qty Pending Order:Float:150\",\"Qty Sisa di Pending Order:Float:200\",\n\t\t\t\"Qty Teralokasi:Float:150\"]\n\t\tselect_field = \" por.`item_code_roll`,por.`colour`,por.`roll_qty`,por.`qty_sisa`,por.`qty_dialokasi` \"\n\t\tiorder_clause = \" ORDER BY por.`item_code_roll` \"\n\telif filters.get(\"group_by\") == \"Colour\":\n\t\tcolumns = [\"Colour:Data:100\",\"Item Code:Link/Item:100\",\"Qty Pending Order:Float:150\",\"Qty Sisa di Pending Order:Float:200\",\n\t\t\t\"Qty Teralokasi:Float:150\"]\n\t\tselect_field = \" por.`colour`,por.`item_code_roll`,por.`roll_qty`,por.`qty_sisa`,por.`qty_dialokasi` \"\n\t\torder_clause = \" ORDER BY por.`colour` \"\n\telif filters.get(\"group_by\") == \"Pending Order\" :\n\t\tcolumns = [\"Pending Order No.:Link/Pending Order:100\",\"Item Code:Link/Item:100\",\"Colour:Data:100\",\"Qty Pending Order:Float:150\",\"Qty Sisa di Pending Order:Float:200\",\n\t\t\t\"Alokasi No.:Link/Alokasi Barang:100\",\"Qty Alokasi:Float:100\"]\n\t\tselect_field = \" po.`name`,por.`item_code_roll`,por.`colour`,por.`roll_qty`,por.`qty_sisa`,ab.`name`,abd.`roll_qty` \"\n\t\tleft_join = \"\"\" LEFT JOIN `tabAlokasi Barang`ab ON ab.`pending_order`=po.`name` AND ab.`docstatus`=1\n\t\t\tLEFT JOIN `tabAlokasi Barang Data`abd ON ab.`name`=abd.`parent` \n\t\t\tAND abd.`item_code_roll`=por.`item_code_roll` AND abd.`colour`=por.`colour` \"\"\"\n\t\torder_clause = \" ORDER BY po.`name` \"\n\telse :\n\t\treturn [],[]\n\t\n\tpo_clause = \"\"\n\tif filters.get(\"pending_order\") :\n\t\tpo_clause = \"\"\" AND po.`name`=\"{0}\" \"\"\".format(filters.get(\"pending_order\"))\n\t\n\titem_clause = \"\"\n\tif filters.get(\"item\") :\n\t\titem_clause = \"\"\" AND por.`item_code_roll`=\"{0}\" \"\"\".format(filters.get(\"item\"))\n\t\n\tcustomer_clause = \"\"\n\tif filters.get(\"customer\") :\n\t\tcustomer_clause = \"\"\" AND po.`customer`=\"{0}\" \"\"\".format(filters.get(\"customer\"))\n\t\n\tcolour_clause = \"\"\n\tif filters.get(\"colour\") :\n\t\tcolour_clause = \"\"\" AND por.`colour`=\"{0}\" \"\"\".format(filters.get(\"colour\"))\n\t\n\t\n\tdelivery_clause = \"\"\n\tif filters.get(\"delivery_from_date\") and filters.get(\"delivery_to_date\"):\n\t\tdelivery_clause = \"\"\" AND po.`expected_delivery_date` BETWEEN \"{0}\" AND \"{1}\" \"\"\".format(filters.get(\"delivery_from_date\"),filters.get(\"delivery_to_date\"))\n\t\n\tdate_clause = \"\"\n\tif filters.get(\"posting_from_date\") and filters.get(\"posting_to_date\"):\n\t\tdelivery_clause = \"\"\" AND po.`posting_date` BETWEEN \"{0}\" AND \"{1}\" \"\"\".format(filters.get(\"posting_from_date\"),filters.get(\"posting_to_date\"))\n\t\n\tdata = frappe.db.sql(\"\"\" SELECT {0}\n\t\tFROM `tabPending Order`po \n\t\tJOIN `tabPending Order Roll`por ON por.`parent`=po.`name`\n\t\t{1}\n\t\tWHERE po.`docstatus`=1\n\t\t{2} {3} {4} {5} {6} {7}\n\t\t{8} \"\"\".format(select_field,left_join,po_clause,item_clause,customer_clause,colour_clause,delivery_clause,date_clause,order_clause))\n\t\n\treturn columns, data\n","sub_path":"inventory/inventory/report/pending_order_teralokasi/pending_order_teralokasi.py","file_name":"pending_order_teralokasi.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"333757533","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### Imports\n\n# In[9]:\n\n\nimport pickle\nimport os, os.path\nimport numpy as np\nimport scipy.stats\nimport time\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport matplotlib.colors as colors\nimport matplotlib.cm as cm\nimport seaborn as sns\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ### Function Defintions\n\n# In[10]:\n\n\ndef get_img_dict(words, path_to_words, compress=True, compress_dim=300, complexity_dim=3):\n img_dict = {}\n img_array_dict = {}\n img_array_complexity_dict = {}\n for word in words:\n img = []\n img_array = []\n img_array_complexity = []\n folder = path_to_words + '{}'.format(word)\n pics = [name for name in os.listdir(folder) if os.path.isfile(os.path.join(folder, name))]\n for pic in pics:\n try:\n filename = 'downloads/{}/{}'.format(word,pic)\n if os.path.splitext(filename)[1] != '.svg':\n img_raw = Image.open(filename)\n if compress == True:\n img_compress = img_raw.resize((compress_dim,compress_dim),Image.ANTIALIAS)\n if np.shape(np.array(img_compress)) == (compress_dim, compress_dim, 3):\n img.append(img_compress)\n img_array.append(np.array(img_compress))\n img.append(img_raw)\n img_array.append(np.array(img_raw))\n img_compress_complexity = img_raw.resize((complexity_dim,complexity_dim),Image.ANTIALIAS)\n img_array_complexity.append(np.array(img_compress_complexity))\n \n img_dict[word] = img\n img_array_dict[word] = img_array\n img_array_complexity_dict[word] = img_array_complexity\n \n except: pass\n \n return img_dict, img_array_dict, img_array_complexity_dict\n\n\n# In[11]:\n\n\ndef get_rgb_distributions(img_dict):\n rgb_dict = {}\n for key in img_dict:\n rgb = []\n for i in range(len(img_dict[key])):\n r = np.sum(np.ravel(img_dict[key][i][:,:,0]))\n g = np.sum(np.ravel(img_dict[key][i][:,:,1]))\n b = np.sum(np.ravel(img_dict[key][i][:,:,2]))\n tot = 1.*r+g+b\n rgb.append([r/tot,g/tot,b/tot])\n rgb_dict[key] = rgb\n return rgb_dict\n\n\n# In[12]:\n\n\ndef compress_img_array(words, img_array_dict, compress_dim=300):\n compressed_img_array_dict = {}\n for word in words:\n compressed_img_array = np.zeros((compress_dim,compress_dim,3))\n for n in range(len(img_array_dict[word])):\n if np.shape(img_array_dict[word][n]) == (compress_dim, compress_dim, 3):\n for i in range(compress_dim):\n for j in range(compress_dim):\n compressed_img_array[i][j] += img_array_dict[word][n][i][j]/(1.*len(img_array_dict[word]))\n compressed_img_array_dict[word] = compressed_img_array\n return compressed_img_array_dict\n\n\n# In[13]:\n\n\ndef cross_entropy_between_images(rgb_dict):\n entropy_dict = {}\n for key in rgb_dict:\n entropy_array = []\n for i in range(len(rgb_dict[key])):\n for j in range(len(rgb_dict[key])):\n entropy_array.append((scipy.stats.entropy(rgb_dict[key][i],rgb_dict[key][j])+scipy.stats.entropy(rgb_dict[key][j],rgb_dict[key][i]))/2.)\n entropy_dict[key] = entropy_array\n return entropy_dict\n\n\n# In[14]:\n\n\ndef cross_entropy_between_labels(rgb_dict, words):\n mean_rgb_dict = {}\n for key in rgb_dict:\n mean_rgb_array = np.mean(np.array(rgb_dict[key]),axis=0)\n mean_rgb_dict[key] = mean_rgb_array\n labels_entropy_dict = {}\n color_sym_matrix = []\n for word1 in words:\n row = []\n for word2 in words:\n entropy = (scipy.stats.entropy(mean_rgb_dict[word1],mean_rgb_dict[word2])+scipy.stats.entropy(mean_rgb_dict[word2],mean_rgb_dict[word1]))/2.\n row.append(entropy)\n labels_entropy_dict[word1 + word2] = entropy\n color_sym_matrix.append(row)\n return labels_entropy_dict, color_sym_matrix\n\n\n# ### Test\n\n# In[17]:\n\n\n#path_to_words = 'downloads/'\n\n#words=['old man']\n\n#Load the dictionary of images \n#img_dict, img_array_dict, img_array_complexity_dict = get_img_dict(words, path_to_words)\n\n#Get the rgb distributions for each image \n#rgb_dict = get_rgb_distributions(img_array_dict)\n#rgb_dict_complexity = get_rgb_distributions(img_array_complexity_dict)\n\n#Processes similarity of images \n#entropy_dict = cross_entropy_between_images(rgb_dict)\n#complexity_dict = cross_entropy_between_images(rgb_dict_complexity)\n\n#compressed_img_array_dict = compress_img_array(words, img_array_dict)\n#cross_entropy_between_labels_dict, cross_entropy_matrix = cross_entropy_between_labels(rgb_dict)\n#cross_complexity_between_labels_dict = cross_entropy_between_labels(rgb_dict_complexity)\n\n","sub_path":"RGBAnalysisFunctions.py","file_name":"RGBAnalysisFunctions.py","file_ext":"py","file_size_in_byte":4977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"231691434","text":"# -*- coding: utf-8 -*-\n\n# =============================================================================\n# =======概述\n# 简述:绘图窗口类\n#\n# =======使用说明\n# \n#\n# =======日志\n# \n\n# =============================================================================\nimport re\nimport pandas as pd\n# =============================================================================\n# Qt imports\n# =============================================================================\nfrom PyQt5.QtWidgets import (QPlainTextEdit, QMessageBox, QAction, QDialog,\n QMenu)\nfrom PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QTextCursor\nfrom PyQt5.QtCore import Qt, QRegExp, QCoreApplication, pyqtSignal\n\n# =============================================================================\n# Package views imports\n# =============================================================================\nfrom models.datafile_model import Normal_DataFile\nfrom views.custom_dialog import SelParasDialog\n\n#用于将特定字符加高亮\nclass Highlighter(QSyntaxHighlighter):\n \n def __init__(self, parent = None, paras : list = None):\n \n super().__init__(parent)\n \n# 定义参数这类字符的高亮格式\n self.para_format = QTextCharFormat()\n self.para_format.setForeground(Qt.blue)\n# self.para_format.setFontItalic(True)\n \n self.highlight_rules = []\n# 定义需要高亮的参数字符\n for para in paras:\n pattern = QRegExp(r'\\b' + para + r'\\b')\n self.highlight_rules.append((pattern, self.para_format))\n\n# 重载函数 \n def highlightBlock(self, text : str):\n\n for rule in self.highlight_rules:\n expr = QRegExp(rule[0])\n index = expr.indexIn(text)\n while index >= 0:\n length = expr.matchedLength()\n self.setFormat(index, length, rule[1])\n index = expr.indexIn(text, index + length)\n\nclass MathematicsEditor(QPlainTextEdit):\n\n signal_compute_result = pyqtSignal(pd.DataFrame)\n \n def __init__(self, parent = None):\n \n super().__init__(parent)\n\n self._current_files = []\n# 存储上一条语句\n self.pre_exper = ''\n self.RESERVED = 'RESERVED'\n self.PARA = 'PARA'\n self.VAR = 'VAR'\n self.INT = 'INT'\n self.FLOAT = 'FLOAT'\n# 目前,只允许进行四则运算\n self.token_exprs = [\n# 前两个表达式匹配空格和注释\n ('\\s+', None),\n ('\\=', self.RESERVED),\n ('\\(', self.RESERVED),\n ('\\)', self.RESERVED),\n ('\\+', self.RESERVED),\n ('\\-', self.RESERVED),\n ('\\*', self.RESERVED),\n ('\\/', self.RESERVED),\n ('[0-9]+\\.[0-9]+', self.FLOAT),\n ('[0-9]+', self.INT),\n (r'[A-Za-z][A-Za-z0-9_]*', self.VAR)]\n# 为以后开发解释器时使用\n# self.expression_consist_of_tokens = []\n self.paras_on_expr = []\n \n self.setup()\n \n def setup(self):\n \n# 添加输入标志,并把光标移动到最后\n self.setPlainText('>>')\n text_cursor = self.textCursor()\n text_cursor.movePosition(QTextCursor.End)\n self.setTextCursor(text_cursor)\n \n self.setContextMenuPolicy(Qt.CustomContextMenu)\n# 添加右键动作\n self.action_add_para = QAction(self)\n self.action_add_para.setText(QCoreApplication.\n translate('MathematicsEditor', '添加参数'))\n self.action_pre_exper = QAction(self)\n self.action_pre_exper.setText(QCoreApplication.\n translate('MathematicsEditor', '上一条表达式'))\n self.action_clear_editor = QAction(self)\n self.action_clear_editor.setText(QCoreApplication.\n translate('MathematicsEditor', '清空所有输入'))\n \n self.customContextMenuRequested.connect(self.conmandline_context_menu)\n self.action_add_para.triggered.connect(self.slot_add_para)\n self.action_clear_editor.triggered.connect(self.slot_clear)\n self.action_pre_exper.triggered.connect(self.slot_insert_pre_exper)\n \n# 判断用户是在哪里输入文字,只有在当前textblock内才能输入\n self.cursorPositionChanged.connect(self.slot_cursor_pos)\n self.blockCountChanged.connect(self.slot_exec_block)\n\n# =============================================================================\n# slots模块\n# ============================================================================= \n def keyPressEvent(self, event):\n \n# Qt的enter与事件的enter不知道为什么差了个1\n# 之所以要重写按下enter后的事件,是为了保证用户在表达式中使用enter也能执行整行代码\n if event.key() + 1 == Qt.Key_Enter:\n text_cursor = self.textCursor()\n text_cursor.movePosition(QTextCursor.End)\n self.setTextCursor(text_cursor)\n QPlainTextEdit.keyPressEvent(self, event)\n \n def slot_cursor_pos(self):\n \n document = self.document()\n# 文档最后的textblock\n block_on_doc_last = document.lastBlock() \n text_cursor = self.textCursor()\n# 光标所在的textblock\n block_on_cursor = text_cursor.block()\n# 如果两个block不一样则将光标移到文档最后\n if block_on_doc_last != block_on_cursor:\n text_cursor.movePosition(QTextCursor.End)\n# 不允许光标移动到输入标志'>>'里\n elif text_cursor.positionInBlock() < 2:\n text = block_on_cursor.text()\n if (len(text) >= 2):\n if(text[1] == '>'):\n text_cursor.setPosition(block_on_cursor.position() + 2)\n# 为避免删除输入标志\n else:\n text_cursor.setPosition(block_on_cursor.position() + 1)\n text_cursor.insertText('>')\n# 回车后创建输入标志\n else:\n text_cursor.insertText('>')\n self.setTextCursor(text_cursor)\n \n def slot_exec_block(self, count):\n \n# 经过slot_cursor_pos和keyPressEvent函数,已保证了MATLAB那种代码交互效果\n# 所以当blockcount变化时,当前的block是新输入block,前一个block是需要执行的代码\n document = self.document()\n current_block = document.lastBlock()\n exec_block = current_block.previous()\n exec_text = exec_block.text()\n if (len(exec_text) > 2):\n# 剔除输入标志'>>'\n exec_text = exec_text[2 : ]\n self.pre_exper = exec_text\n# 解析exec_text,如果满足要求,则执行运算\n if self.lex(exec_text) and self.paras_on_expr:\n reg_df = self.pretreat_paras()\n# 将参数的数据读入内存\n for paraname in self.paras_on_expr:\n exper = paraname + ' = reg_df[\\'' + paraname + '\\']'\n exec(exper)\n try:\n# 注意此时result是series对象\n result = eval(exec_text)\n# 判断结果是否仍然是时间序列\n if len(result) == len(reg_df):\n df_result = pd.DataFrame({'Time' : reg_df.iloc[:, 0], \n 'Result': result}, columns = ['Time', 'Result'])\n# 否则认为是一个数\n else:\n df_result = pd.DataFrame({'Label' : 1,\n 'Result': result}, columns = ['Label', 'Result'])\n self.signal_compute_result.emit(df_result)\n except:\n QMessageBox.information(self,\n QCoreApplication.translate(\"MathematicsEditor\", \"提示\"),\n QCoreApplication.translate(\"MathematicsEditor\", '无法执行这条语句'))\n else:\n QMessageBox.information(self,\n QCoreApplication.translate(\"MathematicsEditor\", \"提示\"),\n QCoreApplication.translate(\"MathematicsEditor\", '无法执行这条语句'))\n\n def conmandline_context_menu(self, pos):\n \n menu = QMenu(self)\n menu.addActions([self.action_add_para,\n self.action_pre_exper,\n self.action_clear_editor])\n if self.pre_exper:\n self.action_pre_exper.setEnabled(True)\n else:\n self.action_pre_exper.setEnabled(False)\n menu.exec_(self.mapToGlobal(pos))\n\n def slot_add_para(self):\n \n# 采用单选模式\n dialog = SelParasDialog(self, self._current_files, 0)\n return_signal = dialog.exec_()\n if (return_signal == QDialog.Accepted):\n paras = dialog.get_list_sel_paras()\n if paras:\n self.insertPlainText(paras[0])\n \n def slot_clear(self):\n \n self.clear()\n \n def slot_insert_pre_exper(self):\n \n if self.pre_exper:\n text_cursor = self.textCursor()\n text_cursor.insertText(self.pre_exper)\n self.setTextCursor(text_cursor)\n \n def slot_update_current_files(self, files : list):\n \n self._current_files = files\n paras = []\n for file in files:\n normal_file = Normal_DataFile(file)\n paras += normal_file.paras_in_file\n if paras:\n# 更新需要高亮的参数\n self.highlighter = Highlighter(self.document(), paras)\n token_exprs = [\n # 前两个表达式匹配空格和注释\n ('\\s+', None),\n ('\\=', self.RESERVED),\n ('\\(', self.RESERVED),\n ('\\)', self.RESERVED),\n ('\\+', self.RESERVED),\n ('\\-', self.RESERVED),\n ('\\*', self.RESERVED),\n ('\\/', self.RESERVED),\n ('[0-9]+\\.[0-9]+', self.FLOAT),\n ('[0-9]+', self.INT)]\n \n for para in paras:\n token_exprs.append((para, self.PARA))\n # 先匹配参数名,如果不是参数再认为是变量\n token_exprs.append((r'[A-Za-z][A-Za-z0-9_]*', self.VAR))\n self.token_exprs = token_exprs\n \n# =============================================================================\n# 功能函数模块 \n# ============================================================================= \n# 需要保证charaters非空,找到这个charaters中包含的参数并且保证只执行taoken_exprs限制的运算\n def lex(self, charaters):\n \n pos = 0\n paranames = []\n while pos < len(charaters):\n match = None\n for token_expr in self.token_exprs:\n pattern, tag = token_expr\n regex = re.compile(pattern)\n match = regex.match(charaters, pos)\n if match:\n text = match.group(0)\n# if tag:\n if (tag == 'PARA') and not(text in paranames):\n paranames.append(text)\n break\n if not match:\n QMessageBox.information(self,\n QCoreApplication.translate(\"MathematicsEditor\", \"提示\"),\n QCoreApplication.translate(\"MathematicsEditor\", '非法字符: %s' % charaters[pos]))\n# self.expression_consist_of_tokens = []\n self.paras_on_expr = []\n return False\n else:\n pos = match.end(0)\n# self.expression_consist_of_tokens = tokens\n self.paras_on_expr = paranames\n return True\n \n def dict_current_files(self):\n \n dict_files = {}\n if self._current_files:\n for file_dir in self._current_files:\n normal_file = Normal_DataFile(file_dir)\n dict_files[file_dir]= normal_file.paras_in_file\n return dict_files\n \n# 将参数读入内存中,并进行时间同步处理,返回一个dataframe\n def pretreat_paras(self):\n \n df_list = []\n dict_files = self.dict_current_files()\n# 因为self.paras_on_expr只是一个参数列表,所以要先将其规整下,方便按文件读取\n dict_paras = {}\n for para in self.paras_on_expr:\n for file_dir in dict_files:\n if para in dict_files[file_dir]:\n if file_dir in dict_paras:\n dict_paras[file_dir].append(para)\n else:\n dict_paras[file_dir] = []\n dict_paras[file_dir].append(para)\n break\n# 从文件中读取参数数据,并在不同文件读出来的dataframe中第一列加入时间\n for file_dir in dict_paras:\n file = Normal_DataFile(file_dir)\n dict_paras[file_dir].insert(0, file.paras_in_file[0])\n df = file.cols_input(file_dir, dict_paras[file_dir], '\\s+')\n df_list.append(df)\n \n df_all = pd.concat(df_list,axis = 1,join = 'outer',\n ignore_index = False)\n return df_all","sub_path":"lib/models/mathematics_model.py","file_name":"mathematics_model.py","file_ext":"py","file_size_in_byte":13720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"130720768","text":"# -*- coding: utf-8 -*-\nimport re\nimport pprint\nfrom .dotexdict import dotexdict\n\n\nclass LdapObject(dotexdict):\n\n def __init__(self, *args, **kwargs):\n super(LdapObject, self).__init__(*args, **kwargs)\n\n def pretty_data(self):\n \"\"\"\n :return: dict with selected attributes - that in self._print_attributes\n \"\"\"\n result = {}\n for key in self._print_attributes:\n try:\n assert isinstance(key, str)\n if type(self[key]) is not list:\n self[key] = [self[key]]\n value = [str(value) for value in self[key]]\n result[key] = value\n except:\n pass\n return result\n\n def pretty_print(self):\n \"\"\"\n pretty print of the pretty data\n \"\"\"\n print (self.pretty_data())\n pp = pprint.PrettyPrinter(indent=2)\n pp.pprint(self.pretty_data())\n\n def _extract_keys_from_dn(self, keys, distinguish_name):\n \"\"\"\n :param keys: list of keys to extract from the dn\n :param distinguish_name: DN we want to extract fields from\n :return: list of fields (keys) extracted from the DN\n \"\"\"\n result = []\n dn = self._dn_to_dict(distinguish_name.lower())\n for key in keys:\n if key in dn:\n result.append(dn[key])\n return result\n\n def _extract_keys_from_list_of_dn(self, keys, distinguish_names):\n \"\"\"\n :param keys: list of keys to extract from the dn\n :param distinguish_names: list of distinguish names (DN)\n :return: list of fields (keys) extracted from the DN\n \"\"\"\n result = []\n for dn_str in distinguish_names:\n extracted_keys = self._extract_keys_from_dn(keys, dn_str)\n if extracted_keys:\n result.append(extracted_keys)\n return result\n\n def _dn_to_dict(self, dn):\n \"\"\"\n :param dn: distinguish names (DN) string\n :return: dict representing the DN data (keys and values)\n \"\"\"\n return dict((key, value) for key, value in (item.split('=') for item in dn.split(',')))\n\n def _aliases_to_cammelcase(self, attributes):\n \"\"\"\n :param attributes: list of attributes in CamelCase format\n :return: dictionary of desire aliases - snake_case format alias to CamelCase\n \"\"\"\n result = {}\n for attr in attributes:\n result[self._cammelcase_to_snakecase(attr)] = attr\n return result\n\n def _cammelcase_to_snakecase(self, camelcase):\n \"\"\"\n :param camelcase: attribute name in CamelCase format\n :return: the attribute in snake_case format\n \"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', camelcase)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n","sub_path":"ldappy/ldapobject.py","file_name":"ldapobject.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"150330263","text":"import json\n\nimport pytest\n\nfrom newstory_scraper.pub_sub.queue import Queue\nfrom newstory_scraper.pub_sub.queue_registry import QueueRegistry\n\n\n@pytest.fixture()\ndef mock_consumer_factory():\n def inner(group_id):\n if group_id is None:\n raise ValueError(\"group_id cannot be None\")\n print(f\"added queue to group: {group_id}\")\n\n return inner\n\n\nclass MockQueue(Queue):\n def __init__(self, name, group_id, *args, **kwargs):\n self.name = name\n self.group_id = group_id\n super(MockQueue, self).__init__(*args, **kwargs)\n\n def process_message(self, *args, **kwargs):\n pass\n\n def enqueue(self, key, value):\n print(f\"enqueued to {self.name}\", key)\n print(\" VALUE \".center(30, \"#\"))\n print(json.dumps(value))\n print(\"\".center(30, \"#\"))\n\n\n@pytest.fixture()\ndef mock_registry(mock_consumer_factory):\n reg = QueueRegistry()\n MockQueue(\n \"new_post\",\n registry=reg,\n group_id=\"new_post\",\n consumer_factory=mock_consumer_factory,\n )\n return reg\n","sub_path":"tests/queue/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"391005511","text":"# ===== modules ===== #\nimport pandas as pd\nimport numpy as np\nimport argparse, os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm\nfrom time import sleep\n\n# ===== setup ===== #\nsns.set_style('whitegrid')\nnp.random.seed(0)\n\n# ===== main ===== #\ndef main():\n # - Argparse - #\n parser = argparse.ArgumentParser()\n parser.add_argument('--data', type=str, default='./data/emo_optimized_trade_data.csv',\n help='Path to csv file which has trade data')\n parser.add_argument('--result', type=str, default='./result-sector-simple-TPFINC/',\n help='Path to saving directory')\n args = parser.parse_args()\n\n # - Setup - #\n print('Setup...')\n if not os.path.exists(args.result):\n os.makedirs(args.result)\n\n # - Load data - #\n print('Load data...')\n data = pd.read_csv(args.data)\n data['datetime'] = pd.to_datetime(data['datetime'])\n data = data[data['sector'] == 'TPFINC']\n data.to_csv(os.path.join(args.result, 'TPFINC.csv'), index=False)\n\n # - Run calculation - #\n print('Run calculation...')\n plt.figure(figsize=(9,9))\n data_plot = data.groupby('datetime').sum()['daily_pnl']\n date = data_plot.index\n pnl_daily = np.cumsum( data_plot.values )\n plt.plot(date, pnl_daily)\n plt.savefig( os.path.join(args.result, 'TPFINC.png') )\n plt.close('all')\n\nif __name__ == '__main__':\n main()\n","sub_path":"simple-plot-TPFINC.py","file_name":"simple-plot-TPFINC.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"241752514","text":"from api import Api\nfrom printer import BasePrinter, DefaultPrinter\nimport os\n\n\nclass Game:\n def __init__(self,\n players,\n user_id,\n printer: BasePrinter = DefaultPrinter()):\n self.printer = printer\n self.players = players\n self.user_id = user_id\n\n self.player_token = ''\n self.bot_token = ''\n\n self.api = Api('http://127.0.0.1:3000/api')\n\n def accept(self, game_token):\n os.system(\"clear\")\n player = self.api.accept(self.user_id, game_token)\n state = self.api.state(self.user_id)\n self.printer.draw_field(\n state[\"playerGameState\"][\"playerState\"][\"field\"],\n state[\"opponentGameState\"][\"playerState\"][\"field\"])\n return player[\"userToken\"]\n\n def accepted(self):\n os.system(\"clear\")\n state = self.api.state(self.user_id)\n print(\"Opponent accepted challenge\")\n self.printer.draw_field(\n state[\"playerGameState\"][\"playerState\"][\"field\"],\n state[\"opponentGameState\"][\"playerState\"][\"field\"])\n\n def start(self):\n player = self.api.start(self.user_id)\n return player[\"userToken\"], player[\"gameToken\"]\n\n def shot(self):\n os.system(\"clear\")\n state = self.api.state(self.user_id)\n self.printer.draw_field(\n state[\"playerGameState\"][\"playerState\"][\"field\"],\n state[\"opponentGameState\"][\"playerState\"][\"field\"])\n if state[\"playerGameState\"][\"turn\"]:\n print(\"Your turn\")\n else:\n print(\"Enemy turn\")\n\n def shoot(self, x, y):\n os.system(\"clear\")\n result = self.api.shoot(x, y, self.user_id)\n if result is not None:\n print(result[\"message\"])\n\n state = self.api.state(self.user_id)\n self.printer.draw_field(\n state[\"playerGameState\"][\"playerState\"][\"field\"],\n state[\"opponentGameState\"][\"playerState\"][\"field\"])\n if state[\"playerGameState\"][\"turn\"]:\n print(\"Your turn\")\n else:\n print(\"Enemy turn\")\n","sub_path":"src/BGE.TextClient/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"254882492","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n##########################################\n#\n# 20160926\n# 比对两个目录文件的md5 并生成.md5文件\n##########################################\n__author__ = 'c8d8z8@gmail.com'\n\n# 配置日志\nimport commonlib.logginglib\ncommonlib.logginglib.configure('logging.conf')\nlogger = commonlib.logginglib.getLogger('zqb')\n\nimport hashlib\nimport os, sys\n\ndef calFileMD5(filepath):\n with open(filepath, \"rb\") as f:\n md5obj = hashlib.md5()\n md5obj.update(f.read())\n hash = md5obj.hexdigest()\n print(hash)\n return hash\n\ndef gci(path):\n parents = os.listdir(path)\n for parent in parents:\n child = os.path.join(path,parent)\n if os.path.isdir(child):\n gci(child)\n # print(child)\n else:\n print(child)\n fullpath = os.path.abspath(child)\n #createFileMD5(fullpath)\n\n\ndef createFileMD5(dirpath):\n print(dirpath)\n filemd5 = calFileMD5(dirpath)\n file_object = open(dirpath+'.md5', 'w')\n file_object.write(filemd5)\n file_object.close()\n\nif __name__ == \"__main__\":\n #calFileMD5(\"test1.txt\")\n #calFileMD5(\"test2.txt\")\n gci(\".\")\n","sub_path":"increment_sync_folder.py","file_name":"increment_sync_folder.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"89183349","text":"import wikipediaapi\nwiki = wikipediaapi.Wikipedia('en')\nmain = input(\"Insert title of Wikipedia Main Page: \")\nmainpage = wiki.page(main)\npAllLinks_main = []\n\nsimilar = input(\"Insert title of Wikipedia Related Page: \")\nrelatedpage = wiki.page(similar)\npAllLinks_similar = []\n\nbad_words = ['user:', 'talk:', 'wikipedia:', 'template:', 'category:', 'file:', 'files:', 'portal:', 'draft:']\n\n\ndef find_links(page, listAll):\n links = page.links\n for title in sorted(links.keys()):\n listAll.append(title)\n\ndef checkBad_Words(res, toCheck, bad_words):\n bool = True\n toCheck_lowered = toCheck.lower()\n for word in bad_words:\n if word in toCheck_lowered:\n bool = False\n break\n\n if bool:\n res.append(toCheck)\n\ndef remove_bad_links(result, links):\n for link in links:\n checkBad_Words(result, link, bad_words)\n\n\n\nres_main = []\nfind_links(mainpage, pAllLinks_main)\n#print(pAllLinks_main)\nremove_bad_links(res_main, pAllLinks_main)\nprint(res_main)\nprint(\"\\n\\n\")\n\nres_similar= []\nfind_links(relatedpage, pAllLinks_similar)\n#print(pAllLinks_similar)\nremove_bad_links(res_similar, pAllLinks_similar)\nprint(res_similar)\nprint(\"\\n\")\nprint(\"DIFFERENCE = \")\nprint(list(set(pAllLinks_similar) - set(pAllLinks_main)))","sub_path":"FINALV2-GEORGE/MissingFinder.py","file_name":"MissingFinder.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"17881891","text":"register_doctor_payload = {\n \"event\": \"signup\",\n \"instance_id\": \"c74c545a-4dff-4d4d-832c-bff8bbe94922\",\n \"user\": {\n \"id\": \"17d5b44c-1472-4445-a9d0-d63dabbe369f\",\n \"aud\": \"\",\n \"role\": \"\",\n \"email\": \"kullen.hatim@lcelandic.com\",\n \"confirmation_sent_at\": \"2018-09-05T07:19:47Z\",\n \"app_metadata\": {\n \"provider\": \"email\"\n },\n \"user_metadata\": {\n \"Business_Role\": \"doctor\",\n \"Contact_Number\": \"0987654321234567\",\n \"Date_Of_Birth\": \"12/01/1993\",\n \"Email\": \"kullen.hatim@lcelandic.com\",\n \"Gender\": \"F\",\n \"First_Name\": \"Test\",\n \"Full_Name\": \"Test Test\",\n \"Last_Name\": \"Test\",\n \"address\": {\n \"Country\": \"United States\",\n \"Postcode\": \"10013\",\n \"State\": \"NY\",\n \"Street\": \"17 Greenwich St\"\n }\n },\n \"created_at\": \"2018-09-05T07:19:47Z\",\n \"updated_at\": \"2018-09-05T07:19:47Z\"\n }\n}\n\nregister_receptionist_payload = {\n \"event\": \"signup\",\n \"instance_id\": \"c74c545a-4dff-4d4d-832c-bff8bbe94923\",\n \"user\": {\n \"id\": \"17d5b44c-1472-4445-a9d0-d63dabbe3690\",\n \"aud\": \"\",\n \"role\": \"\",\n \"email\": \"kullen.hatim.receptionist@lcelandic.com\",\n \"confirmation_sent_at\": \"2018-09-05T07:19:47Z\",\n \"app_metadata\": {\n \"provider\": \"email\"\n },\n \"user_metadata\": {\n \"Business_Role\": \"receptionist\",\n \"Contact_Number\": \"0987654321234567\",\n \"Date_Of_Birth\": \"12/01/1993\",\n \"Email\": \"kullen.hatim.receptionist@lcelandic.com\",\n \"First_Name\": \"Test\",\n \"Gender\": \"M\",\n \"Full_Name\": \"Test Test\",\n \"Last_Name\": \"Test\",\n \"address\": {\n \"Country\": \"United States\",\n \"Postcode\": \"10013\",\n \"State\": \"NY\",\n \"Street\": \"17 Greenwich St\"\n }\n },\n \"created_at\": \"2018-09-05T07:19:47Z\",\n \"updated_at\": \"2018-09-05T07:19:47Z\"\n }\n}\n\nadd_patient_payload = {\n \"Contact_Number\": \"0400000000\",\n \"Date_Of_Birth\": \"12/01/1993\",\n \"Email\": \"kullen.hatim.patient@lcelandic.com\",\n \"First_Name\": \"Test\",\n \"Gender\": \"M\",\n \"Full_Name\": \"Test Test\",\n \"Last_Name\": \"Test\",\n \"address\": {\n \"Country\": \"United States\",\n \"Postcode\": \"10013\",\n \"State\": \"NY\",\n \"Street\": \"17 Greenwich St\"\n }\n}\n\nupdate_patient_payload = {\n \"AddressId\": 3,\n \"Contact_Number\": \"0400000000\",\n \"Date_Of_Birth\": \"12/01/1993\",\n \"Email\": \"kullen.hatim.patient@lcelandic.com\",\n \"First_Name\": \"Updated\",\n \"Gender\": \"M\",\n \"Last_Name\": \"Test\",\n \"Patient_Id\": 1,\n \"address\": {\n \"AddressId\": 3,\n \"Country\": \"Australia\",\n \"Postcode\": 10013,\n \"State\": \"NSW\",\n \"Street\": \"17 Greenwich St\",\n \"Suburb\": \"\",\n \"Unit\": \"\"\n }\n}\n\ncreate_medical_case_payload = {\n \"Patient_Id\" : 1,\n \"Medical_Case_Name\": \"test\",\n \"Medical_Case_Description\": \"test\",\n \"doctors\": [\n {\n \"AddressId\": 3,\n \"Contact_Number\": \"04000000000\",\n \"Date_Of_Birth\": \"26/01/1997\",\n \"Doctor_Id\": 13,\n \"Email\": \"patm007@hotmail.com\",\n \"First_Name\": \"Patrick\",\n \"Gender\": \"M\",\n \"Last_Name\": \"Miziewicz\",\n \"User_Id\": \"b64bfe4a-ce81-459b-816a-a7cbb24e770d\",\n \"address\": {\n \"AddressId\": 3,\n \"Country\": \"Australia\",\n \"Postcode\": 2000,\n \"State\": \"NSW\",\n \"Street\": \"5 Main St\",\n \"Suburb\": \"Castle Hill\",\n \"Unit\": \"\"\n }\n },\n {\n \"AddressId\": 6,\n \"Contact_Number\": \"098765432123456\",\n \"Date_Of_Birth\": \"12/01/1993\",\n \"Doctor_Id\": 18,\n \"Email\": \"kullen.hatim@lcelandic.com\",\n \"First_Name\": \"Test\",\n \"Gender\": \"F\",\n \"Last_Name\": \"Test\",\n \"User_Id\": \"17d5b44c-1472-4445-a9d0-d63dabbe369f\",\n \"address\": {\n \"AddressId\": 6,\n \"Country\": \"United States\",\n \"Postcode\": 10013,\n \"State\": \"NY\",\n \"Street\": \"17 Greenwich St\",\n \"Suburb\": \"\",\n \"Unit\": \"\"\n }\n }\n ]\n}\n\nupdate_medical_case_payload = {\n \"Medical_Case_Description\": \"test\",\n \"Medical_Case_Id\": 1,\n \"Medical_Case_Name\": \"test\",\n \"Patient_Id\": 1,\n \"doctors\": [\n {\n \"AddressId\": 1,\n \"Contact_Number\": \"098765432123456\",\n \"Date_Of_Birth\": \"12/01/1993\",\n \"Doctor_Id\": 1,\n \"Email\": \"kullen.hatim@lcelandic.com\",\n \"First_Name\": \"Test\",\n \"Gender\": \"F\",\n \"Last_Name\": \"Test\",\n \"User_Id\": \"17d5b44c-1472-4445-a9d0-d63dabbe369f\",\n \"address\": {\n \"AddressId\": 1,\n \"Country\": \"United States\",\n \"Postcode\": 10013,\n \"State\": \"NY\",\n \"Street\": \"17 Greenwich St\",\n \"Suburb\": \"\",\n \"Unit\": \"\"\n },\n \"medical_cases\": []\n }\n ],\n \"patient\": {\n \"AddressId\": 1,\n \"Contact_Number\": \"0400000000\",\n \"Date_Of_Birth\": \"11/11/1990\",\n \"Email\": \"ajsdlakjsd@lakjdlakjdklsa.com\",\n \"First_Name\": \"UPDATED1231eqqsdasd\",\n \"Gender\": \"F\",\n \"Last_Name\": \"TESTaaaaafg\",\n \"Patient_Id\": 1,\n \"address\": {\n \"AddressId\": 1,\n \"Country\": \"United States\",\n \"Postcode\": 10010,\n \"State\": \"NY\",\n \"Street\": \"12 Lexington Ave\",\n \"Suburb\": \"\",\n \"Unit\": \"\"\n }\n }\n}\n\n#\n# Appointment Test cases\n#\ncreate_appointment_payload = {\n \"Patient_Id\":1,\n \"Doctor_Id\":1,\n \"Start_Date\":\"01/02/2019 22:30:00\",\n \"End_Date\":\"02/02/2019 23:30:00\"\n}\n\n\n\n","sub_path":"resources/test/payloads.py","file_name":"payloads.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"561124494","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Oct 28 15:52:36 2018\r\n\r\n@author: kate\r\n\"\"\"\r\n\r\n##########################################\r\n#### Think Like A Computer Sciencitst ####\r\n##########################################\r\n\r\n### Chapter 2 ###\r\n\r\n## Holiday ##\r\n\r\ndays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\r\n\r\nstartingDay = input(\"\\nWhat is they starting day of your vacation? \")\r\nlengthStay = int(input(\"\\nWhat is the length of your stay? \"))\r\n\r\nholiday = days.index(startingDay) + lengthStay\r\n\r\nif holiday > 7:\r\n duration = holiday % 7\r\nelse:\r\n duration = holiday\r\n \r\nprint(\"You will return on: \" + days[duration] + \".\")","sub_path":"Chapter2/Holiday.py","file_name":"Holiday.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"356628643","text":"#!/usr/bin/env python3\nfrom model_classes.regress import Regress\nfrom keras.utils import np_utils\nimport numpy as np\nfrom binance.client import Client\nfrom matplotlib import pyplot as plt\n\napi_key = \"\"\napi_secret = \"\"\nclient = Client(api_key, api_secret)\n\nklines = client.get_historical_klines(\"ETHUSDT\", Client.KLINE_INTERVAL_1DAY, \"100 day ago UTC\")\ndata = np.asarray(klines, dtype=np.float32)\ndata = np.delete(data, -1, axis=1)\ndata_plt = data[:,1:2].copy()\nendle_point = data[99,:].copy()\nprint(endle_point)\ny_train = data[:98, 1:2].copy()\ny_test = data[98:99, 1:2].copy()\n\nmean = data.mean(axis=0)\nstd = data.std(axis=0)\ndata -= mean\ndata /= std\nx_train = data[:98,:]\nx_test = data[98:99,:]\n\nregress_model = Regress(x_train, y_train, x_test, y_test)\nregress_model.add_layer(100*12, 10*12, \"relu\", x_train.shape[1])\nregress_model.compile(\"adam\", \"mse\", [\"mae\"])\nregress_model.fit(200, 1)\npred = regress_model.predict(data[99:,:])\npred_rok = regress_model.predict(data[99:,:])\nplt.plot(pred)\nplt.plot(pred_rok)\nprint(f\"Nowday:{y_test[-1]}, Predict:{pred}, Last_day_data:{endle_point}\")\nplt.show()\n","sub_path":"summer_time/regress_test.py","file_name":"regress_test.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"70478745","text":"import os\n\nclass EscridturaMidi:\n\n def __init__(self, nombre_cancion):\n self.nombre_cancion = nombre_cancion\n self.midi = None\n self.header = None\n self.type_header = b'MThd'\n self.length_header = b'\\x00\\x00\\x00\\x06'\n self.data_header = None\n self.formato_midi = 1\n self.numero_canales = 1\n self.numero_ticks_tiempo_musical = 160\n self.canal = b''\n self.type_canal = b'MTrk'\n self.length_canal = None\n self.data_canal = None\n self.tiempo_note_on = 0\n self.mensaje_note_on = b'\\x90'\n self.mensaje_note_off = b'\\x80'\n self.bytes_cierre = b'\\x00\\xff/\\x00'\n self.diccionario_tiempos = {\"Redonda\": 4, \"Blanca\": 2, \"Negra\": 1,\n \"Corchea\": 0.5, \"Semicorchea\": 0.25, \"Fusa\":\n 0.125, \"Semifusa\": 0.0625 }\n self.diccionario_notas = {}\n\n def agregar_header(self):\n bytes_formato_midi = self.formato_midi.to_bytes(2, byteorder=\"big\")\n bytes_numero_canales = self.numero_canales.to_bytes(2, byteorder=\"big\")\n bytes_numero_ticks_tiempo_musical = self.numero_ticks_tiempo_musical.\\\n to_bytes(2, byteorder=\"big\")\n self.data_header = bytes_formato_midi + bytes_numero_canales + \\\n bytes_numero_ticks_tiempo_musical\n self.header = self.type_header + self.length_header + self.data_header\n self.midi = self.header\n\n def agregar_type_canal(self):\n self.midi += self.type_canal\n\n def agregar_nota(self, tiempo, nota, intensidad, silencio):\n tiempo_note_on = self.tiempo(self.tiempo_note_on)\n byte_nota = int(nota).to_bytes(1, byteorder=\"big\")\n byte_intensidad = int(intensidad).to_bytes(1, byteorder=\"big\")\n mensaje_note_on = b''\n if silencio is False:\n mensaje_note_on = tiempo_note_on + self.mensaje_note_on + \\\n byte_nota + byte_intensidad\n tiempo_note_off = self.tiempo(tiempo)\n mensaje_note_off = tiempo_note_off + self.mensaje_note_off + \\\n byte_nota + byte_intensidad\n self.canal += mensaje_note_on + mensaje_note_off\n\n def agregar_length_canal(self):\n length_canal = len(self.canal).to_bytes(4, byteorder=\"big\")\n self.midi += length_canal + self.canal\n\n def agregar_valores_cierre(self):\n self.canal += self.bytes_cierre\n\n def escribir_archivo(self, path):\n with open(os.path.normpath(\"{}/{}.mid\".format(path, self.nombre_cancion\n )), \"wb\") as \\\n midi_file:\n midi_file.write(self.midi)\n\n def tiempo(self, ticks):\n #primer paso\n binario = format(ticks, 'b')\n #segundo paso\n lista_binarios = list()\n while len(binario) > 0:\n lista_binarios.append(binario[-7:])\n binario = binario[:-7]\n nueva_lista_binarios = list()\n while len(lista_binarios) > 0:\n elem = lista_binarios.pop(-1)\n if len(elem) < 7:\n numero_ceros = 7 - len(elem)\n string_ceros = \"0\"*numero_ceros\n elem = string_ceros + elem\n nueva_lista_binarios.append(elem)\n #tercer paso\n nueva_lista_binarios1 = list()\n largo_inicial_lista_bin = len(nueva_lista_binarios)\n while len(nueva_lista_binarios) > 0:\n if len(nueva_lista_binarios) == largo_inicial_lista_bin:\n elem = nueva_lista_binarios.pop(-1)\n nuevo_bin = \"0\" + elem\n nueva_lista_binarios1.append(nuevo_bin)\n else:\n elem = nueva_lista_binarios.pop(-1)\n nuevo_bin = \"1\" + elem\n nueva_lista_binarios1.append(nuevo_bin)\n nueva_lista_binarios1 = nueva_lista_binarios1[::-1]\n #cuarto paso\n lista_bytes = list()\n for elem in nueva_lista_binarios1:\n byte = int(elem, 2).to_bytes(1, byteorder=\"big\")\n lista_bytes.append(byte)\n byte_string = b''.join(lista_bytes)\n return byte_string\n\n","sub_path":"Tareas/T06/generar_midi.py","file_name":"generar_midi.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"318670024","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.conf.urls.static import static\n\n\n\n\n\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^accounts/', include ('allauth.urls')),\n url(r'^$', 'videos.views.homepage', name='homepage'),\n url(r'^s/$', 'videos.views.search', name='search'),\n url(r'^content/', include('videos.urls')),\n url(r'^test/(?P[\\w-]+)/$', 'accounts.views.add_to_list', name='add_to_list'),\n url(r'^favourite/$', 'accounts.views.user_content', name='favourite'),\n url(r'^learned/$', 'accounts.views.user_content', name='learned'),\n url(r'^later/$', 'accounts.views.user_content', name='later'),\n url(r'^added-by-me/$', 'accounts.views.user_content', name='added-by-me'),\n url(r'^user-detail/$', 'accounts.views.user_detail', name='user_detail'),\n url(r'^(?P\\d+)/$', 'accounts.views.single_user', name='single-user'),\n url(r'^events/$', 'events.views.event_view', name='events'),\n url(r'^events/my$', 'events.views.user_event_view', name='my_events'),\n url(r'^events/attending$', 'events.views.attending_view', name='attending'),\n url(r'events/category/(?P[\\w-]+)/$', 'events.views.category_event', name='category-event'),\n url(r'events/(?P[\\w-]+)/$', 'events.views.event_detail', name='event-detail'),\n url(r'^add-event/$', 'events.views.add_event', name='add_event'),\n url(r'^edit-event/(?P\\d+)/$', 'events.views.edit_event', name='edit-event'),\n url(r'^users/$', 'accounts.views.all_users', name='users'),\n\n\n]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"edventure/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"638273541","text":"import os, json\n\n\nclass Config:\n\n def __init__(self, name):\n self.name = name\n self.config = {}\n self.load()\n\n def get(self, key, default = None):\n value = self.config.get(key)\n if value is None:\n self.set({key: default})\n return default\n return value\n\n def set(self, pairs, save=True):\n self.config.update(pairs)\n if save:\n self.save()\n\n def load(self):\n if not os.path.isfile(self.name+\".json\"):\n self.save()\n else:\n with open(self.name+\".json\", 'r') as f:\n self.config = json.load(f)\n\n def save(self):\n with open(self.name+\".json\", 'w') as f:\n json.dump(self.config, f)\n","sub_path":"app/JSONconfig.py","file_name":"JSONconfig.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"233208677","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse,Http404\nfrom .models import Location,Category,Image\n\n\n# Create your views here.\n\n\ndef landing(request):\n all_images = Image.objects.all()\n locations = Location.objects.all()\n categories = Category.objects.all()\n title = 'Home'\n\n return render(request,'index.html', {'all_images':all_images,'locations':locations,'categories':categories, 'title':title})\n\n\ndef search_results(request):\n locations = Location.objects.all()\n categories = Category.objects.all()\n title = 'Search'\n\n if 'searchcat' in request.GET and request.GET[\"searchcat\"]:\n search_term = request.GET.get(\"searchcat\")\n searched_images = Image.search_category(search_term)\n message = f\"Results for: {search_term}\"\n\n return render(request, 'index.html',{\"message\":message,\"all_images\": searched_images,'locations':locations,'categories':categories, 'title':title})\n\n else:\n message = \"You haven't searched for any term.\"\n return render(request, 'index.html',{\"message\":message, 'locations':locations,'categories':categories, 'title':title})\n\n\ndef page_category(request,category):\n locations = Location.objects.all()\n categories = Category.objects.all()\n title = f\"{category}\"\n category_results = Image.search_category(category)\n return render(request,'index.html',{'all_images':category_results,'locations':locations,'categories':categories, 'title':title})\n\ndef page_location(request,location):\n locations = Location.objects.all()\n categories = Category.objects.all()\n title = f\"{location}\"\n location_results = Image.filter_location(location)\n return render(request,'index.html',{'all_images':location_results,'locations':locations,'categories':categories, 'title':title})\n","sub_path":"personal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"168644494","text":"'''\nGoal: Create bar graphs for each word conjugation across the different \ncategories (initial or final)\n'''\n\n# Import libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Import data\ncategories = pd.read_excel('word_categories.xlsx')\ndata = pd.read_excel('responses.xlsx')\n\n# Edit data so only words and average responses remain\ndata = data.drop(data.columns[0:3], axis = 1, inplace = False) #removing unnecessary columns\nmean = data[data.columns].mean() #finding the means of each column\ndata = data.append(mean, ignore_index = True) #add the means to the df to maintain df integrity\naverages = data.drop(range(len(data.index) - 1), axis = 0, inplace = False) #remove unnecessary remaining rows\n\n# Important categories\nconjugations = ['A. \"-ed\"', 'B. \"/æ/\"', 'C. \"/ʌ/\"']\ninitials = ['sCC', 'sC', 'CC', 'C']\nfinals = ['nasal', 'k/g', 'n/m', 'C']\n\n'''\nFunction that displays a bar_graph of the average score given to a specific\ncategory under a specific conjugation type with the parameters of a conjugation\ntype, the types of categories being considered and the section in which they\nare being considered.\n'''\ndef from_conjugation(conjugation, types, section):\n aves = []\n for i in types: \n words = categories.loc[categories[section] == i][conjugation].tolist()\n conj_ave = averages\n for col in conj_ave.columns:\n if not any(x in col for x in words):\n conj_ave = conj_ave.drop(col, axis = 1, inplace = False)\n aves.append(conj_ave.mean(axis=1).tolist()[0])\n\n plt.bar(types, aves)\n plt.ylim(0, 7)\n plt.title(conjugation + ' ' + section)\n plt.xlabel('Consonant Categories')\n plt.ylabel('Average Given Score')\n plt.show()\n\n\n\ntesting = False\n\nif not testing:\n\n # Create a comparison graph for all categories under all conjugations\n for i in conjugations:\n from_conjugation(i, initials, 'initial_consonants')\n from_conjugation(i, finals, 'final_consonants')","sub_path":"across_categories.py","file_name":"across_categories.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"198551921","text":"import os\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\nclass User(db.Model):\n __tablename__ = \"users\"\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String, nullable=False)\n email = db.Column(db.String, nullable=False)\n password = db.Column(db.String, nullable=False)\n reviews = db.relationship(\"Review\", backref=\"User\", lazy=True)\n \n \nclass Book(db.Model):\n __tablename__ = \"books\"\n id = db.Column(db.Integer, primary_key=True)\n isbn = db.Column(db.String, nullable=False)\n title = db.Column (db.String, nullable=False)\n author = db.Column (db.String, nullable=False)\n year = db.Column (db.Integer, nullable=False)\n reviews = db.relationship(\"Review\", backref=\"Book\", lazy=True)\n goodreads = db.relationship(\"Goodreads\", backref=\"Book\", lazy=True)\n \n def add_review(self,rating,review,user_id):\n r = Review(rating=rating, review=review, user_id=user_id, book_id=self.id)\n db.session.add(r)\n db.session.commit() \n \n def update_goodreads(self,avg_rating):\n r = Goodreads(avg_rating=avg_rating, book_id=self.id)\n db.session.add(r)\n db.session.commit() \n\n \nclass Review(db.Model):\n __tablename__ = \"reviews\"\n id = db.Column(db.Integer, primary_key=True)\n rating = db.Column (db.Integer, nullable=False)\n review = db.Column (db.String, nullable=False) \n user_id = db.Column(db.Integer, db.ForeignKey(\"users.id\"), nullable=False)\n book_id = db.Column(db.Integer, db.ForeignKey(\"books.id\"), nullable=False)\n\nclass Goodreads(db.Model):\n __tablename__ = \"goodreads\"\n id = db.Column(db.Integer, primary_key=True)\n avg_rating = db.Column (db.Float, nullable=False)\n book_id = db.Column(db.Integer, db.ForeignKey(\"books.id\"), nullable=False) \n \n \n ","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"471637950","text":"from __future__ import absolute_import, division, print_function\n\nimport botocore\nimport cloudknot.config\nimport ipaddress\nimport logging\nimport six\nimport tenacity\nfrom collections import namedtuple\n\nfrom .base_classes import clients, NamedObject, \\\n ResourceExistsException, ResourceDoesNotExistException, \\\n CannotCreateResourceException, CannotDeleteResourceException, \\\n CloudknotInputError\n\n__all__ = [\"Vpc\", \"SecurityGroup\"]\n\nmod_logger = logging.getLogger(__name__)\n\n\n# noinspection PyPropertyAccess,PyAttributeOutsideInit\nclass Vpc(NamedObject):\n \"\"\"Class for defining an Amazon Virtual Private Cloud (VPC)\"\"\"\n def __init__(self, vpc_id=None, name=None, use_default_vpc=False,\n ipv4_cidr=None, instance_tenancy=None):\n \"\"\"Initialize a Vpc instance\n\n Parameters\n ----------\n vpc_id : string\n VPC-ID for the VPC to be retrieved\n\n name : string\n Name of the VPC to be retrieved or created\n\n use_default_vpc : bool\n if True, create or retrieve the default VPC\n if False, use other input args to create a non-default VPC\n\n ipv4_cidr : string\n IPv4 CIDR block to be used for creation of a new VPC\n\n instance_tenancy : string\n Instance tenancy for this VPC, one of ['default', 'dedicated']\n Default: 'default'\n \"\"\"\n # User must supply vpc_id or name, or specify use_default_vpc\n if not (vpc_id or name or use_default_vpc):\n raise CloudknotInputError('name or vpc_id is required.')\n\n # If user supplies vpc_id, then no other input is allowed\n if vpc_id and any([name, ipv4_cidr, instance_tenancy]):\n raise CloudknotInputError(\n 'You must specify either a VPC id for an existing VPC or '\n 'input parameters for a new VPC. You cannot do both.'\n )\n\n if use_default_vpc and any([\n vpc_id, name, ipv4_cidr, instance_tenancy\n ]):\n raise CloudknotInputError('You may not specify any other input if'\n 'requesting the default VPC')\n\n if use_default_vpc:\n try:\n response = clients['ec2'].create_default_vpc()\n vpc_id = response.get('Vpc').get('VpcId')\n except clients['ec2'].exceptions.ClientError as e:\n error_code = e.response.get('Error').get('Code')\n if error_code == 'DefaultVpcAlreadyExists':\n response = clients['ec2'].describe_vpcs(Filters=[{\n 'Name': 'isDefault',\n 'Values': ['true']\n }])\n vpc_id = response.get('Vpcs')[0].get('VpcId')\n elif error_code == 'UnauthorizedOperation':\n raise CannotCreateResourceException(\n 'Cannot create a default VPC because this is an '\n 'unauthorized operation. You may not have the proper '\n 'permissions to create a default VPC.'\n )\n elif error_code == 'OperationNotPermitted':\n raise CannotCreateResourceException(\n 'Cannot create a default VPC because this is an '\n 'unauthorized operation. You might have resources in '\n 'EC2-Classic in the current region.'\n )\n else:\n raise e\n\n # Check for pre-existence based on vpc_id or name\n resource = self._exists_already(vpc_id, name)\n self._pre_existing = resource.exists\n\n if resource.exists:\n # If resource exists and user supplied an ipv4, abort\n if ipv4_cidr or instance_tenancy:\n raise ResourceExistsException(\n 'The specified ipv4 CIDR block is already in use by '\n 'vpc {id:s}'.format(id=resource.vpc_id),\n resource_id=resource.vpc_id\n )\n\n super(Vpc, self).__init__(name=resource.name)\n\n self._vpc_id = resource.vpc_id\n self._ipv4_cidr = resource.ipv4_cidr\n self._instance_tenancy = resource.instance_tenancy\n self._subnet_ids = resource.subnet_ids\n self._is_default = resource.is_default\n\n self._section_name = self._get_section_name('vpc')\n cloudknot.config.add_resource(\n self._section_name, self.vpc_id, self.name\n )\n\n self._gateway_id = resource.internet_gateway_id\n self._network_acl_ids = resource.net_acl_ids\n self._route_table_ids = resource.route_table_ids\n\n mod_logger.info('Retrieved pre-existing VPC {id:s}'.format(\n id=self.vpc_id\n ))\n else:\n if vpc_id:\n raise ResourceDoesNotExistException(\n 'You specified a vpc_id that does not exist.',\n vpc_id\n )\n\n super(Vpc, self).__init__(name=name)\n\n # Check that ipv4 is a valid network range or set the default value\n if ipv4_cidr:\n try:\n self._ipv4_cidr = str(ipaddress.IPv4Network(\n six.text_type(ipv4_cidr)\n ))\n except (ipaddress.AddressValueError, ValueError):\n raise CloudknotInputError(\n 'If provided, ipv4_cidr must be a valid IPv4 network '\n 'range.'\n )\n else:\n self._ipv4_cidr = str(ipaddress.IPv4Network(u'172.31.0.0/16'))\n if instance_tenancy:\n if instance_tenancy in ('default', 'dedicated'):\n self._instance_tenancy = instance_tenancy\n else:\n raise CloudknotInputError(\n 'If provided, instance tenancy must be '\n 'one of (\"default\", \"dedicated\").'\n )\n else:\n self._instance_tenancy = 'default'\n\n self._vpc_id = self._create()\n self._subnet_ids = self._add_subnets()\n self._is_default = False\n\n # Declare read-only properties\n @property\n def pre_existing(self):\n \"\"\"Boolean flag to indicate whether this resource was pre-existing\n\n True if resource was retrieved from AWS,\n False if it was created on __init__.\n \"\"\"\n return self._pre_existing\n\n @property\n def is_default(self):\n \"\"\"True if this is the default VPC, False otherwise\"\"\"\n return self._is_default\n\n @property\n def ipv4_cidr(self):\n \"\"\"IPv4 CIDR block assigned to this VPC\"\"\"\n return self._ipv4_cidr\n\n @property\n def instance_tenancy(self):\n \"\"\"Instance tenancy for this VPC, one of ['default', 'dedicated']\"\"\"\n return self._instance_tenancy\n\n @property\n def vpc_id(self):\n \"\"\"The ID for this Amazon virtual private cloud\"\"\"\n return self._vpc_id\n\n @property\n def subnet_ids(self):\n \"\"\"List of subnet IDs for this subnets in this VPC\"\"\"\n return self._subnet_ids\n\n def _exists_already(self, vpc_id, name):\n \"\"\"Check if an AWS VPC exists already\n\n If VPC exists, return namedtuple with VPC info. Otherwise, set the\n namedtuple's `exists` field to `False`. The remaining fields default\n to `None`.\n\n Returns\n -------\n namedtuple RoleExists\n A namedtuple with fields ['exists', 'name', 'ipv4_cidr',\n 'instance_tenancy', 'vpc_id', 'subnet_ids', 'is_default',\n 'internet_gateway_id', 'net_acl_ids', 'route_table_ids']\n \"\"\"\n # define a namedtuple for return value type\n ResourceExists = namedtuple(\n 'ResourceExists',\n ['exists', 'name', 'ipv4_cidr', 'instance_tenancy',\n 'vpc_id', 'subnet_ids', 'is_default', 'internet_gateway_id',\n 'net_acl_ids', 'route_table_ids']\n )\n # make all but the first value default to None\n ResourceExists.__new__.__defaults__ = \\\n (None,) * (len(ResourceExists._fields) - 1)\n\n if vpc_id:\n try:\n # If user supplied vpc_id, check that\n response = clients['ec2'].describe_vpcs(VpcIds=[vpc_id])\n\n # Save vpcs for outside the if/else block\n vpcs = response.get('Vpcs')\n except clients['ec2'].exceptions.ClientError as e:\n error_code = e.response['Error']['Code']\n if error_code == 'InvalidVpcID.NotFound':\n # VPC doesn't exist\n # Save vpcs for outside the if/else block\n vpcs = None\n else: # pragma: nocover\n # I can't think of a test case for this\n # But we should pass through any unexpected errors\n raise e\n else:\n # Else check for the tag \"Name: name\"\n response = clients['ec2'].describe_tags(\n Filters=[\n {'Name': 'resource-type', 'Values': ['vpc']},\n {'Name': 'key', 'Values': ['Name']},\n {'Name': 'value', 'Values': [name]}\n ]\n )\n\n if response.get('Tags'):\n vpc_id = response.get('Tags')[0]['ResourceId']\n response = clients['ec2'].describe_vpcs(VpcIds=[vpc_id])\n vpcs = response.get('Vpcs')\n else:\n vpcs = None\n\n if vpcs:\n vpc = vpcs[0]\n try:\n tags = vpc['Tags']\n except KeyError:\n tags = []\n ipv4_cidr = vpc['CidrBlock']\n vpc_id = vpc['VpcId']\n instance_tenancy = vpc['InstanceTenancy']\n is_default = vpc['IsDefault']\n\n # Find the name tag\n try:\n name_tag = list(filter(lambda d: d['Key'] == 'Name', tags))[0]\n name = name_tag['Value']\n except IndexError:\n name = 'cloudknot-acquired-pre-existing-vpc'\n\n retry = tenacity.Retrying(\n wait=tenacity.wait_exponential(max=16),\n stop=tenacity.stop_after_delay(120),\n retry=tenacity.retry_if_exception_type(\n clients['ec2'].exceptions.ClientError\n )\n )\n\n retry.call(\n clients['ec2'].create_tags,\n Resources=[vpc_id],\n Tags=[\n {'Key': 'owner', 'Value': 'cloudknot'},\n {'Key': 'Name', 'Value': name}\n ]\n )\n\n response = clients['ec2'].describe_subnets(Filters=[{\n 'Name': 'vpc-id',\n 'Values': [vpc_id]\n }])\n\n subnet_ids = [d['SubnetId'] for d in response.get('Subnets')]\n\n response = clients['ec2'].describe_internet_gateways(Filters=[{\n 'Name': 'attachment.vpc-id',\n 'Values': [vpc_id]\n }])\n\n gateways = response.get('InternetGateways')\n internet_gateway_id = gateways[0].get('InternetGatewayId') \\\n if gateways else None\n\n response = clients['ec2'].describe_network_acls(Filters=[\n {'Name': 'vpc-id', 'Values': [vpc_id]},\n {'Name': 'default', 'Values': ['false']}\n ])\n\n net_acl_ids = [n['NetworkAclId']\n for n in response.get('NetworkAcls')]\n\n response = clients['ec2'].describe_route_tables(Filters=[\n {'Name': 'vpc-id', 'Values': [vpc_id]},\n {'Name': 'association.main', 'Values': ['false']}\n ])\n\n route_table_ids = [rt['RouteTableId']\n for rt in response.get('RouteTables')]\n\n mod_logger.info(\n 'VPC {vpcid:s} already exists.'.format(vpcid=vpc_id)\n )\n\n return ResourceExists(\n exists=True, name=name, ipv4_cidr=ipv4_cidr,\n instance_tenancy=instance_tenancy, vpc_id=vpc_id,\n subnet_ids=subnet_ids, is_default=is_default,\n internet_gateway_id=internet_gateway_id,\n net_acl_ids=net_acl_ids, route_table_ids=route_table_ids\n )\n else:\n return ResourceExists(exists=False)\n\n def _create(self):\n \"\"\"Create AWS virtual private cloud (VPC) using instance parameters\n\n Returns\n -------\n string\n VPC-ID for the created VPC\n \"\"\"\n response = clients['ec2'].create_vpc(\n CidrBlock=self.ipv4_cidr,\n InstanceTenancy=self.instance_tenancy\n )\n\n vpc_id = response.get('Vpc')['VpcId']\n\n mod_logger.info('Created VPC {vpcid:s}.'.format(vpcid=vpc_id))\n\n # Wait for VPC to exist and be available\n wait_for_vpc = clients['ec2'].get_waiter('vpc_exists')\n wait_for_vpc.wait(VpcIds=[vpc_id])\n wait_for_vpc = clients['ec2'].get_waiter('vpc_available')\n wait_for_vpc.wait(VpcIds=[vpc_id])\n\n retry = tenacity.Retrying(\n wait=tenacity.wait_exponential(max=16),\n stop=tenacity.stop_after_delay(120),\n retry=tenacity.retry_if_exception_type(\n clients['ec2'].exceptions.ClientError\n )\n )\n\n # Tag the VPC with name and owner\n retry.call(\n clients['ec2'].create_tags,\n Resources=[vpc_id],\n Tags=[\n {'Key': 'owner', 'Value': 'cloudknot'},\n {'Key': 'Name', 'Value': self.name}\n ]\n )\n\n # Create and attach an internet gateway to this VPC\n response = clients['ec2'].create_internet_gateway()\n self._gateway_id = response.get('InternetGateway').get(\n 'InternetGatewayId'\n )\n\n clients['ec2'].attach_internet_gateway(\n InternetGatewayId=self._gateway_id,\n VpcId=vpc_id\n )\n\n # Create a route table and add a route for all internet traffic\n response = clients['ec2'].create_route_table(VpcId=vpc_id)\n self._route_table_ids = [\n response.get('RouteTable').get('RouteTableId')\n ]\n\n clients['ec2'].create_route(\n DestinationCidrBlock='0.0.0.0/0',\n GatewayId=self._gateway_id,\n RouteTableId=self._route_table_ids[0],\n )\n\n # Create a network access control list for this VPC\n response = clients['ec2'].create_network_acl(VpcId=vpc_id)\n self._network_acl_ids = [\n response.get('NetworkAcl').get('NetworkAclId')\n ]\n\n # Add this VPC to the list of VPCs in the config file\n self._section_name = self._get_section_name('vpc')\n cloudknot.config.add_resource(self._section_name, vpc_id, self.name)\n\n return vpc_id\n\n def _add_subnets(self):\n \"\"\"Add one subnet to this VPC for each availability zone\"\"\"\n # Add a subnet for each availability zone\n response = clients['ec2'].describe_availability_zones()\n zones = response.get('AvailabilityZones')\n\n # Get an IPv4Network instance representing the VPC CIDR block\n cidr = ipaddress.IPv4Network(six.text_type(self.ipv4_cidr))\n\n # Get list of subnet CIDR blocks truncating list to len(zones)\n subnet_ipv4_cidrs = list(cidr.subnets(new_prefix=20))\n\n # Ensure that the CIDR block has enough addresses to cover each zone\n if len(subnet_ipv4_cidrs) < len(zones): # pragma: nocover\n raise CloudknotInputError('IPv4 CIDR block does not have enough '\n 'addresses for each availability zone')\n\n subnet_ipv4_cidrs = subnet_ipv4_cidrs[:len(zones)]\n\n subnet_ids = []\n\n for zone, subnet_cidr in zip(zones, subnet_ipv4_cidrs):\n # Create a subnet for each zone\n response = clients['ec2'].create_subnet(\n AvailabilityZone=zone['ZoneName'],\n CidrBlock=str(subnet_cidr),\n VpcId=self.vpc_id\n )\n\n subnet_id = response.get('Subnet')['SubnetId']\n clients['ec2'].modify_subnet_attribute(\n MapPublicIpOnLaunch={'Value': True},\n SubnetId=subnet_id\n )\n\n clients['ec2'].associate_route_table(\n RouteTableId=self._route_table_ids[0],\n SubnetId=subnet_id\n )\n\n subnet_ids.append(subnet_id)\n\n mod_logger.info('Created subnet {id:s}.'.format(id=subnet_id))\n\n # Tag all subnets with name and owner\n wait_for_subnet = clients['ec2'].get_waiter('subnet_available')\n retry = tenacity.Retrying(\n wait=tenacity.wait_exponential(max=16),\n stop=tenacity.stop_after_delay(60),\n retry=tenacity.retry_if_exception_type(\n botocore.exceptions.WaiterError\n )\n )\n retry.call(wait_for_subnet.wait, SubnetIds=subnet_ids)\n\n retry = tenacity.Retrying(\n wait=tenacity.wait_exponential(max=16),\n stop=tenacity.stop_after_delay(120),\n retry=tenacity.retry_if_exception_type(\n clients['ec2'].exceptions.ClientError\n )\n )\n\n retry.call(\n clients['ec2'].create_tags,\n Resources=subnet_ids,\n Tags=[\n {'Key': 'owner', 'Value': 'cloudknot'},\n {'Key': 'vpc-name', 'Value': self.name}\n ]\n )\n\n return subnet_ids\n\n def clobber(self):\n \"\"\"Delete this AWS virtual private cloud (VPC)\"\"\"\n if self.clobbered:\n return\n\n self.check_profile_and_region()\n\n try:\n # Only try to delete non-default VPCs\n if not self.is_default:\n retry = tenacity.Retrying(\n wait=tenacity.wait_exponential(max=16),\n stop=tenacity.stop_after_delay(60),\n retry=tenacity.retry_if_exception_type(\n clients['ec2'].exceptions.ClientError\n )\n )\n\n # Delete the subnets\n for subnet_id in self.subnet_ids:\n retry.call(clients['ec2'].delete_subnet,\n SubnetId=subnet_id)\n mod_logger.info('Deleted subnet {id:s}'\n ''.format(id=subnet_id))\n\n # Delete the network ACL\n for net_id in self._network_acl_ids:\n retry.call(clients['ec2'].delete_network_acl,\n NetworkAclId=net_id)\n\n # Delete the route table\n for rt_id in self._route_table_ids:\n retry.call(clients['ec2'].delete_route_table,\n RouteTableId=rt_id)\n\n # Detach and delete the internet gateway\n if self._gateway_id:\n retry.call(clients['ec2'].detach_internet_gateway,\n InternetGatewayId=self._gateway_id,\n VpcId=self.vpc_id)\n retry.call(clients['ec2'].delete_internet_gateway,\n InternetGatewayId=self._gateway_id)\n\n # Delete the VPC\n retry.call(clients['ec2'].delete_vpc, VpcId=self.vpc_id)\n\n # Remove this VPC from the list of VPCs in the config file\n cloudknot.config.remove_resource(self._section_name, self.vpc_id)\n\n # Set the clobbered parameter to True,\n # preventing subsequent method calls\n self._clobbered = True\n\n mod_logger.info('Deleted VPC {name:s}'.format(name=self.name))\n except clients['ec2'].exceptions.ClientError as e:\n # Check for dependency violation and pass exception to user\n error_code = e.response['Error']['Code']\n if error_code == 'DependencyViolation':\n response = clients['ec2'].describe_security_groups(\n Filters=[{\n 'Name': 'vpc-id',\n 'Values': [self.vpc_id]\n }]\n )\n\n ids = [sg['GroupId']\n for sg in response.get('SecurityGroups')]\n\n raise CannotDeleteResourceException(\n 'Could not delete this VPC because it has '\n 'dependencies. It may have security groups associated '\n 'with it. If you still want to delete this VPC, you '\n 'should first delete the security groups with the '\n 'following IDs {sg_ids!s}'.format(sg_ids=ids),\n resource_id=ids\n )\n else: # pragma: nocover\n # I can't think of a test case to make this happen\n raise e\n except tenacity.RetryError as error:\n try:\n error.reraise()\n except clients['ec2'].exceptions.ClientError as e:\n # Check for dependency violation and pass exception to user\n error_code = e.response['Error']['Code']\n if error_code == 'DependencyViolation':\n response = clients['ec2'].describe_security_groups(\n Filters=[{\n 'Name': 'vpc-id',\n 'Values': [self.vpc_id]\n }]\n )\n\n ids = [sg['GroupId']\n for sg in response.get('SecurityGroups')]\n\n raise CannotDeleteResourceException(\n 'Could not delete this VPC because it has '\n 'dependencies. It may have security groups associated '\n 'with it. If you still want to delete this VPC, you '\n 'should first delete the security groups with the '\n 'following IDs {sg_ids!s}'.format(sg_ids=ids),\n resource_id=ids\n )\n else: # pragma: nocover\n # I can't think of a test case to make this happen\n raise e\n\n\n# noinspection PyPropertyAccess,PyAttributeOutsideInit\nclass SecurityGroup(NamedObject):\n \"\"\"Class for defining an AWS Security Group\"\"\"\n def __init__(self, security_group_id=None, name=None, vpc=None,\n description=None):\n \"\"\"Initialize an AWS Security Group.\n\n Parameters\n ----------\n security_group_id : string\n ID of the security group to be retrieved\n\n name : string\n Name of the security group to be created\n\n vpc : Vpc\n Amazon virtual private cloud in which to establish this\n security group\n\n description : string\n description of this security group\n if description == None (default), then description is set to\n \"This security group was generated by cloudknot\"\n Default: None\n \"\"\"\n # User must specify either an ID or a name and VPC\n if not (security_group_id or (name and vpc)):\n raise CloudknotInputError(\n 'You must specify either a security group id for an existing '\n 'security group or a name and VPC for a new security group.'\n )\n\n # Check that user didn't over-specify input\n if security_group_id and any([name, vpc, description]):\n raise CloudknotInputError(\n 'You must specify either a security group id for an existing '\n 'security group or input parameters for a new security group. '\n 'You cannot do both.'\n )\n\n # Validate VPC input\n if vpc and not isinstance(vpc, Vpc):\n raise CloudknotInputError('If provided, vpc must be an '\n 'instance of Vpc.')\n\n vpc_id = vpc.vpc_id if vpc else None\n\n resource = self._exists_already(security_group_id, name, vpc_id)\n self._pre_existing = resource.exists\n\n if resource.exists:\n super(SecurityGroup, self).__init__(name=resource.name)\n\n self._vpc = None\n self._vpc_id = resource.vpc_id\n self._description = resource.description\n self._security_group_id = resource.security_group_id\n\n if name or vpc:\n raise ResourceExistsException(\n 'The security group name {name:s} is already in use for '\n 'VPC {vpc_id:s}. If you would like to retrieve this '\n 'security group, try SecurityGroup(security_group_id='\n '{sg_id:s}).'.format(\n name=self.name, vpc_id=self.vpc_id,\n sg_id=self.security_group_id\n ),\n resource_id=self.security_group_id\n )\n\n self._section_name = self._get_section_name('security-groups')\n cloudknot.config.add_resource(\n self._section_name, self.security_group_id, self.name\n )\n\n mod_logger.info(\n 'Retrieved pre-existing security group {id:s}'.format(\n id=self.security_group_id\n )\n )\n else:\n if security_group_id:\n raise ResourceDoesNotExistException(\n 'The security group ID that you provided does not exist.',\n resource_id=security_group_id\n )\n\n super(SecurityGroup, self).__init__(name=name)\n\n self._vpc = vpc\n self._vpc_id = vpc.vpc_id\n self._description = str(description) if description else \\\n 'This security group was automatically generated by cloudknot.'\n self._security_group_id = self._create()\n\n # Declare read-only properties\n @property\n def pre_existing(self):\n \"\"\"Boolean flag to indicate whether this resource was pre-existing\n\n True if resource was retrieved from AWS,\n False if it was created on __init__.\n \"\"\"\n return self._pre_existing\n\n @property\n def vpc(self):\n \"\"\"Amazon virtual private cloud in which this security group resides\"\"\"\n return self._vpc\n\n @property\n def vpc_id(self):\n \"\"\"ID for the VPC in which this security group resides\"\"\"\n return self._vpc_id\n\n @property\n def description(self):\n \"\"\"The description for this security group\"\"\"\n return self._description\n\n @property\n def security_group_id(self):\n \"\"\"The AWS ID for this security group\"\"\"\n return self._security_group_id\n\n def _exists_already(self, security_group_id, name, vpc_id):\n \"\"\"Check if an AWS security group exists already\n\n If security group exists, return namedtuple with security group info.\n Otherwise, set the namedtuple's `exists` field to `False`. The\n remaining fields default to `None`.\n\n Returns\n -------\n namedtuple RoleExists\n A namedtuple with fields\n ['exists', 'name', 'vpc_id', 'description', 'security_group_id']\n \"\"\"\n # define a namedtuple for return value type\n ResourceExists = namedtuple(\n 'ResourceExists',\n ['exists', 'name', 'vpc_id', 'description', 'security_group_id']\n )\n # make all but the first value default to None\n ResourceExists.__new__.__defaults__ = \\\n (None,) * (len(ResourceExists._fields) - 1)\n\n if security_group_id:\n try:\n response = clients['ec2'].describe_security_groups(\n GroupIds=[security_group_id]\n )\n except clients['ec2'].exceptions.ClientError as e:\n # If the group_id doesn't exist or isn't formatted correctly,\n # return exists=False\n if e.response.get('Error')['Code'] in [\n 'InvalidGroup.NotFound', 'InvalidGroupId.Malformed'\n ]:\n return ResourceExists(exists=False)\n else: # pragma: no cover\n # I could not think of a unit test case where the\n # describe_security_groups request would yield a different\n # error, but one should still pass through unhandled\n # errors even if (especially if) one can't think of what\n # they'll be.\n raise e\n else:\n response = clients['ec2'].describe_security_groups(\n Filters=[\n {\n 'Name': 'group-name',\n 'Values': [name]\n },\n {\n 'Name': 'vpc-id',\n 'Values': [vpc_id]\n }\n ]\n )\n\n sg = response.get('SecurityGroups')\n if sg:\n name = sg[0]['GroupName']\n vpc_id = sg[0]['VpcId']\n description = sg[0]['Description']\n group_id = sg[0]['GroupId']\n return ResourceExists(\n exists=True, name=name, vpc_id=vpc_id, description=description,\n security_group_id=group_id\n )\n else:\n return ResourceExists(exists=False)\n\n def _create(self):\n \"\"\"Create AWS security group using instance parameters\n\n Returns\n -------\n string\n security group ID for the created security group\n \"\"\"\n # Create the security group\n response = clients['ec2'].create_security_group(\n GroupName=self.name,\n Description=self.description,\n VpcId=self.vpc.vpc_id\n )\n\n group_id = response.get('GroupId')\n\n # Add ingress rules to the security group\n ipv4_ranges = [{\n 'CidrIp': '0.0.0.0/0'\n }]\n\n ipv6_ranges = [{\n 'CidrIpv6': '::/0'\n }]\n\n ip_permissions = [{\n 'IpProtocol': 'TCP',\n 'FromPort': 80,\n 'ToPort': 80,\n 'IpRanges': ipv4_ranges,\n 'Ipv6Ranges': ipv6_ranges\n }, {\n 'IpProtocol': 'TCP',\n 'FromPort': 22,\n 'ToPort': 22,\n 'IpRanges': ipv4_ranges,\n 'Ipv6Ranges': ipv6_ranges\n }]\n\n retry = tenacity.Retrying(\n wait=tenacity.wait_exponential(max=16),\n stop=tenacity.stop_after_delay(120),\n retry=tenacity.retry_if_exception_type(\n clients['ec2'].exceptions.ClientError\n )\n )\n retry.call(\n clients['ec2'].authorize_security_group_ingress,\n GroupId=group_id,\n IpPermissions=ip_permissions\n )\n\n mod_logger.info('Created security group {id:s}'.format(id=group_id))\n\n # Tag the security group with owner=cloudknot\n retry.call(\n clients['ec2'].create_tags,\n Resources=[group_id],\n Tags=[{'Key': 'owner', 'Value': 'cloudknot'}]\n )\n\n # Add this security group to the config file\n self._section_name = self._get_section_name('security-groups')\n cloudknot.config.add_resource(self._section_name, group_id, self.name)\n\n return group_id\n\n def clobber(self):\n \"\"\"Delete this AWS security group and associated resources\"\"\"\n if self.clobbered:\n return\n\n self.check_profile_and_region()\n\n # Get dependent EC2 instances\n response = clients['ec2'].describe_instances(Filters=[{\n 'Name': 'vpc-id',\n 'Values': [self.vpc_id]\n }])\n\n def has_security_group(instance, sg_id):\n return sg_id in [d['GroupId'] for d in instance['SecurityGroups']]\n\n deps = []\n for r in response.get('Reservations'):\n deps = deps + [i['InstanceId'] for i in r['Instances']\n if has_security_group(i, self.security_group_id)]\n\n # Delete the dependent instances\n if deps:\n clients['ec2'].terminate_instances(InstanceIds=deps)\n mod_logger.warning(\n 'Deleted dependent EC2 instances: {deps!s}'.format(deps=deps)\n )\n\n # Delete the security group\n retry = tenacity.Retrying(\n wait=tenacity.wait_exponential(max=16),\n stop=tenacity.stop_after_delay(300),\n retry=tenacity.retry_if_exception_type(\n botocore.exceptions.ClientError\n )\n )\n retry.call(\n clients['ec2'].delete_security_group,\n GroupId=self.security_group_id\n )\n\n # Remove this VPC from the list of VPCs in the config file\n cloudknot.config.remove_resource(\n self._section_name, self.security_group_id\n )\n\n # Set the clobbered parameter to True,\n # preventing subsequent method calls\n self._clobbered = True\n\n mod_logger.info('Clobbered security group {id:s}'.format(\n id=self.security_group_id\n ))\n","sub_path":"cloudknot/aws/ec2.py","file_name":"ec2.py","file_ext":"py","file_size_in_byte":33596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"152559197","text":"# -*- coding: utf-8 -*-\n'''\nCreated on Sep 7, 2017\n\n@author: tom\n'''\nfrom __future__ import absolute_import, division, unicode_literals, print_function\nimport logging\nimport os\nimport re\n\n\ndef get_latest_model(model_folder):\n '''\n Returns the path to the latest model in a folder, using the\n epoch number.\n\n We assume the epoch number is specified in the model name as:\n ...epoch023...hdf5\n\n Args:\n model_folder: Path to the folder where to search for the latest\n model.\n\n Returns:\n A tuple (, ).\n If no model could be found, returns: (-1, None).\n '''\n pattern = r'.*epoch(?P[0-9]+)-.*\\.hdf5'\n latest_epoch_id = -1\n latest_model_path = None\n for filename in os.listdir(model_folder):\n model_match = re.search(pattern, filename)\n if not model_match:\n continue\n epoch_id = int(model_match.group('epoch_id'))\n if epoch_id > latest_epoch_id:\n latest_epoch_id = epoch_id\n latest_model_path = os.path.join(model_folder, filename)\n return latest_epoch_id, latest_model_path\n\n\nif __name__ == '__main__':\n logging.basicConfig()\n","sub_path":"second_hand_cars/ml/experiments/experiments_utils.py","file_name":"experiments_utils.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"69933428","text":"#!/usr/bin/env python3\n# Copyright (c) 2018, CNRS-LAAS\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport datetime\nimport threading\nimport subprocess\nimport pymorse\nimport tempfile\n\nimport numpy as np\n\nimport rospy\nfrom std_msgs.msg import Header\nfrom geometry_msgs.msg import Point\n\nfrom fire_rs.simulation.morse import MorseWildfire\n\nimport serialization\n\nfrom supersaop.msg import Timed2DPointStamped, WildfireMap\n\n\nclass Resource:\n def __init__(self):\n self._value = None\n self._ready = threading.Event()\n\n def set(self, value):\n self._value = value\n self._ready.set()\n\n def get(self):\n val = self._value\n self._ready.clear()\n return val\n\n def is_ready(self):\n return self._ready.is_set()\n\n def wait(self, timeout=None):\n self._ready.wait(timeout)\n\n\nclass MorseProcess:\n def __init__(self, path, sim_env, python_path=None):\n self.path = path\n self.sim_env = sim_env\n self.python_path = None\n if python_path is not None:\n self.python_path = {'PYTHONPATH': python_path}\n self.process = None\n\n def run(self):\n self.process = subprocess.Popen(args=['morse', 'run', self.sim_env], cwd=self.path,\n env=self.python_path)\n if self.is_alive():\n rospy.loginfo(\"Morse is running\")\n\n def kill(self):\n if self.process:\n self.process.kill()\n\n def is_alive(self):\n if self.process:\n if self.process.poll() is None:\n return True\n else:\n return False\n\n\nclass MorseWildfireNode:\n def __init__(self, wildfire_res):\n rospy.init_node(\"morse_wildfire\")\n rospy.loginfo(\"Starting {}\".format(self.__class__.__name__))\n\n self.sub_predicted_wildfire = rospy.Subscriber(\"real_wildfire\", WildfireMap,\n callback=self.on_predicted_wildfire,\n queue_size=1)\n self.shared_wildfire_map = wildfire_res\n\n def on_predicted_wildfire(self, msg: WildfireMap):\n rospy.loginfo(\"Wildfire map received\")\n raster = serialization.geodata_from_raster_msg(msg.raster, \"ignition\")\n self.shared_wildfire_map.set(raster)\n\n\nif __name__ == '__main__':\n\n address = ('localhost', 4000)\n terrain_obj_name = \"elevation\"\n\n wf = Resource()\n node = MorseWildfireNode(wf)\n m = MorseWildfire(address, terrain_obj_name)\n\n stop_signal = False\n\n def update_map():\n while not (rospy.is_shutdown() or stop_signal):\n wf.wait(timeout=1.)\n if wf.is_ready():\n m.set_wildfire_prediction_map(wf.get())\n\n th = threading.Thread(target=update_map, daemon=True)\n th.start()\n\n try:\n r = rospy.Rate(1 / 60.) # Once a minute\n rospy.sleep(1.)\n while not rospy.is_shutdown():\n try:\n rospy.loginfo(\"Updating wildfire in morse\")\n m.update(rospy.Time.now().to_sec())\n except ConnectionError as e:\n rospy.logerr(e)\n except ValueError as e:\n rospy.logwarn(e)\n r.sleep()\n except rospy.ROSInterruptException:\n stop_signal = True\n th.join()\n","sub_path":"supersaop/src/morse_wildfire.py","file_name":"morse_wildfire.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"425235683","text":"from backend.contexts.context import HeuristicException, UnderstandingProcessor\nfrom backend.contexts.LCTContext import LCTContext\nfrom backend.models.fr import FR\nfrom backend.models.graph import Frame, Identifier\nfrom functools import reduce\n\nimport operator\n\n\n# Finds learned tasks in long-term memory that relate to the input \"to do\" task, and moves them into working memory.\n# To do this, the following must be true:\n# 1) The TMR is prefix\n# 2) There are matching events in LT memory that have the same concept as the main TMR event, and share at least\n# THEME (by concept).\n# For each match found, load the entire of that event (by LCT.from_context ID) into working memory.\nclass RecallTaskFromLongTermMemoryUnderstandingProcessor(UnderstandingProcessor):\n\n def __init__(self, context):\n super().__init__()\n self.context = context\n\n def _logic(self, agent, tmr):\n\n if not tmr.is_prefix():\n raise HeuristicException()\n\n def _fillers_to_concepts(graph, fillers):\n return set(map(lambda filler: filler.resolve().concept(), fillers))\n\n event = tmr.find_main_event()\n themes = _fillers_to_concepts(tmr, event[\"THEME\"])\n\n results = agent.lt_memory.search(Frame.q(agent).isa(event.concept()))\n results = list(filter(lambda result: len(_fillers_to_concepts(agent.lt_memory, result[\"THEME\"]).intersection(themes)) > 0, results))\n\n if len(results) == 0:\n raise HeuristicException()\n\n for result in results:\n id_map = {}\n temp = FR(\"TEMP\", agent.ontology)\n for instance in agent.lt_memory.search(Frame.q(agent).f(LCTContext.FROM_CONTEXT, result[LCTContext.FROM_CONTEXT][0])):\n id_map[instance._identifier.render()] = instance._identifier.render(graph=False)\n id = Identifier(None, instance._identifier.name, instance=instance._identifier.instance)\n temp[id] = instance\n\n for instance in temp:\n for slot in temp[instance]:\n for filler in temp[instance][slot]:\n if isinstance(filler._value, Identifier) and filler._value.render() in id_map:\n filler._value = id_map[filler._value.render()]\n\n id_map = agent.wo_memory.import_fr(temp)\n\n agent.wo_memory[id_map[result._identifier.render()]][self.context.DOING] = True\n\n\n# Assuming a currently doing task, finds any preconditions for that task and makes them into actions on the agent queue.\n# 1) There are events marked as ACT.doing\n# 2) Those events have PRECONDITIONs\n# For each matching precondition, map it to an action to take (if applicable) and add those actions to the agent queue.\nclass QueuePreconditionActionsUnderstandingProcessor(UnderstandingProcessor):\n\n def __init__(self, context):\n super().__init__()\n self.context = context\n\n def _logic(self, agent, tmr):\n doing = agent.wo_memory.search(Frame.q(agent).f(self.context.DOING, True))\n\n if len(doing) == 0:\n raise HeuristicException()\n\n preconditions = list(map(lambda filler: filler.resolve(), reduce(operator.add, map(lambda event: event[\"PRECONDITION\"], doing))))\n\n if len(preconditions) == 0:\n raise HeuristicException()\n\n agent.action_queue.extend(set(filter(lambda action: action is not None, map(lambda precondition: self.precondition_to_action(agent, precondition), preconditions))))\n\n def precondition_to_action(self, agent, precondition):\n if precondition ^ agent.ontology[\"POSSESSION-EVENT\"]:\n themes = set(map(lambda theme: theme.resolve().concept(), precondition[\"THEME\"]))\n\n if len(themes) == 0:\n return None\n\n actions = list(map(lambda theme: \"ROBOT.GET(\" + theme + \")\", themes))\n\n return \" and \".join(actions)\n\n return None","sub_path":"backend/heuristics/actcontext/act_agenda_heuristics.py","file_name":"act_agenda_heuristics.py","file_ext":"py","file_size_in_byte":3904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"370648725","text":"import matplotlib\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\nfrom matplotlib.figure import Figure\nfrom array import array\n\nimport tkinter as tk\nfrom tkinter import ttk\nimport numpy as np\nimport can\nimport time\nimport csv\n\n\nLARGE_FONT= (\"Verdana\", 12)\n\n\ndef compress(x, y):\n # Combine steps which have equal values\n\n #If we were to set same value during more time\n #we would take x axis take range of values\n\n ny = np.concatenate([[np.nan], y, [np.nan]])\n ys = np.diff(ny) != 0\n x = x[ys]\n y = y[ys[:-1]]\n pass\n\n\nclass TestSetup(tk.Tk):\n\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n\n tk.Tk.wm_title(self, \"Dynamic Inverter Test Setup\")\n\n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand=True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n content = tk.StringVar()\n global rms\n #rms = np.zeros(10, dtype=int)\n # up to 10 entries\n rms = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n global second\n second = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n self.counter = 0\n\n with open('logger.csv', mode='w') as csv_file:\n global fieldnames\n fieldnames = ['timestamp', 'id', 'value']\n global writer\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n\n writer.writeheader()\n\n self.frames = {}\n\n for F in (StartPage, PageOne):\n frame = F(container, self)\n\n self.frames[F] = frame\n\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n self.show_frame(StartPage)\n\n def draw(self):\n\n f = Figure(figsize=(5, 5), dpi=100)\n b = f.add_subplot(111)\n\n\n b.plot(second[0:self.counter], rms[0:self.counter], drawstyle='steps')\n #b.step(second[0:self.counter], rms[0:self.counter])\n canvas = FigureCanvasTkAgg(f, self)\n canvas.draw()\n canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)\n\n toolbar = NavigationToolbar2Tk(canvas, self)\n toolbar.update()\n canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)\n\n ax = f.gca() # get axis handle\n\n line = ax.lines[0]\n xaxis=line.get_xdata()\n yaxis = line.get_ydata()\n print(xaxis)\n print(yaxis)\n\n #print(np.piecewise(rms[0:self.counter], second[0:self.counter]))\n # I want from every second, 4 values\n #value = 4\n valu = int(str(value.get()))\n countt = 0\n prevlen=0\n repeatt = np.empty(500)\n global new\n new = np.empty(0)\n print(len(xaxis))\n for r in np.nditer(xaxis):\n # number of seconds\n if (countt != 0) and (countt1):\n\t\t\t\t\toutputfile.write(line2)\n\t\tif(cnt>1):\n\t\t\toutputfile.write(line1)\n\t\telse:\n\t\t\tfinal_userfile.write(line1)\n\n\narg=list(sys.argv)\ninputfile1=open(arg[1],\"r\")\ninputfile2=open(arg[1],\"r\")\noutputfile=open(\"Duplicate_UserIDs.csv\",\"w+\")\nfinal_userfile=open(\"final_userfile.csv\",\"w+\")\ncolumn_to_search_for_userid=0\nskip_first_line=\"y\"\nFindDuplicateUserID(column_to_search_for_userid,skip_first_line)\n\ninputfile1.seek(0,0)\ninputfile2.seek(0,0)\nsendmail.sendmailto(\"Duplicate_UserIDs.csv,final_userfile.csv\")\nprint(\"Email sent successfully. Please check your inbox....!!!\")\n\n","sub_path":"Automation/alerts_testsuite/migration/AG_csv_file_proccessing/Advisorgroup_csv_automation_DEV/Userfile_processing.py","file_name":"Userfile_processing.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"357899341","text":"#Creating HTML file in Python\r\n\r\ncreatefile=open('ourHtmlFile.html','w')\r\n\r\n\r\ncreatefile.write(\"\"\r\n \"\\n\"\r\n\t\t \"\\n\"\r\n\t\t \"\\nPyhton Course\"\r\n\t\t \"\\n\"\r\n\t\t \"\\n\"\r\n\t\t \"\\n

    This is Our HTML File!

    \"\r\n\t\t \"\\n\"\r\n\t\t \"\\n\"\r\n\t\t )\r\ncreatefile.close()","sub_path":"filehandling/createhtmlfile.py","file_name":"createhtmlfile.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"16491816","text":"import json # 파이썬 표준라이브러리인 json의 모든 코드를 임포트한다.\n\nfrom urllib.request import urlopen # 표준 urllib 라이브러리에서 urlopen 함수만 임포트한다.\n\n# 웹사이트 주소를 url변수에 할당한다.\nurl = \"https://raw.githubusercontent.com/AstinChoi/introducing-python/master/intro/top_rated.json\"\n\nresponse = urlopen(url) # URL에 해당하는 웹 서버에 연결하고 특정 웹 서비스를 요청한다.\ncontents = response.read() # 요청한 데이터를 얻어서 contents 변수에 할당한다.\ntext = contents.decode('utf8') # 데이터를 JSON 형식으로 된 텍스트 문자열로 디코딩하고 text 변수에 담는다.\ndata = json.loads(text) # 동영상에 대한 자료가 담긴 text변수를 파이썬의 자료구조로 변환해서 data 변수에 담는다.\n\n# 한 번에 한 동영상에 대한 정보를 얻어 와서 이를 video 변수에 담는다.\n# 2차원 딕셔너리(data['feed']['entry'])와 슬라이스([0:6])를 사용한다.\nprint('0 To 6 ]=========================')\nfor video in data['feed']['entry'][0:6]:\n print(video['title']['$t']) # 동영상의 제목을 print함수로 출력한다\n\n# 한 번에 한 동영상에 대한 정보를 얻어 와서 이를 video 변수에 담는다.\nprint('\\nall ]============================')\nfor video in data['feed']['entry']:\n print(video['title']['$t']) # 동영상의 제목을 print함수로 출력한다","sub_path":"01_intro/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"499792269","text":"from mint import Grid\nimport numpy\nimport sys\nfrom pathlib import Path\nimport vtk\n\n\ndef test_create_grid():\n # create the grid\n gr = Grid()\n # 2 cells\n points = numpy.array([(0., 0., 0.),\n (1., 0., 0.),\n (1., 1., 0.),\n (0., 1., 0.),\n (1., 0., 0.),\n (2., 0., 0.),\n (2., 1., 0.),\n (1., 1., 0.)]).reshape(2, 4, 3)\n gr.setPoints(points)\n gr.dump('test_create_grid.vtk')\n\ndef test_attach_data():\n # create the grid\n gr = Grid()\n # 2 cells\n points = numpy.array([(0., 0., 0.),\n (1., 0., 0.),\n (1., 1., 0.),\n (0., 1., 0.),\n (1., 0., 0.),\n (2., 0., 0.),\n (2., 1., 0.),\n (1., 1., 0.)]).reshape(2, 4, 3)\n gr.setPoints(points)\n # create cell data, 3 per cell\n nDataPerCell = 3\n data = numpy.arange(0, 2*nDataPerCell, dtype=numpy.float64).reshape((2, nDataPerCell))\n gr.attach('mydata', data)\n gr.dump('test_create_grid_with_data.vtk')\n # read the data back to check the layout of the data\n reader = vtk.vtkUnstructuredGridReader()\n reader.SetFileName('test_create_grid_with_data.vtk')\n reader.Update()\n ugrid = reader.GetOutput()\n arr = ugrid.GetCellData().GetArray('mydata')\n assert(arr.GetNumberOfTuples() == gr.getNumberOfCells())\n assert(arr.GetNumberOfComponents() == nDataPerCell)\n\ndef test_load_grid():\n gr = Grid()\n gr.load('test_create_grid.vtk')\n ncells = gr.getNumberOfCells()\n print(f'ncells = {ncells}')\n assert(ncells == 2)\n\ndef test_load_from_ugrid_file():\n data_dir = Path(__file__).absolute().parent / '../../data'\n gr = Grid()\n gr.setFlags(1, 1)\n filename = str(data_dir / Path('cs_4.nc'))\n gr.loadFrom2DUgrid(f'{filename}:physics')\n nedges = gr.getNumberOfEdges()\n print(f'nedges = {nedges}')\n assert(nedges == 192)\n ncells = gr.getNumberOfCells()\n for icell in range(ncells):\n for iedge in range(4):\n edgeId, edgeSign = gr.getEdgeId(icell, iedge)\n nodeIds = gr.getNodeIds(icell, iedge)\n print(f'cell {icell} edge {iedge}: edgeId = {edgeId}, {edgeSign} nodeIds = {nodeIds}')\n # attaching a 3 components field to the grid\n data = numpy.array(range(ncells*4*3), numpy.float64)\n gr.attach('myData', data)\n\ndef test_edge_arc_lengths():\n data_dir = Path(__file__).absolute().parent / '../../data'\n gr = Grid()\n gr.setFlags(1, 1)\n filename = str(data_dir / Path('cs_4.nc'))\n gr.loadFrom2DUgrid(f'{filename}:physics')\n gr.computeEdgeArcLengths()\n ncells = gr.getNumberOfCells()\n for icell in range(ncells):\n for edgeIndex in range(4):\n arcLength = gr.getEdgeArcLength(icell, edgeIndex)\n print(f'cell {icell} edge {edgeIndex} edge arc length (radius=1): {arcLength}')\n\n\nif __name__ == '__main__':\n\n test_edge_arc_lengths()\n test_attach_data()\n test_create_grid()\n test_load_grid()\n test_load_from_ugrid_file()\n\n","sub_path":"mint/tests/test_grid.py","file_name":"test_grid.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"541022374","text":"#!/usr/bin/env python\n## fui Copyright (C) 2008 Donn.C.Ingle\n## Contact: donn.ingle@gmail.com - I hope this email lasts.\n##\n## This file is part of fui.\n## fui 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 3 of the License, or\n## (at your option) any later version.\n##\n## fui 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 fui. If not, see .\n\n\nimport os, sys, glob, fnmatch\nfrom distutils.core import setup, Extension\nimport distutils.command.install_data\n\nimport fuimodules.i18n # to install gettext for fuimodules.strings\nimport fuimodules.strings\n\n## Code borrowed from wxPython's setup and config files\n## Thanks to Robin Dunn for the suggestion.\n## I am not 100% sure what's going on, but it works!\ndef opj(*args):\n path = os.path.join(*args)\n return os.path.normpath(path)\n\n# Specializations of some distutils command classes\nclass wx_smart_install_data(distutils.command.install_data.install_data):\n \"\"\"need to change self.install_dir to the actual library dir\"\"\"\n def run(self):\n install_cmd = self.get_finalized_command('install')\n self.install_dir = getattr(install_cmd, 'install_lib')\n return distutils.command.install_data.install_data.run(self)\n\ndef find_data_files(srcdir, *wildcards, **kw):\n # get a list of all files under the srcdir matching wildcards,\n # returned in a format to be used for install_data\n def walk_helper(arg, dirname, files):\n if '.svn' in dirname:\n return\n names = []\n lst, wildcards = arg\n for wc in wildcards:\n wc_name = opj(dirname, wc)\n for f in files:\n filename = opj(dirname, f)\n if \".pyc\" not in filename:\n if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):\n names.append(filename)\n if names:\n lst.append( (dirname, names ) )\n\n file_list = []\n recursive = kw.get('recursive', True)\n if recursive:\n os.path.walk(srcdir, walk_helper, (file_list, wildcards))\n else:\n walk_helper((file_list, wildcards),\n srcdir,\n [os.path.basename(f) for f in glob.glob(opj(srcdir, '*'))])\n return file_list\n\n## This is a list of files to install, and where:\n## Make sure the MANIFEST.in file points to all the right \n## directories too.\nfiles = find_data_files('fuimodules/', '*.*')\n\nsetup(name = fuimodules.strings.appname,\n version = fuimodules.strings.version,\n description = fuimodules.strings.description,\n author = \"Donn.C.Ingle\",\n author_email = fuimodules.strings.contact,\n license = fuimodules.strings.licence,\n url = fuimodules.strings.url,\n packages = ['fuimodules'],\n data_files = files,\n ## Borrowed from wxPython too:\n ## Causes the data_files to be installed into the modules directory.\n ## Override some of the default distutils command classes with my own.\n cmdclass = { 'install_data': wx_smart_install_data },\n\n scripts = [fuimodules.strings.appname],\n long_description = fuimodules.strings.long_description,\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'Intended Audience :: End Users/Desktop',\n 'License :: OSI Approved :: GNU General Public License (GPL)',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python',\n 'Topic :: Utilities',\n ]\n)\n","sub_path":"pypi_install_script/fui-0.0.7.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"426020154","text":"import os\n\nfrom urllib.parse import urlencode\n\nfrom requests import Session\n\n\nAPI_URL = os.getenv(\n \"BLOG_API\", \"https://admin.insights.ubuntu.com/wp-json/wp/v2\"\n)\n\napi_session = Session()\n\n\ndef process_response(response):\n response.raise_for_status()\n\n return response.json()\n\n\ndef build_url(endpoint, params={}):\n \"\"\"\n Build url to fetch articles from Wordpress api\n :param endpoint: The REST endpoint to fetch data from\n :param params: Dictionary of parameter keys and their values\n\n :returns: URL to Wordpress api\n \"\"\"\n\n clean_params = {}\n for key, value in params.items():\n if value:\n if type(value) is list:\n clean_params[key] = \",\".join(str(item) for item in value)\n else:\n clean_params[key] = value\n\n query = urlencode({**clean_params, \"_embed\": \"true\"})\n\n return f\"{API_URL}/{endpoint}?{query}\"\n\n\ndef get_articles(\n tags=None,\n tags_exclude=None,\n exclude=None,\n categories=None,\n sticky=None,\n before=None,\n after=None,\n author=None,\n groups=None,\n per_page=12,\n page=1,\n):\n \"\"\"\n Get articles from Wordpress api\n :param tags: Array of tag ids to fetch articles for\n :param per_page: Articles to get per page\n :param page: Page number to get\n :param tags_exclude: Array of IDs of tags that will be excluded\n :param exclude: Array of article IDs to be excluded\n :param categories: Array of categories, which articles\n should be fetched for\n :param sticky: string 'true' or 'false' to only get featured articles\n :param before: ISO8601 compliant date string to limit by date\n :param after: ISO8601 compliant date string to limit by date\n :param author: Name of the author to fetch articles from\n\n :returns: response, metadata dictionary\n \"\"\"\n url = build_url(\n \"posts\",\n {\n \"tags\": tags,\n \"per_page\": per_page,\n \"page\": page,\n \"tags_exclude\": tags_exclude,\n \"exclude\": exclude,\n \"categories\": categories,\n \"group\": groups,\n \"sticky\": sticky,\n \"before\": before,\n \"after\": after,\n \"author\": author,\n },\n )\n\n response = api_session.get(url)\n total_pages = response.headers.get(\"X-WP-TotalPages\")\n total_posts = response.headers.get(\"X-WP-Total\")\n\n return (\n process_response(response),\n {\"total_pages\": total_pages, \"total_posts\": total_posts},\n )\n\n\ndef get_article(slug, tags=None, tags_exclude=None):\n \"\"\"\n Get an article from Wordpress api\n :param slug: Article slug to fetch\n \"\"\"\n url = build_url(\n \"posts\", {\"slug\": slug, \"tags\": tags, \"tags_exclude\": tags_exclude}\n )\n\n response = api_session.get(url)\n\n data = process_response(response)\n if len(data) > 0:\n return data[0]\n else:\n return None\n\n\ndef get_tag_by_name(name):\n url = build_url(\"tags\", {\"search\": name})\n\n response = api_session.get(url)\n\n try:\n tag_response = process_response(response)\n return tag_response[0]\n except Exception:\n return None\n\n\ndef get_tags_by_ids(ids):\n url = build_url(\"tags\", {\"include\": ids})\n\n response = api_session.get(url)\n\n return process_response(response)\n\n\ndef get_categories():\n url = build_url(\"categories\", {\"per_page\": 100})\n\n response = api_session.get(url)\n\n return process_response(response)\n\n\ndef get_group_by_slug(slug):\n url = build_url(\"group\", {\"slug\": slug})\n\n response = api_session.get(url)\n\n if not response.ok:\n return None\n try:\n groups_response = process_response(response)\n return groups_response[0]\n except Exception:\n return None\n\n\ndef get_group_by_id(id):\n url = build_url(f\"group/{str(id)}\")\n\n response = api_session.get(url)\n group = process_response(response)\n return group\n\n\ndef get_category_by_slug(slug):\n url = build_url(\"categories\", {\"slug\": slug})\n\n response = api_session.get(url)\n\n if not response.ok:\n return None\n try:\n category = process_response(response)\n return category[0]\n except Exception:\n return None\n\n\ndef get_category_by_id(id):\n url = build_url(f\"categories/{str(id)}\")\n\n response = api_session.get(url)\n category = process_response(response)\n return category\n\n\ndef get_tag_by_slug(slug):\n url = build_url(\"tags\", {\"slug\": slug})\n\n response = api_session.get(url)\n\n try:\n tag = process_response(response)\n return tag[0]\n except Exception:\n return None\n\n\ndef get_media(media_id):\n url = build_url(f\"media/{str(media_id)}\")\n response = api_session.get(url)\n\n if not response.ok:\n return None\n\n return process_response(response)\n\n\ndef get_user_by_username(username):\n url = build_url(\"users\", {\"slug\": username})\n response = api_session.get(url)\n\n if not response.ok:\n return None\n\n processed_response = process_response(response)\n if not processed_response:\n return None\n else:\n return processed_response[0]\n\n\ndef get_user(user_id):\n url = build_url(f\"users/{str(user_id)}\")\n response = api_session.get(url)\n\n return process_response(response)\n","sub_path":"canonicalwebteam/blog/wordpress_api.py","file_name":"wordpress_api.py","file_ext":"py","file_size_in_byte":5261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"109036583","text":"# N개의 양의 정수에서 가장 큰 수와 가장 작은 수의 차이를 출력하시오.\n\n\n# [입력]\n\n# 첫 줄에 테스트 케이스의 수 T가 주어진다. ( 1 ≤ T ≤ 50 )\n\n# 각 케이스의 첫 줄에 양수의 개수 N이 주어진다. ( 5 ≤ N ≤ 1000 )\n\n# 다음 줄에 N개의 양수 ai가 주어진다. ( 1 ≤ ai≤ 1000000 )\n\n# [출력]\n\n# 각 줄마다 \"#T\" (T는 테스트 케이스 번호)를 출력한 뒤, 답을 출력한다.\n\nnum = int(input())\nres=num *[0]\nans=num*[0]\nfor i in range(num): \n count = int(input())\n number=input().split()\n res[i] = list(map(int, number))\n ans[i]=max(res[i])-min(res[i])\n\nfor i in range(num):\n print(\"#{} {}\".format(i+1,ans[i]))\n","sub_path":"KJW/Intermediate/1.List/min max.py","file_name":"min max.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"109512836","text":"nums = [1,1,1,2,2,3]\nk = 2\n\nclass Solution:\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n \n from collections import Counter\n c = Counter(nums)\n \n return [x[0] for x in c.most_common(k)]\n\nif __name__ == '__main__':\n leetcode = Solution()\n print(leetcode.topKFrequent(nums, k))\n","sub_path":"347/pythonic.py","file_name":"pythonic.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"391277369","text":"from Acquisition import aq_inner\nfrom Acquisition import aq_parent\nfrom opengever.base.request import tracebackify\nfrom opengever.base.utils import ok_response\nfrom opengever.task.interfaces import IYearfolderStorer\nfrom opengever.task.util import change_task_workflow_state\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFPlone.utils import safe_unicode\nfrom Products.Five.browser import BrowserView\nfrom zExceptions import Unauthorized\n\n\n@tracebackify\nclass StoreForwardingInYearfolderView(BrowserView):\n\n def __call__(self):\n if self.is_already_done():\n return ok_response()\n\n mtool = getToolByName(self.context, 'portal_membership')\n member = mtool.getAuthenticatedMember()\n\n if not member.checkPermission('Add portal content', self.context):\n raise Unauthorized()\n\n successor_oguid = self.request.get('successor_oguid')\n transition = self.request.get('transition')\n response_text = safe_unicode(self.request.get('response_text'))\n\n if transition:\n change_task_workflow_state(self.context,\n transition,\n text=response_text,\n successor_oguid=successor_oguid)\n\n IYearfolderStorer(self.context).store_in_yearfolder()\n\n return ok_response()\n\n def is_already_done(self):\n \"\"\"When the sender (caller of this view) has a conflict error, this\n view is called on the receiver multiple times, even when the changes\n are already done the first time. We need to detect such requests and\n tell the sender that it has worked.\n \"\"\"\n\n parent = aq_parent(aq_inner(self.context))\n if parent.portal_type == 'opengever.inbox.yearfolder':\n return True\n else:\n return False\n","sub_path":"opengever/task/browser/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"514491272","text":"#!/usr/bin/env python3\r\n#\r\n\r\n\r\nimport json\r\nimport redis\r\nimport datetime\r\nimport sys\r\nimport multiprocessing\r\nimport time\r\nfrom datetime import date\r\nfrom urllib import parse\r\n\r\nQUEUE = \"apply\"\r\nredisPool = redis.ConnectionPool(host='localhost', port=6379)\r\nclient = redis.Redis(connection_pool=redisPool)\r\n\r\n\r\ndef send(key, value):\r\n value = json.dumps(value, ensure_ascii=False)\r\n client.hset(QUEUE, key, value)\r\n\r\n\r\ndef send_demo():\r\n for k in range(10):\r\n gmt_create = datetime.datetime.now().strftime('%H%M%S%f')\r\n print(gmt_create)\r\n time.sleep(1)\r\n gmt_update = datetime.datetime.now().strftime('%H%M%S%f')\r\n send(gmt_create, {\"category\": '请求订单', \"gmt_create\": gmt_create, \"gmt_update\": gmt_update})\r\n\r\n\r\ndef get(queue, key):\r\n if client.hexists(queue, key):\r\n kv = client.hget(queue, key)\r\n client.hdel(queue, key)\r\n return json.loads(kv)\r\n\r\n\r\ndef get_demo():\r\n queue = QUEUE\r\n return get(queue, '161807993622')\r\n\r\n\r\nif __name__ == '__main__':\r\n # send_demo()\r\n kv = get_demo()\r\n print(kv)\r\n","sub_path":"basic_/redis_/demo01.py","file_name":"demo01.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"82165111","text":"from p5 import *\r\nimport matplotlib.pyplot as plt\r\n\r\nwidth = 600\r\nheight = 500\r\nx = []\r\nt = []\r\ni = 0\r\n\r\nclass Spring_Pendulum:\r\n def __init__(self,r1,m1,a1,a1_v,a1_a,g):\r\n self.r1 = r1\r\n self.m1 = m1\r\n self.a1 = a1\r\n self.a1_v = a1_v\r\n self.a1_a = a1_a\r\n self.g = g\r\n self.k = 0.3\r\n self.px2 = -1\r\n self.py2 = -1\r\n self.cx = width / 2\r\n self.cy = height / 3\r\n self.x1 = 0\r\n self.y1 = 0\r\n self.x = 0\r\n self.x_a = 0\r\n self.x_v = 0\r\n\r\n def update(self):\r\n try:\r\n self.x_a = (self.r1+self.x)*self.a1_v*self.a1_v - (self.k/self.m1)*self.x + self.g*cos(self.a1)\r\n self.a1_a = -(self.g/(self.r1+self.x))*sin(self.a1) - ((2*self.x_v)/(self.r1+self.x))*self.a1_v\r\n\r\n self.x1 = (self.r1 + self.x) * sin(self.a1)\r\n self.y1 = (self.r1+self.x) * cos(self.a1)\r\n\r\n except:\r\n print(\"a1: \", self.a1)\r\n exit()\r\n\r\n def move(self):\r\n self.x_v += self.x_a\r\n self.x += self.x_v\r\n self.a1_v += self.a1_a\r\n self.a1 += self.a1_v\r\n\r\n #self.a1_v *= 0.99\r\n\r\n def draw__pen(self):\r\n translate(self.cx, self.cy)\r\n stroke(0)\r\n stroke_weight(2)\r\n\r\n line((0, 0), (self.x1, self.y1))\r\n fill(0)\r\n stroke('purple')\r\n ellipse((self.x1, self.y1), self.m1, self.m1)\r\n\r\n\r\npendulum = Spring_Pendulum(125,10,PI/3,0,0,1)\r\n\r\ndef setup():\r\n size(width, height)\r\n\r\n\r\ndef draw():\r\n global i\r\n\r\n background(175)\r\n\r\n pendulum.update()\r\n\r\n pendulum.draw__pen()\r\n\r\n pendulum.move()\r\n\r\n t.append(i)\r\n x.append(pendulum.x1)\r\n\r\n i+=1\r\n\r\n print(i)\r\n\r\n if(i == 300):\r\n plt.plot(t,x)\r\n plt.show()\r\n\r\nwhile True:\r\n if __name__ == '__main__':\r\n run(None,None,30)\r\n","sub_path":"spring.py","file_name":"spring.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"542560243","text":"'''\ncode and explanation from http://www.rricard.me/machine/learning/generative/adversarial/networks/keras/tensorflow/2017/04/05/gans-part2.html\n'''\n'''\nGAN拟合一个正弦函数图像\n代码框架:生成器网络->判别器网络->GAN网络->真假数据生成->预训练D->训练G->分析结果\n结果比较可靠,可以仔细研究!\n'''\nimport os\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom tqdm import tqdm_notebook as tqdm\nfrom keras.models import Model, Sequential\nfrom keras.layers import Input, Reshape, Dense\nfrom keras.layers.core import Activation, Dropout, Flatten\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.convolutional import UpSampling1D, Conv1D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import TensorBoard\n\n# network structure\n# Generator\ndef get_generative(G_in, dense_dim=200, out_dim=50, lr=1e-3):\n G = Sequential()\n G.add(Dense(units=dense_dim, input_dim=G_in, activation='tanh')) # add input layer and hidden layer\n G_out = Dense(units=out_dim) #add output layer\n G.add(G_out)\n G.compile(loss='binary_crossentropy', optimizer=SGD(lr=lr))\n return G, G_out\n\n# Discriminator\ndef get_discriminative(D_in, lr=1e-3, drate=.25, n_channels=50, conv_sz=5):\n D = Sequential()\n D.add(Reshape((-1,1), input_shape=(D_in,))) # add Reshape layer(input_shape transform into given_shape)\n D.add(Conv1D(n_channels, conv_sz, activation='relu'))\n D.add(Dropout(drate))\n D.add(Flatten())\n D.add(Dense(units=n_channels))\n D_out = Dense(units=2, activation='sigmoid')\n D.add(D_out);\n D.compile(loss='binary_crossentropy', optimizer=Adam(lr=lr))\n return D, D_out\n\n# freezing function that we will apply on the discriminative model each time we train the GAN, in order to train the generative model.\n# layer.trainable==false -> this layer cannot update weights\ndef set_trainability(model, trainable=False):\n model.trainable = trainable\n for layer in model.layers:\n layer.trainable = trainable\n\n# chain the two models into a GAN that will serve to train the generator while we freeze the discriminator\n# train G by freezing D weights\ndef make_gan(GAN_in, G, D):\n set_trainability(D, False)\n GAN = Sequential()\n GAN.add(G)\n GAN_out = GAN.add(D)\n GAN.compile(loss='binary_crossentropy', optimizer=G.optimizer)\n return GAN, GAN_out\n\n# generate data\ndef sample_data(n_samples=10000, x_vals=np.arange(0, 5, .1), max_offset=100, mul_range=[1, 2]):\n vectors = []\n for i in range(n_samples):\n offset = np.random.random() * max_offset\n mul = mul_range[0] + np.random.random() * (mul_range[1] - mul_range[0])\n vectors.append(np.sin(offset + x_vals * mul) / 2 + .5)\n return np.array(vectors)\nax = pd.DataFrame(np.transpose(sample_data(5))).plot()\nplt.show()\n# generate some fake and real data and pre-train the discriminator before starting the gan\ndef sample_data_and_gen(G, noise_dim=10, n_samples=10000):\n real_data = sample_data(n_samples=n_samples)\n noise = np.random.uniform(0, 1, size=[n_samples, noise_dim])\n fake_data = G.predict(noise) # noise -> G -> fake data\n X = np.concatenate((real_data, fake_data)) # real_data+fake_data->D\n y = np.zeros((2 * n_samples, 2)) # all labels 20000*2\n y[:n_samples, 1] = 1\n y[n_samples:, 0] = 1\n return X, y\n\ndef pretrain(G, D, noise_dim=10, n_samples=10000, batch_size=32):\n X, y = sample_data_and_gen(G, n_samples=n_samples, noise_dim=noise_dim)\n set_trainability(D, True)\n D.fit(X, y, epochs=1, batch_size=batch_size)\n\ndef sample_noise(G, noise_dim=10, n_samples=10000):\n X = np.random.uniform(0, 1, size=[n_samples, noise_dim])\n y = np.zeros((n_samples, 2))\n y[:, 1] = 1\n return X, y\n\ndef train(GAN, G, D, epochs=200, n_samples=10000, noise_dim=10, batch_size=32, verbose=False, v_freq=50):\n d_loss = []\n g_loss = []\n e_range = range(epochs)\n if verbose:\n e_range = tqdm(e_range)\n for epoch in e_range:\n X, y = sample_data_and_gen(G, n_samples=n_samples, noise_dim=noise_dim)\n set_trainability(D, True)\n d_loss.append(D.train_on_batch(X, y))\n\n X, y = sample_noise(G, n_samples=n_samples, noise_dim=noise_dim)\n set_trainability(D, False)\n g_loss.append(GAN.train_on_batch(X, y))\n if verbose and (epoch + 1) % v_freq == 0:\n print(\"Epoch #{}: Generative Loss: {}, Discriminative Loss: {}\".format(epoch + 1, g_loss[-1], d_loss[-1]))\n return d_loss, g_loss\n\n#################Gan start##########################\n# generator network\nG_in = 10\nG, G_out = get_generative(G_in)\nG.summary()\n# discriminator network\nD_in = 50\nD, D_out = get_discriminative(D_in)\nD.summary()\n# gan network\nGAN_in = 10\nGAN, GAN_out = make_gan(GAN_in, G, D)\nGAN.summary()\n# train D\npretrain(G, D)\n# train G and D by freezing D\nd_loss, g_loss = train(GAN, G, D, verbose=True)\n#################Gan end##########################\n\n# plt training loss\nax = pd.DataFrame({'Generative Loss': g_loss,'Discriminative Loss': d_loss,}).plot(title='Training loss', logy=True)\nax.set_xlabel(\"Epochs\")\nax.set_ylabel(\"Loss\")\nax.plot()\nplt.show()\n# plt generated sinusoidal curves\nN_VIEWED_SAMPLES = 2\ndata_and_gen, _ = sample_data_and_gen(G, n_samples=N_VIEWED_SAMPLES)\npd.DataFrame(np.transpose(data_and_gen[N_VIEWED_SAMPLES:])).rolling(5).mean()[5:].plot()\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"gan_code/keras_gan_sine.py","file_name":"keras_gan_sine.py","file_ext":"py","file_size_in_byte":5535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"648273909","text":"import numpy as np\r\nimport cv2\r\n\r\nfaceCascade = cv2.CascadeClassifier('/home/pi/Downloads/opencv/data/haarcascades/haarcascade_frontalface_alt.xml')\r\n\r\nfaceCascade2 = cv2.CascadeClassifier('/home/pi/Downloads/opencv/data/haarcascades/haarcascade_frontalface_default.xml')\r\n\r\nnumcorrect = 0\r\nnumnodetect = 0\r\nnumtoomanydetect = 0\r\nnumfixed = 0\r\n\r\npeople = ['Amanda', 'Andrew W', 'Josh', 'Julia']\r\n\r\n\r\nfor name in people:\r\n\tfor i in range(1,11):\r\n\t\tstring = name + str(i) + '.jpg'\r\n\r\n\t\timg = cv2.imread(string)\r\n\r\n\t\theight, width = img.shape[:2]\r\n\t\r\n\t\timg = cv2.resize(img,(width//2, height//2), interpolation = cv2.INTER_AREA)\r\n\r\n\t\timg = img[75:425, 225:475]\r\n\r\n\t\tgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\r\n\t\tfaces = faceCascade.detectMultiScale(gray)\r\n\r\n\t\tprint(name, i, len(faces))\r\n\r\n\t\tif len(faces) != 0:\r\n\t\t\tif len(faces) == 1:\r\n\t\t\t\tfor x,y,w,h in faces:\r\n\t\t\t\t\tcv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\r\n\t\t\t\t\troi_gray = gray[y:y+h, x:x+w]\r\n\t\t\t\t\troi_color = img[y:y+h, x:x+w]\r\n\r\n\t\t\t\tnumcorrect = numcorrect + 1\t\r\n\t\t\t\r\n\t\t\t\tcv2.imshow('img',img)\r\n\t\t\t\tcv2.waitKey(0)\r\n\t\t\t\tcv2.destroyAllWindows()\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\telse:\r\n\t\t\t\tfacecheck = faceCascade2.detectMultiScale(gray)\r\n\t\t\r\n\t\t\t\tif len(facecheck) == 1:\r\n\t\t\t\t\tprint('Second check correct')\r\n\t\t\t\r\n\t\t\t\t\tfor x,y,w,h, in facecheck:\r\n\t\t\t\t\t\tcv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\r\n\t\t\t\t\t\troi_gray = gray[y:y+h, x:x+w]\r\n\t\t\t\t\t\troi_color = img[y:y+h, x:x+w]\r\n\r\n\t\t\t\t\tnumcorrect = numcorrect + 1\r\n\r\n\t\t\t\t\tnumfixed = numfixed + 1;\t\r\n\t\t\t\r\n\t\t\t\t\tcv2.imshow('img',img)\r\n\t\t\t\t\tcv2.waitKey(0)\r\n\t\t\t\t\tcv2.destroyAllWindows()\r\n\t\t\t\r\n\t\t\t\telse:\r\n\t\t\t\t\tnumtoomanydetect = numtoomanydetect + 1;\r\n\t\t\t\t\tprint('too many faces detected')\r\n\t\t\t\r\n\t\t\t\t\tcv2.imshow('img',img)\r\n\t\t\t\t\tcv2.waitKey(0)\r\n\t\t\t\t\tcv2.destroyAllWindows()\r\n\t\t\t\r\n\t\telse:\r\n\t\t\tfacecheck = faceCascade2.detectMultiScale(gray)\r\n\t\t\r\n\t\t\tif len(facecheck) == 1:\r\n\t\t\t\tprint('Second check correct')\r\n\t\t\t\r\n\t\t\t\tfor x,y,w,h, in facecheck:\r\n\t\t\t\t\tcv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\r\n\t\t\t\t\troi_gray = gray[y:y+h, x:x+w]\r\n\t\t\t\t\troi_color = img[y:y+h, x:x+w]\r\n\r\n\t\t\t\tnumcorrect = numcorrect + 1\r\n\r\n\t\t\t\tnumfixed = numfixed + 1;\t\r\n\t\t\t\r\n\t\t\t\tcv2.imshow('img',img)\r\n\t\t\t\tcv2.waitKey(0)\r\n\t\t\t\tcv2.destroyAllWindows()\r\n\t\t\telse: \r\n\t\t\t\tnumnodetect = numnodetect + 1;\r\n\t\t\t\tprint('no faces detected')\r\n\t\t\r\n\t\t\t\tcv2.imshow('img',img)\r\n\t\t\t\tcv2.waitKey(0)\r\n\t\t\t\tcv2.destroyAllWindows()\r\n\r\nprint('Number of No Detections:')\r\nprint(numnodetect)\r\n\r\nprint('Number of Too Many Detections:')\r\nprint(numtoomanydetect)\r\n\r\nprint('Number of Fixed Detections with Second Classifier')\r\nprint(numfixed)\r\n\r\npercent = numcorrect/40\r\nprint('Number of Correct Detections:')\r\nprint(numcorrect)\r\nprint('% Correct')\r\nprint(percent)","sub_path":"Pi_Test_Photos/pitest.py","file_name":"pitest.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"349728677","text":"\"\"\"Platform compatibility.\"\"\"\n# pylint: skip-file\n\nfrom __future__ import absolute_import, unicode_literals\n\nfrom typing import Tuple, cast\nimport platform\nimport re\nimport struct\nimport sys\n\n# Jython does not have this attribute\ntry:\n from socket import SOL_TCP\nexcept ImportError: # pragma: no cover\n from socket import IPPROTO_TCP as SOL_TCP # noqa\n\n\nRE_NUM = re.compile(r'(\\d+).+')\n\n\ndef _linux_version_to_tuple(s):\n # type: (str) -> Tuple[int, int, int]\n return cast(Tuple[int, int, int], tuple(map(_versionatom, s.split('.')[:3])))\n\n\ndef _versionatom(s):\n # type: (str) -> int\n if s.isdigit():\n return int(s)\n match = RE_NUM.match(s)\n return int(match.groups()[0]) if match else 0\n\n\n# available socket options for TCP level\nKNOWN_TCP_OPTS = {\n 'TCP_CORK', 'TCP_DEFER_ACCEPT', 'TCP_KEEPCNT',\n 'TCP_KEEPIDLE', 'TCP_KEEPINTVL', 'TCP_LINGER2',\n 'TCP_MAXSEG', 'TCP_NODELAY', 'TCP_QUICKACK',\n 'TCP_SYNCNT', 'TCP_USER_TIMEOUT', 'TCP_WINDOW_CLAMP',\n}\n\nLINUX_VERSION = None\nif sys.platform.startswith('linux'):\n LINUX_VERSION = _linux_version_to_tuple(platform.release())\n if LINUX_VERSION < (2, 6, 37):\n KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')\n\n # Windows Subsystem for Linux is an edge-case: the Python socket library\n # returns most TCP_* enums, but they aren't actually supported\n if platform.release().endswith(\"Microsoft\"):\n KNOWN_TCP_OPTS = {'TCP_NODELAY', 'TCP_KEEPIDLE', 'TCP_KEEPINTVL',\n 'TCP_KEEPCNT'}\n\nelif sys.platform.startswith('darwin'):\n KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')\n\nelif 'bsd' in sys.platform:\n KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')\n\n# According to MSDN Windows platforms support getsockopt(TCP_MAXSSEG) but not\n# setsockopt(TCP_MAXSEG) on IPPROTO_TCP sockets.\nelif sys.platform.startswith('win'):\n KNOWN_TCP_OPTS = {'TCP_NODELAY'}\n\nelif sys.platform.startswith('cygwin'):\n KNOWN_TCP_OPTS = {'TCP_NODELAY'}\n\n# illumos does not allow to set the TCP_MAXSEG socket option,\n# even if the Oracle documentation says otherwise.\nelif sys.platform.startswith('sunos'):\n KNOWN_TCP_OPTS.remove('TCP_MAXSEG')\n\n# aix does not allow to set the TCP_MAXSEG\n# or the TCP_USER_TIMEOUT socket options.\nelif sys.platform.startswith('aix'):\n KNOWN_TCP_OPTS.remove('TCP_MAXSEG')\n KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')\n\nif sys.version_info < (2, 7, 7): # pragma: no cover\n import functools\n\n def _to_bytes_arg(fun):\n @functools.wraps(fun)\n def _inner(s, *args, **kwargs):\n return fun(s.encode(), *args, **kwargs)\n return _inner\n\n pack = _to_bytes_arg(struct.pack)\n pack_into = _to_bytes_arg(struct.pack_into)\n unpack = _to_bytes_arg(struct.unpack)\n unpack_from = _to_bytes_arg(struct.unpack_from)\nelse:\n pack = struct.pack\n pack_into = struct.pack_into\n unpack = struct.unpack\n unpack_from = struct.unpack_from\n\n__all__ = [\n 'LINUX_VERSION',\n 'SOL_TCP',\n 'KNOWN_TCP_OPTS',\n 'pack',\n 'pack_into',\n 'unpack',\n 'unpack_from',\n]\n","sub_path":"sdk/eventhub/azure-eventhub/azure/eventhub/_pyamqp/_platform.py","file_name":"_platform.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"559133539","text":"# -*- coding: utf-8 -*-\n\"\"\"\nClass definition of YOLO_v3 style detection model on image and video\n\"\"\"\n\nimport colorsys\nfrom timeit import default_timer as timer\nimport numpy as np\nfrom PIL import Image, ImageFont, ImageDraw\nimport cv2\nimport tensorflow as tf\nfrom yolo3.model import yolo_eval, darknet_yolo_body, mobilenetv2_yolo_body,efficientnet_yolo_body,YoloEval\nfrom yolo3.utils import letterbox_image, get_anchors, get_classes\nfrom yolo3.enum import OPT, BACKBONE\nfrom yolo3.map import MAPCallback\nimport os\nfrom typing import List, Tuple\nfrom tensorflow_serving.apis import prediction_log_pb2,predict_pb2\nfrom tensorflow.python import debug as tf_debug\nfrom functools import partial\n\ntf.keras.backend.set_learning_phase(0)\n\nclass YOLO(object):\n _defaults = {\n \"score\": 0.2,\n \"nms\": 0.5,\n }\n\n @classmethod\n def get_defaults(cls, n: str):\n if n in cls._defaults:\n return cls._defaults[n]\n else:\n return \"Unrecognized attribute name '\" + n + \"'\"\n\n def __init__(self, FLAGS):\n self.__dict__.update(self._defaults) # set up default values\n self.backbone=FLAGS['backbone']\n self.opt=FLAGS['opt']\n self.class_names = get_classes(\n FLAGS['classes_path'])\n self.anchors = get_anchors(\n FLAGS['anchors_path'])\n self.input_shape = FLAGS['input_size']\n config = tf.ConfigProto()\n\n if self.opt == OPT.XLA:\n config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1\n sess = tf.Session(config=config)\n tf.keras.backend.set_session(sess)\n elif self.opt == OPT.MKL:\n config.intra_op_parallelism_threads = 4\n config.inter_op_parallelism_threads = 4\n sess = tf.Session(config=config)\n tf.keras.backend.set_session(sess)\n elif self.opt == OPT.DEBUG:\n tf.logging.set_verbosity(tf.logging.DEBUG)\n sess = tf_debug.TensorBoardDebugWrapperSession(\n tf.Session(config=tf.ConfigProto(log_device_placement=True)),\n \"localhost:6064\")\n tf.keras.backend.set_session(sess)\n else:\n sess = tf.keras.backend.get_session()\n self.sess = sess\n self.generate(FLAGS)\n\n def generate(self,FLAGS):\n model_path = os.path.expanduser(FLAGS['model'])\n assert model_path.endswith(\n '.h5'), 'Keras model or weights must be a .h5 file.'\n\n # Load model, or construct model and load weights.\n num_anchors = len(self.anchors)\n num_classes = len(self.class_names)\n try:\n model = tf.keras.models.load_model(model_path, compile=False)\n except:\n if self.backbone == BACKBONE.MOBILENETV2:\n model_body= partial(mobilenetv2_yolo_body,alpha=FLAGS['alpha'])\n elif self.backbone == BACKBONE.DARKNET53:\n model_body = darknet_yolo_body\n elif self.backbone == BACKBONE.EFFICIENTNET:\n model_body = partial(efficientnet_yolo_body,model_name='efficientnet-b4')\n if tf.executing_eagerly():\n model = model_body(\n tf.keras.layers.Input(shape=(*self.input_shape, 3),\n name='predict_image'),\n num_anchors=num_anchors // 3, num_classes=num_classes)\n else:\n self.input = tf.keras.layers.Input(shape=(None, None, 3),\n name='predict_image',\n dtype=tf.uint8)\n input = tf.map_fn(\n lambda image: tf.image.convert_image_dtype(\n image, tf.float32), self.input, tf.float32)\n image, shape = letterbox_image(input, self.input_shape)\n self.input_image_shape = tf.shape(input)[1:3]\n image = tf.reshape(image, [-1, *self.input_shape, 3])\n model = model_body(image, num_anchors=num_anchors // 3,\n num_classes=num_classes)\n model.load_weights(model_path) # make sure model, anchors and classes match\n else:\n assert model.layers[-1].output_shape[-1] == \\\n num_anchors / len(model.output) * (num_classes + 5), \\\n 'Mismatch between model and given anchor and class sizes'\n print('{} model, anchors, and classes loaded.'.format(model_path))\n # Generate colors for drawing bounding boxes.\n if tf.executing_eagerly():\n self.yolo_model = model\n else:\n output=YoloEval(self.anchors,len(self.class_names),self.input_image_shape,score_threshold=self.score,iou_threshold=self.nms,name='yolo')(model.output)\n # output = tf.keras.layers.Lambda(lambda input: yolo_eval(\n # input,\n # self.anchors,\n # len(self.class_names),\n # self.input_image_shape,\n # score_threshold=self.score,\n # iou_threshold=self.nms),name='yolo')(model.output)\n self.yolo_model = tf.keras.Model(model.input, output)\n # Generate output tensor targets for filtered bounding boxes.\n hsv_tuples: List[Tuple[float, float, float]] = [\n (x / len(self.class_names), 1., 1.)\n for x in range(len(self.class_names))\n ]\n self.colors: List[Tuple[float, float, float]] = list(\n map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n self.colors: List[Tuple[int, int, int]] = list(\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\n self.colors))\n np.random.seed(10101) # Fixed seed for consistent colors across runs.\n np.random.shuffle(\n self.colors) # Shuffle colors to decorrelate adjacent classes.\n np.random.seed(None) # Reset seed to default.\n\n def detect_image(self, image,draw=True) -> Image:\n if tf.executing_eagerly():\n image_data = tf.expand_dims(image, 0)\n if self.input_shape != (None, None):\n boxed_image, image_shape = letterbox_image(\n image_data, tuple(reversed(self.input_shape)))\n else:\n height, width, _ = image_data.shape\n new_image_size = (width - (width % 32), height - (height % 32))\n boxed_image, image_shape = letterbox_image(\n image_data, new_image_size)\n image_data = np.array(boxed_image)\n start = timer()\n output = self.yolo_model.predict(image_data)\n out_boxes, out_scores, out_classes = yolo_eval(\n output,\n self.anchors,\n len(self.class_names),\n image.shape[0:2],\n score_threshold=self.score,\n iou_threshold=self.nms)\n end = timer()\n image = Image.fromarray((np.array(image) * 255).astype('uint8'),\n 'RGB')\n else:\n image_data = np.expand_dims(image, 0)\n start = timer()\n out_boxes, out_scores, out_classes = self.sess.run(\n self.yolo_model.output, feed_dict={self.input: image_data})\n end = timer()\n\n print('Found {} boxes for {}'.format(len(out_boxes), 'img'))\n if draw:\n font = ImageFont.truetype(font='font/FiraMono-Medium.otf',\n size=np.floor(3e-2 * image.size[1] +\n 0.5).astype('int32'))\n thickness = (image.size[1] + image.size[0]) // 300\n draw = ImageDraw.Draw(image)\n for i, c in reversed(list(enumerate(out_classes))):\n predicted_class = self.class_names[c]\n box = out_boxes[i]\n score = out_scores[i]\n\n label = '{} {:.2f}'.format(predicted_class, score)\n\n label_size = draw.textsize(label, font)\n\n top, left, bottom, right = box\n print(label, (left, top), (right, bottom))\n\n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n\n # My kingdom for a good redistributable image drawing library.\n for i in range(thickness):\n draw.rectangle([left + i, top + i, right - i, bottom - i],\n outline=self.colors[c])\n draw.rectangle(\n [tuple(text_origin),\n tuple(text_origin + label_size)],\n fill=self.colors[c])\n draw.text(text_origin, label, fill=(0, 0, 0), font=font)\n del draw\n print(end - start)\n return image\n else:\n return out_boxes, out_scores, out_classes\n\ndef export_tfjs_model(yolo,path):\n import tensorflowjs as tfjs\n tfjs.converters.save_keras_model(yolo.yolo_model, path,quantization_dtype=np.uint8)\n\ndef export_serving_model(yolo, path):\n if tf.version.VERSION.startswith('1.'):\n tf.saved_model.simple_save(\n yolo.sess,\n path,\n inputs={'predict_image:0': yolo.input},\n outputs={t.name: t for t in yolo.yolo_model.output})\n else:\n signature_def_map = {\n tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n tf.saved_model.signature_def_utils.predict_signature_def(\n {'predict_image:0': yolo.input},\n {t.name: t for t in yolo.yolo_model.output})\n }\n tf.saved_model.experimental.save(yolo.yolo_model, path,\n signature_def_map)\n asset_extra=os.path.join(path,\"assets.extra\")\n tf.io.gfile.mkdir(asset_extra)\n with tf.io.TFRecordWriter(os.path.join(asset_extra,\"tf_serving_warmup_requests\")) as writer:\n request = predict_pb2.PredictRequest()\n request.model_spec.name = 'detection'\n request.model_spec.signature_name = 'serving_default'\n image = Image.open('../download/image3.jpeg')\n scale = yolo.input_shape[0] / max(image.size)\n if scale < 1:\n image = image.resize((int(line * scale) for line in image.size),\n Image.BILINEAR)\n image_data = np.array(image, dtype='uint8')\n image_data = np.expand_dims(image_data, 0)\n request.inputs['predict_image:0'].CopyFrom(tf.make_tensor_proto(image_data))\n log=prediction_log_pb2.PredictionLog(predict_log=prediction_log_pb2.PredictLog(request=request))\n writer.write(log.SerializeToString())\n\ndef export_tflite_model(yolo, path):\n yolo.yolo_model.input.set_shape([None, *yolo.input_shape, 3])\n converter = tf.lite.TFLiteConverter.from_session(\n yolo.sess, [yolo.yolo_model.input], list(yolo.yolo_model.output))\n converter.allow_custom_ops=True\n converter.inference_type = tf.lite.constants.FLOAT\n converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\n input_arrays = converter.get_input_arrays()\n converter.quantized_input_stats = {input_arrays[0]: (0., 1.)}\n tflite_model = converter.convert()\n open(path, \"wb\").write(tflite_model)\n\ndef calculate_map(yolo, glob):\n mAP = MAPCallback(glob,\n yolo.input_shape,\n yolo.anchors,\n yolo.class_names)\n mAP.set_model(yolo.yolo_model)\n APs = mAP.calculate_aps()\n for cls in range(len(yolo.class_names)):\n if cls in APs:\n print(yolo.class_names[cls] + ' ap: ', APs[cls])\n mAP = np.mean([APs[cls] for cls in APs])\n print('mAP: ', mAP)\n\ndef detect_imgs(yolo,input):\n with open(input) as file:\n for image_path in file.readlines():\n image_path=image_path.strip()\n try:\n if tf.executing_eagerly():\n content = tf.io.read_file(image_path)\n image = tf.image.decode_image(content,\n channels=3,\n dtype=tf.float32)\n else:\n image = Image.open(image_path)\n except:\n print('Open Error! Try again!')\n else:\n r_image = yolo.detect_image(image)\n r_image.save(os.path.join('chengyun',image_path.split('/')[-1]))\n yolo.close_session()\n\ndef detect_img(yolo):\n while True:\n image_path = input('Input image filename:')\n try:\n if tf.executing_eagerly():\n content = tf.io.read_file(image_path)\n image = tf.image.decode_image(content,\n channels=3,\n dtype=tf.float32)\n else:\n image = Image.open(image_path)\n except:\n print('Open Error! Try again!')\n else:\n r_image = yolo.detect_image(image)\n r_image.show()\n yolo.close_session()\n\n\ndef detect_video(yolo: YOLO, video_path: str, output_path: str = \"\"):\n vid = cv2.VideoCapture(video_path)\n if not vid.isOpened():\n raise IOError(\"Couldn't open webcam or video\")\n video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC))\n video_fps = vid.get(cv2.CAP_PROP_FPS)\n video_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n isOutput = True if output_path != \"\" else False\n if isOutput:\n print(\"!!! TYPE:\", type(output_path), type(video_FourCC),\n type(video_fps), type(video_size))\n out = cv2.VideoWriter(output_path, video_FourCC, video_fps, video_size)\n accum_time = 0\n curr_fps = 0\n fps = \"FPS: ??\"\n prev_time = timer()\n detected=False\n trackers=[]\n font = ImageFont.truetype(font='font/FiraMono-Medium.otf',\n size=30)\n thickness = 1\n frame_count = 0\n while True:\n return_value, frame = vid.read()\n image = Image.fromarray(frame)\n image_data = np.array(image) / 255.\n draw = ImageDraw.Draw(image)\n if detected:\n for tracker,predicted_class in trackers:\n success,box=tracker.update(frame)\n left,top,width,height=box\n right=left+width\n bottom=top+height\n\n label = '{}'.format(predicted_class)\n\n label_size = draw.textsize(label, font)\n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n\n # My kingdom for a good redistributable image drawing library.\n for i in range(thickness):\n draw.rectangle([left + i, top + i, right - i, bottom - i],\n outline=yolo.colors[c])\n draw.rectangle(\n [tuple(text_origin),\n tuple(text_origin + label_size)],\n fill=yolo.colors[c])\n draw.text(text_origin, label, fill=(0, 0, 0), font=font)\n frame_count+=1\n if frame_count == 100:\n for tracker in trackers:\n del tracker\n trackers=[]\n frame_count=0\n detected=False\n else:\n if tf.executing_eagerly():\n boxes, scores, classes = yolo.detect_image(image_data,False)\n else:\n boxes, scores, classes = yolo.detect_image(image, False)\n for i, c in enumerate(classes):\n predicted_class = yolo.class_names[c]\n top, left, bottom, right=boxes[i]\n height=abs(bottom-top)\n width=abs(right-left)\n tracker = cv2.TrackerCSRT_create()\n #tracker = cv2.TrackerKCF_create()\n #tracker = cv2.TrackerMOSSE_create()\n tracker.init(frame,(left,top,width,height))\n trackers.append([tracker,predicted_class])\n\n label = '{}'.format(predicted_class)\n label_size = draw.textsize(label, font)\n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n\n # My kingdom for a good redistributable image drawing library.\n for i in range(thickness):\n draw.rectangle([left + i, top + i, right - i, bottom - i],\n outline=yolo.colors[c])\n draw.rectangle(\n [tuple(text_origin),\n tuple(text_origin + label_size)],\n fill=yolo.colors[c])\n draw.text(text_origin, label, fill=(0, 0, 0), font=font)\n detected=True\n del draw\n result = np.asarray(image)\n curr_time = timer()\n exec_time = curr_time - prev_time\n prev_time = curr_time\n accum_time = accum_time + exec_time\n curr_fps = curr_fps + 1\n if accum_time > 1:\n accum_time = accum_time - 1\n fps = \"FPS: \" + str(curr_fps)\n curr_fps = 0\n cv2.putText(result,\n text=fps,\n org=(3, 15),\n fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n fontScale=0.50,\n color=(255, 0, 0),\n thickness=2)\n cv2.namedWindow(\"result\", cv2.WINDOW_NORMAL)\n cv2.imshow(\"result\", result)\n\n if isOutput:\n out.write(result)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n yolo.close_session()\n","sub_path":"yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":18039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"509523340","text":"import sys, os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom sklearn.tree import DecisionTreeClassifier\nimport mglearn\nfrom sklearn import svm\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom sklearn.tree import export_graphviz\nimport graphviz\nimport pydot\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import tree\nfrom sklearn.model_selection import GridSearchCV\n\n# gen training data #\ncur_path = os.getcwd()\nN = str(20)\n\nf = open(cur_path+'/../../input/FandLP/large/f'+N+'_hex.list', 'r')\nhexcode = f.readlines()\nf.close()\nfor i in range(0,len(hexcode)):\n hexcode[i] = hexcode[i].split(' ')\n\nf = open(cur_path+'/../../post_recent/output/df_1009test_'+N+'.list', 'r')\n#f = open(cur_path+'/../../post_recent/output/df_1007test_'+N+'.list', 'r')\nhexdata = f.readlines()\nf.close() \nfor i in range(0,len(hexdata)):\n hexdata[i] = hexdata[i].split(' ')\nhexcode = np.array(hexcode)\nhexdata = np.array(hexdata)\nprint (\"code, data shape:\")\nprint (hexcode.shape)\nprint (hexdata.shape)\n\n# code:0 / data:1\nc_sum, d_sum, t_sum = 0.0, 0.0, 0.0\nstep =1 \ny_code = [1]*hexcode.shape[0]\ny_data = [0]*hexdata.shape[0]\nx_train = (np.concatenate((hexcode,hexdata ), axis=0))\ny_train = (np.concatenate((y_code,y_data ), axis=0))\nprint (\"x_train, y_train shape:\")\nprint (x_train.shape)\nprint (y_train.shape)\n\n\nmax_features = 1\nfor i in range(0,len(x_train)):\n for j in range(0,len(x_train[i])):\n #x_train[i][j] = x_train[i][j].astype(np.int64)\n x_train[i][j] = int (\"0x\"+x_train[i][j], 16)\n\n\nval_x = np.array(x_train)\nval_y = np.array(y_train)\n\n\nidx = np.arange(x_train.shape[0])\nnp.random.shuffle(idx)\nx_train = x_train[idx]\ny_train = y_train[idx]\nx_test = x_train[:30000]\nx_train = x_train[30000:]\ny_test = y_train[:30000]\ny_train = y_train[30000:]\nprint (x_train.shape)\nprint (x_test.shape)\n\ntext_max_words = int(N)\nx_train = sequence.pad_sequences(x_train, maxlen=text_max_words)\nx_test = sequence.pad_sequences(x_test, maxlen=text_max_words)\nprint (x_train.shape)\nprint (x_test.shape)\n\n\ndt = DecisionTreeClassifier(min_samples_split=2, max_depth=3)\ndt.fit(x_train, y_train)\ndt.predict_proba(x_test)\nprint(dt.score(x_test, y_test))\n#dt = DecisionTreeClassifier(min_samples_split=2, max_depth=3)\n#score = cross_val_score(dt, x_train, y_train, cv=5)\n#print (\"cross: \", np.round(score,4))\n#print (\"cross_avg: \", np.round(np.mean(score),4))\nexport_graphviz(dt, out_file=\"tree.dot\", class_names=[\"data\", \"code\"],\n feature_names=None, impurity=False, filled=True)\n\n(graph,) = pydot.graph_from_dot_file('tree.dot', encoding='utf8')\ngraph.write_png('1009tree.png')\n\n\nparam = {'max_depth':range(5)}\nclf = GridSearchCV(tree.DecisionTreeClassifier(), param, n_jobs=4)\nclf.fit(val_x, val_y)\ntree_model = clf.best_estimator_\nprint (clf.best_score_, clf.best_params_)\n\n# feature importance\nidx = np.arange(int(N))\nfeature_imp = dt.feature_importances_\nplt.barh(idx, feature_imp, align='center')\n#plt.yticks(idx, [\"data\", \"code\"])\nplt.xlabel('feature importance')\nplt.ylabel('feature')\nplt.show()\nplt.savefig('1009dt_featureImp.png')\n\n","sub_path":"learning/dt/1009.py","file_name":"1009.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"255470747","text":"import torch\nimport numpy as np\nimport math\n\nimport deepshift.kernels\n\ndef round_to_fixed(input, fraction=16, integer=16):\n assert integer >= 1, integer\n if integer == 1:\n return torch.sign(input) - 1\n delta = math.pow(2.0, -(fraction))\n bound = math.pow(2.0, integer-1)\n min_val = - bound\n max_val = bound - 1\n rounded = torch.floor(input / delta) * delta\n\n clipped_value = torch.clamp(rounded, min_val, max_val)\n return clipped_value\n\ndef get_shift_and_sign(x, rounding='deterministic'):\n sign = torch.sign(x)\n\n x_abs = torch.abs(x)\n shift = round(torch.log(x_abs) / np.log(2), rounding)\n\n return shift, sign\n\ndef round_power_of_2(x, rounding='deterministic'):\n shift, sign = get_shift_and_sign(x, rounding)\n # print(shift)\n x_rounded = (2.0 ** shift) * sign\n return x_rounded\n\ndef round(x, rounding='deterministic'):\n assert(rounding in ['deterministic', 'stochastic'])\n if rounding == 'stochastic':\n x_floor = x.floor()\n return x_floor + torch.bernoulli(x - x_floor)\n else:\n return x.round()\n\nclass ConcWeight():\n def __init__(self, data=None, base=0, bits=8):\n self.data = data\n self.base = base\n self.bits = bits\n\n##concatenate shift and sign together\ndef compress_bits(shift, sign):\n conc_weight = ConcWeight()\n\n if len(shift.shape) == 2:\n shift = shift.unsqueeze(-1).unsqueeze(-1)\n\n # if sign is ternary, then use a big shift value that is equivalent to multiplying by zero\n zero_sign_indices = (sign == 0).nonzero(as_tuple=True)\n shift[zero_sign_indices] = -32\n sign[zero_sign_indices] = +1\n\n conc_weight.bits = math.ceil(torch.log( - torch.min(shift) + 1)/ np.log(2))\n # treat shift to the right as the default\n shift = shift * -1\n minimum = int(torch.min(shift))\n if minimum < 0:\n conc_weight.base = minimum\n shift = shift - minimum\n else:\n conc_weight.base = 0\n\n num = int(32 / (conc_weight.bits + 1))\n row_length = int((shift.shape[1] * shift.shape[2] * shift.shape[3] + num -1) / num )\n size = row_length * shift.shape[0]\n\n conc_weight.data = deepshift.kernels.compress_sign_and_shift(shift.int().cuda(), sign.int().cuda(), size, conc_weight.base, conc_weight.bits, row_length, num)\n\n return conc_weight","sub_path":"deepshift/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"580889505","text":"import os\r\nimport sklearn\r\nfrom src.utils import exists\r\nfrom argparse import ArgumentParser\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom src.plot_cm import plot_confusion_matrix\r\nfrom src.plot_incorr import plot_incorrect\r\n\r\ndef parseint(string):\r\n return int(''.join([x for x in string if x.isdigit()]))\r\n\r\n\r\ndef metrics(test_file, inference_file, return_incorr=False):\r\n \"\"\" using sklearn.metrics lib to calculate accuracy score and Confusion matrix.\r\n\r\n Args:\r\n test_file (str):txt file with path to png samples and true labels.\r\n inference_file (str):txt file with path to png samples and predicted labels.\r\n\r\n Returns:\r\n float: accuracy_score.\r\n array: Confusion matrix.\r\n \"\"\"\r\n with open(test_file) as f, open(inference_file) as ff:\r\n true_labels = []\r\n predicted_labels = []\r\n inCorrect={}\r\n i=0\r\n for line1, line2 in zip(f, ff):\r\n true = parseint(line1.split(\",\")[1])\r\n pred = parseint(line2.split(\",\")[1])\r\n path_to_img = line1.split(\",\")[0]\r\n true_labels.append(parseint(line1.split(\",\")[1]))\r\n predicted_labels.append(parseint(line2.split(\",\")[1]))\r\n if return_incorr and true != pred:\r\n inCorrect[i] = [path_to_img,true,pred]\r\n i += 1\r\n cm = confusion_matrix(true_labels, predicted_labels, labels=[i for i in range(10)], sample_weight=None)\r\n accuracy_score = sklearn.metrics.accuracy_score(true_labels, predicted_labels, normalize=True, sample_weight=None)\r\n\r\n return accuracy_score, cm, inCorrect\r\n\r\n\r\ndef build_parser():\r\n parser = ArgumentParser()\r\n parser.add_argument('--test-file', '-T', type=str, dest='test_file',\r\n help='txt file with path to png samples and true labels',\r\n metavar='TXT_FILE', required=True)\r\n\r\n parser.add_argument('--inference-file', '-I', type=str, dest='inference_file',\r\n help='txt file with path to png samples and predicted labels',\r\n metavar='INFERENCE_FILE', required=True)\r\n\r\n parser.add_argument('--plot-incorr', '-P', dest='plot_incorr', action='store_true', help='plot incorrect classified images')\r\n\r\n return parser\r\n\r\n\r\ndef main():\r\n parser = build_parser()\r\n options = parser.parse_args()\r\n\r\n if not exists(options.test_file):\r\n print(f'{options.test_file} does not exist!')\r\n return -1\r\n elif not exists(options.inference_file):\r\n print(f'{options.inference_file} does not exist!')\r\n return -1\r\n\r\n if options.plot_incorr:\r\n accuracy_score, cm, inCorrect = metrics(test_file=options.test_file, inference_file=options.inference_file,return_incorr=True)\r\n else:\r\n accuracy_score, cm, _ = metrics(test_file=options.test_file, inference_file=options.inference_file)\r\n \r\n print(f'confusion_matrix: \\n{cm}')\r\n print(f'accuracy_score: {accuracy_score}')\r\n\r\n target_names = [i for i in range(10)]\r\n png_path = f'{options.inference_file[0:-4]}.png' # cut off .txt part and add .png in inference path\r\n png_path_incorr = f'{options.inference_file[0:-4]}_incorr.png' # cut off .txt part and add _incorr.png in inference path \r\n \r\n path, file = os.path.split(options.inference_file)\r\n plot_confusion_matrix(cm=cm, target_names=target_names, path=png_path, normalize=False,\r\n title=f'{file} Confusion matrix')\r\n print(f'{file} Confusion matrix plot saved @ {png_path}')\r\n\r\n \r\n if options.plot_incorr:\r\n plot_incorrect(inCorrect,png_path_incorr)\r\n print(f'{file} Plot with incorrect images saved @ {png_path_incorr}')\r\n \r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"381845255","text":"# Copyright 2016 - Alcatel-Lucent\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom oslo_log import log as logging\n\nfrom vitrage.common.constants import EdgeLabels\nfrom vitrage.common.constants import EntityTypes\nfrom vitrage.common.constants import SyncMode\nfrom vitrage.common.constants import VertexProperties\nfrom vitrage.entity_graph.transformer import base\nfrom vitrage.entity_graph.transformer.base import extract_field_value\nimport vitrage.graph.utils as graph_utils\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass HostTransformer(base.TransformerBase):\n\n HOST_TYPE = 'nova.host'\n\n # Fields returned from Nova Availability Zone snapshot\n HOST_NAME = {\n SyncMode.SNAPSHOT: ('host_name',),\n SyncMode.INIT_SNAPSHOT: ('host_name',)\n }\n\n ZONE_NAME = {\n SyncMode.SNAPSHOT: ('zone',),\n SyncMode.INIT_SNAPSHOT: ('zone',)\n }\n\n TIMESTAMP = {\n SyncMode.SNAPSHOT: ('sample_date',),\n SyncMode.INIT_SNAPSHOT: ('sample_date',)\n }\n\n def __init__(self, transformers):\n self.transformers = transformers\n\n def _create_entity_vertex(self, entity_event):\n\n sync_mode = entity_event['sync_mode']\n\n host_name = extract_field_value(\n entity_event,\n self.HOST_NAME[sync_mode]\n )\n metadata = {VertexProperties.NAME: host_name}\n\n entity_key = self.extract_key(entity_event)\n\n timestamp = extract_field_value(\n entity_event,\n self.TIMESTAMP[sync_mode]\n )\n\n return graph_utils.create_vertex(\n entity_key,\n entity_id=host_name,\n entity_category=EntityTypes.RESOURCE,\n entity_type=self.HOST_TYPE,\n update_timestamp=timestamp,\n metadata=metadata\n )\n\n def _create_neighbors(self, entity_event):\n\n sync_mode = entity_event['sync_mode']\n\n neighbors = []\n\n timestamp = extract_field_value(\n entity_event,\n self.TIMESTAMP[sync_mode]\n )\n\n zone_neighbor = self._create_zone_neighbor(\n entity_event,\n timestamp,\n self.extract_key(entity_event),\n self.ZONE_NAME[sync_mode]\n )\n\n if zone_neighbor is not None:\n neighbors.append(zone_neighbor)\n\n return neighbors\n\n def _create_zone_neighbor(\n self, entity_event, timestamp, host_vertex_id, zone_name_path):\n\n zone_transformer = self.transformers['nova.zone']\n\n if zone_transformer:\n\n zone_name = extract_field_value(entity_event, zone_name_path)\n\n zone_neighbor = zone_transformer.create_placeholder_vertex(\n zone_name,\n timestamp\n )\n relation_edge = graph_utils.create_edge(\n source_id=zone_neighbor.vertex_id,\n target_id=host_vertex_id,\n relationship_type=EdgeLabels.CONTAINS\n )\n return base.Neighbor(zone_neighbor, relation_edge)\n else:\n LOG.warning('Cannot find zone transformer')\n\n return None\n\n def _key_values(self, mutable_fields):\n\n fixed_fields = [EntityTypes.RESOURCE, self.HOST_TYPE]\n return fixed_fields + mutable_fields\n\n def extract_key(self, entity_event):\n\n host_name = extract_field_value(\n entity_event,\n self.HOST_NAME[entity_event['sync_mode']]\n )\n\n key_fields = self._key_values([host_name])\n return base.build_key(key_fields)\n\n def create_placeholder_vertex(self, host_name, timestamp):\n\n key_fields = self._key_values([host_name])\n\n return graph_utils.create_vertex(\n base.build_key(key_fields),\n entity_id=host_name,\n entity_category=EntityTypes.RESOURCE,\n entity_type=self.HOST_TYPE,\n update_timestamp=timestamp,\n is_placeholder=True\n )\n","sub_path":"vitrage/entity_graph/transformer/host_transformer.py","file_name":"host_transformer.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"615574805","text":"from __future__ import print_function\nimport os, socket, sys\nfrom novaclient.client import Client as NovaClient\nimport time\ndef isOpen(ip, port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(5)\n try:\n s.connect((ip, int(port)))\n s.shutdown(socket.SHUT_RDWR)\n return True\n except:\n return False\n finally:\n s.close()\n\nusername=os.getenv('OS_USERNAME')\npassword=os.getenv('OS_PASSWORD')\nauth_url=os.getenv('OS_AUTH_URL')\nproject_name=os.getenv('OS_TENANT_NAME')\nregion_name=os.getenv('OS_REGION_NAME')\n\nnovaclient = NovaClient('2', username=username, password=password, auth_url=auth_url, project_name=project_name, region_name=region_name)\n\nvms=novaclient.servers.list(search_opts={'all_tenants': 1,'status': 'ACTIVE'})\n\ncount = 1\nresults = {}\nfor vm in vms:\n\n print(str(count)+' of '+str(len(vms)),end='\\r')\n sys.stdout.flush()\n count = count + 1\n for key in vm.addresses:\n floatingip = 'NA'\n nics = vm.addresses[key]\n for nic in nics:\n if nic['OS-EXT-IPS:type'] == 'floating':\n floatingip = nic['addr']\n break\n\n hypervisor = getattr(vm, 'OS-EXT-SRV-ATTR:hypervisor_hostname')\n port_test = True\n iplist = []\n if( floatingip != 'NA' ):\n port_test = isOpen(floatingip, 22)\n\n\n if( results.has_key(hypervisor) == False):\n results[hypervisor] = { 'active': 0, 'iplist': []}\n \n results[hypervisor]['active'] = results[hypervisor]['active'] + 1\n if ( port_test == False):\n results[hypervisor]['iplist'].append(floatingip)\n\n\nprint('Compute Activevms Failedvms IpList')\nfor hypervisor in results:\n if(len(results[hypervisor]['iplist']) != 0):\n print(hypervisor, results[hypervisor]['active'], len(results[hypervisor]['iplist']), results[hypervisor]['iplist'])\n","sub_path":"openstack/sshtest.py","file_name":"sshtest.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"189569015","text":"# https://leetcode.com/problems/subarray-sum-equals-k/#/description\n\nclass Solution(object):\n def subarraySum(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n sums = {}\n sum = 0\n for i in range(len(nums)):\n sum += nums[i]\n l = sums.get(sum,[])\n l.append(i)\n sums[sum] = l\n res = 0\n sum = 0\n for i in range(len(nums)):\n indices = sums.get(sum+k, [])\n for x in indices:\n res += 1 if x >= i else 0\n sum += nums[i]\n return res\n\n# Solution 2\nclass Solution(object):\n def subarraySum(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n sums = []\n result = 0\n myMap = collections.Counter()\n myMap[0] = 1\n for num in nums:\n sums.append(sums[-1]+num) if sums else sums.append(num)\n for val in sums:\n balance = val - k\n result += myMap[balance]\n myMap[val] += 1\n return result\n","sub_path":"subarray-sum-equals-k.py","file_name":"subarray-sum-equals-k.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"54456581","text":"from Report import Report\nfrom Products.ProjectDatabase.utils import inner_strip\n\nclass FMIReceivablesReportFactory(object):\n\n def __init__(self, projectdatabase, **kw):\n self.projectdatabase = projectdatabase\n self.params = kw\n\n def getReport(self, name, type):\n # create and fill the report\n report = Report(name)\n report.setReportHeaders(( name,),)\n report.setTableHeaders(((\n 'IMIS No.',\n 'Project Title',\n 'Executing Agency',\n 'GEF Grant',\n 'Total Disbursements',\n 'Total Expenditures',\n 'Receivable/ (Payable)',\n ),))\n report.setTableRows(self.getReportData(type))\n # report.setTableTotals([])\n # report.setReportFooters()\n return report\n\n def getReportData(self, type):\n projects = self.params.get('projects', None)\n result = []\n for project in projects:\n ob = project.fmi_folder.get(type, None)\n if ob is not None:\n result.append((\n ob.getIMISNumber(),\n project.project_general_info.Title(),\n project.project_general_info.getLeadExecutingAgencyNames(),\n inner_strip(ob.getCommittedGEFGrant()),\n inner_strip(ob.getSumCashDisbursements()),\n inner_strip(ob.getSumYearlyExpenditures()),\n inner_strip(ob.getAmountReceivable()),\n ))\n return result\n\n","sub_path":"unep.project-database/branches/rijk-reportname-refactor/reports/FMIReceivablesReportFactory.py","file_name":"FMIReceivablesReportFactory.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"38582321","text":"import numpy as np\nfrom django.db import models\nfrom icecream import ic\nimport pandas as pd\nfrom admin.common.models import ValueObject\nfrom sklearn.model_selection import train_test_split, StratifiedShuffleSplit\nimport matplotlib.pyplot as plt\n\n\nclass HousingService(object):\n def __init__(self):\n self.dfg = ValueObject()\n self.dfg.fname = 'admin/housing/data/housing.csv'\n self.df = self.dfg.create_model()\n\n def housing_info(self):\n self.dfg.model_info(self.df)\n #\n # def housing_hist(self):\n # self.model.fname.hist(bins=50, figsize=(20, 15))\n # plt.savefig('admin/housing/image/housing-hist.png')\n #\n # def split_model(self) -> []:\n # train_set, test_set = train_test_split(self.new_model(), test_size=0.2, random_state=42)\n # return [train_set, test_set]\n #\n # def income_cat_hist(self):\n # h = self.new_model()\n # h['income_cat'] = pd.cut(h['median_income'],\n # bims=[0., 1.5, 3.0, 4.5, 6., np.inf], # np.inf is NaN(Not a Number)\n # labels=[1, 2, 3, 4, 5])\n # h['income_cat'].hist()\n # plt.savefig('admin/housing/image/income-cat.png')\n #\n # def split_model_by_income_cat(self) -> []:\n # h = self.new_model()\n # split = StratifiedShuffleSplit(n_splits=1, test=0.2, random_state=42)\n # for train_idx, test_idx in split.split(h, h['income_cat']):\n # temp_train_set = h.loc(train_idx)\n # temp_test_set = h.loc(test_idx)\n # ic(temp_test_set-'income_cat').value_counts() / len(temp_test_set)\n\n\nclass Housing(models.Model):\n use_in_migrations = True\n housing_id = models.AutoField(primary_key=True)\n longitude = models.FloatField()\n latitude = models.FloatField()\n housing_median_age = models.FloatField()\n total_rooms = models.FloatField()\n total_bedrooms = models.FloatField()\n population = models.FloatField()\n households = models.FloatField()\n median_income = models.FloatField()\n median_house_value = models.FloatField()\n ocean_proximity = models.TextField()\n\n class Meta:\n db_table = 'housings'\n\n def __str__(self):\n return f'[{self.pk}] {self.housing_id}'\n\n\nif __name__ == '__main__':\n h = HousingService()\n ic(h.new_model())","sub_path":"backend/admin/housing/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"578755434","text":"#!/usr/bin/env python3\n\"\"\"Custom json reporter for pylint and json to html export utility.\"\"\"\nimport os\nimport sys\nimport json\nimport html\nimport argparse\nimport logging\nfrom datetime import datetime\nfrom glob import glob\nfrom collections import OrderedDict\nfrom pylint.reporters.base_reporter import BaseReporter\nimport pandas as pd\n\n# pylint: disable=invalid-name\n\nlog = logging.getLogger()\n\nHTML_HEAD = \"\"\"\n\n\nPylint report\n\n\n\n\"\"\"\n\ndef get_score(stats):\n \"\"\"Compute score.\"\"\"\n if 'statement' not in stats or stats['statement'] == 0:\n return None\n\n s = stats.get('statement')\n e = stats.get('error', 0)\n w = stats.get('warning', 0)\n r = stats.get('refactor', 0)\n c = stats.get('convention', 0)\n\n # https://docs.pylint.org/en/1.6.0/faq.html\n return 10 - 10*(5 * e + w + r + c) / s\n\ndef get_score_history(score_dir):\n \"\"\"Return a ordered dict of score history as sha:score pairs.\n\n Note\n -----\n The following assumptions regarding the score files in score_dir are made:\n\n - the filenames are ``pylint_NUMBER.SHORT_SHA.log``\n - each file contains only one number (the score)\n\n Returns\n --------\n :obj:`collections.OrderedDict`\n Sha:score pairs.\n\n \"\"\"\n # pylint: disable=redefined-outer-name\n out = OrderedDict()\n for f in sorted(glob(os.path.join(score_dir, 'pylint_*.log'))):\n with open(f) as h:\n s = h.readline(1)\n out[f.split('.')[-2]] = float(s)\n return out\n\ndef plot_score_history(scores, fig_name):\n \"\"\"Plot score history.\n\n Parameters\n ----------\n scores : :obj:`collections.OrderedDict`\n Scores generated using :func:`get_score_history`.\n fig_name : :obj:`str`\n Name of file where to save the figure.\n\n \"\"\"\n try:\n import matplotlib.pyplot as plt\n plt.rcParams.update({'font.size': 18,\n 'axes.titlesize': 18,\n 'axes.labelsize': 18,\n 'xtick.labelsize': 18,\n 'ytick.labelsize': 18,\n 'legend.fontsize': 18,\n 'figure.titlesize': 18})\n except ModuleNotFoundError:\n log.warning('matplotlib not found, plot_score_history cannot be used.')\n\n plt.figure(figsize=(15, 5))\n plt.plot(list(scores.values()), 'bo--')\n plt.xticks(range(len(scores)), list(scores.keys()), rotation='vertical')\n plt.yticks([2, 4, 6, 8, 10])\n plt.grid(True)\n plt.xlabel('commits')\n plt.ylabel('score')\n plt.autoscale(enable=True, axis='x', tight=True)\n plt.subplots_adjust(bottom=0.35)\n plt.title('Score history')\n plt.savefig(fig_name, dpi=200)\n\ndef json2html(data, score_figure=None):\n \"\"\"Generate an html file (based on :obj:`data`).\"\"\"\n out = HTML_HEAD\n out += '\\n

    Pylint report

    \\n'\n\n now = datetime.now()\n out += ('Report generated on {} at {} by '\n 'pytest-report'\n '\\n'). format(now.strftime('%Y-%d-%m'),\n now.strftime('%H:%M:%S'))\n\n score = get_score(data['stats'])\n out += '

    Score: {:.2f} / 10

    \\n'.\\\n format(score if score is not None else -1)\n\n if score_figure is not None:\n out += '\"Score\\n'.format(score_figure)\n\n msg = dict()\n if data['messages']:\n msg = {name: df_.sort_values(['line', 'column']).reset_index(drop=True) for\n name, df_ in pd.DataFrame(data['messages']).groupby('module')}\n\n # modules summary\n out += '
      '\n for module in data['stats']['by_module'].keys():\n if module in msg:\n out += '
    • {0} ({1})
    • \\n'.format(module,\n len(msg[module]))\n else:\n out += '
    • {0} ({1})
    • \\n'.format(module, 0)\n out += '
    '\n\n # modules\n section = ('\\n

    Module: '\n '{0} ({1})

    \\n')\n cols2keep = ['line', 'column', 'symbol', 'type', 'obj', 'message']\n for module, value in msg.items():\n out += '
    \\n
    '\n out += section.format(module, len(value))\n out += '
    '\n\n out += ''\n\n s1 = value.groupby('symbol')['module'].count().to_frame().reset_index().\\\n rename(columns={'module': '# msg'}).to_html(index=False, justify='center')\n\n s2 = value.groupby('type')['module'].count().to_frame().reset_index().\\\n rename(columns={'module': '# msg'}).to_html(index=False, justify='center')\n\n out += ''.join(['\\n\\n',\n '\\n\\n'])\n out += '
    \\n' + s1 + '\\n\\n' + s2 + '\\n
    '\n\n out += value[cols2keep].to_html(justify='center').replace('\\\\n', '
    ')\n out += '\\n
    \\n'\n\n # end of document\n out += '\\n'\n return out\n\nclass _SetEncoder(json.JSONEncoder):\n \"\"\"Handle sets when dumping to json.\n\n Note\n -----\n See https://stackoverflow.com/a/8230505\n \"\"\"\n # pylint: disable=method-hidden\n def default(self, o):\n if isinstance(o, set):\n return list(o)\n return json.JSONEncoder.default(self, o)\n\nclass CustomJsonReporter(BaseReporter):\n \"\"\"Customize the default json reporter.\n\n Note\n -----\n See ``pylint/reporters/json_reporter.py``\n\n \"\"\"\n\n name = \"custom json\"\n\n def __init__(self, output=sys.stdout):\n \"\"\"Construct object.\"\"\"\n super().__init__(output)\n self.messages = []\n\n def handle_message(self, msg):\n \"\"\"Manage message of different type and in the context of path.\"\"\"\n self.messages.append({\"type\": msg.category,\n \"module\": msg.module,\n \"obj\": msg.obj,\n \"line\": msg.line,\n \"column\": msg.column,\n \"path\": msg.path,\n \"symbol\": msg.symbol,\n \"message\": html.escape(msg.msg or \"\", quote=False),\n \"message-id\": msg.msg_id})\n\n def display_messages(self, layout):\n \"\"\"See ``pylint/reporters/base_reporter.py``.\"\"\"\n\n def display_reports(self, layout):\n \"\"\"See ``pylint/reporters/base_reporter.py``.\"\"\"\n\n def _display(self, layout):\n \"\"\"See ``pylint/reporters/base_reporter.py``.\"\"\"\n\n def on_close(self, stats, previous_stats):\n \"\"\"See ``pylint/reporters/base_reporter.py``.\"\"\"\n print(json.dumps({'messages': self.messages,\n 'stats': stats,\n 'previous_stats': previous_stats},\n cls=_SetEncoder, indent=2),\n file=self.out)\n\ndef register(linter):\n \"\"\"Register a reporter (required by :mod:`pylint`).\"\"\"\n linter.register_reporter(CustomJsonReporter)\n\ndef get_parser():\n \"\"\"Define command-line argument parser.\"\"\"\n parser = argparse.ArgumentParser()\n # see https://stackoverflow.com/a/11038508\n parser.add_argument(\n 'json_file',\n nargs='?',\n type=argparse.FileType('r'),\n default=sys.stdin,\n help='Json file/stdin generated by pylint.')\n parser.add_argument(\n '-o', '--html-file',\n type=argparse.FileType('w'),\n default=sys.stdout,\n help='Name of html file to generate.')\n parser.add_argument(\n '-s', '--score',\n action='store_true',\n help='Output only the score.')\n parser.add_argument(\n '--score-history-dir',\n default=None,\n help='Directory with score history.')\n parser.add_argument(\n '--score-history-fig',\n default=None,\n help='Filename where to store the score history figure.')\n\n return parser\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n args = get_parser().parse_args()\n\n if args.score_history_dir is not None:\n if args.score_history_fig is not None:\n plot_score_history(get_score_history(args.score_history_dir),\n args.score_history_fig)\n else:\n log.warning(('Score history figure not generated '\n '(--score_history-fig flag not provided).'))\n else:\n with args.json_file as h:\n json_data = json.load(h)\n\n if args.score:\n print('pylint score: {:.2f}'.format(get_score(json_data['stats'])),\n file=sys.stdout)\n else:\n print(json2html(json_data, args.score_history_fig), file=args.html_file)\n","sub_path":"pylint_report/pylint_report.py","file_name":"pylint_report.py","file_ext":"py","file_size_in_byte":9031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"137913041","text":"import matplotlib\nmatplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\nimport string\n\n\ndef plot_2D(N, R, name,xl,yl):\n plt.cla()\n plt.plot(N, R)\n #plt.plot(N, np.sqrt(N)) #auskommentiert für S\n plt.xlabel(xl)\n plt.ylabel(yl, rotation = 0)\n #plt.legend([\"MD\",\"sqrt(N)\"]) #auskom für S\n plt.title(name)\n plt.savefig(name + '.pdf')\n\n\ndef main():\n I, T = np.loadtxt('times_ps.txt', delimiter = ';', unpack = True)\n plot_2D(I, T, \"time_ps\",\"Iterations\",\"Time\")\n\n\nif __name__ == '__main__':\n main()\n\n\n\"\"\" x = []\n y = []\n with open('results/times_ps.txt','r') as csvfile:\n plots = csv.reader(csvfile, delimiter=';')\n for row in plots:\n x.append(float(row[0]))\n y.append(float(row[1])) \n\"\"\"\n\"\"\"\" plt.plot(x,y, label='Loaded from file!')\n plt.xlabel('Iteration')\n plt.ylabel('Time')\n plt.title('Interesting Graph\\nCheck it out')\n plt.legend()\n plt.show()\"\"\"","sub_path":"FloriansDaten/time_iter_plotting.py","file_name":"time_iter_plotting.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"313133497","text":"from pandas import read_excel, isnull\nfrom json import dump\nfrom codecs import open\nfrom sys import argv\n\nlatest = read_excel(\"citycountries.xlsx\")\nfilename = \"citycountries.json\"\n\nif len(argv) == 2 and argv[1] == \"test\":\n latest = latest[latest[\"test\"] == True]\n filename = \"citycountries_test.json\"\n\nfixture = []\n\ni = 1\ncountry_pk = {}\nfor country in latest[\"country\"].unique():\n if not isnull(country):\n data = {\n \"pk\": i,\n \"model\": \"hlwtadmin.Country\",\n \"fields\": {\n \"name\": country,\n \"iso_code\": latest[latest[\"country\"] == country][\"iso_code\"].values[0].lower() if not isnull(latest[latest[\"country\"] == country][\"iso_code\"].values[0]) else \"NA\"\n }\n }\n country_pk[country] = i\n i += 1\n\n fixture.append(data)\n\ni = 1\nlocation_pk = {}\nfor location in latest[[\"name\", \"subcountry\", \"country\"]].itertuples():\n print(location)\n city = location[1]\n subcountry = location[2]\n country = location[3]\n if not isnull(city) and not isnull(subcountry) and not isnull(country) and (city, subcountry, country) not in location_pk:\n data = {\n \"pk\": i,\n \"model\": \"hlwtadmin.Location\",\n \"fields\": {\n \"city\": city,\n \"subcountry\": subcountry,\n \"country\": country_pk[country]\n }\n }\n location_pk[(city, subcountry, country)] = i\n i += 1\n fixture.append(data)\n\nwith open(filename, \"w\", \"utf-8\") as f:\n dump(fixture, f, indent=4)\n","sub_path":"hlwtadmin/fixtures/citycountries.py","file_name":"citycountries.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"291085051","text":"# -*- coding: utf-8 -*-\n\nSWAGGER_SETTINGS = {\n 'SUPPORTED_SUBMIT_METHOD': ['get', 'post', 'put', 'delete'],\n 'USE_SESSION_AUTH': True,\n 'LOGIN_URL': '/admin',\n 'JSON_EDITOR': True,\n 'LOGOUT_URL': '/admin/logout',\n 'SECURITY_DEFINITIONS': {\n 'Bearer': {\n 'type': 'apiKey',\n 'name': 'Authorization',\n 'in': 'header',\n },\n },\n 'APIS_SORTER': 'alpha',\n 'SHOW_REQUEST_HEADERS': True,\n 'VALIDATOR_URL': None,\n 'DEFAULT_MODEL_RENDERING': 'example',\n}\n\nLOGOUT_URL = '/admin/logout'\n","sub_path":"{{cookiecutter.project_name}}/server/settings/components/swagger.py","file_name":"swagger.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"28487225","text":"\"\"\"\n -------------------------------------------------------------------------\n Universidad del Valle de Guatemala\n Ingenieria en Ciencias de la Computacion y Tecnologias de la Informacion\n Graficas por Computadora - Seccion 10\n Dieter de Wit - Carnet 15146\n -------------------------------------------------------------------------\n Funciones de Creacion de objetos Bitmap, lectura de ellos y mimica de GL\n -------------------------------------------------------------------------\n\"\"\"\n\n# **************** Imports ***************\nimport struct\nfrom collections import namedtuple\nimport math\n# ****************************************\n\n\n# --- Estructurar datos String como Binarios ---\ndef char(c):\n return struct.pack(\"=c\", c.encode('ascii'))\n\n\ndef word(c):\n return struct.pack(\"=h\", c)\n\n\ndef dword(c):\n return struct.pack(\"=l\", c)\n# ----------------------------------------------\n\n\n# Formato de Color RGB\ndef color(r, g, b):\n return bytes([b, g, r])\n\n\n# -------------------------------- Operaciones sobre Vectores ----------------------------------\nV2 = namedtuple('Vertex2', ['x', 'y'])\nV3 = namedtuple('Vertex3', ['x', 'y', 'z'])\n\n\ndef suma(v0, v1):\n return V3(v0.x + v1.x, v0.y + v1.y, v0.z + v1.z)\n\n\ndef sub(v0, v1):\n return V3(v0.x - v1.x, v0.y - v1.y, v0.z - v1.z)\n\n\ndef mul(v0, k):\n return V3(v0.x * k, v0.y * k, v0.z * k)\n\n\ndef dot(v0, v1):\n return v0.x * v1.x + v0.y * v1.y + v0.z * v1.z\n\n\ndef cross(v0, v1):\n return V3(v0.y * v1.z - v0.z * v1.y, v0.z * v1.x - v0.x * v1.z, v0.x * v1.y - v0.y * v1.x)\n\n\ndef length(v0):\n return (v0.x ** 2 + v0.y ** 2 + v0.z ** 2) ** 0.5\n\n\ndef norm(v0):\n nlength = length(v0)\n if nlength == 0:\n return V3(0, 0, 0)\n else:\n return V3(v0.x / nlength, v0.y / nlength, v0.z / nlength)\n# ----------------------------------------------------------------------------------------------\n\n\n# Muestreo de los tamanos de recuadros\ndef bbox(A, B, C):\n xs = sorted([A.x, B.x, C.x])\n ys = sorted([A.y, B.y, C.y])\n v1 = V2(int(xs[0]), int(ys[0]))\n v2 = V2(int(xs[2]), int(ys[2]))\n return v1, v2\n\n\n# Transformacion de coordenadas de los vertices\ndef barycentric(A, B, C, P):\n cx, cy, cz = cross(\n V3(B.x - A.x, C.x - A.x, A.x - P.x),\n V3(B.y - A.y, C.y - A.y, A.y - P.y)\n )\n if cz == 0: # cz no puede ser menor que 1\n return -1, -1, -1\n\n # Se calculan las coordenadas baricentricas\n u = cx/cz\n v = cy/cz\n w = 1 - (u + v)\n return w, v, u\n\n\n# Funcion de Multiplicacion de 2 Matrices\ndef mult_matrices(matrix1, matrix2):\n resultante = []\n filas = len(matrix1)\n columnas = len(matrix2[0])\n longitud = len(matrix1[0])\n longitud2 = len(matrix2)\n\n if longitud != longitud2:\n return None\n\n for i in range(filas):\n fila = []\n for j in range(columnas):\n count = 0\n for k in range(longitud):\n count += matrix1[i][k] * matrix2[k][j]\n fila.append(count)\n resultante.append(fila)\n return resultante\n\n\n# ************************************************************************************\n# Objeto: Permite la escritura a un archivo BMP y funciones de Renderizado\n# Bitmap\n# ************************************************************************************\nclass Bitmap(object):\n\n # Inicializacion General: Variables\n def __init__(self, width, height):\n self.x = 0\n self.y = 0\n self.vx = 0\n self.vy = 0\n self.width = width\n self.height = height\n self.framebuffer = []\n self.zbuffer = []\n self.shader = color(0, 0, 0)\n self.material = {}\n self.vertex_color = color(255, 255, 0)\n self.colorin = self.shader\n self.Model = []\n self.View = []\n self.Projection = []\n self.Viewport = []\n self.glInit()\n\n # Inicializacion Secundaria: Funciones que Inicializan nuestro Software Renderer\n def glInit(self):\n self.glClear()\n\n # Crecion del Viewport que tiene las dimensiones de Escritura del BMP\n def glViewPort(self, x, y, width, height):\n self.vx = width\n self.vy = height\n self.x = x\n self.y = y\n\n # Realiza la limpieza de ambos Buffers\n def glClear(self):\n self.framebuffer = [\n [\n color(0, 0, 0) # Escritura de pixeles negros\n for x in range(self.width)\n ]\n for y in range(self.height)\n ]\n\n self.zbuffer = [\n [\n -1 * float('inf')\n for x in range(self.width)\n ]\n for y in range(self.height)\n ]\n\n # Limpiaeza del zbuffer para escritura de nuevos .obj\n def glClearZbuffer(self):\n self.zbuffer = [\n [\n -1 * float('inf')\n for x in range(self.width)\n ]\n for y in range(self.height)\n ]\n\n # Funcion de escritura de un pixel\n def glVertex(self, x, y):\n try:\n self.framebuffer[y][x] = self.vertex_color\n except IndexError:\n pass\n\n # Varia el color del glVertex\n def glColor(self, r, g, b):\n self.vertex_color = color(r, g, b)\n\n # Creacion del archivo .bmp\n def glFinish(self, filename):\n f = open(filename, 'bw')\n\n # File Header (14)\n f.write(char('B'))\n f.write(char('M'))\n f.write(dword(162 + self.width * self.height))\n f.write(dword(0))\n f.write(dword(54))\n\n # Image Header (40)\n f.write(dword(40))\n f.write(dword(self.width))\n f.write(dword(self.height))\n f.write(word(1))\n f.write(word(24))\n f.write(dword(0))\n f.write(dword(self.width * self.height * 3))\n f.write(dword(0))\n f.write(dword(0))\n f.write(dword(0))\n f.write(dword(0))\n\n # Escritura al Buffer\n for x in range(self.height):\n for y in range(self.width):\n f.write(self.framebuffer[x][y])\n\n # Se cierra el archivo\n f.close()\n\n # Funcion de linea en cualquier cuadrante\n def glLine(self, x0, y0, x1, y1):\n\n # Diferenciales para la pendiente\n dx = abs(x1 - x0)\n dy = abs(y1 - y0)\n\n # Si la diferencia de y es mayor se debe de pintar mas pixeles en ese eje\n steep = dy > dx\n\n if steep:\n x0, y0 = y0, x0\n x1, y1 = y1, x1\n\n # Cuando el punto inicial en x es mayor que el final se cambian\n if x0 > x1:\n x0, x1 = x1, x0\n y0, y1 = y1, y0\n\n # Calculamos las diferenciales por si hubo cambio de puntos\n dx = abs(x1 - x0)\n dy = abs(y1 - y0)\n\n offset = 0\n threshold = dx\n y = y0\n\n for x in range(x0, x1 + 1):\n if steep:\n self.glVertex(y, x)\n else:\n self.glVertex(x, y)\n\n offset += dy\n if offset >= threshold:\n y += 1 if y0 < y1 else -1\n threshold += dx\n\n # z-buffer\n def glTransform(self, vertex, translate=(0, 0, 0), scale=(1, 1, 1)):\n # Vertex aumentado para la Matriz Pipe resultante\n matrix_vertex = [[vertex[0]], [vertex[1]], [vertex[2]], [1]]\n\n # Transformar un vertice a Tupla\n matriz1 = mult_matrices(self.Model, self.View)\n matriz2 = mult_matrices(self.Projection, matriz1)\n matriz3 = mult_matrices(self.Viewport, matriz2)\n transformed = mult_matrices(matriz3, matrix_vertex)\n\n # Se construye el vertice ya transformado\n vtransformed = [\n (transformed[0][0] / transformed[3][0]),\n (transformed[1][0] / transformed[3][0]),\n (transformed[2][0] / transformed[3][0])\n ]\n return V3(\n (vtransformed[0] + translate[0]) * scale[0],\n (vtransformed[1] + translate[1]) * scale[1],\n (vtransformed[2] + translate[2]) * scale[2]\n )\n\n # Lee y pinta la imagen de fondo por medio de un framebuffer\n def framebuffer_fondo(self, texture):\n for x in range(texture.width):\n for y in range(texture.height):\n fcolor = texture.pixels[y][x]\n self.glColor(fcolor[0], fcolor[1], fcolor[2])\n self.glVertex(x, y)\n\n # Funcion de camara que define desde que angulo realizamos la escritura de nuestro modelos\n def lookAt(self, eye, center, up):\n # Coordenadas de Proyeccion\n z = norm(sub(eye, center))\n x = norm(cross(up, z))\n y = norm(cross(z, x))\n\n # Creacion de la matriz View\n self.loadViewMatrix(x, y, z, center)\n self.loadProjectionMatrix(-1 / length(sub(eye, center)))\n self.loadViewportMatrix()\n\n # Creacion y uso de las Matrices de Traslacion, Rotacion y Escala a utilizar\n def loadModelMatrix(self, translate=(0, 0, 0), scale=(1, 1, 1), rotate=(0, 0, 0)):\n # Creacion de la matriz Translate\n mtranslate = [\n [1, 0, 0, translate[0]],\n [0, 1, 0, translate[1]],\n [0, 0, 1, translate[2]],\n [0, 0, 0, 1]\n ]\n # Creacion de la matriz Scale\n mscale = [\n [scale[0], 0, 0, 0],\n [0, scale[1], 0, 0],\n [0, 0, scale[2], 0],\n [0, 0, 0, 1]\n ]\n\n # ---- Creacion de las tres matrices Rotation ----\n a = rotate[0]\n rotation_x = [\n [1, 0, 0, 0],\n [0, math.cos(a), -1 * (math.sin(a)), 0],\n [0, math.sin(a), math.cos(a), 0],\n [0, 0, 0, 1]\n ]\n a = rotate[1]\n rotation_y = [\n [math.cos(a), 0, math.sin(a), 0],\n [0, 1, 0, 0],\n [-1 * (math.sin(a)), 0, math.cos(a), 0],\n [0, 0, 0, 1]\n ]\n a = rotate[2]\n rotation_z = [\n [math.cos(a), -1 * (math.sin(a)), 0, 0],\n [math.sin(a), math.cos(a), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ]\n # ------------------------------------------------\n\n r_matrix = mult_matrices(rotation_y, rotation_z)\n r_matrix = mult_matrices(r_matrix, rotation_x)\n matrix = mult_matrices(r_matrix, mscale)\n self.Model = mult_matrices(mtranslate, matrix)\n\n def loadViewMatrix(self, x, y, z, center):\n M = [\n [x.x, x.y, x.z, 0],\n [y.x, y.y, y.z, 0],\n [z.x, z.y, z.z, 0],\n [0, 0, 0, 1]\n ]\n O = [\n [1, 0, 0, -center.x],\n [0, 1, 0, -center.y],\n [0, 0, 1, -center.z],\n [0, 0, 0, 1]\n ]\n self.View = mult_matrices(M, O)\n\n def loadProjectionMatrix(self, coeff):\n self.Projection = [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, coeff, 1]\n ]\n\n def loadViewportMatrix(self, x=0, y=0):\n w = int(self.width / 2)\n h = int(self.height / 2)\n self.Viewport = [\n [w, 0, 0, x + w],\n [0, w, 0, y + h],\n [0, 0, 128, 128],\n [0, 0, 0, 1]\n ]\n\n def glTriangle(self, A, B, C, directional_light, normal_coords, mtl_color=None):\n bbox_min, bbox_max = bbox(A, B, C)\n\n for x in range(bbox_min.x, bbox_max.x + 1):\n for y in range(bbox_min.y, bbox_max.y + 1):\n w, v, u = barycentric(A, B, C, V2(x, y))\n\n if w < 0 or v < 0 or u < 0:\n continue\n\n self.colorin = self.shader(bar = (w, v, u), varying_normals = normal_coords, light = directional_light, mtl_color = mtl_color, xyCoords = (x, y))\n\n self.glColor(self.colorin[0], self.colorin[1], self.colorin[2])\n\n z = A.z * w + B.z * v + C.z * u\n\n if x < 0 or y < 0:\n continue\n\n if x < len(self.zbuffer) and y < len(self.zbuffer[x]) and z > self.zbuffer[x][y]:\n self.glVertex(x, y)\n self.zbuffer[x][y] = z\n\n # Carga el Obj y realiza las operaciones de Traslacion, Escala, Rotacion y aplicacion del Material\n def glLoad(self, filename, translate=(0, 0, 0), scale=(1, 1, 1), rotate=(0, 0, 0), mtl='None'):\n self.loadModelMatrix(translate, scale, rotate)\n model = Obj(filename)\n self.glRead(mtl)\n\n for face in model.faces:\n vcount = len(face)\n\n if vcount >= 3:\n f1 = face[0][0] - 1\n f2 = face[1][0] - 1\n f3 = face[2][0] - 1\n\n a = self.glTransform(model.vertices[f1], translate, scale)\n b = self.glTransform(model.vertices[f2], translate, scale)\n c = self.glTransform(model.vertices[f3], translate, scale)\n\n n1 = face[0][2] - 1\n n2 = face[1][2] - 1\n n3 = face[2][2] - 1\n nA = V3(*model.normales[n1])\n nB = V3(*model.normales[n2])\n nC = V3(*model.normales[n3])\n\n luz = V3(0.1, 0.6, 0.9)\n\n red = round(self.material[face[3]][0] * 255)\n green = round(self.material[face[3]][1] * 255)\n blue = round(self.material[face[3]][2] * 255)\n\n self.glTriangle(A=a, B=b, C=c, directional_light=luz, normal_coords=(nA, nB, nC), mtl_color=(red, green, blue))\n\n # Lectura del archivo .mtl para el muestreo de los colores del material\n def glRead(self, mtl):\n with open(mtl) as f2:\n lineas = f2.read().splitlines()\n\n for linea in lineas:\n if linea:\n prefix, value = linea.split(' ', 1)\n if prefix == 'newmtl':\n indice = lineas.index(linea)\n for read_line in range(indice, indice + 5):\n prefix2, colores = lineas[read_line].split(' ', 1)\n if prefix2 == 'Kd':\n self.material.update({value: list(map(float, (colores.split(' '))))})\n\n # Gouraud Shader que se utiliza para agregar efectos de sombreado asi como aumento a las normales poligonales\n def gouraud(self, **kwargs):\n\n # Recibe las coordenadas normales, barycentricas, los colores del archivo mtl y la luz\n w, v, u = kwargs['bar']\n nA, nC, nB = kwargs['varying_normals']\n light = kwargs['light']\n r, g, b = kwargs['mtl_color']\n\n nx = nA.x * w + nB.x * v + nC.x * u\n ny = nA.y * w + nB.y * v + nC.y * u\n nz = nA.z * w + nB.z * v + nC.z * u\n\n # Se obtiene un vector normal por cada punto\n vertex_normal = V3(nx, ny, nz)\n\n # Se calcula el valor de la intensidad de la luz\n intensity = dot(vertex_normal, light)\n\n r = int(r * intensity)\n g = int(g * intensity)\n b = int(b * intensity)\n\n return (\n r if 255 > r > 0 else 0,\n g if 255 > g > 0 else 0,\n b if 255 > b > 0 else 0\n )\n\n # Shader que se utiliza para agregar efecto de color laser chinto en los proyectiles\n def laser_shader(self, **kwargs):\n\n # Recibe las coordenadas normales, barycentricas, los colores del archivo mtl y la luz\n w, v, u = kwargs['bar']\n nA, nC, nB = kwargs['varying_normals']\n light = kwargs['light']\n r, g, b = kwargs['mtl_color']\n\n nx = nA.x * w + nB.x * v + nC.x * u\n ny = nA.y * w + nB.y * v + nC.y * u\n nz = nA.z * w + nB.z * v + nC.z * u\n\n # Se obtiene un vector normal por cada punto\n vertex_normal = V3(nx, ny, nz)\n\n # Se calcula el valor de la intensidad de la luz\n intensity = dot(vertex_normal, light)\n\n r = int(r * intensity)\n g = int(g * intensity)\n b = int(b * intensity)\n\n return (\n r if 100 > r > 0 else 60,\n g if 255 > g > 200 else 244,\n b if 75 > b > 0 else 50\n )\n\n # Shader que se utiliza para colocar el arc fighter mas brillante, ya que no se miraba\n # y colocarle color azul en las sombras del motor debido a que va entrar en hiperespacio\n def arc_shader(self, **kwargs):\n\n # Recibe las coordenadas normales, barycentricas, los colores del archivo mtl y la luz\n w, v, u = kwargs['bar']\n nA, nC, nB = kwargs['varying_normals']\n light = kwargs['light']\n r, g, b = kwargs['mtl_color']\n\n nx = nA.x * w + nB.x * v + nC.x * u\n ny = nA.y * w + nB.y * v + nC.y * u\n nz = nA.z * w + nB.z * v + nC.z * u\n\n # Se obtiene un vector normal por cada punto\n vertex_normal = V3(nx, ny, nz)\n\n # Se calcula el valor de la intensidad de la luz\n intensity = dot(vertex_normal, light)\n\n r = int(r * intensity)\n g = int(330 - g * intensity)\n b = int(300 - b * intensity)\n\n return (\n r if 155 > r > 0 else 55,\n g if 255 > g > 0 else 0,\n b if 255 > b > 0 else 0\n )\n\n # Shader que se utiliza para agregar efecto de luz roja en el Tie-Fighter,\n # Por la utilizacion de la coordenada barimetrica 'v' el shader es paralelo a la direccion de\n # la cara de la nave, por esta razon crea la sensacion de sombra roja debajo de las alas\n def tie_shader(self, **kwargs):\n\n # Recibe las coordenadas normales, barycentricas, los colores del archivo mtl y la luz\n w, v, u = kwargs['bar']\n nA, nC, nB = kwargs['varying_normals']\n light = kwargs['light']\n r, g, b = kwargs['mtl_color']\n\n nx = nA.x * w + nB.x * v + nC.x * u\n ny = nA.y * w + nB.y * v + nC.y * u\n nz = nA.z * w + nB.z * v + nC.z * u\n\n # Se obtiene un vector normal por cada punto\n vertex_normal = V3(nx, ny, nz)\n\n # Se calcula el valor de la intensidad de la luz\n intensity = dot(vertex_normal, light)\n\n r = int((r * intensity)/(v * 5))\n g = int((g * intensity))\n b = int((b * intensity))\n\n return (\n r if 255 > r > 0 else 0,\n g if 255 > g > 0 else 0,\n b if 255 > b > 0 else 0\n )\n\n\n# ****************************************************************************************\n# Objeto: Permite la lectura de un archivo BMP para la aplicacion del fondo y de Texturas\n# Texture\n# ****************************************************************************************\nclass Texture(object):\n def __init__(self, path):\n self.path = path\n self.width = 0\n self.height = 0\n self.pixels = []\n self.read()\n\n def read(self):\n img = open(self.path, \"rb\")\n img.seek(10)\n header_size = struct.unpack(\"=l\", img.read(4))[0]\n img.seek(18)\n self.width = struct.unpack(\"=l\", img.read(4))[0]\n self.height = struct.unpack(\"=l\", img.read(4))[0]\n img.seek(header_size)\n\n for y in range(self.height):\n self.pixels.append([])\n for x in range(self.width):\n b = ord(img.read(1))\n g = ord(img.read(1))\n r = ord(img.read(1))\n self.pixels[y].append(color(b, g, r))\n\n img.close()\n\n def get_color(self, tx, ty, intensity=1):\n x = int(tx * self.width)\n y = int(ty * self.height)\n\n return bytes(\n map(\n lambda b: round(b*intensity) if b*intensity > 0 else 0,\n self.pixels[y][x]\n )\n )\n\n\n# *************************************************************************************************\n# Objeto: Permite la lectura de un archivo .obj para la aplicacion del modelo al Software Renderer\n# Obj\n# *************************************************************************************************\nclass Obj(object):\n def __init__(self, filename):\n with open(filename) as f:\n self.lines = f.read().splitlines()\n\n self.vertices = []\n self.tvertices = []\n self.normales = []\n self.mtl = []\n self.faces = []\n self.lista = []\n self.read()\n\n def space(self, face):\n\n self.lista = face.split('/')\n\n if \"\" in self.lista:\n self.lista[1] = 0\n\n return map(int, self.lista)\n\n def read(self):\n for line in self.lines:\n if line:\n prefix, value = line.split(' ', 1)\n\n if prefix == 'usemtl':\n material = value\n # self.mtl.append(value.split(' '))\n\n if prefix == 'v':\n self.vertices.append(list(map(float, value.split(' '))))\n\n if prefix == 'vt':\n self.tvertices.append(list(map(float, value.split(' '))))\n\n elif prefix == 'f':\n listita = [list(self.space(face)) for face in value.split(' ')]\n # self.faces.append([list(self.try_int(face)) for face in value.split(' ')])\n listita.append(material)\n self.faces.append(listita)\n # self.faces.append([list(map(int,face.split('/'))) for face in value.split(' ')])\n\n elif prefix == 'vn':\n self.normales.append(list(map(float, value.split(' '))))\n","sub_path":"KryuGL.py","file_name":"KryuGL.py","file_ext":"py","file_size_in_byte":21211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"356091362","text":"#!/usr/bin/env python3\n\nfrom sys import argv\n\nignore = ['duplex', 'alias', 'Current configuration']\nwith open(argv[1], 'r') as fr:\n for line in fr:\n for ig_item in ignore:\n if ig_item in line:\n break\n else:\n with open('config_sw1_cleared.txt', 'a') as fw:\n fw.write(line)\n","sub_path":"tasks/t7-2b.py","file_name":"t7-2b.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"464925526","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('bulls', '0003_auto_20160522_1354'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='game',\n options={'ordering': ['team'], 'verbose_name': 'peli', 'verbose_name_plural': 'pelit'},\n ),\n ]\n","sub_path":"bulls/migrations/0004_auto_20160522_1406.py","file_name":"0004_auto_20160522_1406.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"381731760","text":"# stat_tests.py\n# Script to find some stats about survey results\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\n\n# I assume values and frequencies are both vectors\ndef frequency_table_mean_and_stddev(values, frequencies):\n\tmean = np.sum(values * frequencies)/np.sum(frequencies)\n\tvariance = np.sum([(values[i]-mean)**2 * frequencies[i] for i in range(len(values))])/np.sum(frequencies)\n\treturn mean, np.sqrt(variance)\n\n# Load data, make contingency tables for:\n\t# what tables do I need??\n\nf = open('../Data/pretty_tables.csv', 'r')\n\nlines = [line for line in f.read().split('\\n')]\ntable = [[value for value in line.split(',')] for line in lines]\n\nbach_vs_computer_values = np.zeros([8,3,2]) # question * education level * bach/computer\nbach_vs_computer_stddev = np.zeros([8,3])\nbach_vs_computer = np.zeros([8,3])\nbach_vs_computer_confidence_interval = np.zeros([8,3])\nlikeability = np.zeros([8,3])\nlikeability_stddev = np.zeros([8,3])\nlikeability_values = np.zeros([8,3,5])\nlikeability_confidence_interval = np.zeros([8,3])\n\nlines_of_interest = []\nfor i, line in enumerate(lines):\n\tif len(line) > 0 and line[0] == '#':\n\t\tlines_of_interest.append(i)\nbetter_lines = [lines_of_interest[i] for i in range(4,20,2)]\n\n\nfor i,val in enumerate(better_lines):\n\t#print(table[val+1:val+12])\n\tbach_vs_computer_values[i,0] = np.array(table[val+1:val+3])[:,6].T.astype(np.int32)\n\tbach_vs_computer_values[i,1] = np.array(table[val+1:val+3])[:,9].T.astype(np.int32)\n\tbach_vs_computer_values[i,2] = np.array(table[val+1:val+3])[:,12].T.astype(np.int32)\n\tbach_vs_computer[i,0], bach_vs_computer_stddev[i,0] = frequency_table_mean_and_stddev(np.array([1,0]),\n\t\tbach_vs_computer_values[i,0])\n\tbach_vs_computer_confidence_interval[i,0] = 1.96 * bach_vs_computer_stddev[i,0] / np.sqrt(np.sum(bach_vs_computer_values[i,0]))\n\n\tbach_vs_computer[i,1], bach_vs_computer_stddev[i,1] = frequency_table_mean_and_stddev(np.array([1,0]),\n\t\tbach_vs_computer_values[i,1])\n\tbach_vs_computer_confidence_interval[i,1] = 1.96 * bach_vs_computer_stddev[i,1] / np.sqrt(np.sum(bach_vs_computer_values[i,1]))\n\n\tbach_vs_computer[i,2], bach_vs_computer_stddev[i,2] = frequency_table_mean_and_stddev(np.array([1,0]),\n\t\tbach_vs_computer_values[i,2])\n\tbach_vs_computer_confidence_interval[i,2] = 1.96 * bach_vs_computer_stddev[i,2] / np.sqrt(np.sum(bach_vs_computer_values[i,2]))\n\n\n\tlikeability_values[i,0] = np.array(table[val+7:val+12])[:,6].T.astype(np.int32)\n\tlikeability_values[i,1] = np.array(table[val+7:val+12])[:,9].T.astype(np.int32)\n\tlikeability_values[i,2] = np.array(table[val+7:val+12])[:,12].T.astype(np.int32)\n\tlikeability[i,0], likeability_stddev[i,0] = frequency_table_mean_and_stddev(np.array([5,4,3,2,1]),\n\t\tlikeability_values[i,0])\n\tlikeability_confidence_interval[i,0] = 1.96 * likeability_stddev[i,0] / np.sqrt(np.sum(likeability_values[i,0]))\n\n\tlikeability[i,1], likeability_stddev[i,1] = frequency_table_mean_and_stddev(np.array([5,4,3,2,1]),\n\t\tlikeability_values[i,1])\n\tlikeability_confidence_interval[i,1] = 1.96 * likeability_stddev[i,1] / np.sqrt(np.sum(likeability_values[i,1]))\n\n\tlikeability[i,2], likeability_stddev[i,2] = frequency_table_mean_and_stddev(np.array([5,4,3,2,1]),\n\t\tlikeability_values[i,2])\n\tlikeability_confidence_interval[i,2] = 1.96 * likeability_stddev[i,2] / np.sqrt(np.sum(likeability_values[i,2]))\n\n#print(likeability_stddev)\n\n\n\n\n\n\n\n# make bar graphs for:\n\t# bach vs. computer for each of 8 categories split by education level\nN = 8 # 8 categories to compare in three things\nind = np.arange(N)\nwidth = 0.25\nfig, ax = plt.subplots()\nrects1a = ax.bar(ind, bach_vs_computer_values[:,0,0]/np.sum(bach_vs_computer_values[:,0], axis=1), width, color = 'purple', label='Musician, knows Bach',\n\tyerr=bach_vs_computer_confidence_interval[:,0], error_kw=dict(ecolor='black'))\n#rects1b = ax.bar(ind, bach_vs_computer[:,0,1]/np.sum(bach_vs_computer[:,0], axis=1), width, \n#\tbottom=bach_vs_computer[:,0,0]/np.sum(bach_vs_computer[:,0], axis=1), color='b')\n\nrects2a = ax.bar(ind + width, bach_vs_computer_values[:,1,0]/np.sum(bach_vs_computer_values[:,1], axis=1), width,color='blue', label='Musician, doesn\\'t know Bach',\n\tyerr=bach_vs_computer_confidence_interval[:,1], error_kw=dict(ecolor='black'))\n#rects2b = ax.bar(ind + width, bach_vs_computer[:,1,1]/np.sum(bach_vs_computer[:,1], axis=1), width, \n#\tbottom=bach_vs_computer[:,1,0]/np.sum(bach_vs_computer[:,1], axis=1), color='b')\n\nrects3a = ax.bar(ind + 2 * width, bach_vs_computer_values[:,2,0]/np.sum(bach_vs_computer_values[:,2], axis=1), width,color='cyan', label='Non-musician',\n\tyerr=bach_vs_computer_confidence_interval[:,2], error_kw=dict(ecolor='black'))\n#rects3b = ax.bar(ind + 2 * width, bach_vs_computer[:,2,1]/np.sum(bach_vs_computer[:,2], axis=1), width, \n#\tbottom=bach_vs_computer[:,2,0]/np.sum(bach_vs_computer[:,2], axis=1), color='b')\n\nax.set_ylim([0,1])\nax.set_ylabel('Percent')\nax.set_title('Survey Responses: Bach or Computer?')\nax.set_xticks(ind + width * 3 / 2)\nax.set_xticklabels(('Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8'))\n\nax.legend(loc=2)\n\nplt.show()\n\n# next I want to calculate 95% confidence intervals.\n\n\n\t# average likeability for each of 8 categories split by education level\nN = 8 # 8 categories to compare in three things\nind = np.arange(N)\nwidth = 0.25\nfig, ax = plt.subplots()\nrects1a = ax.bar(ind, likeability[:,0], width, yerr=likeability_confidence_interval[:,0], error_kw=dict(ecolor='black'), color='purple', label='Musician, knows Bach')\n\nrects2a = ax.bar(ind + width, likeability[:,1], width, yerr=likeability_confidence_interval[:,1], error_kw=dict(ecolor='black'), color='blue', label='Musician, doesn\\'t know Bach')\n\nrects3a = ax.bar(ind + 2 * width, likeability[:,2], width, yerr=likeability_confidence_interval[:,2], error_kw=dict(ecolor='black'), color='cyan', label='Non-musician')\n\nax.set_ylabel('Average Response')\nax.set_title('Survey Responses: Likeability')\nax.set_xticks(ind + width * 3 / 2)\nax.set_xticklabels(('Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8'))\nax.set_yticks(np.arange(1,6))\nax.set_yticklabels(('Dislike a Lot', 'Dislike', 'Neutral', 'Like', 'Like a Lot'))\n\nax.legend(loc=2)\n\nplt.show()","sub_path":"src/stat_tests_alternate.py","file_name":"stat_tests_alternate.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"434089941","text":"import MySQLdb\nimport config\n\n# PROCESSING UNIPROT DATA FILES AND CREATING DATABASE\n\ndef ExtractAllWords(Line):\n TempWords = str(Line).split(' ')\n WordAll = []\n for word in TempWords:\n if word != '': WordAll.append(word)\n return (WordAll)\ndef ExtractSEQ(ListLines):\n Out = []\n for Lines in ListLines:\n Temp = ExtractAllWords(Lines)\n Temp = [item.split('\\n')[0] for item in Temp]\n Out = Out+ Temp\n Out = ''.join(Out)\n return (Out)\n\ndef filterData(cur, temp0, temp1, temp2,temp3,temp4,temp5,temp6,temp7,temp8):\n add_register = (\"INSERT INTO evoluniprotv1.UNIPROTDB \"\n \"(UNIPROTID, UNIPROTAC, GENEID, GO) \"\n \"VALUES (%s, %s, %s, %s)\")\n\n if temp6 == 'Homo sapiens (Human).\\n':\n temp2 = temp2.split(';')[0]\n data_register = (temp0, temp2, temp3,temp8)\n cur.execute(add_register, data_register)\n \n \ndef UniprotDataBaseHS_Create():\n global DatabaseName\n \n \n TABLES= (\n \"CREATE TABLE `UNIPROTDB` (\"\n \" `UNIPROTID` varchar(50),\"\n \" `UNIPROTAC` TEXT,\" \n \" `GENEID` TEXT,\"\n \" `GO` TEXT\" \n \")\")\n db= MySQLdb.connect(host=config.host,passwd=config.password,user=config.user,db=DatabaseName) \n cur = db.cursor()\n print(\"Creating table : UNIPROTDB_FILTERED\")\n cur.execute(TABLES)\n print ('UNIPROTDB_FILTERED was created')\n\n\ndef UniprotDataBaseHS_ADD(UFile):\n\n global DatabaseName\n \n \n db= MySQLdb.connect(host=config.host,passwd=config.password,user=config.user,db=\"\") \n print(\"Adding records to table : UNIPROTDB_ALL\")\n f = open(UFile,'r')\n\n Continue = False\n for Line in f:\n \n Line = str(Line)\n TempList = ExtractAllWords(Line)\n \n if TempList[0]=='ID':\n Continue = False\n Record_ID = []\n Record_AC = []\n Record_ST = []\n Record_GID = []\n Record_GO = []\n Record_OX = []\n Record_OC = []\n Record_OS = []\n Record_SEQ = []\n Record_ID.append(TempList[1])\n T = str(TempList[2]).split(';')[0]\n Record_ST.append(T)\n if TempList[0]=='AC':\n T = TempList[1:len(TempList)]\n T = ''.join(T)\n T = str(T).split('\\n')[0]\n if T[len(T)-1] == ';': T = T[0:len(T)-1]\n Record_AC.append(T)\n if TempList[0]=='GeneID':\n T = str(str(TempList[1]).split(';')[0]).split('=')[1]\n Record_OX.append(T)\n if TempList[0]=='OS':\n \n T = TempList[1:len(TempList)]\n T = ' '.join(T)\n Record_OS.append(T)\n if TempList[0]=='OC':\n \n T = TempList[1:len(TempList)]\n T = ' '.join(T)\n Record_OC.append(T)\n if TempList[0]=='DR' and TempList[1]=='GeneID;':\n T= str(TempList[2]).split(';')[0]\n Record_GID.append(T)\n if TempList[0]=='SQ': Continue = True\n if Continue == True and TempList[0]!='SQ' and (Line[0]+Line[1])!='//': Record_SEQ.append(Line) \n if TempList[0]=='DR' and TempList[1]=='GO;':\n T= str(TempList[2]).split(';')[0]\n Record_GO.append(T)\n if (Line[0]+Line[1])=='//':\n Continue = False\n Temp = []\n Temp.append(Record_ID[0])\n Temp.append(Record_ST[0])\n if len(Record_AC)>0:\n Temp.append(Record_AC[0])\n else:\n Temp.append('')\n if len(Record_GID)>0:\n Temp.append(Record_GID[0])\n else:\n Temp.append('')\n if len(Record_OX)>0:\n Temp.append(Record_OX[0])\n else:\n Temp.append('')\n if len(Record_OC)>0:\n Temp.append(''.join(Record_OC))\n else:\n Temp.append('')\n if len(Record_OS)>0:\n Temp.append(''.join(Record_OS))\n else:\n Temp.append('')\n if len(Record_SEQ)>0:\n T = ExtractSEQ(Record_SEQ)\n Temp.append(T)\n else:\n Temp.append('')\n if len(Record_GO)>0:\n Temp.append(';'.join(Record_GO))\n else:\n Temp.append('')\n cur = db.cursor()\n filterData(cur, Temp[0], Temp[1], Temp[2],Temp[3],Temp[4],Temp[5],Temp[6],Temp[7],Temp[8])\n db.commit()\n \n f.close\n print ('File Processed')\n \n# Main program UniprotDB_ALL.py \n\nif __name__ == '__main__':\n \n dirSprotDat = config.basedir + 'resources/uniprot_sprot.dat'\n DatabaseName = 'evoluniprot'\n SprotFile = dirSprotDat\n UniprotDataBaseHS_Create()\n UniprotDataBaseHS_ADD (SprotFile)\n print ('SWI Processed')\n \n \n","sub_path":"Scripts/Anexo VII - uniprotDB_ALL.py","file_name":"Anexo VII - uniprotDB_ALL.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"363733940","text":"import json\r\nimport requests\r\n\r\nother_db = requests.get(url='https://fantasy.premierleague.com/drf/bootstrap-static').json()\r\n\r\nfixtures_infos = {}\r\nfor i in range(1,len(other_db['elements'])+1):\r\n other_db1 = requests.get(url='https://fantasy.premierleague.com/drf/element-summary/{}'.format(i)).json()\r\n fixtures_infos['{}'.format(i)] = other_db1\r\n\r\nwith open(\"player_fixtures.txt\", \"w\") as g:\r\n g.write(json.dumps(fixtures_infos))\r\n\r\n\r\nother_db1 = requests.get(url='https://fantasy.premierleague.com/drf/bootstrap-static').json()\r\nwith open(\"player_infos.txt\", \"w\") as g:\r\n g.write(json.dumps(other_db1))\r\n","sub_path":"product-files/database_grabber.py","file_name":"database_grabber.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"604640486","text":"\nfhand = input('Enter file name:')\nfhand = open(fhand)\n\nmails = dict()\nfor lines in fhand:\n words = lines.split()\n if len(words) < 3 or words[0] != 'From': continue\n else:\n if words[1] not in mails:\n mails[words[1]] = 1\n else:\n mails[words[1]] += 1\nprint(mails)\n\n","sub_path":"Exercises/9. dictionaries/9.3 histogram.py","file_name":"9.3 histogram.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"295215384","text":"# coding: utf-8\nfrom django.shortcuts import render\nfrom django.http import Http404, JsonResponse\nimport json\nfrom .models import ServerHeartBeat\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.db.models import Count\nfrom django.utils import timezone as datetime\n\n\n@csrf_exempt\ndef beat(request):\n if not request.method == 'POST':\n raise Http404\n try:\n result = json.loads(request.body)\n ServerHeartBeat.objects.create(server_fqdn=result['server_fqdn'])\n except ValueError:\n return JsonResponse({'ok': False, 'error': 'Bad json request'})\n except KeyError:\n return JsonResponse({'ok': False, 'error': 'No Server_FQDN information'})\n return JsonResponse({'ok': True})\n\n\n@csrf_exempt\ndef statistics(request):\n hours_24_ago = datetime.now() - datetime.timedelta(days=1)\n servers_fqdn = ServerHeartBeat.objects.filter(timestamp__gte=hours_24_ago).values('server_fqdn').annotate(count=Count('id'))\n for fqdn in servers_fqdn:\n fqdn['uptime'] = fqdn['count']/(60*24.0)\n del fqdn['count']\n return JsonResponse({'ok': True, 'result': list(servers_fqdn)})\n\n","sub_path":"python_webapp/serverheartbeat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"175177147","text":"import pickle\n\nlayer = 2\n\nPATH_LI = \"/home/niit1/PycharmProjects/Data-Mining-Research/eclipse/entropy/local_influence/definition_2/\"\nPATH_EDGES = \"/home/niit1/PycharmProjects/Data-Mining-Research/eclipse/edges/definition_2/\"\nPATH_NEIGH = \"/home/niit1/PycharmProjects/Data-Mining-Research/eclipse/neighbours/definition_2/\"\n\nwith open(PATH_LI + \"layer_\" + str(layer) + \"_local_influence.txt\", 'rb') as fp:\n li = pickle.load(fp)\n\nwith open(PATH_EDGES + \"layer\" + str(layer) + \"_edges_fc.txt\", 'rb') as fp:\n edges = pickle.load(fp)\n\nwith open(PATH_NEIGH + \"layer_\" + str(layer) + \"_neighbours.txt\", 'rb') as fp:\n graph = pickle.load(fp)\n\nindirect_influence = {}\nremain = len(graph.keys())\nfor i in graph.keys():\n print(\"Remaining:\", remain)\n sg = graph[i]\n\n hop2_neighs_dict = {}\n hop2_neighs = set()\n for j in sg:\n ssg = graph[j]\n\n for k in ssg:\n if k in sg or k == i:\n pass\n else:\n hop2_neighs.add(k)\n\n hop2_neighs_dict[j] = ssg\n\n ii = 0\n tot = 0\n for j in hop2_neighs:\n pairwise_li = 0\n cnt = 0\n for k in hop2_neighs_dict:\n if j in hop2_neighs_dict[k]:\n pairwise_li += li[i] * li[k]\n cnt += 1\n ii += pairwise_li / cnt\n tot += 1\n\n try:\n indirect_influence[i] = ii / tot\n except ZeroDivisionError:\n print(i)\n\n remain -= 1\n\n\nwith open(\"indirect_influence_\" + str(layer) + \".txt\", 'wb') as fp:\n pickle.dump(indirect_influence, fp)\n","sub_path":"eclipse/indirect_influence/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"200767881","text":"from unittest import TestCase\nfrom itertools import product\n\nfrom markovchain.image.traversal import (\n Traversal, Lines, HLines, VLines, Spiral, Hilbert, Blocks\n)\n\n\nclass TestLines(TestCase):\n def setUp(self):\n Traversal.add_class(Lines)\n\n def tearDown(self):\n Traversal.remove_class(Lines)\n\n def test_save_load(self):\n tests = [(0, False), (2, True)]\n for test in tests:\n test = Lines(*test)\n saved = test.save()\n loaded = Traversal.load(saved)\n self.assertEqual(test, loaded)\n\n\nclass TestHLines(TestCase):\n def test_traverse(self):\n test = HLines()\n\n test.reverse = 0\n self.assertEqual(list(test(2, 3, False)),\n [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)])\n self.assertEqual(list(test(2, 3, True)),\n [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)])\n test.reverse = 1\n self.assertEqual(list(test(2, 3)),\n [(1, 0), (0, 0), (1, 1), (0, 1), (1, 2), (0, 2)])\n test.reverse = 2\n self.assertEqual(list(test(2, 3)),\n [(1, 0), (0, 0), (0, 1), (1, 1), (1, 2), (0, 2)])\n test.reverse = 0\n test.line_sentences = True\n self.assertEqual(list(test(2, 3, True)),\n [(0, 0), (1, 0), None,\n (0, 1), (1, 1), None,\n (0, 2), (1, 2), None])\n self.assertEqual(list(test(2, 3, False)),\n [(0, 0), (1, 0), (0, 1),\n (1, 1), (0, 2), (1, 2)])\n\n def test_save_load(self):\n tests = [(0, False), (2, True)]\n for test in tests:\n test = HLines(*test)\n saved = test.save()\n loaded = Traversal.load(saved)\n self.assertEqual(test, loaded)\n\n\nclass TestVLines(TestCase):\n def test_traverse(self):\n test = VLines()\n\n test.reverse = 0\n self.assertEqual(list(test(2, 3)),\n [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)])\n test.reverse = 1\n self.assertEqual(list(test(2, 3)),\n [(0, 2), (0, 1), (0, 0), (1, 2), (1, 1), (1, 0)])\n test.reverse = 2\n self.assertEqual(list(test(2, 3)),\n [(0, 2), (0, 1), (0, 0), (1, 0), (1, 1), (1, 2)])\n test.reverse = 0\n test.line_sentences = True\n self.assertEqual(list(test(2, 3)),\n [(0, 0), (0, 1), (0, 2), None,\n (1, 0), (1, 1), (1, 2), None])\n self.assertEqual(list(test(2, 3, False)),\n [(0, 0), (0, 1), (0, 2),\n (1, 0), (1, 1), (1, 2)])\n\n def test_save_load(self):\n tests = [(0, False), (2, True)]\n for test in tests:\n test = VLines(*test)\n saved = test.save()\n loaded = Traversal.load(saved)\n self.assertEqual(test, loaded)\n\n\nclass TestSpiral(TestCase):\n def test_traverse(self):\n test = Spiral()\n tests = product(range(1, 7), range(1, 7))\n for width, height in tests:\n test.reverse = False\n res = list(test(width, height, False))\n self.assertCountEqual(res, product(range(width), range(height)))\n test.reverse = True\n res2 = list(test(width, height, False))\n res.reverse()\n self.assertEqual(res2, res)\n\n def test_save_load(self):\n tests = [(False,), (True,)]\n for test in tests:\n test = Spiral(*test)\n saved = test.save()\n loaded = Traversal.load(saved)\n self.assertEqual(test, loaded)\n\n\nclass TestHilbert(TestCase):\n def test_traverse(self):\n test = Hilbert()\n tests = product(range(1, 7), range(1, 7))\n for width, height in tests:\n res = list(test(width, height))\n self.assertCountEqual(res, product(range(width), range(height)))\n\n def test_save_load(self):\n test = Hilbert()\n saved = test.save()\n loaded = Traversal.load(saved)\n self.assertEqual(test, loaded)\n\n\nclass TestBlocks(TestCase):\n def test_traverse(self):\n def hline(width, height, ends): # pylint: disable=unused-argument\n for x in range(width):\n yield (x, 0)\n if ends and x == 0:\n yield None\n\n def vline(width, height, ends): # pylint: disable=unused-argument\n for y in range(height):\n yield (0, y)\n if ends:\n yield None\n\n traverse = Blocks(block_size=(2, 2),\n block_sentences=False,\n traverse_image=hline,\n traverse_block=vline)\n\n tests = [\n ((4, 4, False), [(0, 0), (0, 1), (2, 0), (2, 1)]),\n ((3, 3, False), [(0, 0), (0, 1)]),\n ((4, 4, True), [(0, 0), (0, 1), None, (2, 0), (2, 1)])\n ]\n\n for test, res in tests:\n self.assertEqual(list(traverse(*test)), res)\n\n traverse.block_sentences = True\n\n tests = [\n ((4, 4, False), [(0, 0), (0, 1), (2, 0), (2, 1)]),\n ((3, 3, True), [(0, 0), (0, 1), None, None]),\n ((4, 4, True), [(0, 0), (0, 1), None, None, (2, 0), (2, 1), None])\n ]\n\n for test, res in tests:\n self.assertEqual(list(traverse(*test)), res)\n\n def test_save_load(self):\n tests = [\n ((8, 8), True,\n HLines(reverse=1, line_sentences=True),\n VLines(reverse=2, line_sentences=False))\n ]\n for test in tests:\n test = Blocks(*test)\n saved = test.save()\n loaded = Traversal.load(saved)\n self.assertEqual(test, loaded)\n","sub_path":"tests/image/test_traversal.py","file_name":"test_traversal.py","file_ext":"py","file_size_in_byte":5847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"23161380","text":"from flask import Flask\r\nfrom flask import render_template\r\nimport pandas as pd\r\nimport tensorflow as tf\r\nimport numpy as np\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers\r\n\r\nimport psycopg2\r\nprint('TensorFlow version: %s' % tf.__version__)\r\nprint('Keras version: %s' % tf.keras.__version__)\r\n\r\nlist =[]\r\n\r\ntry:\r\n connection = psycopg2.connect(user=\"postgres\",\r\n password=\"0115\",\r\n host=\"localhost\",\r\n port=\"5432\",\r\n database=\"project\")\r\n cursor = connection.cursor()\r\n postgreSQL_select_Query = \"SELECT tip.user_id, business.business_id, business.stars FROM business, tip WHERE tip.business_id = business.business_id;\"\r\n\r\n cursor.execute(postgreSQL_select_Query)\r\n print(\"Selecting rows from user and business table using cursor.fetchall\")\r\n user_records = cursor.fetchall()\r\n\r\n print(\"Print each row and it's columns values\")\r\n for row in user_records:\r\n\r\n list.append(row)\r\nexcept (Exception, psycopg2.Error) as error:\r\n print(\"Error while fetching data from PostgreSQL\", error)\r\n\r\nfinally:\r\n # closing database connection.\r\n if connection:\r\n cursor.close()\r\n connection.close()\r\n print(\"PostgreSQL connection is closed\")\r\ndf = pd.DataFrame(list)\r\n\r\ndf = df.rename(columns={0:\"userID\",1:\"businessID\",2:\"stars\",3:\"address\",4:\"totalieks\"})\r\n\r\nusers_ids = df[\"userID\"].unique().tolist()\r\n\r\n\r\nuser2user_encoded = {x: i for i, x in enumerate(users_ids)}\r\nuserencoded2user = {i:x for i, x in enumerate(users_ids)}\r\nbusiness_ids = df[\"businessID\"].unique().tolist()\r\nbusiness2business_encoded = {x: i for i, x in enumerate(business_ids)}\r\nbusiness_encoded2business = {i: x for i, x in enumerate(business_ids)}\r\n\r\ndf[\"user\"] = df[\"userID\"].map(user2user_encoded)\r\ndf[\"business\"] = df[\"businessID\"].map(business2business_encoded)\r\nnum_users = len(user2user_encoded)\r\nnum_business = len(business2business_encoded)\r\n\r\nx = df[[\"user\", \"business\"]].values\r\ndf[\"stars\"] = df[\"stars\"].values.astype(np.float32)\r\n\r\nmin_rating = min(df[\"stars\"])\r\nmax_rating = max(df[\"stars\"])\r\n\r\nprint(\r\n \"Number of users: {}, Number of Business: {}, Min rating: {}, Max rating: {}\".format(\r\n num_users, num_business, min_rating, max_rating\r\n )\r\n)\r\n\r\ndf = df.sample(frac=1, random_state=42)\r\nx = df[[\"user\", \"business\"]].values\r\n\r\ny = df[\"stars\"].apply(lambda x: (x - min_rating) / (max_rating - min_rating)).values\r\n\r\ntrain_indices = int(0.9 * df.shape[0])\r\n\r\n\r\nx_train, x_val, y_train, y_val = (\r\n x[:train_indices],\r\n x[train_indices:],\r\n y[:train_indices],\r\n y[train_indices:],\r\n)\r\n\r\n###Create the model\r\nEMBEDDING_SIZE = 500\r\n\r\n\r\nclass RecommenderNet(keras.Model):\r\n def __init__(self, num_users, num_business, embedding_size, **kwargs):\r\n super(RecommenderNet, self).__init__(**kwargs)\r\n self.num_users = num_users\r\n self.num_business = num_business\r\n self.embedding_size = embedding_size\r\n self.user_embedding = layers.Embedding(\r\n num_users,\r\n embedding_size,\r\n embeddings_initializer=\"he_normal\",\r\n embeddings_regularizer=keras.regularizers.l2(1e-6),\r\n )\r\n self.user_bias = layers.Embedding(num_users, 1)\r\n self.num_business_embedding = layers.Embedding(\r\n num_business,\r\n embedding_size,\r\n embeddings_initializer=\"he_normal\",\r\n\r\n embeddings_regularizer=keras.regularizers.l2(1e-6),\r\n )\r\n self.business_bias = layers.Embedding(num_business, 1)\r\n\r\n def call(self, inputs):\r\n user_vector = self.user_embedding(inputs[:, 0])\r\n\r\n user_bias = self.user_bias(inputs[:, 0])\r\n\r\n business_vector = self.num_business_embedding(inputs[:, 1])\r\n\r\n business_bias = self.business_bias(inputs[:, 1])\r\n\r\n dot_user_business = tf.tensordot(user_vector, business_vector, 2)\r\n\r\n # Add all the components (including bias)\r\n\r\n\r\n\r\n x = dot_user_business + user_bias + business_bias\r\n # The sigmoid activation forces the rating to between 1 and 5\r\n return tf.nn.sigmoid(x)\r\n\r\n\r\nmodel = RecommenderNet(num_users, num_business, EMBEDDING_SIZE)\r\nmodel.compile(\r\n loss=tf.keras.losses.BinaryCrossentropy(), optimizer=keras.optimizers.Adam(lr=0.001)\r\n)\r\n\r\nmodel = model.fit(\r\n x=x_train,\r\n y=y_train,\r\n batch_size=64,\r\n epochs=5,\r\n verbose=1,\r\n validation_data=(x_val, y_val),\r\n)\r\n\r\nmodel.save(\"neural_network4\")\r\n\r\n\r\n","sub_path":"recommendation_source_code.py","file_name":"recommendation_source_code.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"274335419","text":"from __future__ import print_function\nimport torch \n\nx = torch.empty(6,5) # 초기화되지 않은 행렬 생성\n#x = torch.rand(6,5) # 무작위로 초개ㅣ화된 행렬 생성\n#x = torch.zeros(6,5, dtype=torch.long) #dtype long인 0으로 초기화된 행렬 생성\n#x = torch.tensor([[1.1,3],[2.5,8.1],[4.11,9.11]]) # 임의의 텐서 생성\n#x = x.new_ones(6,5,dtype = torch.double) # new_*메소드는 크기를 받는다\n#x = torch.randn_like(x, dtype = torch.float) # dtype을 오버라이드 한다. 결과는 동일한 크기\n#print(x.size()) #행렬의 크기\n#y = torch.rand(6,5)\n#print(x + y) # 행렬 덧셈연산 = print(torch.add(x, y))\n# result = torch.empty(6,5) \n# torch.add(x,y, out = result ) # 연산 결과를 result로 넘김\n#y.add_(x) # y에 x 더해서 대입\n#x = torch.randn(4,4)\n#y = x.view(16)\n#z = x.view(-1,8) # -1인자는 다른 차원에서 유추\n#print(x.size(),y.size(),z.size())\nif torch.cuda.is_available():\n device = torch.device(\"cuda\") # CUDA 장치 객체(device object)로\n y = torch.ones_like(x, device=device) # GPU 상에 직접적으로 tensor를 생성하거나\n x = x.to(device) # ``.to(\"cuda\")`` 를 사용하면 됩니다.\n z = x + y\n print(z)\n print(z.to(\"cpu\", torch.double)) # ``.to`` 는 dtype도 함께 변경합니다!","sub_path":"study/study_210225.py","file_name":"study_210225.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"132916971","text":"'''Notes:\n1. Need to add the previous seasons average to the csv file. After that, the machine learning section should be broken out to its own module and then called on all of the important\nfeatures in determining the fan duel fantasy score. The players year should be entered, but this should be a dummy variable\ninstead of an actual int value. \n\n3. This should be imported into the flask site with the ability to import all of the days players'''\n\nimport pandas as pd\nimport numpy as np\nimport os\nfrom regressor import rf_regressor\n\n# Data Cleanup\n\nos.chdir(r'F:\\Projects\\NBA\\DB_Files')\ndf = pd.read_csv('master.csv')\n\ntargets = ['TOV', 'REB', '3PM', 'FGM', 'PTS', 'AST', 'STL', 'BLK']\n\ndf.drop(columns=['PTS','Home', 'Away','Game', 'MIN', 'Date','FTM', '3P%', '3PA', 'PF', 'FG%', 'FGA',\n 'OREB', 'FT%', 'FTA', 'DREB','+/-', '1QH', '2QH', '3QH', '4QH', '1QA', '2QA', '3QA',\n '4QA', 'Total_H', 'Total_A', 'W/L','Fantasy_Score'], axis=1,inplace=True)\n\n\ndf_dummies = pd.get_dummies(df)\n\ndf_dummies = df_dummies.fillna(0)\n\nresults = rf_regressor(df_dummies)\n\ndef fantasy_points(df):\n score = (df['3PM'] * 3) + (df['FGM'] * 2) + (df['REB'] * 1) + (df['AST'] * 1.5) + (df['BLK'] * 3) + (df['STL'] * 3) + (df['TOV'] * -1)\n return score\n\nresults['Fantasy Score'] = results.apply(fantasy_points, axis=1)\n\n\nprint(results)","sub_path":"Random_Forest/Random_Forest.py","file_name":"Random_Forest.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"67805964","text":"# exercise\n# write a function that takes a dictionary, return the sum of keys and sum of values\n\nset2 = {'a', 'b', 'c'}\nset2.add('a')\n\nprint(set2)\n\nfor n in set2:\n print(n)\n\n# set1 = set([1, 2, 3, 4])\n# set1 = set ('123456')\n\n# find if one string contains the same letter as anther string\n# 'abbbcd' 'acbddd'\ndef diff(str1, str2):\n set1 = set(str1) # {'a', 'b', 'c', 'd'}\n set2 = set(str2) # {'a', 'c', 'b', 'd'}\n\n if set1 - set2 == {}:\n return True\n else:\n return False\n\n\ndiff('abbbcd', 'acbddd')\n\n\nset1 = {1, 2, 3, 4}\nset2 = {2, 5}\nprint(set1 - set2)\n\nint()","sub_path":"python_demo_programs/2020/example_20201010.py","file_name":"example_20201010.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"651160396","text":"#!/usr/bin/env/python3\n\nimport db\nfrom objects import Movie\n\ndef display_welcome():\n print(\"The Movie List program\")\n print() \n display_menu()\n\ndef display_menu():\n print(\"COMMAND MENU\")\n print(\"cat - View movies by category\")\n print(\"year - View movies by year\")\n print(\"add - Add a movie\")\n print(\"del - Delete a movie\")\n print(\"exit - Exit program\")\n print() \n\ndef display_categories():\n print(\"CATEGORIES\")\n categories = db.get_categories() \n for category in categories:\n print(str(category.id) + \". \" + category.name)\n print()\n\ndef display_movies_by_category():\n category_id = int(input(\"Category ID: \"))\n print()\n category = db.get_category(category_id)\n movies = db.get_movies_by_category(category_id)\n display_movies(movies, category.name.upper())\n \ndef display_movies(movies, title_term):\n print(\"MOVIES - \" + title_term)\n line_format = \"{:3s} {:37s} {:6s} {:5s} {:10s}\"\n print(line_format.format(\"ID\", \"Name\", \"Year\", \"Mins\", \"Category\"))\n print(\"-\" * 64)\n for movie in movies:\n print(line_format.format(str(movie.id), movie.name,\n str(movie.year), str(movie.minutes),\n movie.category.name))\n print() \n\ndef display_movies_by_year():\n year = int(input(\"Year: \"))\n print()\n movies = db.get_movies_by_year(year)\n display_movies(movies, str(year))\n\ndef add_movie():\n name = input(\"Name: \")\n year = int(input(\"Year: \"))\n minutes = int(input(\"Minutes: \"))\n category_id = int(input(\"Category ID: \"))\n \n category = db.get_category(category_id)\n movie = Movie(name=name, year=year, minutes=minutes,\n category=category)\n db.add_movie(movie) \n print(name + \" was added to database.\\n\")\n\ndef delete_movie():\n movie_id = int(input(\"Movie ID: \"))\n db.delete_movie(movie_id)\n print(\"Movie ID \" + str(movie_id) + \" was deleted from database.\\n\")\n \ndef main():\n db.connect()\n display_welcome()\n display_categories()\n while True: \n command = input(\"Command: \")\n if command == \"cat\":\n display_movies_by_category()\n elif command == \"year\":\n display_movies_by_year()\n elif command == \"add\":\n add_movie()\n elif command == \"del\":\n delete_movie()\n elif command == \"exit\":\n break\n else:\n print(\"Not a valid command. Please try again.\\n\")\n display_menu()\n db.close()\n print(\"Bye!\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/python/murach_python/book_apps/ch17/movies/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"242346645","text":"import requests, json\nfrom bs4 import BeautifulSoup\nfrom pprint import pprint\nimport pymysql\nimport re\n\ndef get_conn(db):\n return pymysql.connect(\n host='34.85.73.154',\n user='root',\n password='1q2w3e',\n port=3306,\n db=db,\n charset='utf8')\n\n\nurl = \"https://openapi.naver.com/v1/search/blog.json\"\n\ntitle = \"파이썬\"\nparams = {\n \"query\": title,\n \"display\": 100,\n \"start\": 1,\n \"sort\": \"date\"\n}\n\nheaders = {\n \"X-Naver-Client-Id\": \"JdPJow_YardxNqZZ_Xa1\",\n \"X-Naver-Client-Secret\": \"zWrh7TvHer\"\n}\n\nresult = requests.get(url, params=params, headers=headers).text\n\njsonData = json.loads(result)\n# print(jsonData['items'])\n# exit()\npattern1 = re.compile('\\/\\/.*\\/(.*)')\n\npattern2 = re.compile('\\/\\/(.*)\\/')\n\n\nbllst = []\nblplst = []\nfor bl in jsonData['items']:\n t_lst1 = []\n t_lst2 = []\n t_bllnk = bl['bloggerlink']\n det = re.findall(pattern2, t_bllnk)[0]\n if det == 'blog.naver.com':\n blID = re.findall(pattern1, t_bllnk)[0]\n else:\n blID = det\n blname = bl['bloggername']\n t_lst1.append(blID)\n t_lst1.append(blname)\n t_lst1.append(t_bllnk)\n bllst.append(t_lst1)\n title = bl['title']\n link = bl['link']\n postdate = bl['postdate']\n t_lst2.append(title)\n t_lst2.append(link)\n t_lst2.append(blID)\n t_lst2.append(postdate)\n blplst.append(t_lst2)\n\n\nconn = get_conn('melondb')\nwith conn:\n cur = conn.cursor()\n sqlbl = \"\"\"insert ignore into Blogger(bloggerID, bloggerName, bloggerLink)\n values(%s, %s, %s)\"\"\"\n cur.executemany(sqlbl, bllst)\n\n sqlblp = \"\"\"insert ignore into BlogPost(postName, postLink, bloggerID, postDate)\n values(%s, %s, %s, %s)\"\"\"\n cur.executemany(sqlblp, blplst)\n","sub_path":"20190129/naver_api_mysql.py","file_name":"naver_api_mysql.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"402558772","text":"import matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.style.use('ggplot')\n\nimport numpy as np\nfrom numpy import array\nimport sys\nfrom collections import defaultdict, OrderedDict\n\nimport gym\nimport mytaxi\n\nenv = gym.make('Taxi-v3').unwrapped\nnumS = env.observation_space.n\nnumA = env.action_space.n\nprint(\"#state:{}, #action{}\".format(numS, numA))\n\n\ndef make_epsilon_greedy_policy(Q, epsilon, nA):\n def policy_fn(observation):\n A = np.ones(nA, dtype=float) * epsilon / nA\n best_action = np.argmax(Q[observation])\n A[best_action] += (1.0 - epsilon)\n return A\n return policy_fn\n\n\ndef mc_control_epsilon_greedy(env, num_episodes, epsilon=0.1, runs=10):\n np.random.seed(3)\n env.seed(5)\n\n runs = 10\n rew_alloc = []\n for run in range(runs):\n np.random.seed(run)\n env.seed(run)\n returns_sum = defaultdict(float)\n returns_count = defaultdict(float)\n\n \n Q = defaultdict(lambda: np.zeros(env.action_space.n))\n policy = make_epsilon_greedy_policy(Q, epsilon, numA)\n rew_list = np.zeros(int(num_episodes/50))\n for i_episode in range(num_episodes):\n # Print out which episode we're on, useful for debugging.\n if i_episode % 1000 == 0:\n print(\"\\rEpisode {}/{}.\".format(i_episode, num_episodes), end=\"\")\n sys.stdout.flush()\n\n # Generate an episode.\n # An episode is an array of (state, action, reward) tuples\n episode = []\n state = env.reset()\n done = False\n for t in range(1000):\n probs = policy(state)\n action = np.random.choice(np.arange(len(probs)), p=probs)\n next_state, reward, done, _ = env.step(action)\n episode.append((state, action, reward))\n if i_episode % 50 == 0:\n idx = int(i_episode / 50) \n rew_list[idx] += reward\n if done:\n break\n state = next_state\n\n # Find all (state, action) pairs we've visited in this episode\n sa_in_episode = set([(x[0], x[1]) for x in episode])\n for state, action in sa_in_episode:\n sa_pair = (state, action)\n # Find the first occurance of the (state, action) pair in the episode\n first_occurence_idx = next(i for i,x in enumerate(episode)\n if x[0] == state and x[1] == action)\n # Sum up all rewards since the first occurrence\n G = sum([x[2] for x in episode[first_occurence_idx:]])\n # Update Q\n returns_sum[sa_pair] += G\n returns_count[sa_pair] += 1.0\n Q[state][action] = returns_sum[sa_pair] / returns_count[sa_pair]\n rew_alloc.append(rew_list)\n rew_list = np.mean(np.array(rew_alloc),axis=0)\n fig = plt.figure()\n plt.plot(rew_list)\n plt.savefig('mc_control_interim.eps')\n plt.close(fig)\n \n return Q, policy\n\n\nif __name__ == '__main__':\n\n Q, policy = mc_control_epsilon_greedy(env, num_episodes=10000, epsilon=0.1, runs=10)\n \n\n","sub_path":"hw2/mc_control.py","file_name":"mc_control.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"94427673","text":"import click\n\nfrom pathlib import Path\nfrom azure_file_queue import QueueBlobStorageUploader\n\n\n\n@click.command()\n@click.option('--account_name', prompt='Azure Storage Account Name',\n help=\"Storage account name\")\n@click.option('--account_key', prompt='Azure Storage Account Key',\n help=\"Storage account key\")\n@click.option('--storage_prefix', help='Prefix to be used in queue and blob container name', default='phone-files')\n@click.option('--path', prompt='Directory containing files', default=str(Path.cwd()))\n@click.option('--replace_name',\n help='If flag included, an MD5 hash will be used instead of a filename',\n is_flag=True,\n default=False)\ndef azqueue(path, account_name, account_key, storage_prefix, replace_name):\n \"\"\" Uploads all files in a given directory to Azure Blob Storage - while changing the name to a MD5 hash\n and creating a message in a queue with the path to the new blob. \"\"\"\n\n q = QueueBlobStorageUploader(dir_path=path,\n account_name=account_name,\n account_key=account_key,\n storage_prefix=storage_prefix,\n replace_name=replace_name)\n\n q.enqueue()\n","sub_path":"azure_file_queue/cli/cli_script.py","file_name":"cli_script.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"404772279","text":"# https://www.interviewbit.com/problems/diffk/\n\nclass Solution:\n # @param A : list of integers\n # @param B : integer\n # @return an integer\n \n def diffPossible(self, A, B):\n if len(A) == 0:\n return 0\n i= 0\n j= 1 # { i { i<=j-1 } => { i is at most j-1 }\n if A[j] - A[i] == B:\n return 1\n elif A[j] - A[i] < B:\n j+= 1\n else:\n i+= 1\n j= max(j, i+1)\n # if not ii\n \n if len(A) < 2: return 0\n # --maxdiff-\n if A[-1]-A[0] < k: return 0\n if A[-1]-A[0] == k: return 1\n \n if k == 0:\n # start return self.has_duplicate(A)\n prev_a= A[0]\n for curr_a in A[1:]:\n if prev_a == curr_a:\n return 1\n prev_a= curr_a\n return 0\n # end return self.has_duplicate(A)\n\n \n # start self.remove_duplicates(A)\n A= A[:] # A now points to a copy of input list A\n idx= 0\n len_A= 0 # the number of unique elements encountered\n while idx= min_Ai + k\n target= min_Aj\n min_j_offset= self.binary_search(A[min_j:], target)\n min_j+= min_j_offset\n \n if min_j == len(A):\n return 0\n \n if A[min_j] == target:\n i= min_i # optional\n j= min_j # optional\n return 1\n min_Aj= A[min_j]\n \n min_Ai= min_Aj - k # A[i], if it exists, is ge min_Aj-k, since A[i] >= min_Aj - k\n target= min_Ai\n min_i_offset= self.binary_search(A[min_i:], target)\n min_i+= min_i_offset\n \n # if min_i == len(A): # this condition is\n # return 0 # never trigered\n \n if A[min_i] == target:\n i= min_i # optional\n j= min_j # optional\n return 1\n \n min_Ai= A[min_i] # optional\n \n return 0\n \n # returns idx s.t. idx is the smallest index of lst s.t. target <= lst[idx]\n # note that this means that lst[idx-1] < target (if idx>0)\n def binary_search(self, lst, target):\n A, B = lst, target\n # start from # # https://www.interviewbit.com/problems/sorted-insert-position/\n # def searchInsert(self A, B):\n if B is []: return 0\n if B < A[0]: return 0\n if B > A[-1]: return len(A)\n \n l= 0\n r= len(A) -1\n \n mid= (l+r)/2\n # INVARIANT:\n # A[:l] < B\n # A[r+1:] > B\n while l<=r:\n current= A[mid]\n if B < current:\n r= mid-1\n elif B == current:\n return mid\n else: # B > current\n l= mid+1\n mid= (l+r)/2\n assert l == r + 1\n # A[:l] < B\n # A[r+1:] = A[l:] > B\n #\n # l \n # |\n # _______v________\n # [ B ]\n # ----------------\n return l\n # end from # # https://www.interviewbit.com/problems/sorted-insert-position/","sub_path":"interviewbit.com/Two Pointers/diffk.py","file_name":"diffk.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"346607354","text":"\nimport sys\nimport os\nimport logging\n\n\nthis_env = os.environ\n\ndti_qa_dir = os.path.join(this_env['MYDIR'], 'Code', 'GitRepos', 'DTI_qa')\n\nsys.path.append(dti_qa_dir)\nimport dti_qa_lib as dqa\n\n#Set basic logger\nrootLogger = logging.getLogger()\nrootLogger.setLevel(logging.INFO)\n\n#Set inputs\ndti_dir = os.path.join(this_env['EMDIR'], 'Data', 'MRI', 'BIDS', 'EMERALD', 'sub-{sub}', 'ses-day3', 'dwi')\ndwiprep_dir = os.path.join(this_env['EMDIR'], 'Data', 'MRI', 'BIDS', 'dwiprep', 'sub-{sub}', 'ses-day3')\npost_shell_index_file = os.path.join(this_env['EMDIR'], 'Data', 'MRI', 'BIDS', 'dwiqa', 'PostUpdate_dwi_shell_index.txt')\npre_shell_index_file = os.path.join(this_env['EMDIR'], 'Data', 'MRI', 'BIDS', 'dwiqa', 'PreUpdate_dwi_shell_index.txt')\noutput_dir = os.path.join(this_env['EMDIR'], 'Data', 'MRI', 'BIDS', 'dwiqa')\n\noverwrite = 1\n\nsubs_to_run = [\n 'EM3706',\n 'EM3825',\n 'EM3730',\n 'EM3874'\n ]\n \ngood_runs = []\nbad_runs = []\n\nfor sub in subs_to_run:\n try:\n sub_dti_dir = dti_dir.format(sub=sub)\n sub_dwiprep_dir = dwiprep_dir.format(sub=sub)\n sub_output_dir = os.path.join(output_dir, 'sub-{}'.format(sub))\n dti_image = os.path.join(sub_dti_dir, 'sub-{}_ses-day3_dwi.nii.gz'.format(sub))\n mask_image = os.path.join(sub_dwiprep_dir, 'sub-{}_ses-day3_dwi_d_ss_mask.nii.gz'.format(sub))\n\n #Select the correct shell index file\n if int(sub[-4:]) < 290:\n shell_index_file = pre_shell_index_file\n else:\n shell_index_file = post_shell_index_file\n\n #Try running the QA\n logging.info('Running Participant: {}'.format(sub))\n logging.info('----------Input Variables----------')\n logging.info('dti_image: {}'.format(dti_image))\n logging.info('mask_image: {}'.format(mask_image))\n logging.info('shell_index_file: {}'.format(shell_index_file))\n logging.info('output_dir: {}'.format(sub_output_dir))\n logging.info('overwrite: {}'.format(overwrite))\n logging.info('-----------------------------------')\n\n output_written = dqa.qa_the_dti(sub, dti_image, mask_image, shell_index_file, sub_output_dir, overwrite)\n good_runs.append(sub)\n except Exception as err:\n bad_runs.append(sub)\n logging.error('ERROR: Something went wrong with sub {}: {}'.format(sub,err))\n raise RuntimeError('Something went wrong: {}'.format(err))\n\nlogging.info('Finished Generating QA Metrics')\nlogging.info('------------------------------')\nlogging.info('Good Runs: {}'.format(good_runs))\nlogging.info('Bad Runs: {}'.format(bad_runs))\nlogging.info('------------------------------')","sub_path":"dwi_analysis/run_emerald_dwi_qa_metrics.py","file_name":"run_emerald_dwi_qa_metrics.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"237390291","text":"from os.path import join, dirname\nfrom shutil import copytree\nfrom subprocess import run, DEVNULL, STDOUT\nfrom tempfile import TemporaryDirectory\n\n\nTEMPLATE_TREE = join(dirname(__file__), 'data/Wwise')\n\nWWISE_CLI = '/Applications/Audiokinetic/Wwise {version}/'\nWWISE_CLI += 'Wwise.app/Contents/Tools/WwiseCLI.sh'\n\nCMD = '\"{exe}\" \"{project}\" -GenerateSoundBanks -Platform Windows'\n\nSKIP = 'aevalsrc=0:d={}[slug];[slug][0]concat=n=2:v=0:a=1[out]'\n\n\ndef _find_executable(hint):\n return WWISE_CLI.format(version='2016.1.3.5878')\n\n\ndef generate_banks(filepath, verbose=False, intro=10, offset=30):\n exe = _find_executable(None)\n redirect = {} if verbose else {'stdout': DEVNULL, 'stderr': STDOUT}\n\n with TemporaryDirectory() as tmp:\n base_dir = join(tmp, 'Wwise')\n copytree(TEMPLATE_TREE, base_dir)\n\n sfx_dir = join(base_dir, 'Originals', 'SFX')\n cmd = ['ffmpeg', '-i', filepath]\n run(cmd + ['-filter_complex', SKIP.format(intro), '-map', '[out]',\n join(sfx_dir, 'song.wav')], **redirect)\n run(cmd + ['-ss', str(offset), '-t', '30',\n join(sfx_dir, 'preview.wav')], **redirect)\n\n cmd = CMD.format(exe=exe, project=join(base_dir, 'Template.wproj'))\n run(cmd, shell=True, **redirect)\n\n bnk_dir = join(base_dir, 'GeneratedSoundBanks', 'Windows')\n copytree(bnk_dir, join('.', 'soundbanks'))\n","sub_path":"rocksmith/wwise.py","file_name":"wwise.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"277857969","text":"from django.db.models.signals import pre_save\r\nfrom django.dispatch import receiver\r\nfrom django.contrib.auth.models import Group, User\r\nfrom django.core.exceptions import ObjectDoesNotExist\r\nfrom student_portal.models import Enrollment, Instructor, Mentor, Course\r\n\r\nimport logging\r\nlogger = logging.getLogger('student_portal')\r\n\r\n@receiver(pre_save, sender=Course)\r\ndef recover_director_perms(sender, **kwargs):\r\n \"\"\" Signal receiver to detect Mentor changes and possibly revoke permissions. \"\"\"\r\n instance = kwargs['instance']\r\n try:\r\n course = Course.objects.get(id__exact=instance.id)\r\n if course.director != instance.director: # Detect when Director User changes and try reverting permissions\r\n courses = Course.objects.all().filter(director=course.director)\r\n if (courses.count() <= 1): # When last remaining Director role, remove from Director Group.\r\n director_group = Group.objects.get(name=\"Director\")\r\n course.director.groups.remove(director_group)\r\n except ObjectDoesNotExist: # New Course obj, or Default Groups don't exist\r\n return\r\n# EndDef\r\n\r\n@receiver(pre_save, sender=Instructor)\r\ndef recover_instructor_perms(sender, **kwargs):\r\n \"\"\" Signal receiver to detect Instructor changes and possibly revoke permissions. \"\"\"\r\n instance = kwargs['instance']\r\n try:\r\n instructor = Instructor.objects.get(id__exact=instance.id)\r\n if instructor.instructor != instance.instructor: # Detect when Instructor User changes\r\n instructors = Instructor.objects.all().filter(instructor=instructor.instructor)\r\n if (instructors.count() <= 1): # When last remaining Instructor role, remove from Instructor Group.\r\n instructor_group = Group.objects.get(name=\"Instructor\")\r\n instructor.instructor.groups.remove(instructor_group)\r\n except ObjectDoesNotExist: # New Instructor obj, or Default Groups don't exist\r\n return\r\n# EndDef\r\n\r\n@receiver(pre_save, sender=Mentor)\r\ndef recover_mentor_perms(sender, **kwargs):\r\n \"\"\" Signal receiver to detect Mentor changes and possibly revoke permissions. \"\"\"\r\n instance = kwargs['instance']\r\n try:\r\n mentor = Mentor.objects.get(id__exact=instance.id)\r\n if mentor.mentor != instance.mentor: # Detect when Mentor User has changed\r\n mentors = Mentor.objects.all().filter(mentor=mentor.mentor)\r\n if (mentors.count() <= 1): # When last remaining Mentor role, remove from Mentor Group.\r\n mentor_group = Group.objects.get(name=\"Mentor\")\r\n mentor.mentor.groups.remove(mentor_group)\r\n except ObjectDoesNotExist: # New Mentor obj, or Default Groups don't exist\r\n return\r\n# EndDef\r\n\r\n@receiver(pre_save, sender=Enrollment)\r\ndef recover_mentor_assign_perms(sender, **kwargs):\r\n \"\"\" Signal receiver to detect Mentor changes and possibly revoke permissions. \"\"\"\r\n instance = kwargs['instance']\r\n try:\r\n enrollment = Enrollment.objects.get(id__exact=instance.id)\r\n if enrollment.mentor != instance.mentor: # Detect when Enrollment.Mentor User has changed\r\n mentors = Mentor.objects.all().filter(mentor=enrollment.mentor)\r\n if (mentors.count() <= 1): # When last remaining Mentor role, remove from Mentor Group.\r\n mentor_group = Group.objects.get(name=\"Mentor\")\r\n enrollment.mentor.groups.remove(mentor_group)\r\n except ObjectDoesNotExist: # New Enrollment obj, or Default Groups don't exist\r\n return\r\n# EndDef\r\n","sub_path":"student_portal/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"88285002","text":"import os\n# import sys\nimport time\nfrom datetime import datetime\n\nimport pandas as pd\nimport requests\nimport xlsxwriter\nfrom bs4 import BeautifulSoup as bs\nfrom tqdm import tqdm\n\nlogdir = os.path.isdir('logs')\ndatadir = os.path.isdir('data')\nif not logdir:\n os.mkdir('logs')\nif not datadir:\n os.mkdir('data')\n\nfrom lib.helper_functions import nasdaq, logger\n\nstart_time = time.time()\ncurrent_year = int(datetime.today().year)\n\n\nclass Analyzer:\n def __init__(self):\n pd.set_option('display.max_rows', None)\n pd.set_option('display.max_columns', None)\n filename = datetime.now().strftime('data/stocks_%H:%M_%d-%m-%Y.xlsx')\n self.workbook = xlsxwriter.Workbook(filename)\n self.worksheet = self.workbook.add_worksheet('Results')\n self.worksheet.write(0, 0, \"Stock Ticker\")\n self.worksheet.write(0, 1, \"Capital\")\n self.worksheet.write(0, 2, \"PE Ratio\")\n self.worksheet.write(0, 3, \"Yield\")\n self.worksheet.write(0, 4, \"Current Price\")\n self.worksheet.write(0, 5, \"52 Week High\")\n self.worksheet.write(0, 6, \"52 Week Low\")\n self.worksheet.write(0, 7, \"Profit Margin\")\n self.worksheet.write(0, 8, \"Price Book Ratio\")\n self.worksheet.write(0, 9, \"Return on Equity\")\n self.worksheet.write(0, 10, f\"{current_year + 1} Analysis\")\n self.worksheet.write(0, 11, f\"{current_year} - {current_year + 5} Analysis\")\n self.worksheet.write(0, 12, f\"{current_year - 5} - {current_year} Analysis\")\n\n def write(self):\n n = 0\n i = 0\n # total = len(stocks)\n logger.info('Initializing Analysis on all NASDAQ stocks')\n print('Initializing Analysis on all NASDAQ stocks..')\n for stock in tqdm(stocks, desc='Analyzing Stocks', unit='stock', leave=False):\n i = i + 1\n summary = f'https://finance.yahoo.com/quote/{stock}/'\n stats = f'https://finance.yahoo.com/quote/{stock}/key-statistics/'\n analysis = f'https://finance.yahoo.com/quote/{stock}/analysis/'\n r = requests.get(f'https://finance.yahoo.com/quote/{stock}/')\n try:\n summary_result = pd.read_html(summary, flavor='bs4')\n market_capital = summary_result[-1].iat[0, 1]\n pe_ratio = summary_result[-1].iat[2, 1]\n forward_dividend_yield = summary_result[-1].iat[5, 1]\n\n scrapped = bs(r.text, \"html.parser\")\n raw_data = scrapped.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})[0]\n price = float(raw_data.find('span').text)\n\n stats_result = pd.read_html(stats, flavor='bs4')\n high = stats_result[0].iat[3, 1]\n low = stats_result[0].iat[4, 1]\n profit_margin = stats_result[5].iat[0, 1]\n price_book_ratio = stats_result[0].iat[6, 1]\n return_on_equity = stats_result[6].iat[1, 1]\n\n analysis_result = pd.read_html(analysis, flavor='bs4')\n analysis_next_year = analysis_result[-1].iat[3, 1]\n analysis_next_5_years = analysis_result[-1].iat[4, 1]\n analysis_past_5_years = analysis_result[-1].iat[5, 1]\n\n n = n + 1\n\n self.worksheet.write(n, 0, f'{stock}')\n self.worksheet.write(n, 1, f'{market_capital}')\n self.worksheet.write(n, 2, f'{pe_ratio}')\n self.worksheet.write(n, 3, f'{forward_dividend_yield}')\n\n self.worksheet.write(n, 4, f'{price}')\n\n self.worksheet.write(n, 5, f'{high}')\n self.worksheet.write(n, 6, f'{low}')\n self.worksheet.write(n, 7, f'{profit_margin}')\n self.worksheet.write(n, 8, f'{price_book_ratio}')\n self.worksheet.write(n, 9, f'{return_on_equity}')\n\n self.worksheet.write(n, 10, f'{analysis_next_year}')\n self.worksheet.write(n, 11, f'{analysis_next_5_years}')\n self.worksheet.write(n, 12, f'{analysis_past_5_years}')\n\n except KeyboardInterrupt:\n logger.error('Manual Override: Terminating session and saving the workbook')\n print('\\nManual Override: Terminating session and saving the workbook')\n self.workbook.close()\n logger.info(f'Stocks Analyzed: {n}')\n logger.info(f'Total Stocks looked up: {i}')\n print(f'Stocks Analyzed: {n}')\n print(f'Total Stocks looked up: {i}')\n null = i - n\n if null:\n logger.info(f'Number of stocks failed to analyze: {null}')\n print(f'Number of stocks failed to analyze: {null}')\n exec_time = self.time_converter(round(time.time() - start_time))\n logger.info(f'Total execution time: {exec_time}')\n print(f'Total execution time: {exec_time}')\n exit(0)\n except:\n logger.debug(f'Unable to analyze {stock}')\n\n # display = (f'\\rCurrent status: {i}/{total}\\tProgress: [%s%s] %d %%' % (\n # ('-' * int((i * 100 / total) / 100 * 30 - 1) + '>'),\n # (' ' * (30 - len('-' * int((i * 100 / total) / 100 * 30 - 1) + '>'))), (float(i) * 100 / total)))\n # sys.stdout.write(display)\n # sys.stdout.flush()\n\n self.workbook.close()\n return round(time.time() - start_time), n, i\n\n def time_converter(self, seconds):\n seconds = seconds % (24 * 3600)\n hour = seconds // 3600\n seconds %= 3600\n minutes = seconds // 60\n seconds %= 60\n if hour:\n return f'{hour} hours {minutes} minutes {seconds} seconds'\n elif minutes:\n return f'{minutes} minutes {seconds} seconds'\n elif seconds:\n return f'{seconds} seconds'\n\n\nif __name__ == '__main__':\n stocks = nasdaq()\n timed_response, analyzed, overall = Analyzer().write()\n time_taken = Analyzer().time_converter(timed_response)\n logger.info(f'Stocks Analyzed: {analyzed}')\n logger.info(f'Total Stocks looked up: {overall}')\n print(f'\\nStocks Analyzed: {analyzed}')\n print(f'Total Stocks looked up: {overall}')\n left_overs = overall - analyzed\n if left_overs:\n logger.info(f'Number of stocks failed to analyze: {left_overs}')\n print(f'Number of stocks failed to analyze: {left_overs}')\n logger.info(f'Total execution time: {time_taken}')\n print(f'Total execution time: {time_taken}')\n","sub_path":"analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":6583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"479691214","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# test_module_dictgenerator.py\n#\n# Copyright 2016 Jelle Smet \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 3 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., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n#\n#\n\n\nfrom wishbone.module.dictgenerator import DictGenerator\nfrom wishbone.actor import ActorConfig\nfrom wishbone.utils.test import getter\n\n\ndef test_module_dictgenerator_keys():\n\n actor_config = ActorConfig('template', 100, 1, {}, \"\")\n dictgenerator = DictGenerator(actor_config, keys=[\"one\", \"two\"])\n\n dictgenerator.pool.queue.outbox.disableFallThrough()\n dictgenerator.start()\n\n event = getter(dictgenerator.pool.queue.outbox)\n\n assert \"one\" in event.get().keys()\n assert \"two\" in event.get().keys()\n\n\ndef test_module_dictgenerator_randomize_keys():\n\n actor_config = ActorConfig('template', 100, 1, {}, \"\")\n dictgenerator = DictGenerator(actor_config, randomize_keys=False)\n\n dictgenerator.pool.queue.outbox.disableFallThrough()\n dictgenerator.start()\n\n event = getter(dictgenerator.pool.queue.outbox)\n\n assert '0' in event.get().keys()\n\n\ndef test_module_dictgenerator_num_values():\n\n actor_config = ActorConfig('template', 100, 1, {}, \"\")\n dictgenerator = DictGenerator(actor_config, num_values=True, num_values_min=1, num_values_max=2)\n\n dictgenerator.pool.queue.outbox.disableFallThrough()\n dictgenerator.start()\n\n event = getter(dictgenerator.pool.queue.outbox)\n\n for key, value in event.get().items():\n assert isinstance(value, int)\n\n assert isinstance(list(event.get().items())[0][1], int)\n assert list(event.get().items())[0][1] >= 1 and list(event.get().items())[0][1] <= 2\n\n\ndef test_module_dictgenerator_num_elements():\n\n actor_config = ActorConfig('template', 100, 1, {}, \"\")\n dictgenerator = DictGenerator(actor_config, min_elements=1, max_elements=2)\n\n dictgenerator.pool.queue.outbox.disableFallThrough()\n dictgenerator.start()\n\n event = getter(dictgenerator.pool.queue.outbox)\n\n assert len(event.get().keys()) >= 1 and len(event.get().keys()) <= 2\n","sub_path":"tests/test_module_dictgenerator.py","file_name":"test_module_dictgenerator.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"364335529","text":"print(\"Decimal to Base Converter (Up to Base 36!)\")\r\nprint(\"By Matthew Le Huenen\")\r\nprint(\"----------------------------\")\r\n\r\nwhile True: \r\n\r\n print(\"\")\r\n numberInput = input(\"Enter a number: \")\r\n baseInput = input(\"Enter a base: \")\r\n baseList = [ \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\" ]\r\n\r\n if numberInput.isdigit() and baseInput.isdigit():\r\n\r\n number = int(numberInput)\r\n base = int(baseInput)\r\n convertedNumber = \"\"\r\n\r\n if (base == 0) or (base == 1) or (base > 36):\r\n print(\"\")\r\n print(\"Invalid Base\")\r\n print(\"\")\r\n\r\n else:\r\n\r\n while True:\r\n remainder = number % base\r\n\r\n if (number < base):\r\n\r\n if (remainder < 10):\r\n convertedNumber = convertedNumber + str(number)\r\n\r\n else:\r\n remainderChar = baseList[remainder - 10]\r\n convertedNumber = convertedNumber + str(remainderChar)\r\n\r\n break\r\n\r\n elif (remainder > 9):\r\n remainderChar = baseList[remainder - 10]\r\n convertedNumber = convertedNumber + str(remainderChar)\r\n\r\n else:\r\n convertedNumber = convertedNumber + str(remainder)\r\n\r\n number = number // base\r\n\r\n print(\"\")\r\n print(convertedNumber[::-1])\r\n print(\"\")\r\n\r\n else:\r\n print(\"\")\r\n print(\"Invalid Input\")\r\n print(\"\")\r\n\r\n try_again = (input(\"Press 0 to exit, or anything else to run the program again. \"))\r\n if try_again.isdigit():\r\n if int(try_again) == 0:\r\n break\r\n","sub_path":"DecimaltoBasev3.py","file_name":"DecimaltoBasev3.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"84635903","text":"#flight search engine\n#flight - starting city + time\n#city - strings and time\n\n#1. Good choice of state - Current City and Current Time\n\nfrom search import Problem, breadth_first_search\n\nclass FlightState:\n def __init__(self, city, time):\n self.current_city = city\n self.current_time = time\n\nclass Flight:\n def __init__(self, start_city, start_time, end_city, end_time):\n self.start_city = start_city\n self.start_time = start_time\n self.end_city = end_city\n self.end_time = end_time\n\n def __str__(self):\n return str((self.start_city, self.start_time))+ \"->\"+ str((self.end_city, self.end_time))\n\n def matches(self, city, time):\n #returns boolean whether city and time match those of the flights, flight leaves city past the time argument\n return (self.start_city == city and self.start_time >= time)\n\nflightDB = [Flight(\"Rome\", 1, \"Paris\", 4),\n Flight(\"Rome\", 3, \"Madrid\", 5),\n Flight(\"Rome\", 5, \"Istanbul\", 10),\n Flight(\"Paris\", 2, \"London\", 4),\n Flight(\"Paris\", 5, \"Oslo\", 7),\n Flight(\"Paris\", 5, \"Istanbul\", 9),\n Flight(\"Madrid\", 7, \"Rabat\", 10),\n Flight(\"Madrid\", 8, \"London\", 10),\n Flight(\"Istanbul\", 10, \"Constantinople\", 10)]\n\nclass FlightProblem(Problem): #inheriting from Problem SuperClass\n def __init__(self, start, end):\n super().__init__(start, end) #start contains city and time, end contains city and time\n #calls the super class initialisation, sets initial state and goal state\n \n #implementing abstract methods\n def actions(self, state): #current flight state\n possible_actions = []\n for flight in flightDB:\n if flight.matches(state.city, state.time):\n possible_actions.append(flight)\n return possible_actions #returns a list of possible actions\n \n def result(self, state, action):\n return (FlightState(action.end_city, action.end_time)) #returns a new FlightState from carrying out the action\n\n def goal_test(self, state):\n return state.current_city == self.goal.city and state.current_time <= self.goal.time\n\n\ndef find_itinerary(start_city, start_time, end_city, deadline):\n start_flight_state = FlightState(start_city, start_time)\n end_flight_state = FlightState(end_city, deadline)\n flightProblem = FlightProblem(start_flight_state, end_flight_state)\n solution = breadth_first_search(flightProblem)\n return solution\n\ndef main():\n deadline = 1\n solution = None\n while solution is None:\n solution = find_itinerary('Rome', 1, 'Istanbul', deadline)\n deadline += 1\n\n print(solution.solution())\n\nif __name__ == \"main\":\n main()","sub_path":"Homework 1/.history/codinghwq2_20210602143042.py","file_name":"codinghwq2_20210602143042.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"307857430","text":"import os\n\n# Change this constant to increase/decrease maximum printout length\nMENU_LEN = 63\n\n\nclass TextMenuFormatting:\n @staticmethod\n def main_title(title):\n outer_line = \"|\" + \"*\" * (MENU_LEN - 2) + \"|\"\n middle_line = \"|\" + \\\n (\"{:^\" + str(MENU_LEN - 2) + \"}\").format(title) + \"|\"\n return outer_line + \"\\n\" + middle_line + \"\\n\" + outer_line\n\n @staticmethod\n def sub_title(title):\n outer_line = \"|\" + \"=\" * (MENU_LEN - 2) + \"|\"\n middle_line = \"|\" + \\\n (\"{:^\" + str(MENU_LEN - 2) + \"}\").format(title) + \"|\"\n return outer_line + \"\\n\" + middle_line + \"\\n\" + outer_line\n\n @staticmethod\n def options_menu(options):\n outer_line = \"|\" + \"-\" * (MENU_LEN - 2) + \"|\"\n options_text = \"|\" + \\\n (\"{:<\" + str(MENU_LEN - 2) + \"}\").format(\" Options:\") + \"|\\n\"\n\n for option in options:\n options_text += \"|\" + (\"{:<\" + str(MENU_LEN - 2) + \"}\").format((\" \" * 6)\n + str(options.index(option) + 1) + \". \" + option) + \"|\\n\"\n return options_text + outer_line\n\n @staticmethod\n def body_content(content):\n outer_line = \"|\" + \"-\" * (MENU_LEN - 2) + \"|\"\n string_list = content.split('\\n')\n content_text = \"\"\n\n for string in string_list:\n content_text += \"|\" + \\\n (\"{:<\" + str(MENU_LEN - 2) + \"}\").format(string) + \"|\\n\"\n return content_text + outer_line\n\n @staticmethod\n def error_title(title):\n outer_line = \"|\" + \"#\" * (MENU_LEN - 2) + \"|\"\n middle_line = \"|\" + \\\n (\"{:^\" + str(MENU_LEN - 2) + \"}\").format(title) + \"|\"\n return outer_line + \"\\n\" + middle_line + \"\\n\" + outer_line\n\n @staticmethod\n def clear():\n os.system(\"cls\")\n print(\"\")\n","sub_path":"src/text_menu_formatting.py","file_name":"text_menu_formatting.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"220937691","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@filename :cloud_filter.py\n@brief :点云滤波相关的api\n@time :2021/01/10 22:49:37\n@author :hscoder\n@versions :1.0\n@email :hscoder@163.com\n@usage :\nCopyright (c) 2020. All rights reserved.Created by hanshuo\n'''\n\nimport numpy as np\n\ndef custom_filter(pcd , x_range = [-0.4 , 0.4] , y_range = [0 , 1.5] , z_range = [0.003 , 0.5]): \n xyz = np.asarray(pcd.points)\n x_points = xyz[:, 0]\n y_points = xyz[:, 1]\n z_points = xyz[:, 2]\n \n x_filter = np.logical_and((x_points > x_range[0]) , (x_points < x_range[1]))\n y_filter = np.logical_and((y_points > y_range[0]) , (y_points < y_range[1]))\n z_filter = np.logical_and((z_points > z_range[0]) , (z_points < z_range[1]))\n \n filter = np.logical_and(np.logical_and(x_filter , y_filter) , z_filter)\n indices = np.argwhere(filter).flatten()\n \n return indices","sub_path":"open3d/python/perceptionMagic/utils/cloud_filter.py","file_name":"cloud_filter.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"618256551","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nimport collections\n\n\n# Complete the countingValleys function below.\ndef counting_valleys(n, s):\n # numbers = []\n # hiking_route = 0\n # calc_route = []\n # valley = 0\n # for letter in s:\n # if letter == 'U':\n # numbers.append(1)\n # else:\n # numbers.append(-1)\n #\n # for number in numbers:\n # hiking_route += number\n # calc_route.append(hiking_route)\n #\n # print(f'hiking_route:{numbers}')\n\n # while True:\n # if -1 in calc_route and 0 in calc_route and calc_route:\n # below_zero = calc_route.index(-1)\n # sea_level = calc_route.index(0)\n # if sea_level < below_zero:\n # calc_route.remove(sea_level)\n # else:\n # del calc_route[below_zero:sea_level+1]\n # valley += 1\n # print(calc_route)\n # else:\n # break\n # return valley\n cur_pos = 0\n mode = ''\n valley_counter = 0\n\n for item in s:\n if item == 'U':\n cur_pos += 1\n else:\n cur_pos -= 1\n #if not mode:\n if cur_pos > 0:\n mode = 'm'\n if cur_pos < 0:\n mode = 'v'\n\n if cur_pos == 0 and mode == 'v':\n valley_counter += 1\n continue\n\n return valley_counter\n\nif __name__ == '__main__':\n # n = int(input())\n\n # s = input()\n\n n = 100\n #s = 'DDUUDDUDUUUD'\n #s = 'DDUDDUUDUU'\n s = 'UDDDUDUU'\n #s = 'DDUDUDDUDDUDDUUUUDUDDDUUDDUUDDDUUDDUUUUUUDUDDDDUDDUUDUUDUDUUUDUUUUUDDUDDDDUDDUDDDDUUUUDUUDUUDUUDUDDD'\n result = counting_valleys(n, s)\n\n print(result)\n","sub_path":"src/Week8/counting_valleys.py","file_name":"counting_valleys.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"81258395","text":"# -*- coding: utf-8 -*-\n\nimport os\n# 获得 ip 地址\nip_cmd = 'wsl ip a |wsl grep -w \"inet\" |wsl cut -d \" \" -f 6 |wsl cut -d \"/\" -f 1'\nshells = os.popen(ip_cmd).readlines()\nwsl_ip = shells[1].split(\"\\n\")[0]\nprint(wsl_ip)\n\n# 写入 Windows hosts 文件\nfile_path = \"C:/Windows/System32/drivers/etc/hosts\"\nwith open(file_path, \"r\") as f:\n lines = f.readlines()\n\nfound = False\n# 查找 hostname 为 ubuntu 的行\nfor i, line in enumerate(lines):\n if len(line) > 10 and line.find(\"ubuntu\") > -1:\n found = True\n # 替换为当前的 ip\n lines[i] = wsl_ip + \" ubuntu\"\n print(lines[i])\n break\n\n# 没有hostname 为 ubuntu 的行\nif not found:\n lines.append(\"\\n\" + wsl_ip + \" ubuntu\")\n\n# 写入文件\nif lines:\n with open(file_path, \"w\") as f:\n f.write(\"\".join(lines))\n\n\nssh_res = 'wsl -u root service ssh --full-restart'\ndel_listen = 'netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=22'\nadd_listen = 'netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 \\\n listenport=22 connectaddress=ubuntu connectport=22'\nshow_listen = 'netsh interface portproxy show all'\n\nshells = os.popen(ssh_res).readlines()\nprint(shells)\n\nshells = os.popen(del_listen).readlines()\nprint(shells)\n\nshells = os.popen(add_listen).readlines()\nprint(shells)\n\nshells = os.popen(show_listen).readlines()\nprint(shells)\n","sub_path":"wsl2port.py","file_name":"wsl2port.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"565227953","text":"from itertools import dropwhile\nfrom json import dump, load\nfrom os import remove\nfrom pathlib import Path\nfrom ..staticutils import StaticUtils\n\nclass JsonMeta(type):\n def __getitem__(cls, key):\n return cls.INSTANCE.json[key]\n \n def __setitem__(cls, key, value):\n cls.INSTANCE.json[key] = value\n\n\nclass Result:\n def __init__(self, created):\n self.__created = created\n \n @property\n def created(self):\n return self.__created\n\n\nclass Json(metaclass = JsonMeta):\n def __init__(self, paths, raiseIfFailsToLoad):\n if hasattr(self.__class__, \"INSTANCE\"):\n raise ValueError()\n \n self.__class__.INSTANCE = self\n \n self.__json = dict()\n self.__paths = paths if StaticUtils.isIterable(paths) else (paths, )\n self.__raiseIfFailsToLoad = raiseIfFailsToLoad\n self.__result = None\n self.__upgraders = dict()\n \n @property\n def json(self):\n return self.__json\n \n @property\n def result(self):\n return self.__result\n \n def dump(self):\n try:\n self.__dump(self.__paths[0])\n \n except BaseException as e:\n StaticUtils.showerror(e)\n \n def load(self):\n for created, path in enumerate(self.__paths):\n try:\n with open(path, encoding = \"utf-8\") as f:\n self.__json = load(f)\n \n except FileNotFoundError:\n pass\n \n else:\n self.__result = Result(bool(created))\n \n break\n \n if self.__result is None and self.__raiseIfFailsToLoad:\n raise ValueError(f\"{self.__class__.__name__} not loaded\")\n \n # = Find upgraders = #\n prefix = \"_upgrader_\"\n \n for version in StaticUtils.sortStringsAsIntegers(map(lambda upgraderName: upgraderName[len(prefix):], filter(lambda entry: entry.startswith(prefix), dir(self.__class__))), \"_\"):\n self.__upgraders[version.replace(\"_\", \".\")] = getattr(self, f\"{prefix}{version}\")\n \n def upgrade(self, currentVersion):\n for version, upgrader in dropwhile(lambda e: e[0] != currentVersion, self.__upgraders.items()):\n p = Path(self.__paths[0])\n backup = f\"{p.stem}_{version}{p.suffix}\"\n \n self.__dump(backup)\n \n upgrader()\n \n remove(backup)\n \n def __dump(self, path):\n with open(path, \"w\", encoding = \"utf-8\") as f:\n dump(self.__json, f, ensure_ascii = False, indent = 3)\n f.write(\"\\n\")\n","sub_path":"commonuicomponents/json/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"544004644","text":"import cv2\nimport numpy as np\nimport math\nfrom matplotlib import pyplot as plt\nfrom skimage.feature import greycomatrix, greycoprops\nimport melanopy as mpy\n\n\n\n#CHOOSE IMAGE\n\n#img = cv2.imread('RGB color wheel.png')\n#img = cv2.imread('redcrcle.png')\n#img = cv2.imread('testcrcle.jpg')\n#img = cv2.imread('images.jpg')\n#img = cv2.imread('Malignant1.jpg')\nimg = cv2.imread('benign3.jpg')\n\n#img = cv2.imread('img_buat_flow_chart_1.jpg')\n\nimy,imx,imz = np.shape(img)\nshortening = 5\nimg = img[shortening:imy-shortening,shortening:imx-shortening,:]\nimy,imx,imz = np.shape(img)\ngs = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n\n_,th1 = cv2.threshold(gs,25,255,cv2.THRESH_BINARY)\n\nckernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(8,8))\nclosing = cv2.morphologyEx(th1, cv2.MORPH_CLOSE, ckernel,iterations = 4)\n\nkernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\nerosion = cv2.erode(closing,kernel,iterations = 50)\n\nderm_scope = erosion\n\n\n\n#REMOVING HAIR FILTERING------------- START\n\n#gs_filter = cv2.medianBlur(gs,21) #median blur\n#gs_filter = cv2.GaussianBlur(gs,(31,31),0) #Gaussian Blur\n#gs_filter = cv2.blur(gs,(31,31)) #Averaging\n#REMOVING HAIR FILTERING------------- END\n\n\n\n_,th = cv2.threshold(gs,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n\n#REMOVING HAIR MORPH TRANSFORM------------- START\n#Morphologic Transform ------------- START\nkernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\nerosion = cv2.erode(th,kernel,iterations = int(min([imx,imy])/100))\ndilation = cv2.dilate(erosion,kernel,iterations = int(min([imx,imy])/100))\n#Morphologic Transform ------------- End\n#REMOVING HAIR MORPH TRANSFORM------------- END\n\nsegment_mask = dilation\n\n\n\n\nnmask = cv2.bitwise_and(derm_scope, segment_mask)\n\ncontours,hierarchy = cv2.findContours(nmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\ncontimg = img.copy()\n\nheight, width, channels = img.shape\nall_cnt_bimg = np.zeros((height,width,1), np.uint8)\ncv2.drawContours(all_cnt_bimg, contours, -1, 255, 1)\n\n\n\nif len(contours) != 0:\n #find the biggest area\n c = max(contours, key = cv2.contourArea)\n\n # draw in blue the contours that were founded\n cv2.drawContours(contimg, c, -1, 255, 3)\n \n\n #Finding center of mass\n M = cv2.moments(c)\n cx = int(M[\"m10\"] / M[\"m00\"])\n cy = int(M[\"m01\"] / M[\"m00\"])\n \n t_cx = cx-(imx/2)\n t_cy = cy-(imy/2)\n \n\n #CREATING BORDER \n square_r = np.maximum(imx,imy)\n bimg = np.zeros((height,width,1), np.uint8)\n cv2.drawContours(bimg, c, -1, 255, 1)\n flood_img = bimg.copy()\n maskfill = np.zeros((height+2, width+2), np.uint8) \n cv2.floodFill(flood_img, maskfill, (cx,cy), 255)\n segment = cv2.bitwise_and(img, img, mask=flood_img)\n \n \n\n\n\n\n\n\n \n \n#-------------------------------------------------------------- ASSYMETRY START\n\n rhalf = (square_r/2).astype(int)\n\n nc_img = np.zeros((square_r,square_r,1), np.uint8)\n \n (r_x,r_y),(MA,ma),angle = cv2.minAreaRect(c)\n \n t_cx = r_x-(rhalf)\n t_cy = r_y-(rhalf)\n\n xc,yc,zc = np.shape(c) \n nc = np.zeros([xc,yc,zc])\n\n nc[:,0,0] = c[:,0,0]- t_cx\n nc[:,0,1] = c[:,0,1]- t_cy\n nc = nc.astype(int)\n \n cv2.drawContours(nc_img, nc, -1, 255, 1)\n maskfill = np.zeros((square_r+2, square_r+2), np.uint8) \n cv2.floodFill(nc_img, maskfill, (rhalf,rhalf), 255) \n rotate_M = cv2.getRotationMatrix2D((rhalf,rhalf),angle,1) #rotate Matrix\n rotated = cv2.warpAffine(nc_img,rotate_M,(square_r,square_r)) #rotated image (1 channel)\n \n box = cv2.boxPoints(((rhalf,rhalf),(MA,ma),0))\n box = np.int0(box)\n \n square_x1 = box[1][1]\n square_x2 = box[0][1]\n square_y1 = box[0][0]\n square_y2 = box[2][0]\n \n ROI = rotated[square_x1:square_x2, square_y1:square_y2]\n\n [roiy,roix] = np.shape(ROI)\n\n roix_half = roix/2\n roiy_half = roiy/2\n \n roi_top = ROI[0:(math.floor(roiy_half)),0:roix] \n roi_bot = ROI[math.ceil(roiy_half):roiy,0:roix] \n roi_left = ROI[0:roiy,0:math.floor(roix_half)] \n roi_right = ROI[0:roiy,math.ceil(roix_half):roix] \n roi_right_flip = cv2.flip(roi_right, 1)\n roi_bot_flip = cv2.flip(roi_bot,0)\n \n overlap_y_1 = roi_top - roi_bot_flip\n overlap_y_2= roi_bot_flip - roi_top\n overlap_y = cv2.bitwise_and(overlap_y_1, overlap_y_2)\n _,overlap_y = cv2.threshold(overlap_y,0,255,cv2.THRESH_BINARY)\n\n overlap_x = roi_left - roi_right_flip \n\n overlap_x_1 = roi_left - roi_right_flip\n overlap_x_2= roi_right_flip - roi_left\n overlap_x = cv2.bitwise_and(overlap_x_1, overlap_x_2)\n _,overlap_x = cv2.threshold(overlap_x,0,255,cv2.THRESH_BINARY)\n \n sum_overlap_x = sum(sum(np.int64(overlap_x)))/255\n sum_overlap_y = sum(sum(np.int64(overlap_y)))/255\n sum_roi = sum(sum(np.int64(ROI)))/255\n \n AI = sum([sum_overlap_x, sum_overlap_y])/(2*sum_roi)\n print('Assymetry Index : ' + str(AI))\n print('overlap_x : ' + str(sum_overlap_x))\n print('overlap y : ' + str(sum_overlap_y))\n print('ROI : ' + str(sum_roi))\n \n#-------------------------------------------------------------- ASSYMETRY END\n\n\n\n\n\n\n#-------------------------------------------------------------- BORDER FD START\n\n cv2.drawContours(nc_img, nc, -1, 255, 1)\n fract_dim = np.zeros((square_r,square_r,3), np.uint8)\n fract_dim_cont = fract_dim.copy()\n cv2.drawContours(fract_dim_cont, nc, -1, 255, 1)\n fract_dim =fract_dim_cont.copy()\n \n \n\n divider = 5\n FD_points = 20\n FD_counter = np.zeros(FD_points)\n FD_r = np.zeros([FD_points])\n \n \n \n for n in range (1,FD_points+1): \n FD_r[n-1] = int(square_r/(divider+(n*1.5)))\n for k in range (int(divider+(n*1.5))):\n for l in range (0,int(divider+(n*1.5))):\n mat_xa = int(((l-1)*FD_r[n-1]))\n mat_xb = int((l*FD_r[n-1]))\n mat_ya = int(((k-1)*FD_r[n-1]))\n mat_yb = int((k*FD_r[n-1]))\n mat = fract_dim_cont[mat_ya:mat_yb , mat_xa:mat_xb,0] \n value = np.sum(mat)\n value = int(value/255)\n if value > 0 :\n fract_dim[mat_ya:mat_yb , mat_xa:mat_xb,1] =(50*n)\n cv2.rectangle(fract_dim,(mat_xa,mat_ya),(mat_xb,mat_yb),[50*n,0,0],3)\n FD_counter [n-1] = FD_counter[n-1] + 1\n \n FD_log_n = np.log10(1/FD_counter)\n FD_log_r = np.log10(FD_r) \n\n fit = np.polyfit(FD_log_n,FD_log_r,1)\n fit_fn = np.poly1d(fit)\n plt.plot(FD_log_n,FD_log_r, 'yo', FD_log_n, fit_fn(FD_log_n), '--k')\n plt.title('FRACTAL DIMENSION')\n plt.ylabel('log box radius')\n plt.xlabel('log 1/amount of box')\n plt.legend(['train', 'test'], loc='upper left')\n plt.savefig('fractal dimension.png')\n plt.show()\n\n\n fd = fit_fn[1]\n print('fractal dimension : ' + str(fd))\n \n#-------------------------------------------------------------- BORDER FD END\n \n\n\n#-------------------------------------------------------------- TEXTURE START\n glcm_img = img.copy()\n glcm_rotate_M = cv2.getRotationMatrix2D((r_x,r_y),angle,1)\n glcm_rotated = cv2.warpAffine(glcm_img,glcm_rotate_M,glcm_img.shape[1::-1]) \n \n glcm_mask_img = flood_img.copy()\n glcm_mask_rotated = cv2.warpAffine(glcm_mask_img,glcm_rotate_M,glcm_mask_img.shape[1::-1]) \n \n \n\n GLCM_segment = cv2.bitwise_and(glcm_rotated, glcm_rotated, mask=glcm_mask_rotated)\n glcm_gs = cv2.cvtColor(GLCM_segment,cv2.COLOR_BGR2GRAY)\n\n glcm_contours,_ = cv2.findContours(glcm_mask_rotated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n glcm_c =max(glcm_contours, key = cv2.contourArea)\n\n x,y,w,h = cv2.boundingRect(glcm_c)\n # draw the book contour (in green)\n col_roi1 = glcm_gs[ y:y+h, x:x+w]\n col_roi = cv2.resize(col_roi1, (600,400), interpolation = cv2.INTER_AREA)\n glcm = greycomatrix(col_roi, [1], [0, np.pi/2, np.pi*3/4, np.pi/4],levels = 256)\n glcm_mat = glcm[:,:,0,0]\n glcm_mat = glcm_mat.astype('uint8')\n glcm_mat_norm = glcm_mat/np.sum(glcm_mat)\n \n\n \n R_col_roi1 = GLCM_segment[ y:y+h, x:x+w ,0]\n G_col_roi1 = GLCM_segment[ y:y+h, x:x+w ,1]\n B_col_roi1 = GLCM_segment[ y:y+h, x:x+w ,2]\n\n R_col_roi = cv2.resize(R_col_roi1, (600,400), interpolation = cv2.INTER_AREA)\n G_col_roi = cv2.resize(G_col_roi1, (600,400), interpolation = cv2.INTER_AREA)\n B_col_roi = cv2.resize(B_col_roi1, (600,400), interpolation = cv2.INTER_AREA)\n\n R_glcm = greycomatrix(R_col_roi, [1], [0, np.pi/2, np.pi*3/4, np.pi/4],levels = 256)\n G_glcm = greycomatrix(G_col_roi, [1], [0, np.pi/2, np.pi*3/4, np.pi/4],levels = 256)\n B_glcm = greycomatrix(B_col_roi, [1], [0, np.pi/2, np.pi*3/4, np.pi/4],levels = 256)\n\n\n #GLCM PROPERTIES EXTRACTION\n contrast = greycoprops(glcm, 'contrast')\n dissimilarity = greycoprops(glcm, 'dissimilarity')\n homogeneity = greycoprops(glcm, 'homogeneity')\n ASM = greycoprops(glcm, 'ASM')\n energy = greycoprops(glcm, 'energy')\n correlation = greycoprops(glcm, 'correlation')\n\n R_contrast = greycoprops(R_glcm, 'contrast')\n R_dissimilarity = greycoprops(R_glcm, 'dissimilarity')\n R_homogeneity = greycoprops(R_glcm, 'homogeneity')\n R_ASM = greycoprops(R_glcm, 'ASM')\n R_energy = greycoprops(R_glcm, 'energy')\n R_correlation = greycoprops(R_glcm, 'correlation')\n\n G_contrast = greycoprops(G_glcm, 'contrast')\n G_dissimilarity = greycoprops(G_glcm, 'dissimilarity')\n G_homogeneity = greycoprops(G_glcm, 'homogeneity')\n G_ASM = greycoprops(G_glcm, 'ASM')\n G_energy = greycoprops(G_glcm, 'energy')\n G_correlation = greycoprops(G_glcm, 'correlation')\n \n B_contrast = greycoprops(B_glcm, 'contrast')\n B_dissimilarity = greycoprops(B_glcm, 'dissimilarity')\n B_homogeneity = greycoprops(B_glcm, 'homogeneity')\n B_ASM = greycoprops(B_glcm, 'ASM')\n B_energy = greycoprops(B_glcm, 'energy')\n B_correlation = greycoprops(B_glcm, 'correlation')\n\n\n print('GLCM Contrast : ' + str(contrast))\n print('GLCM Dissimiliartiy : ' + str(dissimilarity))\n print('GLCM homogeneity : ' + str(homogeneity))\n print('GLCM ASM : ' + str(ASM))\n print('GLCM energy : ' + str(energy))\n print('GLCM correlation : ' + str(correlation))\n\n#-------------------------------------------------------------- TEXTURE END\n\n\n\n\n\n#-------------------------------------------------------------- COLOR START\n\n # INVERSE SEGMENTATION OF SKIN\n inv_flood_img = cv2.bitwise_not(flood_img)\n inv_segment = cv2.bitwise_and(img, img, mask=inv_flood_img)\n\n # SPLITTING RGB CHANNEL\n s_R = inv_segment[:,:,2]\n s_G = inv_segment[:,:,1]\n s_B = inv_segment[:,:,0]\n\n # FIND SKIN AVERAGE VALUE\n ave_s_R = np.sum(s_R)/(np.sum(inv_flood_img)/255)\n ave_s_G = np.sum(s_G)/(np.sum(inv_flood_img)/255)\n ave_s_B = np.sum(s_B)/(np.sum(inv_flood_img)/255)\n\n print('red skin average val :' + str(ave_s_R))\n print('Green skin average val :' + str(ave_s_G))\n print('Blue skin average val :' + str(ave_s_B))\n \n # CONVERT RGB DATA TYPE\n R_mat = segment[:,:,2].astype('int32')\n G_mat = segment[:,:,1].astype('int32')\n B_mat = segment[:,:,0].astype('int32')\n\n R_new_val = R_mat - ave_s_R\n G_new_val = G_mat - ave_s_G\n B_new_val = B_mat - ave_s_B\n\n col_segment = np.zeros([imy,imx,3])\n col_segment[:,:,2] = R_new_val\n col_segment[:,:,1] = G_new_val\n col_segment[:,:,0] = B_new_val\n \n col_segment_point = col_segment.reshape([(imx*imy),3])\n \n points = col_segment_point\n \n hist,binedges = mpy.hist_3d(col_segment_point,8)\n \n bg_px = np.sum(inv_flood_img)/255\n hist[0,0,0]=hist[0,0,0] - bg_px\n norm_hist = hist/np.sum(hist)\n#-------------------------------------------------------------- COLOR END\n\n\n\n\n\n\n# SHOWING IMAGE ALGORITHMS ---------------------------------------------------------------------- START\n#Resize settings\nresize = True\nrheight = 600\nrwidth = 800\n\n#Show Image List\nshow_imagename = ['img',\n 'th',\n 'th1',\n 'nmask',\n 'flood img',\n 'blank image',\n 'segment mask',\n 'gs',\n 'segment',\n 'all_cnt_bimg',\n 'erotion',\n 'dilation',\n 'inv_segment',\n 'col_roi',\n 'ROI',\n 'glcm_rotated',\n 'GLCM_segment'\n ]\nshow_image = [img,\n th,\n th1,\n nmask,\n flood_img,\n bimg,\n segment_mask,\n gs,\n segment,\n all_cnt_bimg,\n erosion,\n dilation,\n inv_segment,\n col_roi,\n ROI,\n glcm_rotated,\n GLCM_segment\n ]\n\n\n\n\n\n#show_imagename = ['img','nmask', 'Contour Image', 'Blank Image', 'floodfill','segment','ROI','rotated','fractal dimension','colored ROI','inverse flood image']\n#show_image = [img,nmask, contimg, bimg, flood_img,segment,ROI,rotated,fract_dim,col_roi,inv_flood_img]\nn_showimg = len(show_image)\n\n\n#Image Showing Sequencing\nfor k in range (0,n_showimg):\n if resize == True:\n cv2.namedWindow(show_imagename[k],cv2.WINDOW_NORMAL)\n cv2.resizeWindow(show_imagename[k],rwidth,rheight) \n cv2.imshow(show_imagename[k],show_image[k])\n\n# SHOWING IMAGE ALGORITHMS ---------------------------------------------------------------------- END\n\n\n\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":13518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"519730299","text":"import json\nimport os\nimport time\nfrom json import JSONDecodeError\n\nfrom flask import make_response\nfrom flask_socketio import SocketIO\n\nfrom ctpbee import CtpbeeApi\nfrom ctpbee.constant import LogData, AccountData, ContractData, BarData, OrderData, PositionData, TickData, SharedData, \\\n TradeData\n\n\n\nclass DefaultSettings(CtpbeeApi):\n\n def __init__(self, name, app, socket_io: SocketIO):\n super().__init__(name, app)\n self.io = socket_io\n ## 记录所有的bar\n self.global_bar = {}\n\n ## 记录每个合约是否载入状态\n self.local_status = {}\n\n def on_log(self, log: LogData):\n data = {\n \"type\": \"log\",\n \"data\": log\n }\n self.io.emit('log', data)\n\n def on_account(self, account: AccountData) -> None:\n data = {\n \"type\": \"account\",\n \"data\": account._to_dict()\n }\n self.io.emit('account', data)\n\n def on_contract(self, contract: ContractData):\n pass\n\n def on_bar(self, bar: BarData) -> None:\n timeArray = time.strptime(str(bar.datetime), \"%Y-%m-%d %H:%M:%S\")\n # 转换成时间戳\n timestamp = round(time.mktime(timeArray) * 1000)\n info = [timestamp, bar.open_price, bar.high_price, bar.low_price,\n bar.close_price, bar.volume]\n self.global_bar[bar.local_symbol].append(info)\n\n def on_order(self, order: OrderData) -> None:\n # 更新活跃报单\n active_orders = []\n for order in self.app.recorder.get_all_active_orders(order.local_symbol):\n active_orders.append(order._to_dict())\n data = {\n \"type\": \"active_order\",\n \"data\": active_orders\n }\n\n self.io.emit(\"active_order\", data)\n orders = []\n for order in self.app.recorder.get_all_orders():\n orders.append(order._to_dict())\n data = {\n \"type\": \"order\",\n \"data\": orders\n }\n self.io.emit(\"order\", data)\n\n def on_position(self, position: PositionData) -> None:\n data = {\n \"type\": \"position\",\n \"data\": self.app.recorder.get_all_positions()\n }\n self.io.emit(\"position\", data)\n\n def on_tick(self, tick: TickData) -> None:\n self.local_status.setdefault(tick.local_symbol, False)\n self.global_bar.setdefault(tick.local_symbol, [])\n\n tick.datetime = str(tick.datetime)\n data = {\n \"type\": \"tick\",\n \"data\": tick._to_dict()\n }\n self.io.emit(\"tick\", data)\n data = {\n \"type\": \"position\",\n \"data\": self.app.recorder.get_all_positions()\n }\n self.io.emit(\"position\", data)\n if not self.local_status.get(tick.local_symbol):\n try:\n with open(f\"{os.path.dirname(__file__)}/static/json/{tick.symbol}.json\", \"r\") as f:\n from json import load\n st = True\n try:\n data = load(f)\n except JSONDecodeError:\n st = False\n if data.get(\"data\") is not None and st:\n klines = data.get(\"data\").get(\"lines\")\n assert type(klines) == list\n if len(klines) != 0:\n self.global_bar.get(tick.local_symbol).extend(klines)\n except FileNotFoundError:\n pass\n self.local_status[tick.local_symbol] = True\n\n with open(f\"{os.path.dirname(__file__)}/static/json/{tick.symbol}.json\", \"w\") as f:\n from json import dump\n update_result = {\n \"success\": True,\n \"data\": {\n \"lines\": self.global_bar.get(tick.local_symbol),\n \"depths\": {\n \"asks\": [\n [\n tick.ask_price_1,\n tick.ask_volume_1\n ]\n ],\n \"bids\": [\n [\n tick.bid_price_1,\n tick.bid_volume_1\n ]\n ]\n }\n }\n }\n f.truncate(0)\n dump(update_result, f)\n\n self.io.emit(\"update_all\", update_result)\n\n def on_shared(self, shared: SharedData) -> None:\n shared.datetime = str(shared.datetime)\n data = {\n \"type\": \"shared\",\n \"data\": shared._to_dict()\n }\n self.io.emit('shared', data)\n\n def on_trade(self, trade: TradeData) -> None:\n trades = []\n for trade in self.app.recorder.get_all_trades():\n trades.append(trade._to_dict())\n data = {\n \"type\": \"trade\",\n \"data\": trades\n }\n self.io.emit('trade', data)\n\n\ndef true_response(data=\"\", message=\"操作成功执行\"):\n true_response = {\n \"result\": \"success\",\n \"data.json\": data,\n \"message\": message\n }\n return make_response(json.dumps(true_response))\n\n\ndef false_response(data=\"\", message=\"出现错误, 请检查\"):\n false_response = {\n \"result\": \"failed\",\n \"data.json\": data,\n \"message\": message\n }\n return make_response(json.dumps(false_response))\n\n\ndef warning_response(data=\"\", message=\"警告\"):\n warning_response = {\n \"result\": \"warning\",\n \"data.json\": data,\n \"message\": message\n }\n return make_response(json.dumps(warning_response))\n","sub_path":"examples/web_client/app/default_settings.py","file_name":"default_settings.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"162094627","text":"from unittest.mock import MagicMock\n\nimport pytest\nfrom gb_chat.common.thread_executor import IoThreadExecutor, UiThreadExecutor\nfrom PyQt5.QtWidgets import QApplication\n\n\n@pytest.mark.parametrize(\"tasks\", [[MagicMock()], [MagicMock(), MagicMock()]])\ndef test_io_thread_execute(tasks):\n sut = IoThreadExecutor()\n for task in tasks:\n sut.schedule(task)\n\n sut.execute_all()\n for task in tasks:\n task.assert_called_once()\n\n\n@pytest.mark.parametrize(\"tasks\", [[MagicMock()], [MagicMock(), MagicMock()]])\ndef test_ui_thread_execute(tasks, qapp):\n sut = UiThreadExecutor(qapp)\n for task in tasks:\n sut.schedule(task)\n\n qapp.sendPostedEvents(sut)\n\n for task in tasks:\n task.assert_called_once()\n","sub_path":"tests/test_thread_executor.py","file_name":"test_thread_executor.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"542791147","text":"import pandas as pd\nimport nltk\nfrom numpy import *\nimport re\nimport nltk\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import svm\nimport timeit\nimport itertools\nimport sys\nimport pickle\nimport pymongo\nfrom pymongo import MongoClient\n\npairs = {'(luv)|(<3)': 'love', 'h8': 'hate'}\n\nclass SentimentAnalysis():\n # model needs to be a model from sklearn or obj with function that can predict\n # right now model = random forest, features = bag of words\n def sentiment(self, model, features):\n\n sent = model.predict(features)\n\n total = sent.shape[0]\n\n prop_pos = sum(sent) / total\n prop_neg = 1 - prop_pos\n\n return prop_pos, prop_neg, total\n\n # vectorizer is something we learn at training time\n # includes vocab and other things\n # tweets - a list\n def process_raw_tweet(self, vectorizer, tweets):\n\n test_data_features = vectorizer.transform(tweets)\n test_data_features = test_data_features.toarray()\n return test_data_features\n\n # Reads and Cleans 'n' tweets from corpus so we don't need to read everything\n # each time we train\n def extract_features(self, path, n):\n print(\"Loading Data...\")\n train = pd.read_csv(path + \"training.1600000.processed.noemoticon.csv\", header=None, \\\n delimiter='\",\"', quoting=3, engine='python')\n print(\"Finished Loading!!!\")\n\n # Collect clean review for both positive and negative as well as training and test\n clean_train_reviews_neg = []\n clean_train_reviews_pos = []\n\n clean_test_reviews_neg = []\n clean_test_reviews_pos = []\n\n for i in range(n):\n clean_train_reviews_neg.append(review_to_words(train[5][i]))\n clean_test_reviews_neg.append(review_to_words(train[5][i + n]))\n\n clean_train_reviews_pos.append(review_to_words(train[5][i + 800000]))\n clean_test_reviews_pos.append(review_to_words(train[5][i + 800000 + n]))\n\n if i % 10000 == 0:\n print(i)\n\n\n\n # Write everything to csv\n pos_output = pd.DataFrame(data=clean_train_reviews_pos)\n neg_output = pd.DataFrame(data=clean_train_reviews_neg)\n\n test_pos_output = pd.DataFrame(data=clean_test_reviews_pos)\n test_neg_output = pd.DataFrame(data=clean_test_reviews_neg)\n\n pos_output.to_csv(path + \"data_subset/pos_tweets_train.csv\", index=False)\n neg_output.to_csv(path + \"data_subset/neg_tweets_train.csv\", index=False)\n\n test_pos_output.to_csv(path + \"data_subset/pos_tweets_test.csv\", index=False)\n test_neg_output.to_csv(path + \"data_subset/neg_tweets_test.csv\", index=False)\n\n # Cleans up a tweet - review is from when this was for IMDB\n def review_to_words(self, raw_review):\n\n no_url = re.sub(\"http[s]??://.+?\\\\..+?[ ]?\", \"\", raw_review)\n\n # Remove numerics\n remove_numerics = re.sub(\" [0-9]+? \", \" \", re.sub(\" [^a-zA-z0-9]+? \", \" \", no_url))\n\n # to lowercase\n temp = letters_only.lower()\n\n for regex, repl in pairs:\n temp = re.sub(regex, repl, temp)\n\n word = temp\n\n # remove stop words - the, of , a ....\n stops = set(stopwords.words(\"english\"))\n\n meaningful_words = [w for w in words if not w in stops]\n\n return (\" \".join(meaningful_words))\n\n # predict is a funtion object that will predict sentiment\n def test_model(self, path, n, predict, vectorizer):\n\n print(\"Loading Test Data...\")\n test_pos = pd.read_csv(path + \"pos_tweets_test.csv\", header=0, \\\n delimiter=',', quoting=3, engine='python')\n\n test_neg = pd.read_csv(path + \"neg_tweets_test.csv\", header=0, \\\n delimiter=',', quoting=3, engine='python')\n\n test = pd.concat([test_pos.iloc[0:n], test_neg.iloc[0:n]])\n\n print(\"Test data finished loading !\")\n print(\"Processing Features ... \")\n\n test_data_features = vectorizer.transform(test['0'].values.tolist())\n test_data_features = test_data_features.toarray()\n i = 0\n errors = 0\n for tweet in test_data_features:\n sentiment = predict(tweet)\n if i < n:\n if sentiment != 1:\n errors = errors + 1\n else:\n if sentiment != 0:\n errors = errors + 1\n\n i = i + 1\n\n print(\"Percent Correct: \" + str(float((i - errors)) / i))\n\n def sentiment_analysis(self, path, n, k):\n print(\"Loading Data\")\n\n train_pos = pd.read_csv(path + \"pos_tweets_train.csv\", header=0, \\\n delimiter=',', quoting=3, engine='python')\n\n train_neg = pd.read_csv(path + \"neg_tweets_train.csv\", header=0, \\\n delimiter=',', quoting=3, engine='python')\n\n vectorizer = CountVectorizer(analyzer=\"word\", \\\n tokenizer=None, \\\n preprocessor=None, \\\n stop_words=None, \\\n max_features=k)\n\n print(\"Finished Loading!!!\")\n\n print(\"Processing Bag of Word Features\")\n\n train = pd.concat([train_pos.iloc[0:n], train_neg.iloc[0:n]])\n sentiment = zeros(2 * n)\n sentiment[0:n] = 1\n\n train_data_features = vectorizer.fit_transform(train['0'].values.tolist())\n train_data_features = train_data_features.toarray()\n\n print(\"Beginning Training\")\n start = timeit.default_timer()\n\n forest = RandomForestClassifier(n_estimators=50)\n forest = forest.fit(train_data_features, sentiment)\n\n stop = timeit.default_timer()\n\n print(\"Training Finished!!! Total Time: \" + str(stop - start))\n\n return forest, vectorizer\n\n def train_model(self,path,new_features,n=1000,k=2000):\n if(new_features):\n extract_features(path,n,k)\n\n # show - a string of the name of the show\n # limit - how many tweets to pull\n def readFromMongo(self, show, limit):\n\n # Connect to mongo\n client = MongoClient()\n\n # access movie stream db\n movies = client['movieratings_stream']\n\n # colletion of tweets\n tweets = movies['tweets']\n\n tweet_text = []\n counter = 0\n\n # iterate through cursor that takes the 'limit' most recent tweets with hashtag 'show'\n for tweet in tweets.find({'show_title': show}): # .sort('created_at', pymongo.DESCENDING):\n if counter < limit:\n tweet_text.append(tweet)\n counter += 1\n else:\n break\n\n\n model = pickle.load(open(\"/root/rand_forest.p\", \"rb\"))\n\n vectorizer = pickle.load(open(\"/root/vectorizer.p\", \"rb\"))\n\n cleaned_tweets = self.process_raw_tweet(vectorizer,\n [self.review_to_words(tweet['tweet_text']) for tweet in tweet_text])\n\n return self.sentiment(model, cleaned_tweets)\n\n\nif __name__ == '__main__':\n # DataFrame Structure for the trianingf file\n # 0 - sentiment value\n # 1 - id\n # 2 - date\n # 3 - NO_QUERY ?\n # 4 - person who tweeted\n # 5 - Actual tweet\n\n\n path = '/root/sentiment_data/'\n\n n = 1000\n\n # k = 2000\n\n sa = SentimentAnalysis()\n\n #sa.extract_features(path,n)\n #[model,vectorizer] = sentiment_analysis(path,n,k)\n #test_model(path,n,model.predict,vectorizer)\n show = 'American Horror Story'\n limit = 1000\n\n #sa = SentimentAnalysis()\n print(sa.readFromMongo(show, limit))\n","sub_path":"tv_ratings_frontend/ratings_frontend/backend/twitter_sentiment_analysis.py","file_name":"twitter_sentiment_analysis.py","file_ext":"py","file_size_in_byte":7780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"113149476","text":"import json\nimport base64\nfrom tastypie import fields\nfrom tastypie.authorization import Authorization\nfrom tastypie.resources import ModelResource\nfrom mirrors import models\nfrom django.db.models import get_model\nfrom mirrors.api import fields as api_fields\nfrom mom import net\n\nclass MultipartResource(object):\n def deserialize(self, request, data, format=None):\n if not format:\n format = request.META.get('CONTENT_TYPE', 'application/json')\n\n if format == 'application/x-www-form-urlencoded':\n return request.POST\n\n if format.startswith('multipart'):\n data = request.POST.copy()\n data.update(request.FILES)\n return data\n\n return super(MultipartResource, self).deserialize(request, data, format)\n\n\nclass PolymorphicRelatedField(fields.ToOneField):\n \n def get_related_resource(self, related_instance):\n \"\"\"\n Instaniates the related resource.\n \"\"\"\n to = {\n models.Asset: AssetResource,\n models.Content: ContentResource,\n }\n related_model = get_model(related_instance._meta.app_label, \n related_instance.__class__.__name__)\n related_resource = to[related_model]()\n # Fix the ``api_name`` if it's not present.\n if related_resource._meta.api_name is None:\n if self._resource and not self._resource._meta.api_name is None:\n related_resource._meta.api_name = self._resource._meta.api_name\n\n # Try to be efficient about DB queries.\n related_resource.instance = related_instance\n return related_resource\n\n\nclass MetaDataMixin(object):\n def dehydrate_metadata(self, bundle):\n return bundle.obj.metadata\n\n\nclass AssetResource(MultipartResource, MetaDataMixin, ModelResource):\n data = api_fields.ByteaField(attribute='data')\n data_url = fields.CharField(attribute='data_url', readonly=True)\n\n def deserialize(self, request, data, format=None):\n data = super(AssetResource, self).deserialize(request, data, format)\n if format.startswith('multipart'):\n data['data'] = buffer(data['data'].read())\n else:\n uri = data['data'].encode('ascii', 'ignore')\n data['data'] = buffer(net.data_uri.data_uri_parse(uri)[0])\n return data\n\n class Meta:\n queryset = models.Asset.objects.all()\n resource_name = 'asset'\n authorization= Authorization()\n excludes = ['data']\n \n\nclass SlugResource(ModelResource):\n\n class Meta:\n queryset = models.Slug.objects.all()\n resource_name = 'slug'\n \n\nclass ContentAttributeResource(MetaDataMixin, ModelResource):\n attribute = PolymorphicRelatedField(SlugResource, 'attribute',full=True)\n \n class Meta:\n queryset = models.ContentAttribute.objects.all()\n resource_name = 'contentattribute'\n authorization= Authorization()\n\n\nclass ListMemberResource(ModelResource):\n member = PolymorphicRelatedField(SlugResource, 'member',full=True)\n \n class Meta:\n queryset = models.ListMember.objects.all()\n resource_name = 'listmember'\n authorization= Authorization()\n\n\nclass ContentResource(MetaDataMixin, ModelResource):\n attributes = fields.ToManyField(ContentAttributeResource,\n attribute=lambda bundle: models.ContentAttribute.objects.filter(\n parent=bundle.obj\n ), full=True, null=True)\n members = fields.ToManyField(ListMemberResource,\n attribute=lambda bundle: models.ListMember.objects.filter(\n list=bundle.obj\n ), full=True, null=True)\n\n def dehydrate(self, bundle):\n mdict = {}\n for attribute in bundle.data['attributes']:\n mdict[attribute.data['keyword']] = attribute\n bundle.data['attributes'] = mdict\n return bundle\n \n class Meta:\n queryset = models.Content.objects.all()\n resource_name = 'content'\n authorization= Authorization()\n","sub_path":"mirrors/api/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"182771562","text":"'''\nThis file provides functions which are used in various places throughout the\ncodebase but don't deserve to be methods of any class.\n'''\n\nimport datetime\nimport hashlib\nimport math\nimport mimetypes\nimport os\nimport PIL.Image\nimport unicodedata\n\nfrom . import constants\nfrom . import exceptions\n\nfrom voussoirkit import bytestring\nfrom voussoirkit import pathclass\n\ndef album_zip_directories(album, recursive=True):\n '''\n Given an album, produce a dictionary mapping Album objects to directory\n names as they will appear inside the zip archive.\n Sub-albums become subfolders.\n '''\n directories = {}\n if album.title:\n root_folder = 'album %s - %s' % (album.id, remove_path_badchars(album.title))\n else:\n root_folder = 'album %s' % album.id\n\n directories[album] = root_folder\n if recursive:\n for child_album in album.get_children():\n child_directories = album_zip_directories(child_album, recursive=True)\n for (child_album, child_directory) in child_directories.items():\n child_directory = os.path.join(root_folder, child_directory)\n directories[child_album] = child_directory\n return directories\n\ndef album_zip_filenames(album, recursive=True):\n '''\n Given an album, produce a dictionary mapping local filepaths to the\n filenames that will appear inside the zip archive.\n This includes creating subfolders for sub albums.\n\n If a photo appears in multiple albums, only the first is used.\n '''\n arcnames = {}\n directories = album_zip_directories(album, recursive=recursive)\n for (album, directory) in directories.items():\n photos = album.get_photos()\n for photo in photos:\n filepath = photo.real_path.absolute_path\n if filepath in arcnames:\n continue\n photo_name = '%s - %s' % (photo.id, photo.basename)\n arcnames[filepath] = os.path.join(directory, photo_name)\n\n return arcnames\n\ndef checkerboard_image(color_1, color_2, image_size, checker_size):\n '''\n Generate a PIL Image with a checkerboard pattern.\n\n color_1:\n The color starting in the top left. Either RGB tuple or a string\n that PIL understands.\n color_2:\n The alternate color\n image_size:\n Tuple of two integers, the image size in pixels.\n checker_size:\n Tuple of two integers, the size of each checker in pixels.\n '''\n image = PIL.Image.new('RGB', image_size, color_1)\n checker = PIL.Image.new('RGB', (checker_size, checker_size), color_2)\n offset = True\n for y in range(0, image_size[1], checker_size):\n for x in range(0, image_size[0], checker_size * 2):\n x += offset * checker_size\n image.paste(checker, (x, y))\n offset = not offset\n return image\n\ndef chunk_sequence(sequence, chunk_length, allow_incomplete=True):\n '''\n Given a sequence, divide it into sequences of length `chunk_length`.\n\n allow_incomplete:\n If True, allow the final chunk to be shorter if the\n given sequence is not an exact multiple of `chunk_length`.\n If False, the incomplete chunk will be discarded.\n '''\n (complete, leftover) = divmod(len(sequence), chunk_length)\n if not allow_incomplete:\n leftover = 0\n\n chunk_count = complete + min(leftover, 1)\n\n chunks = []\n for x in range(chunk_count):\n left = chunk_length * x\n right = left + chunk_length\n chunks.append(sequence[left:right])\n\n return chunks\n\ndef comma_space_split(s):\n '''\n Split the string apart by commas and spaces, discarding all extra\n whitespace and blank phrases.\n\n 'a b, c,,d' -> ['a', 'b', 'c', 'd']\n '''\n if s is None:\n return s\n s = s.replace(' ', ',')\n s = [x.strip() for x in s.split(',')]\n s = [x for x in s if x]\n return s\n\ndef dict_to_params(d):\n '''\n Given a dictionary of URL parameters, return a URL parameter string.\n\n {'a':1, 'b':2} -> '?a=1&b=2'\n '''\n if not d:\n return ''\n params = ['%s=%s' % (k, v) for (k, v) in d.items() if v]\n params = '&'.join(params)\n if params:\n params = '?' + params\n return params\n\ndef fit_into_bounds(image_width, image_height, frame_width, frame_height):\n '''\n Given the w+h of the image and the w+h of the frame,\n return new w+h that fits the image into the frame\n while maintaining the aspect ratio.\n\n (1920, 1080, 400, 400) -> (400, 225)\n '''\n width_ratio = frame_width / image_width\n height_ratio = frame_height / image_height\n ratio = min(width_ratio, height_ratio)\n\n new_width = int(image_width * ratio)\n new_height = int(image_height * ratio)\n\n return (new_width, new_height)\n\ndef get_mimetype(filepath):\n '''\n Extension to mimetypes.guess_type which uses my\n constants.ADDITIONAL_MIMETYPES.\n '''\n extension = os.path.splitext(filepath)[1].replace('.', '')\n mimetype = constants.ADDITIONAL_MIMETYPES.get(extension, None)\n if mimetype is None:\n mimetype = mimetypes.guess_type(filepath)[0]\n return mimetype\n\ndef hash_file(filepath, hasher):\n bytestream = read_filebytes(filepath)\n for chunk in bytestream:\n hasher.update(chunk)\n return hasher.hexdigest()\n\ndef hash_file_md5(filepath):\n return hash_file(filepath, hasher=hashlib.md5())\n\ndef hyphen_range(s):\n '''\n Given a string like '1-3', return numbers (1, 3) representing lower\n and upper bounds.\n\n Supports bytestring.parsebytes and hh:mm:ss format, for example\n '1k-2k', '10:00-20:00', '4gib-'\n '''\n s = s.strip()\n s = s.replace(' ', '')\n if not s:\n return (None, None)\n parts = s.split('-')\n parts = [part.strip() or None for part in parts]\n if len(parts) == 1:\n low = parts[0]\n high = None\n elif len(parts) == 2:\n (low, high) = parts\n else:\n raise ValueError('Too many hyphens')\n\n low = _unitconvert(low)\n high = _unitconvert(high)\n if low is not None and high is not None and low > high:\n raise exceptions.OutOfOrder(range=s, min=low, max=high)\n return low, high\n\ndef hms_to_seconds(hms):\n '''\n Convert hh:mm:ss string to an integer seconds.\n '''\n hms = hms.split(':')\n seconds = 0\n if len(hms) == 3:\n seconds += int(hms[0]) * 3600\n hms.pop(0)\n if len(hms) == 2:\n seconds += int(hms[0]) * 60\n hms.pop(0)\n if len(hms) == 1:\n seconds += float(hms[0])\n return seconds\n\ndef is_xor(*args):\n '''\n Return True if and only if one arg is truthy.\n '''\n return [bool(a) for a in args].count(True) == 1\n\ndef now(timestamp=True):\n '''\n Return the current UTC timestamp or datetime object.\n '''\n n = datetime.datetime.now(datetime.timezone.utc)\n if timestamp:\n return n.timestamp()\n return n\n\ndef random_hex(length=12):\n randbytes = os.urandom(math.ceil(length / 2))\n token = ''.join('{:02x}'.format(x) for x in randbytes)\n token = token[:length]\n return token\n\ndef read_filebytes(filepath, range_min=0, range_max=None, chunk_size=2 ** 20):\n '''\n Yield chunks of bytes from the file between the endpoints.\n '''\n filepath = pathclass.Path(filepath)\n if range_max is None:\n range_max = filepath.size\n range_span = range_max - range_min\n\n f = open(filepath.absolute_path, 'rb')\n f.seek(range_min)\n sent_amount = 0\n with f:\n while sent_amount < range_span:\n chunk = f.read(chunk_size)\n if len(chunk) == 0:\n break\n\n yield chunk\n sent_amount += len(chunk)\n\ndef recursive_dict_update(target, supply):\n '''\n Update target using supply, but when the value is a dictionary update the\n insides instead of replacing the dictionary itself.\n '''\n for (key, value) in supply.items():\n if isinstance(value, dict):\n existing = target.get(key, None)\n if existing is None:\n target[key] = value\n else:\n recursive_dict_update(existing, value)\n else:\n target[key] = value\n\ndef recursive_dict_keys(d):\n '''\n Given a dictionary, return a set containing all of its keys and the keys of\n all other dictionaries that appear as values within. The subkeys will use \\\\\n to indicate their lineage.\n\n {\n 'hi': {\n 'ho': 'neighbor'\n }\n }\n\n returns\n\n {'hi', 'hi\\\\ho'}\n '''\n keys = set(d.keys())\n for (key, value) in d.items():\n if isinstance(value, dict):\n subkeys = {'%s\\\\%s' % (key, subkey) for subkey in recursive_dict_keys(value)}\n keys.update(subkeys)\n return keys\n\ndef remove_characters(text, characters):\n translator = {ord(c): None for c in characters}\n text = text.translate(translator)\n return text\n\ndef remove_control_characters(text):\n '''\n Thanks Alex Quinn\n https://stackoverflow.com/a/19016117\n\n unicodedata.category(character) returns some two-character string\n where if [0] is a C then the character is a control character.\n '''\n return ''.join(c for c in text if unicodedata.category(c)[0] != 'C')\n\ndef remove_path_badchars(filepath, allowed=''):\n '''\n Remove the bad characters seen in constants.FILENAME_BADCHARS, except\n those which you explicitly permit.\n\n 'file*name' -> 'filename'\n ('D:\\\\file*name', allowed=':\\\\') -> 'D:\\\\filename'\n '''\n badchars = remove_characters(constants.FILENAME_BADCHARS, allowed)\n filepath = remove_characters(filepath, badchars)\n filepath = remove_control_characters(filepath)\n\n filepath = filepath.replace('/', os.sep)\n filepath = filepath.replace('\\\\', os.sep)\n return filepath\n\ndef seconds_to_hms(seconds):\n '''\n Convert integer number of seconds to an hh:mm:ss string.\n Only the necessary fields are used.\n '''\n seconds = math.ceil(seconds)\n (minutes, seconds) = divmod(seconds, 60)\n (hours, minutes) = divmod(minutes, 60)\n parts = []\n if hours:\n parts.append(hours)\n if minutes:\n parts.append(minutes)\n parts.append(seconds)\n hms = ':'.join('%02d' % part for part in parts)\n return hms\n\ndef select_generator(sql, query, bindings=None):\n '''\n Perform the query, and yield the results.\n '''\n bindings = bindings or []\n cursor = sql.cursor()\n cursor.execute(query, bindings)\n while True:\n fetch = cursor.fetchone()\n if fetch is None:\n break\n yield fetch\n\ndef sql_listify(items):\n '''\n Given a list of strings, return a string in the form of an SQL list.\n\n ['hi', 'ho', 'hey'] -> '(\"hi\", \"ho\", \"hey\")'\n '''\n return '(%s)' % ', '.join('\"%s\"' % item for item in items)\n\ndef truthystring(s):\n '''\n Convert strings to True, False, or None based on the options presented\n in constants.TRUTHYSTRING_TRUE, constants.TRUTHYSTRING_NONE, or False\n for all else.\n\n Case insensitive.\n '''\n if s is None:\n return None\n\n if isinstance(s, (bool, int)):\n return bool(s)\n\n s = s.lower()\n if s in constants.TRUTHYSTRING_TRUE:\n return True\n if s in constants.TRUTHYSTRING_NONE:\n return None\n return False\n\n\n_numerical_characters = set('0123456789.')\ndef _unitconvert(value):\n '''\n When parsing hyphenated ranges, this function is used to convert\n strings like \"1k\" to 1024 and \"1:00\" to 60.\n '''\n if value is None:\n return None\n if ':' in value:\n return hms_to_seconds(value)\n elif all(c in _numerical_characters for c in value):\n return float(value)\n else:\n return bytestring.parsebytes(value)\n","sub_path":"etiquette/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":11655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"584551749","text":"#\n# @lc app=leetcode.cn id=752 lang=python3\n#\n# [752] 打开转盘锁\n#\n# https://leetcode-cn.com/problems/open-the-lock/description/\n#\n# algorithms\n# Medium (47.58%)\n# Likes: 63\n# Dislikes: 0\n# Total Accepted: 5.9K\n# Total Submissions: 12.3K\n# Testcase Example: '[\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"]\\n\"0202\"'\n#\n# 你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8',\n# '9' 。每个拨轮可以自由旋转:例如把 '9' 变为  '0','0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。\n# \n# 锁的初始数字为 '0000' ,一个代表四个拨轮的数字的字符串。\n# \n# 列表 deadends 包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。\n# \n# 字符串 target 代表可以解锁的数字,你需要给出最小的旋转次数,如果无论如何不能解锁,返回 -1。\n# \n# \n# \n# 示例 1:\n# \n# \n# 输入:deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"\n# 输出:6\n# 解释:\n# 可能的移动序列为 \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\"。\n# 注意 \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" 这样的序列是不能解锁的,\n# 因为当拨动到 \"0102\" 时这个锁就会被锁定。\n# \n# \n# 示例 2:\n# \n# \n# 输入: deadends = [\"8888\"], target = \"0009\"\n# 输出:1\n# 解释:\n# 把最后一位反向旋转一次即可 \"0000\" -> \"0009\"。\n# \n# \n# 示例 3:\n# \n# \n# 输入: deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"],\n# target = \"8888\"\n# 输出:-1\n# 解释:\n# 无法旋转到目标数字且不被锁定。\n# \n# \n# 示例 4:\n# \n# \n# 输入: deadends = [\"0000\"], target = \"8888\"\n# 输出:-1\n# \n# \n# \n# \n# 提示:\n# \n# \n# 死亡列表 deadends 的长度范围为 [1, 500]。\n# 目标数字 target 不会在 deadends 之中。\n# 每个 deadends 和 target 中的字符串的数字会在 10,000 个可能的情况 '0000' 到 '9999' 中产生。\n# \n# \n#\n\n\n# @lc code=start\nfrom queue import Queue\nclass Solution:\n def __init__(self):\n print('1')\n def openLock(self, deadends, target: str) -> int:\n if '0000' in deadends:\n return -1\n \n self.start = '0000'\n # self.queue = []\n self.visited = {}\n q= Queue()\n self.deadends = set(deadends)\n self.head, tail = 0,0\n \n step = 0\n q.put(('0000',0))\n # self.queue.append((self.start,step))\n # self.tail = 1 \n \n # while not self.isempty():\n while not q.empty():\n #无解的条件是队空,但队列中没有出现过target\n # 如果target出现在队列中可终止,或队空可终止\n # current, step = self.queue[self.head]#取队头\n current, step = q.get()\n # self.visited[current] = 1#队头标记\n # if current not in self.deadends:\n # self.deadends.add(current)\n\n adj_node = self.increment(current)#找可行邻节点\n if target in adj_node:\n # return self.queue[self.head][1] + 1\n return step + 1\n if len(adj_node)!=0:\n step +=1\n # self.enqueue(adj_node,step)#林结点入队\n for node in adj_node:\n q.put((node,step))\n if node not in self.deadends:\n self.deadends.add(node)\n # print(step)\n # self.dequeue(current)\n\n \n return -1\n\n def isempty(self):\n return True if self.head == self.tail else False\n\n def enqueue(self,node_list,step):\n for node in node_list:\n self.queue.append((node,step))\n self.tail += 1\n\n def dequeue(self,node):\n self.head += 1\n\n def increment(self,current:str):\n # 死亡结点和访问过的结点不入队\n # 返回可行的邻节点\n assert isinstance(current,str),'type current error'\n ret = []\n for state in ['+','-']:\n for bit in range(len(current)):\n if state == '+':\n change_str = current[:bit]+str((int(current[bit])+1)%10)+current[bit+1:]\n if change_str in self.deadends:\n continue\n if state == '-':\n change_str = current[:bit]+str((int(current[bit])-1)%10)+current[bit+1:]\n if change_str in self.deadends:\n continue\n ret.append(change_str)\n return ret\n \n \ns=Solution() \nr=s.openLock([\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"],\"8888\")\nprint('r',r)\n\n\"\"\"\n可以将转盘锁当前的状态视为二维平面图上的一个坐标点,与此点相邻的坐标点有八个,可以理解为相应的增加/减少每一位数字对应的新状态。通过BFS或dfs的方法,如果当前初始状态(或target)经过任何路径都无法达到target(或初始状态)\n则返回1,否则返回步长计数器。\n不可行\n\"\"\"\n \n# @lc code=end\n\n","sub_path":"done/752/752.打开转盘锁.py","file_name":"752.打开转盘锁.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"329967883","text":"from typing import List, Dict, Any, Iterator, Optional\r\nimport bpy\r\nfrom ... import pyscene\r\n\r\n\r\nclass ExportMap:\r\n '''\r\n この中は LeftHanded Y-UP になっていること\r\n '''\r\n def __init__(self, nodes: List[pyscene.Node] = None):\r\n self.nodes: List[pyscene.Node] = []\r\n if nodes:\r\n self.nodes = nodes\r\n self.meshes: List[pyscene.FaceMesh] = []\r\n self._node_map: Dict[bpy.types.Object, pyscene.Node] = {}\r\n self._skin_map: Dict[bpy.types.Object, pyscene.Skin] = {}\r\n self.materials: List[pyscene.UnlitMaterial] = []\r\n self._material_map: Dict[bpy.types.Material, int] = {}\r\n self.vrm = pyscene.Vrm()\r\n\r\n def add_node(self, obj: Any, node: pyscene.Node):\r\n self.nodes.append(node)\r\n self._node_map[obj] = node\r\n\r\n def get_root_nodes(self) -> Iterator[pyscene.Node]:\r\n for node in self.nodes:\r\n if not node.parent:\r\n yield node\r\n\r\n def remove_node(self, node: pyscene.Node):\r\n # _node_map\r\n keys = []\r\n for k, v in self._node_map.items():\r\n if v == node:\r\n keys.append(k)\r\n for k in keys:\r\n del self._node_map[k]\r\n\r\n # _nodes\r\n self.nodes.remove(node)\r\n\r\n # children\r\n if node.parent:\r\n node.parent.remove_child(node)\r\n\r\n def get_node_for_skin(self, skin: pyscene.Skin) -> Optional[pyscene.Node]:\r\n for node in self.nodes:\r\n if node.skin == skin:\r\n return node\r\n\r\n def remove_empty_leaf_nodes(self) -> bool:\r\n bones: List[pyscene.Node] = []\r\n for skin in self._skin_map.values():\r\n skin_node = self.get_node_for_skin(skin)\r\n if not skin_node:\r\n raise Exception()\r\n for bone in skin_node.traverse():\r\n if bone not in bones:\r\n bones.append(bone)\r\n\r\n def is_empty_leaf(node: pyscene.Node) -> bool:\r\n if node.humanoid_bone:\r\n return False\r\n if node.children:\r\n return False\r\n if node.mesh:\r\n return False\r\n if node in bones:\r\n return False\r\n return True\r\n\r\n remove_list = []\r\n for root in self.get_root_nodes():\r\n for node in root.traverse():\r\n if is_empty_leaf(node):\r\n remove_list.append(node)\r\n\r\n if not remove_list:\r\n return False\r\n\r\n for remove in remove_list:\r\n self.remove_node(remove)\r\n\r\n return True\r\n","sub_path":"lib/bpy_helper/exporter/export_map.py","file_name":"export_map.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"241673414","text":"import os\nimport unittest\n\nimport nose\n\nfrom conan.conf import mingw_in_path\nfrom conan.test_regression.utils.base_exe import path_dot\nfrom conans import tools\nfrom conans.model.version import Version\nfrom conans.test.utils.tools import TestServer, TestClient\nfrom conans import __version__ as client_version\n\n\nclass MinGWDiamondTest(unittest.TestCase):\n\n def setUp(self):\n test_server = TestServer(\n [], # write permissions\n users={\"lasote\": \"mypass\"}) # exported users and passwords\n servers = {\"default\": test_server}\n conan = TestClient(servers=servers, users={\"default\": [(\"lasote\", \"mypass\")]})\n if Version(client_version) < Version(\"0.31\"):\n raise nose.SkipTest('Only >= 1.0 version')\n\n from conans.test.integration.diamond_test import DiamondTester\n self.diamond_tester = DiamondTester(self, conan, servers)\n \n def diamond_mingw_test(self):\n if Version(client_version) < Version(\"0.31\"):\n raise nose.SkipTest('Only >= 1.0 version')\n with tools.remove_from_path(\"bash.exe\"):\n with mingw_in_path():\n not_env = os.system(\"g++ --version > nul\")\n if not_env != 0:\n raise Exception(\"This platform does not support G++ command\")\n install = \"install %s -s compiler=gcc -s compiler.libcxx=libstdc++ \" \\\n \"-s compiler.version=4.9\" % path_dot()\n self.diamond_tester.test(install=install, use_cmake=False)\n\n \nclass BuildMingwTest(unittest.TestCase):\n\n def build_mingw_test(self):\n if Version(client_version) < Version(\"0.31\"):\n raise nose.SkipTest('Only >= 1.0 version')\n\n with tools.remove_from_path(\"bash.exe\"):\n with mingw_in_path():\n not_env = os.system(\"c++ --version > nul\")\n if not_env != 0:\n raise Exception(\"This platform does not support G++ command\")\n install = \"install %s -s compiler=gcc -s compiler.libcxx=libstdc++ \" \\\n \"-s compiler.version=4.9\" % path_dot()\n for cmd, lang, static, pure_c in [(install, 0, True, True),\n (install + \" -o language=1 -o static=False\", 1, False, False)]:\n from conans.test.integration.basic_build_test import build\n build(self, cmd, static, pure_c, use_cmake=False, lang=lang)\n","sub_path":"conan/external_tools/bare_mingw_test.py","file_name":"bare_mingw_test.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"602460359","text":"#!/usr/bin/python\n\nimport math\nimport random\n\n\nANGER = 1\nDISGUST = 2\nFEAR = 3\nHAPINESS = 4\nSADNESS = 5\nSURPRISE = 6\n\n\nclass ClassificationResult:\n def __init__(self, result, depth, positiveRate, emotion):\n self.result = result\n self.depth = depth\n self.positiveRate = positiveRate\n self.emotion = emotion\n\n\nclass Node:\n def __init__(self):\n self.label = -1 # Attribute this node is splitting on.\n self.left = None # Branch for negative values of attribute. \n self.right = None # Branch for positive values of attribute.\n self.classVal = None # Classification result (binary, only in leaves).\n self.numExs = None # Number of examples associated with node.\n self.pPos = None # Propotion of positive examples.\n self.emotion = None # Emotion this tree is classifying. \n\n\n # Flatten the tree and return a json log used for visualisation.\n def flatten(self, parent='null'):\n curPar = 'A' + str(self.label + 1) if self.label != -1 else str(self.classVal)\n children = []\n if self.left:\n children.append(self.left.flatten(curPar))\n if self.right:\n children.append(self.right.flatten(curPar))\n return {\n \"name\": curPar,\n \"parent\": parent,\n \"children\": children\n }\n\n # Classify one particular example on this tree.\n def classify(self, example):\n current = self\n count = 0\n PRUNE_THRESHOLD = 120\n p = 0\n while current:\n if current.numExs < PRUNE_THRESHOLD and p == 0:\n p = current.pPos\n count += 1\n classVal = current.classVal\n if not classVal:\n classVal = round(current.pPos)\n if example[current.label] == 0:\n if not current.left:\n return ClassificationResult(classVal, count, p, current.emotion)\n current = current.left\n else:\n if not current.right:\n return ClassificationResult(classVal, count, p, current.emotion)\n current = current.right\n \n\n def __str__(self, level=0):\n return 'A' + str(self.label + 1) if self.label != -1 else str(self.classVal)\n\n\ndef train_and_predict(examples, labels, test_examples):\n trees = train(examples, labels)\n predicted_labels = test_trees(trees, test_examples)\n return predicted_labels\n\n\ndef train(examples, labels):\n trees = []\n for emotion in range(1, 7):\n tree = trainfor(examples, labels, emotion)\n trees.append(tree)\n\n return trees\n\n\ndef trainfor(examples, labels, emotion):\n # Remap the values in function of specific training label.\n posNeg = lambda x: int(x == emotion)\n binaryTargets = list(map(posNeg, labels[:]))\n attributes = set(range(45))\n # Invoke the main decision tree algorithm.\n return decisionTreeLearn(examples, attributes, binaryTargets, emotion)\n\n\ndef decisionTreeLearn(examples, attributes, binaryTargets, emotion):\n # Check to see if all the example values are identical.\n total = sum(binaryTargets)\n node = Node()\n node.emotion = emotion\n node.pPos = total / float(len(binaryTargets))\n node.numExs = len(binaryTargets)\n if total == 0:\n node.classVal = 0\n return node\n if total == len(binaryTargets):\n node.classVal = 1\n return node\n elif not attributes:\n node.classVal = majorityValue(binaryTargets)\n return node\n else:\n bestAttribute = chooseBestDecisionAttribute(examples, attributes, binaryTargets)\n node.label = bestAttribute\n for i in [0, 1]:\n # Examples with same value as i.\n newExamples = []\n newBinaryTargets = []\n for k in range(len(examples)):\n if examples[k][bestAttribute] == i:\n newExamples.append(examples[k])\n newBinaryTargets.append(binaryTargets[k])\n if not newExamples:\n child = Node()\n child.pPos = total / float(len(binaryTargets))\n child.classVal = majorityValue(binaryTargets)\n child.emotion = emotion\n if i == 0:\n node.left = child\n else:\n node.right = child\n else:\n newAttributes = set(attributes)\n newAttributes.remove(bestAttribute)\n child = decisionTreeLearn(newExamples,\n newAttributes,\n newBinaryTargets, emotion)\n if i == 0:\n node.left = child\n else:\n node.right = child\n return node\n\n\n# Binary Entropy function for a list.\ndef binEntr(l):\n size = len(l)\n if size == 0:\n return 0\n pos = sum(l)\n neg = size - pos\n pfrac, nfrac = pos / float(size), neg / float(size)\n if pfrac == 0 or nfrac == 0:\n return 0\n return - pfrac * math.log(pfrac, 2) - nfrac * math.log(nfrac, 2)\n\n\n# rewrite choose BestDecisionAttribute\ndef chooseBestDecisionAttribute(examples, attributes, binaryTargets):\n curMin = 1.1\n minAttr = -1\n for attr in attributes:\n zeroAttr = []\n oneAttr = []\n for k, v in zip(examples, binaryTargets):\n if k[attr] == 0:\n zeroAttr.append(v)\n else:\n oneAttr.append(v)\n I0, I1 = binEntr(zeroAttr), binEntr(oneAttr)\n z0, z1 = float(len(zeroAttr)), float(len(oneAttr))\n size = z0 + z1\n R = z0 / size * I0 + z1 / size * I1\n if R < curMin:\n curMin = R\n minAttr = attr\n return minAttr\n\n\n# Mode function.\ndef majorityValue(binaryTargets):\n ones = binaryTargets.count(1)\n zeroes = len(binaryTargets) - ones\n return 1 if ones > zeroes else 0\n\n\n#\n# Combination of trees\n#\n\n\ndef test_trees(trees, test_data):\n return [pseudoprune_classification(trees, ex) for ex in test_data]\n\n\n# Take the tree with the shallowest leaf.\ndef depth_classification(ts, ex):\n results = [t.classify(ex) for t in ts]\n positive_results = filter(lambda res: res.result, results)\n if not positive_results:\n return int(random.random() * 6) + 1\n return min(positive_results, key=lambda res: res.depth).emotion\n\n\n# Take the tree with the most \"viable\" path.\ndef pseudoprune_classification(ts, ex):\n results = [t.classify(ex) for t in ts]\n results.sort(key=lambda res: res.result + res.positiveRate)\n return results[-1].emotion\n","sub_path":"Decision-Trees/DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":6601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"275383731","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n# Created by wenchao.jia on 19-8-1.\n# Mail:wenchao.jia@qunar.com\nfrom json import dumps\n\nfrom aiohttp import web\nfrom aiohttp.web_response import Response\n\nroutes = web.RouteTableDef()\n\n\ndef json_response(data, status=0, message='', http_status=200, content_type='application/json'):\n if isinstance(data, Exception):\n message = '系统异常'\n status = -1\n data = ''\n text = dumps({'message': message, 'status': status, 'data': data})\n return Response(text=text, status=http_status, content_type=content_type)\n","sub_path":"demo/app/handler/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"370947050","text":"\"\"\"\nTextMining.py counts the adjectives (as determined by Pattern, which is a bit iffy) used most frequently to describe each of the four main characters in Little Women by Louisa May Alcott.\n\nSoftware Design 2016 - Olin College of Engineering\n\n@author: March Saper\n\"\"\"\nfrom pattern.web import*\nfrom pattern.search import search\nfrom pattern.en import parsetree \nimport pickle\nimport pylab \n\n\ndef surrounding_words(L, Names, Wrongs):\n \"\"\"Returns lists of words surrounding the mention of a name only if no other character names are mentioned\n\n >>> surrounding_words(['one', 'short', 'day', 'in', 'the', 'emerald', 'city'], ['kristin', 'idina'], ['bob'])\n []\n >>> surrounding_words(['sharing', 'one', 'wonderful', 'one', 'short', 'day', 'the', 'wizard', 'will', 'see', 'you', 'edna'], ['idina', 'edna'], ['kristin', 'chrystal'])\n [['one', 'wonderful', 'one', 'short', 'day', 'the', 'wizard', 'will', 'see', 'you']]\n >>> surrounding_words(['sharing', 'one', 'wonderful', 'one', 'short', 'day', 'the', 'wizard', 'will', 'see', 'kristin', 'idina'], ['edna', 'idina'], ['kristin', 'chrystal'])\n []\n \"\"\"\n\n name_mentions = []\n for i in range(len(L)):\n if L[i] in Names:\n name_mentions.append(L[i-10:i])\n i += 10\n one_only = []\n for m in range(len(name_mentions)):\n if all(w not in name_mentions[m] for w in Wrongs):\n one_only.append(name_mentions[m])\n\n return one_only\n \n\n\ndef adjectives(L):\n \"\"\"Returns a list of adjecives present in input lists.\n\n >>> adjectives([['big', 'white', 'tall', 'dog'], ['bat', 'tall']])\n ['big', 'white', 'tall', 'tall']\n >>> adjectives([['march'], ['yes', 'i', 'know', 'its', 'almost', 'march']])\n []\n \"\"\"\n\n adjs = []\n for l in range(len(L)):\n current_string = \" \".join(L[l])\n parts_of_speech = parsetree(current_string) \n for i in search(\"JJ\", parts_of_speech): # Search the parsed string for adjectives\n adjs.append(str(i.string))\n\n return adjs\n\n\n\ndef unique_adjectives(L, AllElse):\n \"\"\"Returns a list of adjectives unique to the character.\n\n >>> unique_adjectives(['big', 'tall', 'short'], ['short', 'white', 'black'])\n ['big', 'tall']\n >>> unique_adjectives(['tall', 'short'], ['tall', 'short', 'white'])\n []\n \"\"\"\n\n unique_adjs = []\n for a in range(len(L)):\n if L[a] not in AllElse:\n unique_adjs.append(L[a])\n \n return unique_adjs\n\n\n\n\ndef frequency(L):\n \"\"\"Returns tuples of adjectives and their frequency in input lists.\n\n >>> frequency(['potatoe', 'potatoe', 'potatoe'])\n [(3, 'potatoe')]\n >>> frequency([])\n []\n \"\"\"\n\n freq = {}\n for l in L:\n if l in freq:\n freq[l] += 1\n else:\n freq[l] = 1\n adj_freq = freq.items()\n freq_adj = []\n for adj, freq in adj_freq:\n freq_adj.append((freq, adj))\n freq_adj.sort(reverse = True)\n\n return freq_adj\n\n\n\ndef adj_finder(L, N, W):\n \"\"\"Takes the text of a book, a character's name, and the names of other characters. \n Returns all adjectives used in proximity to the character.\n As the this only calls doctested functions I decided to skip a doctest for this function.\n \"\"\"\n\n Mentions = surrounding_words(L, N, W)\n Adjectives = adjectives(Mentions)\n \n return Adjectives\n\n\n\ndef frequency_unique_adjs(L, AllElse):\n \"\"\"Takes a list of adjectives used to describe a single character as well as all characters.\n Returns tuples of the most frequently used adjectives only used to describe one character.\n As this only calls doctested functions I decided to skip the doctest for this function too.\n \"\"\"\n\n unique_adjs = unique_adjectives(L, AllElse)\n unique_freq_adj = frequency(unique_adjs)\n\n return unique_freq_adj\n\n\n\n\ndef bar_graph(T, L):\n \"\"\"Takes a list of tuples containing frequency and corresponding word.\n Returns a bar graph of top ten most common words and their frequency.\n There is no doctest for this function because how would you even test this.\n \"\"\"\n\n Frequency = []\n Adjective = []\n for f, a in T:\n Frequency.append(f)\n Adjective.append(a)\n \n x = range(9)\n y = Frequency[:9]\n f = pylab.figure()\n ax = f.add_axes([0.1, 0.1, 0.8, 0.8])\n ax.bar(x, y, align='center')\n ax.set_xticks(x)\n ax.set_xticklabels(Adjective[:10])\n pylab.title(L)\n pylab.show()\n\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n \n LW_load = (open('LittleWomen.pickle', 'r'))\n LW = pickle.load(LW_load)\n LW = LW.split()\n\n All_Names = ['meg', 'margaret', 'jo', 'josephine', 'beth', 'elizabeth', 'amy']\n\n\n Meg_a = adj_finder(LW, All_Names[:2], All_Names[2:])\n Jo_a = adj_finder(LW, All_Names[2:4], All_Names[:2] + All_Names[4:])\n Beth_a = adj_finder(LW, All_Names[4:6], All_Names[:4] + All_Names[6:])\n Amy_a = adj_finder(LW, All_Names[6:], All_Names[:6])\n \n\n Meg_u = frequency_unique_adjs(Meg_a, Jo_a + Beth_a + Amy_a)\n Jo_u = frequency_unique_adjs(Jo_a, Meg_a + Beth_a + Amy_a)\n Beth_u = frequency_unique_adjs(Beth_a, Meg_a + Jo_a + Amy_a)\n Amy_u = frequency_unique_adjs(Amy_a, Meg_a + Jo_a + Beth_a)\n\n\n bar_graph(Meg_u, \"Meg's Unique Adjectives\")\n bar_graph(Jo_u, \"Jo's Unique Adjectives\")\n bar_graph(Beth_u, \"Beth's Unique Adjectives\")\n bar_graph(Amy_u, \"Amy's Unique Adjectives\")","sub_path":"TextMining.py","file_name":"TextMining.py","file_ext":"py","file_size_in_byte":5404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"206687641","text":"#!/usr/bin/env python\r\n# -*- coding: UTF-8 -*-\r\n\r\n'''\r\n@author: K. and L. Scholz\r\n@date: 22.11.2019 - 31.1.2020\r\n@note: This is an Ant Colony Optimization Algorithm. It finds the best relationship \r\n between the parameter for training the algorithm using a three dimensional data plotting heatmap.\r\n This program runs best in the Anaconda Spyder IDE.\r\n'''\r\n\r\n# import libraries:\r\nimport random as rn # used for choosing random numbers\r\nimport numpy as np # used for matricies and more dimensional arrays\r\nimport math # used for complex mathematic functions\r\nimport matplotlib.pyplot as plt # used for plotting the results graphically\r\nimport seaborn as sns # used for printing the heatmap\r\nimport re\r\nimport os\r\n\r\n# main class: Ant Colony Optimization Algorithm\r\nclass ACO():\r\n \r\n # function used to initialize public variables\r\n def __init__(self, nodes, iterations, learning_rate, file_coordinates):\r\n self.nodes = nodes\r\n self.iterations = iterations\r\n self.learning_rate = learning_rate\r\n self.coordinates = file_coordinates\r\n\r\n # function to create the distances and the pheromone matrices\r\n def distances_and_pheromone(self):\r\n # create an empty two dimensional array square the size of the nodes\r\n self.distances = np.zeros(self.nodes**2)\r\n # calculate the displacements between the nodes using pythagoras theorem\r\n counter = 0 # varable used for representing the index\r\n for i in range(self.nodes): # for the first node\r\n for n in range(self.nodes): # for the second node\r\n # calculate the change of the x-values with subtraction\r\n x_change = abs(self.coordinates[i][0]-self.coordinates[n][0])\r\n # calculate the change of the y-values with subtraction\r\n y_change = abs(self.coordinates[i][1]-self.coordinates[n][1])\r\n # calculate the distance between the nodes using pythagoras theorem\r\n # save every distance in the distances matrix\r\n self.distances[counter] = math.sqrt(x_change**2 + y_change**2)\r\n # continue with the next distance\r\n counter += 1\r\n # convert distance array into two dimensional array\r\n self.distances = self.distances.reshape(self.nodes, self.nodes)\r\n # create two dimensional array with the same size as the distances matrix\r\n self.pheromone = np.ones(self.distances.shape) / len(self.distances)\r\n # delete every pheromone value referring to one node \r\n for x in range(self.nodes):\r\n self.pheromone[x][x]=0\r\n\r\n # function to determine the chosen way between the nodes from the pheromone matrix\r\n def determine_chosen_path(self):\r\n # starting node is always node 0\r\n self.best_way = [0] # list for the chosen way between the nodes\r\n next_nodes = [] # list for next possible nodes\r\n ctn = 0 # current test node\r\n # list all possible next nodes\r\n counter = 0\r\n for i in range(self.nodes):\r\n next_nodes.append(counter)\r\n counter += 1\r\n # delete already visited nodes saved in best_way\r\n next_nodes = list(set(next_nodes).difference(self.best_way))\r\n # choose the next node\r\n for n in range(self.nodes-1): # this process just needs to run number of nodes -1 times\r\n # find the biggest value in the given pheromone map\r\n max_value = max(self.pheromone[ctn][next_nodes])\r\n # now find the position representing the node\r\n for i in range(self.nodes):\r\n if self.pheromone[ctn][i] == max_value:\r\n ctn = i # current test node changes to the next node with the highest pheromone\r\n break # make sure to leave this loop because ctn is changed now\r\n # add the next node to the list\r\n self.best_way.append(ctn)\r\n # delete already visited nodes saved in best_way\r\n # otherwise it will bounce between two nodes with high pheromone\r\n next_nodes = list(set(next_nodes).difference(self.best_way))\r\n \r\n # function to calculate the total distance of the travelled way\r\n def calculate_travelled_distance(self):\r\n self.total_distance = 0 # the total distance travelled\r\n n1 = 0 # node\r\n for n2 in self.best_way[1:]:\r\n self.total_distance += self.distances[n1][n2] # add the chosen distance connection\r\n n1=n2\r\n # do not forget the last connection to the start node\r\n self.total_distance += self.distances[n2][0]\r\n return self.total_distance\r\n \r\n # main function - train and execute algorithm\r\n def train(self):\r\n repeat = 0 # counting variable\r\n # train the algorithm\r\n # set parameters\r\n alpha = 1\r\n beta = 5\r\n # every repetition conforms to one agent\r\n while repeat < self.iterations:\r\n # always start at a random node in the network\r\n ctn = rn.randint(0,9) # ctn stands for current test node\r\n node_hist = [ctn] # list for visited nodes \r\n # run through the network as long as unused nodes are existing\r\n while len(node_hist) <= self.nodes-1:\r\n counter = 0 # counter variable\r\n score_list = [] # list to save scores between the nodes\r\n prob_list = [] # list to save probabilities of node connections\r\n next_nodes = [] # list to save possible next nodes\r\n # eliminate connections from nodes to itself\r\n for i in self.distances[ctn]: # repeat for every other node\r\n # if connection exists add the refering node to the next possible nodes\r\n if i > 0: \r\n next_nodes.append(counter)\r\n # jump to the next node\r\n counter += 1\r\n # delete already visited nodes from possible next nodes\r\n next_nodes = list(set(next_nodes).difference(node_hist))\r\n # calculate connection scores\r\n for n in next_nodes: # repeat for every possible connection\r\n # calculate the node to node score\r\n score = ((self.pheromone[ctn][n])**alpha) / (self.distances[ctn][n]**beta)\r\n score_list.append(score) # add score to score list\r\n # convert connection scores to connection probabilities\r\n for i in score_list: # repeat for every score\r\n # using probability formula: probability = score(i) / sum_of_all_scores\r\n prob_list.append(i/sum(score_list))\r\n # choose the one next node randomly appropriate to their probabilities\r\n move = int(np.random.choice(next_nodes, 1 ,p=prob_list))\r\n # update pheromone map after which way was chosen\r\n self.pheromone[ctn][move] += 1/(self.distances[ctn][move]) # fist matrix element\r\n self.pheromone[move][ctn] += 1/(self.distances[ctn][move]) # mirror of first element\r\n # old pheromone decays slowly\r\n self.pheromone = self.pheromone * self.learning_rate\r\n # determine the next node\r\n ctn = move\r\n # add this node to the visited nodes\r\n node_hist.append(ctn)\r\n repeat += 1 # increment the training iterations\r\n\r\n# function to read data from the file\r\ndef read_data(data_path, test_data_number):\r\n # generate the path of every file individually\r\n path_of_file = data_path + \"data\" + str(test_data_number) + \".txt\"\r\n # open the file\r\n file = open(path_of_file, \"r\")\r\n # read data from file\r\n file_total_distance = file.readline() # fist line is the solution\r\n # use regex to seperate the number from the rest of the line\r\n file_total_distance = re.findall('[0-9]+.[0-9]+', file_total_distance)\r\n # convert regex string to float\r\n file_total_distance = float(file_total_distance[0])\r\n # convert coordinate list from string to integer\r\n file_coordinates = [] # list for saving the coordinates from the file\r\n file_coordinates = re.findall('.[0-9]+', file.read())\r\n for element in range(len(file_coordinates)):\r\n file_coordinates[element] = int(file_coordinates[element])\r\n # change the dimensions to two dimensional array\r\n file_coordinates = np.array(file_coordinates).reshape(nodes, 2)\r\n file.close() # close file after finished reading\r\n return file_total_distance, file_coordinates\r\n\r\nprint(\"Program started...\")\r\n# set important variables\r\nnodes = 10 # number of nodes in the network\r\ndata_path = \"C:/ENTER_DATA_PATH_HERE\" # path where the data is saved in text files\r\n\r\n# create two dimensional array later used to represent relationship between pheromone and iterations\r\nscores = np.zeros((10, 10))\r\n\r\nrun = 0 # variable to count the runs\r\n\r\n# prepare axis numeration for matplotlib\r\ndecay_rate_list = []\r\niterations_list = []\r\nfor i in range(5):\r\n decay_rate_list.append(99 + i*0.2)\r\n iterations_list.append(i*150)\r\n\r\n# train the ACO using different parameters alpha and beta each time\r\nfor l_rate in range(10):\r\n learning_rate = 0.99 + l_rate*0.1 # set learning rate parameter value\r\n for iterations in range(10):\r\n training_iterations = iterations * 75 # set iterations parameter value\r\n test_data_number = 1 # indicates number of the test data file\r\n score = 0 # score used to compare test data with ACOs results\r\n # repeat for every test data file found in the directory\r\n # compare ACOs result with the saved one\r\n for files in os.listdir(data_path):\r\n # read the data from the file\r\n file_total_distance, file_coordinates = read_data(data_path, test_data_number)\r\n # create new instance of the ACO with specified parameters\r\n aco = ACO(nodes, training_iterations, learning_rate, file_coordinates)\r\n # calculate distances and pheromone according to the given coordinates\r\n aco.distances_and_pheromone()\r\n # train the algorithm - pheromone map changes\r\n aco.train()\r\n # calculate results - optimal path\r\n aco.determine_chosen_path()\r\n # calculate ACOs solution\r\n total_distance = aco.calculate_travelled_distance()\r\n # check if ACO object calculated the right distance\r\n if total_distance == file_total_distance:\r\n score += 1 # if yes, increment the score\r\n # jump to the next test data set\r\n test_data_number += 1\r\n # saved the result in the corresponding score position\r\n scores[l_rate][iterations]=score\r\n # plot the heatmap of the scores after each row is done\r\n fig, ax = plt.subplots(figsize=(7,7))\r\n sns.heatmap(scores, annot=True, cbar=True, vmin=0, vmax=100)\r\n plt.ylabel(\"learning rate\")\r\n plt.xlabel(\"training iterations\")\r\n plt.xticks([0,2,4,6,8,10], decay_rate_list)\r\n plt.yticks([0,2,4,6,8,10], iterations_list)\r\n plt.show()\r\n run += 1\r\n print(run, \"/100 done\")\r\n\r\n# show final heatmap of the scores\r\nfig, ax = plt.subplots(figsize=(7,7))\r\nsns.heatmap(scores, annot=True, cbar=True, vmin=0, vmax=100)\r\nplt.ylabel(\"learning rate\")\r\nplt.xlabel(\"training iterations\")\r\nplt.xticks([0,2,4,6,8,10], decay_rate_list)\r\nplt.yticks([0,2,4,6,8,10], iterations_list)\r\nplt.show() # show graphic\r\nprint(\"Program finished.\")\r\n","sub_path":"ACO3.2 - Lernrate Trainingswiederholungen Parameter Optimierung.py","file_name":"ACO3.2 - Lernrate Trainingswiederholungen Parameter Optimierung.py","file_ext":"py","file_size_in_byte":11628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"339757986","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^grupos/$', views.categoriaVerView, name=\"categoriaVerView\"),\n url(r'^grupos/agregar/', views.categoriaAddView, name=\"categoriaAdd\"),\n url(r'^grupos/eliminar/', views.categoriaBorrar, name=\"categoriaBorrar\"),\n url(r'^grupos/(?P[0-9]+)/$', views.categoriaEditView, name=\"categoriaEditView\"),\n\n]","sub_path":"app/categoria/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"402641448","text":"# faships/views.py\nfrom datetime import datetime\n\nfrom django.views.generic import CreateView, ListView, DetailView, UpdateView\nfrom django.shortcuts import render, redirect, render_to_response\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import permission_required\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib import messages\n\nfrom .models import Faship, Device\nfrom users.models import Pegadri, Cocodri\n\nfrom .forms import FashipForm, DeviceForm, FashipFormSet\nfrom users.forms import AddpegadriForm, AddcocodriForm\n\nfrom jobs.belta import Sfis\nfrom jobs.tasks import add, delay_logging, send_faship_email_task\nfrom jobs.views import send_faship_email\n\n\ndef sfis_update(device_items):\n try:\n sfis = Sfis()\n except Exception as e:\n sfis = Sfis()\n\n for i in range(0, len(device_items)):\n isn = device_items[i].isn\n isn = isn.strip()\n \n s_info = sfis.isninfo(isn)\n s_utk = sfis.utk(isn)\n #s_error = sfis.error(isn, device_items[i].station)\n s_error = sfis.error(isn, str(device_items[i].station).split(',')[1].strip()) #只拿GRPNM\n s_modd = sfis.modd(isn)\n if s_info[0] == 0:\n info = s_info[1]\n config = info['SN1'].split('/')[3]\n unit_no = info['SN1'].split('/')[4]\n Device.objects.filter(isn=device_items[i].isn).update(\n config=config, unit_no=unit_no, sfis_status=True\n )\n else:\n info = s_info[1]\n config = 'no data'\n unit_no = 'no data'\n Device.objects.filter(isn=device_items[i].isn).update(\n sfis_info=str(info)+','+str(datetime.strftime(datetime.now(),'%Y-%m-%d-%H:%M'))\n )\n if s_utk[0] == 0:\n utk = s_utk[1]\n Device.objects.filter(isn=device_items[i].isn).update(\n utk=utk['UTK C_TIME']\n )\n if s_error[0] == 0:\n serror = s_error[1]\n failure_symptoms = serror['PDCS_LIST_OF_FAILTING_TEST']\n Device.objects.filter(isn=device_items[i].isn).update(\n failure_symptoms=failure_symptoms \n )\n else:\n serror = s_error[1]\n failure_symptoms = str(serror)\n Device.objects.filter(isn=device_items[i].isn).update(\n failure_symptoms=str(serror)\n )\n if s_modd[0] == 0:\n smodd = s_modd[1]\n grpnm = str(smodd['MODD GRPNM'])+', '+str(smodd['MODD STATUS'])\n Device.objects.filter(isn=device_items[i].isn).update(\n grpnm=str(grpnm)\n )\n else:\n smodd = s_modd[1]\n grpnm = str(smodd)\n Device.objects.filter(isn=device_items[i].isn).update(\n grpnm=str(grpnm)\n )\n return True\n\n\ndef isn_check(isn):\n \"\"\"check isn illegal\"\"\"\n try:\n sfis = Sfis()\n except Exception as e:\n sfis = Sfis()\n \n isn = isn.strip()\n s_info = sfis.isninfo(isn)\n if s_info[0] == 0:\n return True\n elif s_info[0] == 1:\n return False\n else:\n return False\n\n\nclass FormsetMixin(object):\n object = None\n edit = False\n\n def get(self, request, *args, **kwargs):\n if getattr(self, 'is_update_view', False):\n self.object = self.get_object()\n self.edit = True\n \n form_class = self.get_form_class()\n form = self.get_form(form_class)\n \n formset_class = self.get_formset_class()\n formset = self.get_formset(formset_class)\n\n formp = self.get_formp()\n formc = self.get_formc()\n \n #messages.info(request, '建議在填寫之前請先確認機台狀態。')\n \n return self.render_to_response(\n self.get_context_data(\n form=form, formset=formset,\n formp=formp, formc=formc\n )\n )\n\n def post(self, request, *args, **kwargs):\n if getattr(self, 'is_update_view', False):\n self.object = self.get_object()\n self.edit = True\n \n form_class = self.get_form_class()\n form = self.get_form(form_class)\n\n formset_class = self.get_formset_class()\n formset = self.get_formset(formset_class)\n \n # check the isn, avoid user use back page(but js catch has clean)\n # so check every device's dict\n # remove those function to forms.py\n #for device in formset.cleaned_data:\n # if len(device) != 0:\n # print(device['isn'], isn_check(isn=device['isn']))\n #print(formset.errors)\n\n if form.is_valid() and formset.is_valid():\n return self.form_valid(request, form, formset)\n else:\n return self.form_invalid(form, formset)\n\n def get_formp(self):\n return self.formp\n\n def get_formc(self):\n return self.formc\n\n def get_formset_class(self):\n return self.formset_class\n\n def get_formset(self, formset_class):\n return formset_class(**self.get_formset_kwargs())\n\n def get_formset_kwargs(self):\n kwargs = {\n 'instance': self.object\n }\n if self.request.method in ('POST', 'PUT'):\n kwargs.update({\n 'data': self.request.POST,\n 'files': self.request.FILES,\n })\n return kwargs\n\n def get_form_kwargs(self, *args, **kwargs):\n form_kwargs = super(FormsetMixin, self).get_form_kwargs(*args, **kwargs)\n if self.request.user.is_authenticated():\n form_kwargs['user'] = self.request.user\n form_kwargs['edit'] = self.edit\n return form_kwargs\n\n def form_valid(self, request, form, formset):\n faship = form.save(commit=False)\n if request.user.is_authenticated():\n faship.owner = request.user\n\n self.object = form.save() #faship.save()\n formset.instance = self.object\n formset.save()\n\n #更新 sfis 訊息\n device_items = Device.objects.filter(faship=faship)\n try:\n sfis_update(device_items=device_items)\n except Exception as e:\n raise e\n\n #TODO(yichieh) 因為資料庫設計不好,導致需要先從 request 拿資料\n pegadri_group = request.POST.getlist('pega_dri_mail_group')\n recipient_group = request.POST.getlist('recipient_mail_group')\n if len(pegadri_group) >= 1:\n cc = [Pegadri.objects.get(id=n).email for n in pegadri_group]\n else:\n cc = []\n if len(recipient_group) >= 1:\n rcc = [Cocodri.objects.get(id=n).email for n in recipient_group]\n else:\n rcc = []\n try:\n #raise Exception #for debug\n send_faship_email_task.delay(pk=faship.id, cc=cc+rcc)\n except Exception as e:\n send_faship_email(pk=faship.id, cc=cc)\n\n return redirect(self.object.get_absolute_url())\n \n def form_invalid(self, form, formset):\n return self.render_to_response(self.get_context_data(form=form, formset=formset))\n\n def send_email(self, pk, edit=False):\n return send_faship_email(pk=pk)\n #return send_faship_email_task.delay(pk=pk)\n\n\nclass FashipCreateView(FormsetMixin, CreateView):\n template_name = 'faships/faship_formset.html'\n model = Faship\n form_class = FashipForm\n formset_class = FashipFormSet\n formp = AddpegadriForm\n formc = AddcocodriForm\n\n #def form_valid(self, form):\n # form.send_email()\n # return super(FashipCreateView, self).form_valid(form)\n\n # 這邊要設定權限是關於只有開通權限的人才能進來\n #@method_decorator(permission_required('faships.delete_faship', login_url='/accounts/login/'))\n #def dispatch(self, *args, **kwargs):\n # return super(FashipCreateView, self).dispatch(*args, **kwargs)\n\n\nclass FashipUpdateView(FormsetMixin, UpdateView):\n from django.http import Http404\n template_name = 'faships/faship_formset.html'\n is_update_view = True\n model = Faship\n form_class = FashipForm\n formset_class = FashipFormSet\n formp = AddpegadriForm\n formc = AddcocodriForm\n\n # 這邊要設定權限是關於只有開通權限的人才能進來\n @method_decorator(permission_required('faships.delete_faship', login_url='/pages/403/'))\n def dispatch(self, *args, **kwargs):\n return super(FashipUpdateView, self).dispatch(*args, **kwargs)\n\n\nclass FashipList(ListView):\n\n model = Faship\n paginate_by = 6\n\n\nclass FashipDetail(DetailView):\n\n model = Faship\n\n\nclass DeviceList(ListView):\n\n model = Device\n paginate_by = 6\n\n\nclass DeviceDetail(DetailView):\n\n model = Device\n\n\n# test celery job\ndef smail(request):\n #print(add.delay(1,1).get)\n from django.conf import settings\n import os\n print(os.path.join(os.path.join(settings.BASE_DIR, 'templates'), 'base'))\n return render(request, 'faships/finish.html')\n\n","sub_path":"faships/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"273006298","text":"#User function Template for python3\n\n'''complete function to search pattern in the given string\n p: pattern given in input\n s: string given in the input'''\ndef search(p,s):\n #code here\n \n if s.find(p) > -1 :\n return True\n \n return False\n\n\n\n#{ \n# Driver Code Starts\n#Initial Template for Python 3\n\nimport atexit\nimport io\nimport sys\n\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n\n@atexit.register\n\ndef write():\n sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n\nif __name__=='__main__':\n t = int(input())\n for i in range(t):\n s=str(input())\n p=str(input())\n if(search(p,s)):\n print(\"Yes\")\n else:\n print(\"No\")\n# } Driver Code Ends","sub_path":"Strings/Naive Pattern Search.py","file_name":"Naive Pattern Search.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"471766329","text":"import requests\r\nfrom nonebot import on_command, CommandSession\r\n\r\n@on_command('/cat', aliases=('\\\\cat', '!cat'), only_to_me=False)\r\nasync def cat(session: CommandSession):\r\n url = \"https://api.thecatapi.com/v1/images/search\"\r\n r = requests.get(url)\r\n picurl = r.json()[0][\"url\"]\r\n await session.send(f\"[CQ:image,file={picurl}]\")\r\n \r\n","sub_path":"custom/cat.py","file_name":"cat.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"107359550","text":"\ndef Run(**kwargs): \n \"\"\"\n [Essential]\n \"Load params from 'CONFIG_FOLDER_PATH/EMB_PARAMS_FILE_NAME'\"\n CONFIG_FOLDER_PATH; (e.g.) '/path/to/CONFIG'\n DATA_FOLDER_PATH; (e.g.) '/path/to/DATA/'\n RESULT_FOLDER_PATH; (e.g.) '/path/to/RESULT'\n PROJECT_NAME; (e.g.) 'project'\n EMB_PARAMS_FILE_NAME; (e.g.) 'EMB_PARAMS.txt'\n DATASETS_INFO; dataset.info\n SKIP_EDGE_EXTRACTING; (e.g.) True\n NEW_GAME; (e.g) False \n \n ######################### ALL PARAMS ##############################\n \n [basics]\n CONFIG_FOLDER_PATH; (e.g.) '/path/to/CONFIG'\n DATA_FOLDER_PATH; (e.g.) '/path/to/DATA/'\n RESULT_FOLDER_PATH; (e.g.) '/path/to/RESULT'\n PROJECT_NAME; (e.g.) 'project'\n CDM_DB_NAME; (e.g.) 'cdm_db_name'\n EMB_PARAMS_FILE_NAME; (e.g.) 'EMB_PARAMS.txt'\n \n [runtime_params]\n DATASETS; a dataset object\n SKIP_EDGE_EXTRACTING; (e.g.) True\n NEW_GAME; (e.g) False \n \n [model_params]\n # about edge_extracting\n LEFT_CONTEXT_SIZE; (e.g.) 2\n RIGHT_CONTEXT_SIZE; (e.g.) 2\n DIRECTED; (e.g.) False\n\n MODEL_ARCH; (e.g.) ['LINE_MODEL']\n BATCH_SIZE; (e.g.) [128]\n EMB_SIZE; (e.g.) [32, 64]\n \n # about emb_model\n MODEL_ARCH; (e.g.) [LINE_MODEL]\n BATCH_SIZE; (e.g.) [128]\n EMB_SIZE; (e.g.) [32, 64]\n LR_p1; (e.g.) [5e-1, 5e-2]\n LR_p2; (e.g.) [5e-2]\n DECAY_STEPS; (e.g.) [1000]\n DECAY_RATE; (e.g.) [0.9]\n TRAIN_STEPS_p1; (e.g.) [1000]\n TRAIN_STEPS_p2; (e.g.) [1000]\n PRINT_BY; (e.g.) [2000]\n \"\"\"\n from .utils import get_logger_instance, option_printer, dumpingFiles, loadingFiles, get_param_dict\n from .model import get_model_list\n from .train import Train_model_list\n from .report import Get_datasets_info\n from .emb_dataset import Get_emb_dataset\n import os, glob\n import logging, datetime\n from importlib import reload\n \n ## get params\n param_dict = get_param_dict(kwargs['EMB_PARAMS_FILE_NAME'], kwargs['CONFIG_FOLDER_PATH'])\n param_dict.update(kwargs)\n \n param_dict['DUMPING_PATH'] = os.path.join(param_dict['RESULT_FOLDER_PATH'], \n param_dict['PROJECT_NAME'], \n param_dict['DATASETS_INFO']['CDM_DB_NAME'])\n \n if param_dict['NEW_GAME']:\n print(\"[!!] Are you sure NEW_GAME is True?; \\n\\t(REMOVE ALL RESULTS AND START OVER)\")\n confirm = input()\n if confirm.lower() in ['y', 'yes', 'true']:\n print(\"\\n\\t(NEW_GAME => True)\")\n import shutil, glob, os\n _ = [shutil.rmtree(p) for p in glob.glob(param_dict['DUMPING_PATH'])] #remove param_dict['DUMPING_PATH']\n else:\n print(\"\\n\\t(NEW_GAME => False)\")\n param_dict['NEW_GAME'] = False \n\n if not os.path.exists(param_dict['DUMPING_PATH']): \n os.makedirs(param_dict['DUMPING_PATH'])\n \n ## logger\n logging.shutdown()\n reload(logging)\n main_logger = get_logger_instance(logger_name='emb_pipeline', \n DUMPING_PATH=param_dict['DUMPING_PATH'], \n parent_name=False,\n stream=True)\n \n ## print options\n main_logger.info(\"\\n (params) \\n\")\n option_printer(main_logger, **param_dict)\n main_logger.info(\"=\"*100 + \"\\n\")\n \n ## [1] Make datasets for emb\n param_dict['EMB_DATASETS'] = Get_emb_dataset(**param_dict)\n param_dict['EMB_DATASETS'].info['PROJECT_NAME'] = param_dict['PROJECT_NAME']\n param_dict['EMB_DATASETS'].info['CDM_DB_NAME'] = param_dict['DATASETS_INFO']['CDM_DB_NAME']\n \n main_logger.info(\"\\n[Emb_dataset Info.]\\n\")\n option_printer(main_logger, **param_dict['EMB_DATASETS'].info)\n main_logger.info(\"=\"*100 + \"\\n\")\n \n ## [2] Make Models\n main_logger.info(\"\\n[EMB_model Setting]\\n\")\n model_list = get_model_list(param_dict)\n main_logger.info(\"=\"*100 + \"\\n\")\n \n ## [3] Train Models\n Train_model_list(MODEL_LIST = model_list,\n DATASETS = param_dict['EMB_DATASETS'],\n DUMPING_PATH = param_dict['DUMPING_PATH'], \n new_game = param_dict['NEW_GAME'])\n main_logger.info(\"=\"*100 + \"\\n\")\n \n ## [4] Get Results\n main_logger.info(\"\\n[Model_results]\\n\")\n df_emb_results = loadingFiles(main_logger, param_dict['DUMPING_PATH'], 'df_emb_RESULTS.pkl')\n \n main_logger.info(\"\\nALL DONE!!\")\n for h in list(main_logger.handlers):\n main_logger.removeHandler(h)\n h.flush()\n h.close()\n return df_emb_results\n ","sub_path":"build/lib/medterm2vec/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"266717201","text":"#!/usr/bin/env python\n\nfrom __future__ import (absolute_import, unicode_literals,\n division, print_function)\n\nimport sys\n\nfrom .cli4 import cli4\n\n\ndef main(args=None):\n if args is None:\n args = sys.argv[1:]\n cli4(args)\n\nif __name__ == '__main__':\n main()\n","sub_path":"cli4/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"179524846","text":"from os import environ\n\nPORT = '3031'\nAPI_VERSION = 'v1'\nLOG_LEVEL = environ.get('LOG_LEVEL') or 'INFO'\n\nHOST = environ.get('HOST', '0.0.0.0')\nSQLALCHEMY_DATABASE_URI = environ.get('DATABASE_URL')\n\n# Flask-Restplus settings\nRESTPLUS_VALIDATE = environ.get('API_VALIDATE', True)\nSWAGGER_PATH = environ.get('SWAGGER_PATH', '/api-docs/')\n\ndef get_var(var_name, default=None):\n if var_name in environ:\n return environ[var_name]\n\n return globals().get(var_name, default)","sub_path":"app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"150283890","text":"import scrapy\n\nfrom myproject.items import Page\nfrom myproject.utils import get_content\n\n\nclass BroadSpider(scrapy.Spider):\n name = \"broad\"\n start_urls = (\n # はてなブックマークの新着エントリーページ。\n 'https://b.hatena.ne.jp/hotentry/it',\n )\n\n def parse(self, response):\n \"\"\"\n はてなブックマークの新着エントリーページをパースする。\n \"\"\"\n\n # 個別のWebページへのリンクをたどる。\n for url in response.css('a.js-keyboard-openable::attr(\"href\")').extract():\n # parse_page() メソッドをコールバック関数として指定する。\n yield scrapy.Request(url, callback=self.parse_page)\n\n # of=の値が2桁である間のみ「次の20件」のリンクをたどる(最大5ページ目まで)。\n url_more = response.css('a::attr(\"href\")').re_first(r'.*\\?of=\\d{2}$')\n if url_more:\n # url_moreの値は /entrylist で始まる相対URLなので、\n # response.urljoin()メソッドを使って絶対URLに変換する。\n # コールバック関数を指定していないので、レスポンスはデフォルト値である\n # parse()メソッドで処理される。\n yield scrapy.Request(response.urljoin(url_more))\n\n def parse_page(self, response):\n \"\"\"\n 個別のWebページをパースする。\n \"\"\"\n\n # utils.pyに定義したget_content()関数でタイトルと本文を抽出する。\n title, content = get_content(response.text)\n # Pageオブジェクトを作成してyieldする。\n yield Page(url=response.url, title=title, content=content)","sub_path":"myproject/myproject/spiders/broad.py","file_name":"broad.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"569986952","text":"from bs4 import BeautifulSoup\nimport csv\n\n\"\"\"\n#debug\nfile = open('output.txt', \"r\")\nhtml = file.read()\nfile.close()\n\"\"\"\n\ndef htmlParsing(html):\n #print(html)\n soup = BeautifulSoup(html, 'html.parser')\n div = soup.find('div', id = \"dati\")\n nome = div.find('b')\n nome = nome.text\n table = soup.select_one(\"table\")\n #print(table)\n headers = [th for th in table.select(\"tr\")]\n \n # mese, giorno, pioggia mm, ...\n row = [th.text.strip() for th in headers[0].select(\"th\")]\n new_row = []\n for i in range(len(row)):\n row[i].strip().replace(\"\\n\", \"\") \n new_row.append(\" \".join(row[i].split()))\n new_row.append(nome) \n #dati \n dati = [[td.text for td in row.find_all('td')] for row in table.select(\"tr\")] \n \n\n for a in range(0, len(dati)):\n for j in range(len(dati[a])):\n dati[a][j] = dati[a][j].strip().replace(\"\\n\", \"\") \n dati[a][j] = \" \".join(dati[a][j].split()) \n if (dati[a][j] == '-'):\n dati[a][j] = ''\n \n \n\n \n #write a csv file\n with open(\"hmtlSel.csv\", \"w\") as f:\n wr = csv.writer(f)\n wr.writerow(new_row) \n wr.writerows(dati) \n f.close()\n return\n\n\n#htmlParsing(html)\n","sub_path":"seleniumProject/Friuli/chrome_version/htmlParsing.py","file_name":"htmlParsing.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"23262491","text":"# preprocess lines to data file\n# data file stores a tuple (lines, seq_len, words, map)\n# lines is a matrix of LINES x SEQLEN, zero padding, presenting words\n# seq_len is a vector of length of each line\n# words are list of words (character)\n# map is a reverse map of words to index\n# args: \n\nimport sys\nimport pickle\nimport numpy as np\nfrom itertools import islice, tee\nfrom config import *\nfrom util import tictoc\n\n@tictoc('preprocess')\ndef preprocess(lines):\n pool = ''.join(lines)\n chars = list(set(pool))\n freq = [ (i, pool.count(x)) for i, x in enumerate(chars) ]\n freq.sort(key=lambda x: -x[1])\n\n picks = [ UNK, GOS, EOL ]\n picks.extend([ chars[x[0]] for x in freq ])\n maps = { x: i for i, x in enumerate(picks) }\n\n def transChar(x):\n if x in maps:\n return maps[x]\n return maps[UNK]\n\n def transLine(line):\n l = [maps[GOS]]\n l.extend(list(map(transChar, line)))\n l.extend([ maps[EOL] ] * (SEQLEN + 1 - len(l)))\n return l\n\n lines = filter(lambda x: len(x) < SEQLEN, lines)\n l1, l2 = tee(lines)\n\n seq_len = np.array(list(map(lambda x: len(x) + 1, l1)), dtype=np.int32)\n lines = np.array(list(map(transLine, l2)), dtype=np.int32)\n\n print('{} records'.format(lines.shape[0]))\n\n return lines, seq_len, picks, maps\n\ndef data(path):\n with open(path, encoding=\"utf-8\") as f:\n lines = [ l.strip() for l in f ]\n return preprocess(lines)\n\nif __name__ == '__main__':\n out = data(sys.argv[1])\n with open(sys.argv[2], 'wb') as f:\n pickle.dump(out, f)\n","sub_path":"preprocess2.py","file_name":"preprocess2.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"454750794","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom lib.paginator import *\nfrom lib.utils import *\nfrom handler.base import *\nfrom models.feed import Feed\nfrom models.topic import Topic\nfrom sqlalchemy import desc\n\n\nclass IndexHandler(BaseHandler):\n @tornado.web.authenticated\n def get(self,template_variables={}):\n feedid = self.get_argument('feedid','')\n template_variables['feedid'] = feedid\n template_variables['session'] = self.session\n self.render('admin/topics/index.html',**template_variables)\n\n\nclass DataHandler(BaseHandler):\n @tornado.web.authenticated\n def get(self,template_variables={}):\n p = self.get_argument('p',1)\n feedid = self.get_argument('feedid','')\n title = self.get_argument('title','')\n link = self.get_argument('link','')\n exception = self.get_argument('exception','')\n crawl = self.get_argument('crawl','')\n\n conditions = []\n conditions.append(Feed.id == Topic.feedid)\n\n if feedid: conditions.append(Feed.id == feedid)\n if title: conditions.append(Topic.title.like('%'+title+'%'))\n if link: conditions.append(Topic.link.like('%'+link+'%'))\n if crawl: conditions.append(Topic.crawl == crawl)\n\n if exception: \n if exception == 1:\n conditions.append(Topic.exception != '')\n else:\n conditions.append(Topic.exception == '')\n\n \n count = self.DB_Session.query(Feed,Topic).filter(*conditions).count()\n page = Paginator(30,count,p,self.request.uri)\n topics = self.DB_Session.query(Feed.title.label('feed'),Feed.url,Topic.id,Topic.title,Topic.link,Topic.description,Topic.exception,Topic.crawl).\\\n filter(*conditions).order_by(desc(Topic.id)).slice(page.startRow,page.stopRows).all()\n show = page.show()\n\n feeds = self.DB_Session.query(Feed).order_by(desc(Feed.id)).all()\n\n template_variables['s_feedid'] = feedid\n template_variables['s_title'] = title\n template_variables['s_link'] = link\n template_variables['s_exception'] = exception\n template_variables['s_crawl'] = crawl\n template_variables['topics'] = topics\n template_variables['feeds'] = feeds\n template_variables['show'] = show\n template_variables['filter_tags'] = filter_tags\n template_variables['title'] = \"Topics\"\n template_variables['session'] = self.session\n\n self.render('admin/topics/index.html',**template_variables)\n\n\nclass EditHandler(BaseHandler):\n @tornado.web.authenticated\n def get(self,template_variables={}):\n id = self.get_argument('id','')\n\n if id is None:\n return\n\n topic = self.DB_Session.query(Topic).filter(Topic.id == id).first()\n\n template_variables['title'] = \"Topics\"\n template_variables['session'] = self.session\n template_variables['topic'] = topic\n template_variables['errors'] = template_variables.get('errors')\n template_variables['stamp2time'] = stamp2time\n \n self.render('admin/topicEdit.html',**template_variables)\n\n @tornado.web.authenticated\n def post(self):\n id = self.get_argument('id','')\n title = self.get_argument('title','')\n link = self.get_argument('link','')\n exception = self.get_argument('exception','')\n description = self.get_argument('description','')\n body = self.get_argument('body')\n\n self.DB_Session.query(Topic).filter(Topic.id == id).update({\"title\":title,\"link\":link,\"exception\":exception,\\\n \"description\":description,\"body\":body})\n\n self.redirect(self.request.headers.get(\"Referer\"))\n\n\nclass BlukTrashHandler(BaseHandler):\n @tornado.web.authenticated\n def post(self,template_variables={}):\n checkboxes = self.get_arguments('checkboxes','')\n for id in checkboxes:\n self.DB_Session.query(Topic).filter(Topic.id == id).delete()\n\n self.redirect(self.request.headers.get(\"Referer\"))\n","sub_path":"handler/admin/topics.py","file_name":"topics.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"92900719","text":"\"\"\" Question 2 \"\"\"\n\n# Kate Lu\n# Kevin Jeong\n\n\ndef gcd(a: int, b: int) -> int:\n \"\"\" Return the greatest common divisor of a and b\n\n PRE-COND: a and b must be of type int\n POST-COND: error is raised if either of a or be is not int\"\"\"\n\n if type(a) is not int or type(b) is not int:\n raise ValueError('a and b must be non-zero integers')\n else:\n if a == 0:\n return b\n elif b == 0:\n return a\n elif a != 0 and b != 0 and abs(a) > abs(b):\n return gcd(b, a % b)\n else:\n return gcd(a, b % a)\n\n\ndef main():\n print(gcd(2, 3))\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"A5/q02.py","file_name":"q02.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"86496134","text":"## --*-- coding=utf-8 --*--\nimport threading\nimport requests\nimport time\nfrom queue import Queue\nfrom bs4 import BeautifulSoup as BS\nimport json\n\ndef main(urlqueue,filequeue):\n header={\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\"}\n\n reque1=Request_th(header,urlqueue,filequeue,\"reque1\")\n reque2=Request_th(header,urlqueue,filequeue,\"reque2\")\n reque3=Request_th(header,urlqueue,filequeue,\"reque3\")\n\n resop1=Resoper_th(filequeue,\"resop1\")\n resop2=Resoper_th(filequeue,\"resop2\")\n resop3=Resoper_th(filequeue,\"resop3\")\n\n # region ##start()\n reque1.start()\n reque2.start()\n reque3.start()\n # time.sleep(2)\n resop1.start()\n resop2.start()\n resop3.start()\n # endregion\n reque1.join()\n reque2.join()\n reque3.join()\n resop1.join()\n resop2.join()\n resop3.join()\n\n\nclass Request_th(threading.Thread):\n def __init__(self,header,urlqueue,filequeue,name):\n super().__init__()\n self.urlqueue=urlqueue\n self.filequeue=filequeue\n self.name=name\n self.header=header\n def run(self):\n print(\"%s---线程启动\"%self.name)\n while self.urlqueue.qsize()>0:\n try:\n url=self.urlqueue.get(False)\n req_str=requests.get(url,headers=self.header)\n if req_str.status_code==200:\n filetext=req_str.text\n self.filequeue.put(filetext)\n print(\"+++\"+str(self.filequeue.qsize()))\n # print(filetext)\n except Exception as ee:\n print(\"{}--线程结束\".format(self.name))\n break\n print(\"{}--线程结束\".format(self.name))\n\nclass Resoper_th(threading.Thread):\n def __init__(self,filequeue,name):\n super().__init__()\n self.name=name\n self.fileque=filequeue\n\n def run(self):\n print(\"%s线程启动\"%self.name)\n while True:\n try:\n print(\"--\"+str(self.fileque.qsize()))\n filetext=self.fileque.get(True,timeout=10)\n # print(\"12\")\n Textstr=BS(filetext,\"lxml\")\n lists=Textstr.select(\".cont-list .cont-item\")\n for list in lists:\n title=list.select(\".cont-list-editor\")[0].string\n concet=list.select(\".cont-list-title\")[0].string\n print(concet)\n\n # writejson={\"tile\":title,\"concet\":concet}\n # with open(\"C:\\\\Users\\\\Administrator\\\\Desktop\\\\读写\\\\犯贱.txt\",\"a+\",encoding=\"utf-8\") as fo:\n # fo.write(json.dumps(writejson,ensure_ascii=False,indent=2))\n # fo.write(\"\\n\")\n\n except Exception as ee:\n print(\"%s线程结束\"%self.name)\n break\n print(self.fileque.qsize())\n\nif __name__ == '__main__':\n timestart=time.time()\n url_start=\"http://www.fanjian.net/jiantu-{0}\"\n qstr_url=Queue(500)\n qstr_file=Queue(5000)\n for i in range(1,499):\n urlend=url_start.format(i)\n qstr_url.put(urlend)\n\n main(qstr_url,qstr_file)\n\n timeend=time.time()\n print(\"总消耗时间:{}\".format(timeend-timestart))","sub_path":"多线程爬取犯贱志/爬取.py","file_name":"爬取.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"263668812","text":"#downloadSMBC.py - Downloads every single smbc comic\n\nimport requests, os, bs4\n\ndir_to_store_comics = 'path\\\\to\\\\directory'\n\n#startg url\nurl = 'https://www.smbc-comics.com'\n\n#store comix on ./Desktop/smbc\nos.makedirs(dir_to_store_comics, exist_ok=True)\n\nwhile url != '':\n #download the page\n print('Downloading comic on %s' %url)\n res = requests.get(url)\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, \"html.parser\")\n\n #css selector .className\n date_ = soup.select('.cc-publishtime')[0]\n date_ = date_.getText()\n print(date_, '\\n')\n\n #css selector #id\n comics = soup.select('#cc-comic')\n comic_url = comics[0].get('src')\n comic_url = 'https://www.smbc-comics.com/' + comic_url\n\n #download the comic img file\n res = requests.get(comic_url)\n res.raise_for_status()\n\n #save the img to Desktop\\smbc\n img_file = open(os.path.join(dir_to_store_comics, os.path.basename(comic_url)), 'wb')\n for chunk in res.iter_content(10^5):\n img_file.write(chunk)\n img_file.close()\n\n prev_buttons = soup.select('.prev')\n\n if len(prev_buttons) != 0:\n target_prev_button = prev_buttons[0]\n url = target_prev_button.get('href')\n else:\n url = ''\n\nprint('Done.')","sub_path":"downloadSMBC.py","file_name":"downloadSMBC.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"176957925","text":"\nfrom account.models import Account\n\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\n# Create your models here.\n\nRECEIPT_STATUSES = {\n 'created': {\n 'value': 0,\n 'description': 'Receipt created'},\n 'recognition': {\n 'value': 1,\n 'description': 'Receipt to recognition'},\n 'not_recognized': {\n 'value': 2,\n 'description': 'Not recognized'},\n 'recognized_partially': {\n 'value': 3,\n 'description': 'Recognized partially'},\n 'recognized': {\n 'value': 4,\n 'description': 'Receipt recognized'},\n}\n\n\nclass Product(models.Model):\n raw_name = models.CharField(\n _('Raw name'),\n max_length=70,\n null=False)\n name = models.CharField(\n _('Name'),\n max_length=70,\n null=False)\n descr = models.TextField()\n\n class Meta:\n verbose_name = _('Product')\n verbose_name_plural = _('Products')\n\n\nclass Receipt(models.Model):\n RECEIPT_STATUS_CHOICES = (\n (v['value'], v['description']) for v in RECEIPT_STATUSES.values())\n\n account = models.ForeignKey(\n Account,\n verbose_name=_('Account'),\n related_name='receipts')\n issued_check = models.DateTimeField(\n _('Issued at'),\n null=True,\n blank=True,\n )\n created = models.DateTimeField(\n _('Loaded at'),\n auto_now_add=True\n )\n status = models.IntegerField(\n choices=RECEIPT_STATUS_CHOICES,\n default=RECEIPT_STATUSES['created'])\n deleted = models.BooleanField(\n 'Deleted receipt',\n default=False)\n\n class Meta:\n verbose_name = _('Receipt')\n verbose_name_plural = _('Receipts')\n ordering = ['-issued_check', '-created']\n\n\nclass ProductList(object):\n receipt = models.ManyToManyField(\n Receipt,\n verbose_name=_('Receipt'),\n related_name='product_list')\n product = models.ManyToManyField(\n Product,\n verbose_name=_('Product'),\n related_name='+')\n count = models.IntegerField(\n _('Count'),\n null=False,\n blank=False,\n default=1)\n price = models.DecimalField(\n _('Price'),\n max_digits=8,\n decimal_places=2)\n sum = models.DecimalField(\n _('Sum'),\n max_digits=8,\n decimal_places=2)\n\n class Meta:\n verbose_name = _('Product string')\n verbose_name_plural = _('Products list')\n unique_together = ('receipt', 'product')\n","sub_path":"apps/receipt/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"369971538","text":"\"\"\"empty message\n\nRevision ID: 3f3cf9d79dc7\nRevises: 1cb0c928e584\nCreate Date: 2018-12-26 20:20:53.139596\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '3f3cf9d79dc7'\ndown_revision = '1cb0c928e584'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('problem', sa.Column('category', sa.String(length=100), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('problem', 'category')\n # ### end Alembic commands ###\n","sub_path":"ELEPRO/migrations/versions/3f3cf9d79dc7_.py","file_name":"3f3cf9d79dc7_.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"538681422","text":"import numpy as np\r\nimport pandas as pd\r\n\r\ndef _make_gen(reader):\r\n b = reader(1024 * 1024)\r\n while b:\r\n yield b\r\n b = reader(1024*1024)\r\n\r\ndef _get_num_rows(file_name):\r\n # ... Calculate number of rows in a file\r\n # ... input: file_name as str - name of file to be calculated \r\n # ... output: num_lines as int - number of lines (rows) in a file\r\n f = open(file_name, 'rb')\r\n f_gen = _make_gen(f.raw.read)\r\n num_lines=sum(buf.count(b'\\n') for buf in f_gen )\r\n f.close()\r\n return num_lines\r\n\r\ndef _select_sample_lines(sample_size, file_lines_num):\r\n # ... Random mark of rows from dataset which shoul be selected\r\n # ... input: sample_size as int - number of lines which should be selected\r\n # ... file_lines_num as int - number of all lines in a file\r\n # ... output: keep_lines as [boolean] - array with shape equal to 'files_lines_num' where 'sample_size' items marked as True\r\n keep_lines=[False for x in range(file_lines_num)]\r\n keep_lines[0]=True\r\n keep_ix=np.random.choice(range(1,file_lines_num), sample_size, replace=False)\r\n for ix in keep_ix:\r\n keep_lines[ix]=True\r\n return keep_lines\r\n\r\ndef _get_sample(file_name):\r\n # ... Sample random selection: in case when dataset not more 500000 rows we use whole dataset\r\n # ... in case when dataset bigger then 500000 rows sample of 500000 items will be selected\r\n # ... (it is not high accurate way but much faster then another ones in case of big fitting datasets)\r\n # ... input: file_name as str - name of fit file\r\n # ... output: sample as str - data for fitting\r\n num_lines=_get_num_rows(file_name)\r\n sample=''\r\n max_sample=500000 # ... Ideally should be calculated based on free memory and file size\r\n with open(file_name,\"r+\") as f:\r\n clean_lines = (line.replace('\\t',',') for line in f)\r\n if num_lines>max_sample:\r\n keep_lines=_select_sample_lines(max_sample, num_lines)\r\n sample=list()\r\n for is_keep, line in zip(keep_lines, clean_lines):\r\n if is_keep:\r\n sample.append(line)\r\n sample='\\n'.join(sample)\r\n else:\r\n sample='\\n'.join(clean_lines)\r\n return sample\r\n\r\ndef _get_index(feature_vals):\r\n # ... Count location of max value in a list\r\n # ... input: feature_vals as [int] - list of 257 numbers where 256 first values are related feature values per vacancy\r\n # ... and last value is maximum value\r\n # ... output: counter as int - index of max value (if max value is related for two or more features then lowest index will be chosen)\r\n max_val=feature_vals[256]\r\n counter=1\r\n for val in feature_vals:\r\n if val==max_val:\r\n return counter\r\n break\r\n counter+=1\r\n else: \r\n raise Exception('Max value was not found')\r\n\r\n\r\ndef _get_max_data(data, scaler):\r\n # ... Calculate index of max feature value and related absolute deviation\r\n # ... input: data as pd.DataFrame - dataFrame with feature data\r\n # ... scaler as object - already fitted scaler object\r\n # ... output: data as pd.DataFrame - dataFrame with two columns which contain max feature index and related absolute deviation\r\n data['max_feature_2']=data.max(axis=1)\r\n data['max_feature_2_index']=data.apply(_get_index, axis=1)\r\n mean_vals=scaler.mean_vals.to_dict()\r\n data['max_val_feature']=data.max_feature_2_index.map(lambda x: 'feature_2_'+str(x))\r\n data['max_feature_2_abs_mean_diff']=(data.max_feature_2-data.max_val_feature.map(mean_vals)).round(2)\r\n data=data[['max_feature_2_index', 'max_feature_2_abs_mean_diff']]\r\n return data\r\n \r\ndef convert_data(data, scaler, features, file):\r\n # ... Convert data to output format amd append to a file\r\n # ... input: data as pd.DataFrame - dataFrame with job id, feature code and 256 features\r\n # ... scaler as object - already fitted scaler object\r\n # ... features as [str] - list of feature columns\r\n # ... file as file - opened file object to append data\r\n max_data=_get_max_data(data[features], scaler)\r\n max_data=max_data.astype(str)\r\n scaled_data=scaler.transform(data[features]).round(5)\r\n scaled_data=scaled_data.astype(str)\r\n scaled_data_str=scaled_data.apply(lambda x: ','.join([y for y in x]), axis=1)\r\n del scaled_data\r\n res_data=data[['id_job']].astype(str)\r\n res_data['feature_2_stand']=scaled_data_str\r\n for x in list(max_data.columns):\r\n res_data[x]=max_data[x]\r\n\r\n res_data=res_data.apply(lambda x: '\\t'.join([y for y in x]), axis=1)\r\n res_data='\\n'.join(list(res_data))\r\n file.write(res_data)\r\n\r\ndef write_features(features, file):\r\n # ... Append feature names to a file\r\n # ... input: features as [str] - list of feature columns\r\n # ... file as file - opened file object to append data\r\n features='\\t'.join(features)\r\n file.write(features)\r\n\r\ndef write_data(file_name, scaler, features, input_cols):\r\n # ... Transform data and write them into a file \r\n # ... input: file_name as str - file name of dataset to transform\r\n # ... scaler as object - already fitted scaler object\r\n # ... features as [str] - list of feature columns\r\n # ... input_cols as [str] - list of columns related to input dataframe\r\n num_lines=_get_num_rows(file_name)\r\n max_chunk_size=500000 # ... Ideally should be calculated based on free memory and file size\r\n res=open('test_proc.tsv',\"w+\")\r\n write_features(['id_job', 'feature_2_stand', 'max_feature_2_index', 'max_feature_2_abs_mean_diff'], res)\r\n \r\n with open(file_name,\"r+\") as f:\r\n clean_lines = (line.replace('\\t',',') for line in f)\r\n chunk=list()\r\n cur_chunk_size=0\r\n is_first_chunk=1\r\n for line in clean_lines:\r\n chunk.append(line)\r\n cur_chunk_size+=1\r\n if cur_chunk_size==max_chunk_size: # ... convert chunks and append them to a file\r\n data=pd.read_csv(pd.compat.StringIO('\\n'.join(chunk)), sep=\",\", header=None, names=input_cols, skiprows=is_first_chunk)\r\n convert_data(data, scaler, features, res)\r\n print(str(data.shape[0])+'rows transformed')\r\n is_first_chunk=0\r\n cur_chunk_size=0\r\n chunk=list()\r\n \r\n \r\n if len(chunk)>0: # ... convert last chunk and append it to a file\r\n data=pd.read_csv(pd.compat.StringIO('\\n'.join(chunk)), sep=\",\", header=None, names=input_cols, skiprows=is_first_chunk)\r\n convert_data(data, scaler, features, res)\r\n print(str(data.shape[0])+'rows transformed')\r\n \r\n res.close()\r\n print('Done')\r\n\r\nclass Z_scaler():\r\n # ... Z-scale object\r\n # ... properties: mean_vals as pd.Series - mean values for each feature\r\n # ... std_vals as pd.Series - standard deviation values for each feature\r\n \r\n def __init__(self):\r\n # ... Initialize object\r\n mean_vals=pd.Series()\r\n std_vals=pd.Series()\r\n \r\n def fit(self, data):\r\n # ... Calculate mean and standard deviation values\r\n # ... input: data as pd.DataFrame - dataset to get mean and standard deviation values\r\n self.mean_vals=data.mean()\r\n self.std_vals=data.std()\r\n \r\n def transform(self, data):\r\n # ... Standardize data\r\n # ... input: data as pd.DataFrame - dataset to standardized\r\n # ... output: data as pd.DataFrame - standardized data\r\n data=(data-self.mean_vals)/self.std_vals\r\n return data\r\n \r\n def fit_transform(self, data):\r\n # ... Calculate mean and standard deviation values and standardized data\r\n # ... input: data as pd.DataFrame - dataset to get mean and standard deviation values and to be standardized\r\n # ... output: data as pd.DataFrame - standardized data\r\n self.fit(data)\r\n data=self.transform(data)\r\n return data\r\n\r\nclass Processing():\r\n # ... Object to process data\r\n # ... properties: scaler as object - scaler to use to standardize data\r\n # ... features as [str] - list of features\r\n # ... cols as [str] - list of columns related to input dataframe\r\n \r\n def __init__(self, feature_scaling_type='z_scale'):\r\n # ... Initialing\r\n # ... input: feature_scaling_type as str - type of scaler:\r\n # ... z_scale - standard z-scaling\r\n self.features=['feature_2_'+str(x) for x in range(1,257)]\r\n self.cols=['id_job', 'feature_id']+self.features\r\n if feature_scaling_type=='z_scale':\r\n self.scaler=Z_scaler()\r\n else:\r\n raise Exception('Unknown feature scaling_type')\r\n \r\n def fit(self, file_name):\r\n # ... Fit scaler\r\n #... input: file_name as str - name of file used for fitting\r\n data=pd.read_csv(pd.compat.StringIO(_get_sample(file_name)), sep=\",\", header=None, names=self.cols, skiprows=1)\r\n self.scaler.fit(data[self.features])\r\n \r\n def transform(self, file_name):\r\n # ... Tranform data\r\n #... input: file_name as str - name of file used for scaling\r\n write_data(file_name, self.scaler, self.features, self.cols)\r\n \r\n def fit_tranform(self, file_name):\r\n # ... Tranform data\r\n #... input: file_name as str - name of file used for scaling and which will be transformed\r\n self.fit(file_name)\r\n self.transform(file_name)\r\n","sub_path":"processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":9811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"603472479","text":"\"\"\"Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:\n o produto do dobro do primeiro com metade do segundo .\n a soma do triplo do primeiro com o terceiro.\n o terceiro elevado ao cubo. \"\"\"\n\na = int(input(\"Digite um numero inteiro: \"))\nb = int(input(\"Digite outro numero inteiro: \"))\nc = float(input(\"Digite um numero real: \"))\n\nx1 = (a*2) * (b/2) #o produto do dobro do primeiro com metade do segundo\nx2 = (a*3) + c #a soma do triplo do primeiro com o terceiro.\nx3 = (c**3) #o terceiro elevado ao cubo\n\nprint(\"O produto do dobro do primeiro com a metade do segundo é: {}\".format(x1))\nprint(\"A soma do triplo do primeiro com o terceiro é: {}\".format(x2))\nprint(\"O terceiro elevado ao cubo é: {}\".format(x3))","sub_path":"Estrutura_Sequencial/Exercicio11_Produto.py","file_name":"Exercicio11_Produto.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"594611319","text":"def collatz(num):\r\n #determine if odd or even\r\n if num % 2 == 0:\r\n #num is even\r\n print(num // 2)\r\n return(num //2)\r\n else:\r\n #num is odd\r\n print(num * 3 + 1)\r\n return(num * 3 + 1)\r\n\r\n\r\ngoodInput = False\r\n\r\nwhile goodInput == False:\r\n try:\r\n num = int(input(\"Enter a number\"))\r\n goodInput = True\r\n except ValueError:\r\n print(\"You need to enter a numerical value.\")\r\n\r\nwhile num != 1:\r\n num = collatz(num)","sub_path":"Chapter 03/Collatz/Collatz.py","file_name":"Collatz.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"110219211","text":"#!/usr/bin/env python\nimport sys\nimport os\nfrom subprocess import Popen\n\nroot_dir = os.path.dirname(os.path.realpath(__file__))\npd_dir = os.path.join(root_dir, 'of-tests')\n\noft_path = os.path.join(root_dir, '..', '..', 'submodules', 'oft-infra', 'oft')\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n args += [\"--pd-thrift-path\", pd_dir]\n args += [\"--enable-erspan\", \"--enable-vxlan\", \"--enable-geneve\"]\n child = Popen([oft_path] + args)\n child.wait()\n sys.exit(child.returncode)\n","sub_path":"tools/new_target_template/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"53024623","text":"import os\nfrom contextlib import contextmanager\n\nfrom liblcp import configuration as liblcp_config\n\nimport configuration\n\nconfiguration_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, 'configuration')\n\n\n@contextmanager\ndef configured_for(environment=''):\n configuration_file = os.path.abspath(os.path.join(configuration_path, environment, 'list_loading_service.cfg'))\n configuration.configure_from(configuration_file)\n liblcp_config_data = {}\n try:\n execfile(os.path.abspath(os.path.join(configuration_path, environment, 'servicecontainer.cfg')),\n liblcp_config_data)\n except IOError:\n execfile(os.path.abspath(os.path.join(configuration_path, 'servicecontainer.cfg')), liblcp_config_data)\n liblcp_config.set_configuration(liblcp_config_data)\n yield\n","sub_path":"fabfile/app_configuration.py","file_name":"app_configuration.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"197494502","text":"import pymssql\nimport pandas as pd\nimport h5py\nimport sys\nimport Log\nimport os\nimport numpy as np\nfrom configparser import RawConfigParser\nimport datetime\n\nfrom DataSender.ExcelHelper import ExcelHelper\nfrom DataService.JYDataLoader import JYDataLoader\nfrom DataSender.EmailHelper import EmailHelper\n\n# 显示所有列\npd.set_option('display.max_columns', None)\n# 显示所有行\npd.set_option('display.max_rows', None)\n\nfrom enum import Enum\n\n\nclass IdType(Enum):\n clientId = 1\n accountId = 2\n\n\nclass OrderReporter(object):\n def __init__(self, start, end, clientIds, accountIds):\n self.logger = Log.get_logger(__name__)\n self.tick_path = \"Y:/Data/h5data/stock/tick/\"\n self.server = \"172.10.10.7\"\n self.database = \"AlgoTradeReport\"\n self.user = \"algodb\"\n self.password = \"!AlGoTeAm_\"\n self.conn = None\n\n jyloader = JYDataLoader()\n tradingdays = jyloader.get_tradingday(start, end)\n clientIDs = list(clientIds.split(';'))\n accountIDs = list(accountIds.split(';'))\n self.email = EmailHelper.instance()\n all_ids = {IdType.clientId: clientIDs, IdType.accountId: accountIDs}\n self.run(tradingdays, all_ids)\n\n def get_connection(self):\n try:\n self.conn = pymssql.connect(self.server, self.user, self.password, self.database)\n return self.conn\n except pymssql.OperationalError as e:\n print(e)\n\n def get_receiveList(self, id_type, id):\n accountIds = []\n clientIds = []\n clientName = []\n to_receiver = []\n cc_receiver = []\n with self.get_connection() as conn:\n with conn.cursor(as_dict=True) as cursor:\n if id_type == IdType.clientId:\n stmt = f\"select * from Clients where clientId = \\'{id}\\'\"\n else:\n stmt = f\"select * from Clients where accountId = \\'{id}\\'\"\n cursor.execute(stmt)\n for row in cursor:\n accountIds.append(row['accountId'])\n clientIds.append(row['clientId'])\n clientName.append(row['clientName'])\n to_receiver.append(row['email'])\n cc_receiver.append(row['repsentEmail'])\n\n data = pd.DataFrame(\n {'accountId': accountIds, 'clientId': clientIds, 'clientName': clientName, 'to_receiver': to_receiver,\n 'cc_receiver': cc_receiver})\n return data\n\n def get_clientOrder(self, tradingday, id_type, id):\n \"\"\"\n get_clientOrder\n :param start: '20150101'\n :param end: '20150130'\n :return: df :\n \"\"\"\n orderId = []\n symbol = []\n side = []\n effectiveTime = []\n expireTime = []\n avgprice = []\n cumQty = []\n slipageByVwap = []\n algo = []\n orderQty = []\n orderStatus = []\n VWAP = []\n with self.get_connection() as conn:\n with conn.cursor(as_dict=True) as cursor:\n if id_type == IdType.clientId:\n stmt = f\"select * from ClientOrderView where orderQty>0 and (securityType='RPO' or securityType='EQA') and tradingDay = \\'{tradingday}\\' and clientId like \\'{id}\\'\"\n else:\n stmt = f\"select * from ClientOrderView where orderQty>0 and (securityType='RPO' or securityType='EQA') and tradingDay = \\'{tradingday}\\' and accountId like \\'{id}\\'\"\n cursor.execute(stmt)\n for row in cursor:\n orderId.append(row['orderId'])\n symbol.append(row['symbol'])\n side.append(row['side'])\n effectiveTime.append(row['effectiveTime'])\n expireTime.append(row['expireTime'])\n avgprice.append(row['avgPrice'])\n cumQty.append(row['cumQty'])\n slipageByVwap.append(row['slipageInBps'])\n algo.append(row['algo'])\n orderQty.append(row['orderQty'])\n orderStatus.append(row['orderStatus'])\n VWAP.append(row['iVWP'])\n\n data = pd.DataFrame({'orderId': orderId, 'symbol': symbol, 'side': side, 'effectiveTime': effectiveTime,\n 'expireTime': expireTime, 'avgPrice': avgprice, 'orderQty': orderQty, 'cumQty': cumQty,\n 'algo': algo, 'orderStatus': orderStatus, 'VWAP': VWAP, 'slipageByVWAP': slipageByVwap})\n\n data['cumQty'] = data['cumQty'].astype('int')\n data['avgPrice'] = data['avgPrice'].astype('float')\n data['slipageByVWAP'] = data['slipageByVWAP'].astype('float')\n data['VWAP'] = data['VWAP'].astype('float')\n data['turnover'] = data['avgPrice'] * data['cumQty']\n return data\n\n def get_client_order_count(self, tradingday, id_type, id):\n orderId = []\n sliceStatus = []\n sliceCount = []\n\n with self.get_connection() as conn:\n with conn.cursor(as_dict=True) as cursor:\n if id_type == IdType.clientId:\n stmt = f\"SELECT a.orderId, sliceStatus, sliceCount FROM ClientOrderView a JOIN (SELECT orderId,orderStatus AS sliceStatus,COUNT (*) AS sliceCount FROM ExchangeOrderView WHERE orderStatus IN ('Filled', 'Canceled') GROUP BY orderId,orderStatus) b ON a.orderId = b.orderId WHERE a.tradingDay = \\'{tradingday}\\' AND a.clientId like \\'{id}\\' ORDER BY a.orderId\"\n else:\n stmt = f\"SELECT a.orderId, sliceStatus, sliceCount FROM ClientOrderView a JOIN (SELECT orderId,orderStatus AS sliceStatus,COUNT (*) AS sliceCount FROM ExchangeOrderView WHERE orderStatus IN ('Filled', 'Canceled') GROUP BY orderId,orderStatus) b ON a.orderId = b.orderId WHERE a.tradingDay = \\'{tradingday}\\' AND a.accountId like \\'{id}\\' ORDER BY a.orderId\"\n cursor.execute(stmt)\n for row in cursor:\n orderId.append(row['orderId'])\n sliceStatus.append(row['sliceStatus'])\n sliceCount.append(row['sliceCount'])\n\n data = pd.DataFrame({'orderId': orderId, 'sliceStatus': sliceStatus, 'sliceCount': sliceCount})\n data['sliceCount'] = data['sliceCount'].astype('int')\n return data\n\n def get_exchangeOrder(self, tradingday, id_type, id):\n \"\"\"\n get_clientOrder\n :param start: '20150101'\n :param end: '20150130'\n :return: df :\n \"\"\"\n sliceId = []\n orderId = []\n side = []\n symbol = []\n effectiveTime = []\n qty = []\n cumQty = []\n leavesQty = []\n price = []\n sliceAvgPrice = []\n orderStatus = []\n with self.get_connection() as conn:\n with conn.cursor(as_dict=True) as cursor:\n if id_type == IdType.clientId:\n stmt = f\"SELECT a.sliceId, a.orderId, b.side,b.symbol,a.effectiveTime,a.qty,a.cumQty,a.leavesQty,a.price,a.sliceAvgPrice,a.orderStatus from ExchangeOrderView a join ClientOrderView b on a.orderId=b.orderId where a.orderStatus in ('Filled','Canceled') AND b.tradingDay = \\'{tradingday}\\' AND b.clientId like \\'{id}\\'\"\n else:\n stmt = f\"SELECT a.sliceId, a.orderId, b.side,b.symbol,a.effectiveTime,a.qty,a.cumQty,a.leavesQty,a.price,a.sliceAvgPrice,a.orderStatus from ExchangeOrderView a join ClientOrderView b on a.orderId=b.orderId where a.orderStatus in ('Filled','Canceled') AND b.tradingDay = \\'{tradingday}\\' AND b.accountId like \\'{id}\\'\"\n cursor.execute(stmt)\n for row in cursor:\n sliceId.append(row['sliceId'])\n orderId.append(row['orderId'])\n symbol.append(row['symbol'])\n side.append(row['side'])\n effectiveTime.append(row['effectiveTime'])\n qty.append(row['qty'])\n leavesQty.append(row['leavesQty'])\n cumQty.append(row['cumQty'])\n sliceAvgPrice.append(row['sliceAvgPrice'])\n price.append(row['price'])\n orderStatus.append(row['orderStatus'])\n\n data = pd.DataFrame(\n {'sliceId': sliceId, 'orderId': orderId, 'symbol': symbol, 'side': side, 'effectiveTime': effectiveTime,\n 'qty': qty, 'cumQty': cumQty, 'leavesQty': leavesQty, 'price': price, 'sliceAvgPrice': sliceAvgPrice,\n 'orderStatus': orderStatus})\n\n data['cumQty'] = data['cumQty'].astype('int')\n if data['effectiveTime'].shape[0] > 0:\n data['effectiveTime'] = (data['effectiveTime'] + datetime.timedelta(hours=8)).map(\n lambda x: x.strftime('%H:%M:%S'))\n data.sort_values(by=['effectiveTime'], inplace=True)\n return data\n\n def read_symbol_tick(self, tradingday, symbol):\n with h5py.File(os.path.join(self.tick_path + tradingday + \".h5\"), 'r') as h5file:\n if symbol in h5file.keys():\n df_tick_symbol = pd.DataFrame({'Time': h5file[symbol]['Time'][:],\n 'Price': h5file[symbol]['Price'][:],\n 'AccTurnover': h5file[symbol]['AccTurnover'][:],\n 'AccVolume': h5file[symbol]['AccVolume'][:],\n 'Volume': h5file[symbol]['Volume'][:],\n 'BSFlag': h5file[symbol]['BSFlag'][:],\n 'BidAvgPrice': h5file[symbol]['BidAvgPrice'][:],\n 'High': h5file[symbol]['High'][:],\n 'Low': h5file[symbol]['Low'][:],\n 'MatchItem': h5file[symbol]['MatchItem'][:],\n 'Open': h5file[symbol]['Open'][:],\n 'PreClose': h5file[symbol]['PreClose'][:],\n 'TotalAskVolume': h5file[symbol]['TotalAskVolume'][:],\n 'TotalBidVolume': h5file[symbol]['TotalBidVolume'][:],\n 'Turnover': h5file[symbol]['Turnover'][:],\n 'AskAvgPrice': h5file[symbol]['AskAvgPrice'][:]})\n return df_tick_symbol\n else:\n self.logger.warn(\"there is no TickData (\" + symbol + \") in h5 file, please check your data\")\n return pd.DataFrame()\n\n def get_tick_by_symbol(self, tradingDay, symbol, startTime=90000000, endTime=160000000, price=0, side='Buy'):\n df_tick_symbol = self.read_symbol_tick(tradingDay, symbol)\n if df_tick_symbol.shape[0] == 0:\n return pd.DataFrame()\n if price == 0:\n return df_tick_symbol[(df_tick_symbol['Time'] >= startTime) & (df_tick_symbol['Time'] <= endTime) & (\n df_tick_symbol['Volume'] > 0)]\n else:\n if side == 'Buy' or side == 1:\n return df_tick_symbol[\n (df_tick_symbol['Time'] >= startTime) & (df_tick_symbol['Time'] <= endTime) & (\n df_tick_symbol['Volume'] > 0)]\n else:\n return df_tick_symbol[\n (df_tick_symbol['Time'] >= startTime) & (df_tick_symbol['Time'] <= endTime) & (\n df_tick_symbol['Volume'] > 0)]\n\n def get_twap(self, tradingDay, symbol, startTime=90000000, endTime=160000000, price=0, side='Buy'):\n data = self.get_tick_by_symbol(tradingDay, symbol, startTime, endTime, price, side)\n return data.Price.sum() / data.Volume.count() if data.size > 0 else 0\n\n def stat_summary(self, df, side, field):\n df = df[(df['side'] == side) & (df[field] != 0)]\n amt = sum(df['turnover'])\n if side == 'Buy':\n slipage = 0 if amt == 0 else sum((df[field] - df['avgPrice']) / df[field] * df['turnover']) / sum(\n df['turnover'])\n else:\n slipage = 0 if amt == 0 else sum((df['avgPrice'] - df[field]) / df[field] * df['turnover']) / sum(\n df['turnover'])\n pnl_yuan = slipage * amt\n return amt, slipage, pnl_yuan\n\n def run(self, tradingDays, dict_ids):\n def cal_twap(tradingDay, effectiveTime, expireTime, symbol, price, side, cumQty):\n if cumQty == 0:\n return 0\n effectiveTime = effectiveTime.hour * 10000000 + effectiveTime.minute * 100000 + effectiveTime.second * 1000\n expireTime = expireTime.hour * 10000000 + expireTime.minute * 100000 + expireTime.second * 1000\n self.logger.info(f'cal_twap-{tradingDay}-{effectiveTime}-{expireTime}-{symbol}-{price}-{side}')\n twap = self.get_twap(tradingDay, symbol, effectiveTime, expireTime, price, side)\n return twap\n\n def cal_twap_slipage(twap, side, avgprice):\n avgprice = np.float64(avgprice)\n slipageByTwap = 0.00 if twap == 0.00 else (\n (avgprice - twap) / twap if side == 'Sell' else (twap - avgprice) / twap)\n return slipageByTwap\n\n def cal_ocp(tradingDay, expireTime, symbol, cumQty):\n if cumQty == 0: return 0\n expireTime = expireTime.hour * 10000000 + expireTime.minute * 100000 + expireTime.second * 1000\n self.logger.info(f'cal_ocp-{tradingDay}-{expireTime}-{symbol}')\n tick = read_tick(symbol, tradingDay)\n tick = tick[tick['Time'] <= expireTime]\n return tick.tail(1).iloc[0, :]['Price']\n\n def cal_ocp_slipage(ocp, side, avgprice):\n avgprice = np.float64(avgprice)\n slipageByOCP = 0.00 if ocp == 0.00 else (\n (avgprice - ocp) / ocp if side == 'Sell' else (ocp - avgprice) / ocp)\n return slipageByOCP\n\n def read_tick(symbol, tradingday):\n \"\"\"\n read tick data\n :param symbol: '600000.sh' str\n :param tradingday: '20170104' str\n :return: pd.DataFrame Time类型:93003000 int\n \"\"\"\n with h5py.File(os.path.join(self.tick_path, ''.join([tradingday, '.h5'])), 'r') as f:\n if symbol not in f.keys():\n raise Exception(f'{tradingday}_{symbol} tick 为空')\n time = f[symbol]['Time']\n if len(time) == 0:\n raise Exception(f'{tradingday}_{symbol} tick 为空')\n price = f[symbol]['Price']\n volume = f[symbol]['Volume']\n turnover = f[symbol]['Turnover']\n tick = pd.DataFrame(\n {'Time': time, 'Price': price, 'Volume': volume, 'Turnover': turnover})\n\n return tick\n\n for tradingDay in tradingDays:\n if not os.path.exists(os.path.join(self.tick_path, tradingDay + '.h5')):\n self.logger.error(f'{tradingDay} h5 tick is not existed.')\n continue\n for id_type, ids in dict_ids.items():\n for id in ids:\n self.logger.info(f'start calculator: {tradingDay}__{id_type}__{id}')\n clientOrders = self.get_clientOrder(tradingDay, id_type, id)\n if clientOrders.size == 0:\n continue\n df_client_order_count = self.get_client_order_count(tradingDay, id_type, id)\n df_client_order_count['sliceStatus'] = df_client_order_count['sliceStatus'].map(\n lambda x: x + 'Count')\n df_client_order_count = df_client_order_count.pivot(index='orderId', columns='sliceStatus',\n values='sliceCount')\n clientOrders = clientOrders.merge(df_client_order_count, how='left', left_on='orderId',\n right_index=True)\n clientOrders.fillna(0, inplace=True)\n clientOrders.sort_values(by=['effectiveTime'], inplace=True)\n\n # 调整列顺序\n VWAPs = clientOrders.pop('VWAP')\n clientOrders.insert(clientOrders.shape[1], 'VWAP', VWAPs)\n slipageByVWAPs = clientOrders.pop('slipageByVWAP')\n clientOrders.insert(clientOrders.shape[1], 'slipageByVWAP', slipageByVWAPs)\n\n # 1.计算twap\n clientOrders['TWAP'] = clientOrders.apply(\n lambda x: cal_twap(tradingDay, x['effectiveTime'], x['expireTime'], x['symbol'], x['avgPrice'],\n x['side'], x['cumQty']), axis=1)\n\n # 2.计算slipageByTwap\n clientOrders['slipageByTWAP'] = clientOrders.apply(\n lambda x: cal_twap_slipage(x['TWAP'], x['side'], x['avgPrice']), axis=1)\n clientOrders.loc[clientOrders.loc[:, 'cumQty'] == 0, ['slipageByTWAP']] = 0.00\n clientOrders['TWAP'] = round(clientOrders['TWAP'], 5)\n clientOrders['slipageByTWAP'] = round(clientOrders['slipageByTWAP'] * 10000, 2)\n\n # 3.计算OrderClosePx\n clientOrders['OCP'] = clientOrders.apply(\n lambda x: cal_ocp(tradingDay, x['expireTime'], x['symbol'], x['cumQty']), axis=1)\n clientOrders['slipageByOCP'] = clientOrders.apply(\n lambda x: cal_ocp_slipage(x['OCP'], x['side'], x['avgPrice']), axis=1)\n clientOrders['slipageByOCP'] = round(clientOrders['slipageByOCP'] * 10000, 2)\n\n df_exchange_order = self.get_exchangeOrder(tradingday=tradingDay, id_type=id_type, id=id)\n\n buy_amt, buy_vwap_slipage, buy_pnl_vwap_yuan = self.stat_summary(clientOrders, 'Buy', 'VWAP')\n buy_amt, buy_twap_slipage, buy_pnl_twap_yuan = self.stat_summary(clientOrders, 'Buy', 'TWAP')\n buy_amt, buy_ocp_slipage, buy_pnl_ocp_yuan = self.stat_summary(clientOrders, 'Buy', 'OCP')\n\n sell_amt, sell_vwap_slipage, sell_pnl_vwap_yuan = self.stat_summary(clientOrders, 'Sell', 'VWAP')\n sell_amt, sell_twap_slipage, sell_pnl_twap_yuan = self.stat_summary(clientOrders, 'Sell', 'TWAP')\n sell_amt, sell_ocp_slipage, sell_pnl_ocp_yuan = self.stat_summary(clientOrders, 'Sell', 'OCP')\n\n df_summary = pd.DataFrame(\n {'Side': ['Buy', 'Sell'],\n 'FilledAmt(万元)': [round(buy_amt / 10000, 3), round(sell_amt / 10000, 3)],\n 'PnL2VWAP(BPS)': [round(buy_vwap_slipage * 10000, 2),\n round(sell_vwap_slipage * 10000, 2)],\n 'PnL2TWAP(BPS)': [round(buy_twap_slipage * 10000, 2),\n round(sell_twap_slipage * 10000, 2)],\n 'PnL2OCP(BPS)': [round(buy_ocp_slipage * 10000, 2),\n round(sell_ocp_slipage * 10000, 2)],\n 'PnL2VWAP(YUAN)': [round(buy_pnl_vwap_yuan, 2),\n round(sell_pnl_vwap_yuan, 2)],\n 'PnL2TWAP(YUAN)': [round(buy_pnl_twap_yuan, 2),\n round(sell_pnl_twap_yuan, 2)],\n 'PnL2OCP(YUAN)': [round(buy_pnl_ocp_yuan, 2),\n round(sell_pnl_ocp_yuan, 2)]\n }, index=[1, 2])\n\n df_receive = self.get_receiveList(id_type=id_type, id=id)\n df_receive['tradingDay'] = tradingDay\n\n self.email.add_email_content(f'ClientOrderReporter_{tradingDay}_({id})交易报告,请查收')\n fileName = f'OrderReporter_{tradingDay}_({id}).xlsx'\n pathCsv = os.path.join(f'Data/{fileName}')\n\n ExcelHelper.createExcel(pathCsv)\n clientOrders['effectiveTime'] = clientOrders['effectiveTime'].map(lambda x: x.strftime('%H:%M:%S'))\n clientOrders['expireTime'] = clientOrders['expireTime'].map(lambda x: x.strftime('%H:%M:%S'))\n ExcelHelper.Append_df_to_excel(file_name=pathCsv, df=df_summary, header=True,\n sheet_name='algoSummary', sep_key='all_name')\n ExcelHelper.Append_df_to_excel(file_name=pathCsv, df=clientOrders,\n header=True, sheet_name='algoClientOrder', sep_key='all_name')\n ExcelHelper.Append_df_to_excel(file_name=pathCsv, df=df_exchange_order,\n header=True, sheet_name='algoExchangeOrder', sep_key='all_name')\n ExcelHelper.removeSheet(pathCsv, 'Sheet')\n\n self.email.send_email_file(pathCsv, fileName, df_receive,id, subject_prefix='OrderReporter')\n self.email.content = ''\n self.logger.info(f'calculator: {tradingDay}__{id} successfully')\n\n\nif __name__ == '__main__':\n cfg = RawConfigParser()\n cfg.read('config.ini', encoding='utf-8')\n clientIds = cfg.get('OrderReporter', 'clientId')\n accountIds = cfg.get('OrderReporter', 'accountId')\n start = sys.argv[1]\n end = sys.argv[2]\n reporter = OrderReporter(start, end, clientIds, accountIds)\n","sub_path":"OrderReporter.py","file_name":"OrderReporter.py","file_ext":"py","file_size_in_byte":21756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"565175952","text":"import streamlit as st\r\nimport pickle\r\nst.title('Penguin Classifier')\r\nst.write(\"This app uses 6 inputs to predict the species of penguin using a \"\r\n\"model built on the Palmer's Penguin's dataset. Use the form below to get started!\")\r\n\r\n# load pickle files\r\nrf_pickle = open('random_forest_penguin.pickle', 'rb')\r\nmap_pickle = open('outout_penguin.pickle', 'rb')\r\nrfc = pickle.load(rf_pickle)\r\nunique_penguin_mapping = pickle.load(map_pickle)\r\nrf_pickle.close()\r\nmap_pickle.close()\r\n\r\n# user input\r\nisland = st.selectbox('Penguin Island', options=['Biscoe', 'Dream', 'Torgerson'])\r\nsex = st.selectbox('Sex', options=['Female', 'Male'])\r\nbill_length = st.number_input('Bill Length (mm)', min_value=0)\r\nbill_depth = st.number_input('Bill Depth (mm)', min_value=0)\r\nflipper_length = st.number_input('Flipper Length (mm)', min_value=0)\r\nbody_mass = st.number_input('Body Mass (g)', min_value=0)\r\n\r\nisland_biscoe, island_dream, island_torgerson = 0, 0, 0\r\n# mapping the island data\r\nif island == 'Biscoe':\r\n island_biscoe = 1\r\nelif island == 'Dream':\r\n island_dream = 1\r\nelif island == 'Torgerson':\r\n island_torgerson = 1\r\n\r\n# mapping the sex data\r\nsex_female, sex_male = 0, 0\r\nif sex == 'Female':\r\n sex_female = 1\r\nelif sex == 'Male':\r\n sex_male = 1\r\n\r\nif st.button(\"Classify!\"):\r\n new_prediction = rfc.predict([[bill_length, bill_depth, flipper_length,body_mass,\r\n island_biscoe, island_dream,island_torgerson, sex_female, sex_male]])\r\n prediction_species = unique_penguin_mapping[new_prediction][0]\r\n st.write('We predict your penguin is of the {} species'.format(prediction_species))\r\n","sub_path":"penguin_ml_streamlit.py","file_name":"penguin_ml_streamlit.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"95938914","text":"from datetime import datetime, timezone\nfrom unittest.mock import MagicMock, patch\n\nfrom django.core.management import call_command\nfrom django.test import override_settings, TestCase\n\nfrom skip.models import Alert, Topic\nfrom skip.parsers.gcn_circular_parser import GCNCircularParser\n\n\ntest_superevent_circular_message = {\n 'format': 'circular',\n 'content': {\n 'header': {\n 'TITLE': 'GCN CIRCULAR',\n 'NUMBER': '24442',\n 'SUBJECT': 'LIGO/Virgo S190510g: Identification of a GW compact binary merger candidate',\n 'DATE': '19/05/10 05:51:38 GMT',\n 'FROM': 'Eric Howell at Aus.Intl.Grav.Res.Centre/UWA '\n },\n 'body': 'The LIGO Scientific Collaboration and the Virgo Collaboration report: \\n\\ntest content'\n }\n}\n\n\nclass TestGCNCircularParser(TestCase):\n def setUp(self):\n topic = Topic.objects.create(name='gcn-circular')\n self.alert = Alert.objects.create(raw_message=test_superevent_circular_message, topic=topic)\n\n def test_parse(self):\n parser = GCNCircularParser(self.alert)\n parsed = parser.parse()\n\n self.assertTrue(parsed)\n self.assertDictContainsSubset({'title': 'GCN CIRCULAR', 'number': '24442'}, self.alert.parsed_message)\n self.assertEqual(datetime(2019, 5, 10, 5, 51, 38, tzinfo=timezone.utc), self.alert.timestamp)\n self.assertEqual('24442', self.alert.identifier)\n event = self.alert.events.first()\n self.assertTrue(event.identifier == 'S190510g')\n\n\n@override_settings(HOPSKOTCH_PARSERS={'gcn-circular': 'skip.parsers.gcn_circular_parser.GCNCircularParser'})\nclass TestGCNCircularIngestion(TestCase):\n def setUp(self):\n pass\n\n @patch('skip.management.commands.ingestmessages.Consumer')\n def test_ingest(self, mock_consumer):\n mock_message = MagicMock()\n mock_message.configure_mock(**{\n 'topic.return_value': 'gcn-circular',\n 'value.return_value': test_superevent_circular_message,\n 'error.return_value': None\n })\n # mock_message.topic.return_value = 'gcn-circular'\n # mock_message.value.return_value = test_superevent_circular_message\n # mock_message.error.return_value = None\n print(mock_message.error())\n print(mock_message.value())\n mock_consumer.poll.return_value = mock_message\n print(mock_consumer.poll().error())\n print(mock_consumer.poll().value())\n # mock_consumer = MockConsumer()\n # print(mock_consumer.poll(1).error())\n\n call_command('ingestmessages')\n # command = Command()\n # command.handle()\n","sub_path":"skip/tests/parsers/test_gcn_circular_parser.py","file_name":"test_gcn_circular_parser.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"429436404","text":"\"\"\"\n节点\n\"\"\"\n\n\nclass node(object):\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nn1 = node(1)\nn2 = node(2)\nn3 = node(3)\nn4 = node(4)\n\nn1.next = n2\nn2.next = n3\nn3.next = n4\n\nelement = n1\n\nwhile element:\n print(element.data)\n element = element.next\n","sub_path":"Example/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"304801831","text":"class Ship:\n def __init__(self, length:int, orientation:bool, prow:tuple):\n '''\n Description.\n a ship is defined by:\n - its length\n - its orientation (0 horizontal, 1 vertical)\n - its front cell (or prow, \"proue\" en français) in the form (y-axis value, x-axis value).\n Notes.\n - for the computations, cell positions are tuple of the form (y-axis value, x-axis value).\n - we use sets to store the different cell positions as they are useful to compute intersections, unions, ...\n '''\n self.length = length\n self.orientation = orientation\n self.prow = prow\n self.set_position()\n self.set_surrArea()\n pass\n def __str__(self)->str:\n orToStr = dict({0 : 'Horizontal', 1 : 'Vertical'})\n return '{} ship of length {} and prow {}'.format(orToStr[self.orientation], self.length, self.prow)\n def set_position(self):\n prow = self.prow\n length = self.length\n orientation = self.orientation\n\n # -- values check\n if orientation not in {0,1}:\n raise ValueError(\"orientation must be either 0 or 1\")\n if length not in {2,3,4,5}:\n raise ValueError(\"length should be an int in [2,5]\")\n if prow[0] not in {k for k in range(10)} or prow[1] not in {k for k in range(10)}:\n raise ValueError(\"prow should be in the grid\")\n\n # -- position set\n self.position = {(prow[0]+orientation*k, prow[1]+(1-orientation)*k) for k in range(length)}\n pass\n def set_surrArea(self):\n '''\n Description.\n finds the cells that surround the ship. They are represented by the crosses below.\n x x x x x x\n x s h i p x\n x x x x x x\n Implementation.\n errors can happen if the ship is close to a border, so we check the surroundings beforehand.\n '''\n # -- getting position of the ship\n position = self.position\n surrCells = set()\n # -- checking surroundings; left indicates if the cells at the left of ship exist in the grid. Same for up, down and right\n left, right, up, down = (True, True, True, True)\n for y,x in position:\n if x <= 0:\n left = False\n if x >= 9:\n right = False\n if y <= 0:\n down = False\n if y >= 9:\n up = False\n # -- getting surrounding cells together with ship cells\n for y,x in position:\n surrCells.add((y,x))\n if left:\n surrCells.add((y,x-1))\n if right:\n surrCells.add((y,x+1))\n if up:\n surrCells.add((y+1,x))\n if down:\n surrCells.add((y-1,x))\n if up and right:\n surrCells.add((y+1,x+1))\n if down and right:\n surrCells.add((y-1,x+1))\n if up and left:\n surrCells.add((y+1,x-1))\n if down and left:\n surrCells.add((y-1,x-1))\n self.surrArea = surrCells.difference(position) # keeping only surrounding cells\n pass\n def is_sunk(self, hits:set)->bool:\n '''tells if the hits can sink the ship'''\n if self.position.issubset(hits):\n return True\n\n\n\nif __name__ == \"__main__\":\n ship = Ship(3,1,(5,4))\n print(ship.__str__())","sub_path":"myBattleship/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"377818510","text":"##Just set below things##\n\n#tag='FatJetPreselCleaningWlep_semilep'\ntag='semilep'\n#tag='semilep_tight80XWP'\n\n\nvariablesFile='variables.py' ##what variables to draw\ncutsFile='cuts.py' ## event selection##region selection\nplotFile='plot.py' ##color code and some format-related things\nlumi=35.867\noutputDirPlots='plots_'+tag\nsamplesFile = 'samples_'+tag+'.py'\n\noutputDir = 'rootFile_'+tag\ntreeName='Events'\naliasesFile='aliases.py'\n#nuisancesFile = 'nuisances.py'\n\n\n","sub_path":"Configurations/HWWSemiLepHighMass/old/nanoAODv4_2016/Boosted/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"127958643","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom globeos.scenes.basescene import basescene\nimport pygame \nfrom enum import Enum\nfrom globeos.managers.inputmanager import inputmanager, keyevent\nfrom globeos.managers.overlaymanager import drawdot, drawring\n\nclass calibrationstage(Enum):\n CENTER = 0,\n RADIUS = 1,\n FOCALPOINT = 2,\n PLANEROT = 3,\n \n \nclass calibratescene(basescene):\n def __init__(self, globe, screen, args={}):\n super(calibratescene, self).__init__(globe, screen)\n self.nextscenename = args['nextscene']\n self.inputmanager = inputmanager()\n self.inputmanager.addevent(\"inxval\", keyevent(pygame.K_UP))\n self.inputmanager.addevent(\"dexval\", keyevent(pygame.K_DOWN))\n self.inputmanager.addevent(\"inyval\", keyevent(pygame.K_LEFT))\n self.inputmanager.addevent(\"deyval\", keyevent(pygame.K_RIGHT)) \n self.inputmanager.addevent(\"stopani\", keyevent(pygame.K_p)) \n self.inputmanager.addevent(\"nextstep\", keyevent(pygame.K_RETURN)) \n self.iterat = 0\n self.lockrot = True\n self.calistage = calibrationstage.CENTER\n self.precision = 4\n self.ctime = None\n return\n \n def run(self):\n while not self.done:\n self.screen.fill((0,0,0))\n self.surfarr = pygame.surfarray.array3d(self.screen)\n x, y = np.where(np.logical_and(np.isnan(self.globe.coords[0])==False, np.isnan(self.globe.coords[1])==False))\n self.surfarr[x, y] = [255,255,255]\n \n hevent = None\n hevents = []\n for event in pygame.event.get(): \n hevent = self.inputmanager.handleinput(event)\n hevents.append(hevent)\n super(calibratescene, self).defaultevents(hevent)\n self.docalibration(hevents)\n super(calibratescene, self).draw()\n return self.nextscenename\n \n def docalibration(self, hevents):\n \n if(self.calistage == calibrationstage.CENTER):\n drawring(self.surfarr, self.globe.coords, lat = 0.0, scalelong=2*np.pi+1, scalelat=self.precision/10)\n if(\"inyval\" in hevents):\n self.globe.userparams['poff'][0] -= self.precision\n if(\"deyval\" in hevents):\n self.globe.userparams['poff'][0] += self.precision \n if(\"inxval\" in hevents):\n self.globe.userparams['poff'][1] -= self.precision \n if(\"dexval\" in hevents):\n self.globe.userparams['poff'][1] += self.precision \n if(\"nextstep\" in hevents):\n self.precision /= 2\n if(self.precision == 0.5):\n self.precision = 100\n self.calistage = calibrationstage.RADIUS \n \n if(self.calistage == calibrationstage.RADIUS):\n drawring(self.surfarr, self.globe.coords, lat = np.pi/2, scalelong=2*np.pi+1, scalelat=0.1)\n drawring(self.surfarr, self.globe.coords, lat = np.pi/4, scalelong=2*np.pi+1, scalelat=0.1, color=[0,255,0])\n if(\"inxval\" in hevents):\n self.globe.userparams['r'] += self.precision\n self.globe.generateglobe()\n if(\"dexval\" in hevents):\n self.globe.userparams['r'] -= self.precision\n self.globe.generateglobe()\n if(\"nextstep\" in hevents):\n self.precision /= 2\n if(self.precision <= 10):\n self.precision = 100\n self.calistage = calibrationstage.FOCALPOINT \n \n if(self.calistage == calibrationstage.FOCALPOINT):\n drawring(self.surfarr, self.globe.coords, lat = np.pi/2, scalelong=2*np.pi+1, scalelat=0.1)\n if(\"inxval\" in hevents):\n self.globe.userparams['fpoint'][2] -= self.precision\n self.globe.generateglobe()\n if(\"dexval\" in hevents):\n self.globe.userparams['fpoint'][2] += self.precision\n self.globe.generateglobe() \n if(\"nextstep\" in hevents):\n self.precision -=20\n if(self.precision <= 5):\n self.precision = np.pi/16\n self.calistage = calibrationstage.PLANEROT \n \n if(self.calistage == calibrationstage.PLANEROT):\n self.ctime = pygame.time.get_ticks()\n anitime = ((self.ctime/1000)%10)/10\n drawring(self.surfarr, self.globe.coords, lat = np.pi*anitime, scalelong=(2*np.pi+1), scalelat=0.1)\n if(\"inxval\" in hevents):\n self.globe.userparams['prot'][1] -= self.precision\n self.globe.generateglobe()\n if(\"dexval\" in hevents):\n self.globe.userparams['prot'][1] += self.precision\n self.globe.generateglobe()\n if(\"inyval\" in hevents):\n self.globe.userparams['prot'][0] += self.precision\n self.globe.generateglobe() \n if(\"deyval\" in hevents):\n self.globe.userparams['prot'][0] -= self.precision\n self.globe.generateglobe() \n if(\"nextstep\" in hevents):\n self.precision /= 8\n if(self.precision < np.pi/512):\n self.precision = 4\n self.done=True\n \n\n #drawring(self.surfarr, self.globe.coords, lat = self.iterat, scalelong=2*np.pi, scalelat=0.1)\n return\n \n \n \n","sub_path":"globeos/scenes/calibratescene.py","file_name":"calibratescene.py","file_ext":"py","file_size_in_byte":5599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"212438806","text":"import json\nimport os\nimport random\nimport string\nimport threading\nimport time\n\nimport git\n\nfrom fanscribed.common import app_settings\n\n\n# Twenty minute lock timeout.\nLOCK_TIMEOUT = 20 * 60\n\n\ncommit_lock = threading.Lock()\n\n\ndef _lock_is_expired(timestamp):\n return (timestamp + LOCK_TIMEOUT) < time.time()\n\n\ndef _lock_secret():\n return ''.join(random.choice(string.letters) for x in xrange(16))\n\n\ndef _snippet_ms():\n snippet_seconds = int(app_settings()['fanscribed.snippet_seconds'])\n return snippet_seconds * 1000\n\n\ndef repo_from_request(request, rev=None):\n \"\"\"Return the repository and commit based on the request.\n\n The host of the request is inspected to determine the repository.\n The 'rev' GET param is used to determine the commit (default: master).\n \"\"\"\n repos_path = app_settings()['fanscribed.repos']\n repo_path = os.path.join(repos_path, request.host)\n # Make sure repo path is underneath outer repos path.\n assert '..' not in os.path.relpath(repo_path, repos_path)\n repo = git.Repo(repo_path)\n # Only get rev from user if not specified in function call.\n if rev is None:\n rev = request.GET.get('rev', 'master')\n commit = repo.commit(rev)\n return (repo, commit)\n\n\ndef latest_revision(repo):\n return repo.iter_commits('master').next().hexsha\n\n\ndef file_at_commit(repo, filename, commit, required=False, content_filter=None):\n \"\"\"\n -> (content-string, mtime) for the given filename+commit.\n -> ('', None) if file not found and not required.\n \"\"\"\n tree = commit.tree\n if (filename in tree) or required:\n blob = tree[filename]\n content = blob.data_stream.read().decode('utf8')\n most_recent_commit = repo.iter_commits(commit, 'speakers.txt').next()\n mtime = most_recent_commit.authored_date\n if content_filter is not None:\n content = content_filter(content)\n return (content, mtime)\n else:\n # File does not exist in tree as of this commit.\n return ('', None)\n\n\ndef json_file_at_commit(repo, filename, commit, required=False):\n content, mtime = file_at_commit(repo, filename, commit, required)\n return (json.loads(content), mtime)\n\n\ndef most_recent_revision(repo, filename):\n try:\n most_recent_commit = repo.iter_commits('master', 'custom.css').next()\n except StopIteration:\n return None\n else:\n return most_recent_commit.hexsha\n\n\ndef speakers_map(repo, commit):\n text, mtime = file_at_commit(repo, 'speakers.txt', commit)\n d = {}\n for line in text.splitlines():\n if ';' in line:\n left, right = line.split(';', 1)\n else:\n # No ; found, so skip\n continue\n left = left.strip().lower()\n right = right.strip()\n d[left] = right\n return d\n\n\ndef get_locks(tree):\n if 'locks.json' in tree:\n blob = tree['locks.json']\n return json.load(blob.data_stream)\n else:\n return {}\n\n\ndef save_locks(repo, index, locks):\n filename = os.path.join(repo.working_dir, 'locks.json')\n with open(filename, 'wb') as f:\n json.dump(locks, f, indent=4)\n index.add(['locks.json'])\n\n\ndef get_remaining_snippets(tree):\n blob = tree['remaining_snippets.json']\n return json.load(blob.data_stream)\n\n\ndef save_remaining_snippets(repo, index, snippets):\n filename = os.path.join(repo.working_dir, 'remaining_snippets.json')\n with open(filename, 'wb') as f:\n json.dump(snippets, f, indent=4)\n index.add(['remaining_snippets.json'])\n\n\ndef remove_snippet_from_remaining(repo, index, starting_point):\n tree = repo.tree('master')\n snippets = get_remaining_snippets(tree)\n while starting_point in snippets:\n snippets.remove(starting_point)\n save_remaining_snippets(repo, index, snippets)\n\n\ndef get_remaining_reviews(tree):\n blob = tree['remaining_reviews.json']\n return json.load(blob.data_stream)\n\n\ndef save_remaining_reviews(repo, index, reviews):\n filename = os.path.join(repo.working_dir, 'remaining_reviews.json')\n with open(filename, 'wb') as f:\n json.dump(reviews, f, indent=4)\n index.add(['remaining_reviews.json'])\n\n\ndef remove_review_from_remaining(repo, index, starting_point):\n tree = repo.tree('master')\n reviews = get_remaining_reviews(tree)\n while starting_point in reviews:\n reviews.remove(starting_point)\n save_remaining_reviews(repo, index, reviews)\n\n\ndef lock_available_snippet(repo, index, desired_starting_point):\n \"\"\"Return a (starting_point, lock_secret) tuple of a newly-locked snippet,\n or (None, message) if there are none remaining or all are locked.\"\"\"\n tree = repo.tree('master')\n remaining = set(get_remaining_snippets(tree))\n if len(remaining) == 0 and desired_starting_point is None:\n # All of them have been transcribed.\n return (None, 'All snippets have been completed.')\n # Remove expired locks.\n lock_structure = get_locks(tree)\n locks = lock_structure.setdefault('snippet', {})\n for lock_name, lock in locks.items():\n lock_timestamp = lock['timestamp']\n if _lock_is_expired(lock_timestamp):\n del locks[lock_name]\n if desired_starting_point is None:\n # Find one that's unlocked, if there are any.\n locked = set(int(lock_name) for lock_name in locks)\n unlocked = remaining - locked\n if len(unlocked) == 0:\n # All remaining have valid locks.\n return (None, 'All snippets are locked; try again later.')\n else:\n # Pick the next one and lock it with a secret.\n starting_point = sorted(unlocked)[0]\n else:\n # See if the desired starting point is locked already.\n if str(desired_starting_point) in locks:\n return (None, 'The requested snippet is locked; try again later.')\n else:\n starting_point = desired_starting_point\n # The starting point is not locked... lock it!\n lock_secret = _lock_secret()\n locks[str(starting_point)] = {\n 'secret': lock_secret,\n 'timestamp': time.time(),\n }\n save_locks(repo, index, lock_structure)\n return (starting_point, lock_secret)\n\n\ndef lock_available_review(repo, index):\n \"\"\"Return a (starting_point, lock_secret) tuple of a newly-locked review,\n or (None, message) if there are none remaining or all are locked.\"\"\"\n snippet_ms = _snippet_ms()\n tree = repo.tree('master')\n remaining = set(get_remaining_reviews(tree))\n if len(remaining) == 0:\n # All of them have been reviewed.\n return (None, 'All reviews have been completed.')\n # Remove expired locks.\n lock_structure = get_locks(tree)\n locks = lock_structure.setdefault('review', {})\n snippet_locks = lock_structure.setdefault('snippet', {})\n for lock_name, lock in locks.items():\n lock_timestamp = lock['timestamp']\n if _lock_is_expired(lock_timestamp):\n del locks[lock_name]\n # Find one that's unlocked, if there are any.\n locked = set(int(lock_name) for lock_name in locks)\n unlocked = remaining - locked\n # Discard all of the reviews where the snippets are still remaining.\n if len(unlocked) > 0:\n remaining_snippets = set(get_remaining_snippets(tree))\n unlocked -= remaining_snippets\n else:\n # All remaining have valid locks.\n return (None, 'All reviews are locked; try again later.')\n # Also discard any reviews where the second snippet of the review still remains.\n if len(unlocked) > 0:\n adjacent_empty = set()\n for starting_point in unlocked:\n candidate = starting_point + snippet_ms\n if candidate in remaining_snippets:\n adjacent_empty.add(starting_point)\n unlocked -= adjacent_empty\n if len(unlocked) == 0:\n # All remaining have valid locks.\n return (None, 'Not enough snippets have been transcribed.')\n else:\n # Pick the first available one and lock it with a secret.\n starting_point = sorted(unlocked)[0]\n lock_secret = _lock_secret()\n timestamp = time.time()\n locks[str(starting_point)] = {\n 'secret': lock_secret,\n 'timestamp': timestamp,\n }\n # Also lock the associated snippets, so no-one can edit a\n # snippet that is under review.\n snippet_locks[str(starting_point)] = {\n 'secret': _lock_secret(),\n 'timestamp': timestamp,\n }\n snippet_locks[str(starting_point + snippet_ms)] = {\n 'secret': _lock_secret(),\n 'timestamp': timestamp,\n }\n # Save.\n save_locks(repo, index, lock_structure)\n return (starting_point, lock_secret)\n\n\ndef lock_is_valid(repo, index, lock_type, starting_point, lock_secret):\n tree = repo.tree('master')\n lock_structure = get_locks(tree)\n locks = lock_structure.get(lock_type, {})\n lock_name = str(starting_point)\n if lock_name not in locks:\n return False\n lock_detail = locks[lock_name]\n return (lock_detail['secret'] == lock_secret)\n\n\ndef remove_lock(repo, index, lock_type, starting_point):\n tree = repo.tree('master')\n lock_structure = get_locks(tree)\n locks = lock_structure.get(lock_type, {})\n lock_name = str(starting_point)\n if lock_name in locks:\n del locks[lock_name]\n if lock_type == 'review':\n # Also unlock associated snippets.\n snippet_locks = lock_structure.get('snippet', {})\n lock2_name = str(starting_point + _snippet_ms())\n if lock_name in snippet_locks:\n del snippet_locks[lock_name]\n if lock2_name in snippet_locks:\n del snippet_locks[lock2_name]\n save_locks(repo, index, lock_structure)\n\n\ndef snippet_text(repo, index, starting_point):\n tree = repo.tree('master')\n filename = '{0:016d}.txt'.format(starting_point)\n if filename in tree:\n blob = tree[filename]\n return blob.data_stream.read().decode('utf8')\n else:\n # new snippet\n return u''\n\n\ndef save_snippet_text(repo, index, starting_point, text):\n filename = os.path.join(\n repo.working_dir,\n '{0:016d}.txt'.format(starting_point),\n )\n with open(filename, 'wb') as f:\n f.write(text.encode('utf8'))\n index.add([filename])\n","sub_path":"fanscribed/repos.py","file_name":"repos.py","file_ext":"py","file_size_in_byte":10328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"239233767","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef proie_seule(u,t):\n return a*u\n\ndef proie_predateur(X,t):\n u,v = X\n return np.array([u*(a-b*v),-v*(c-d*u)])\n\ndef euler(F, a, b, y0, h):\n \"\"\"Solution de y'=F(y,t) sur [a,b], y(a) = y0, pas h\"\"\"\n y = y0\n t = a\n y_list = [y0] \n t_list = [a]\n while t+h <= b:\n \n y = y + h * F(y, t)\n y_list.append(y)\n t = t + h\n t_list.append(t)\n return t_list, y_list\n \n\n\na=0.13\nb=0.005\nu0 = 15\nc = 0.03\nd = 0.001\nv0 = 20\nt0,t1,h = 0,20,.01\n\n# Question 1 : Donner la population de la proie au bout de 20 unités de temps.\n\n# t_list,A_list = euler(proie_seule,t0,t1,u0,h)\n# plt.plot(t_list,A_list)\n# plt.xlabel('Temps ($s$)')\n# plt.ylabel('Concentration ($mol$)')\n# plt.grid()\n# plt.show()\n\n# Question 2 Donner la population de proies et prédateurs au bout de 300 unités de temps.\n\n\nX0 = np.array([u0,v0])\nt_list, X_list = euler(proie_predateur,0,300,X0,h)\n\nu_list = [X[0] for X in X_list]\nv_list = [X[1] for X in X_list]\nplt.clf()\n\nplt.plot(t_list,u_list)\nplt.plot(t_list,v_list)\n\nplt.xlabel('Temps ($s$)')\nplt.ylabel('Position ($m$)')\nplt.grid()\nplt.show()\n\n","sub_path":"2019_2020/DS05/pp.py","file_name":"pp.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"171716042","text":"import os\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nos.environ['KERAS_BACKEND'] = 'tensorflow'\nimport keras.backend as K\n\nK.set_image_dim_ordering('tf')\n# K.set_image_dim_ordering('th')\nimport time\nimport sys\n\nsys.path.insert(0, './utils/')\nimport numpy as np\nfrom build_model import *\nfrom keras.utils.vis_utils import plot_model\nfrom keras.optimizers import *\nfrom keras.callbacks import EarlyStopping, Callback, ReduceLROnPlateau, CSVLogger\nfrom extract_patches import get_data_training\n\nconf = tf.ConfigProto()\nconf.gpu_options.allow_growth = True\nsess = tf.Session(config=conf)\nimport configparser\n\nconfig = configparser.ConfigParser()\nnp.random.seed(1337)\nfrom keras.utils import multi_gpu_model\n\n\nclass Tee(object):\n def __init__(self, *files):\n self.files = files\n\n def write(self, obj):\n for f in self.files:\n f.write(obj)\n\n def flush(self):\n pass\n\n\n# Get neural network\ndef get_net(inp_shape, algorithm):\n if algorithm == 'deform':\n return build_deform_cnn(inp_shape=inp_shape)\n elif algorithm == 'unet':\n return build_2d_unet_model(inp_shape=inp_shape)\n elif algorithm == 'deform_unet':\n return build_deform_unet(inp_shape=inp_shape)\n elif algorithm == 'fcn_paper':\n return build_2d_fcn_paper_model(inp_shape=inp_shape)\n elif algorithm == 'R2UNet':\n return BuildR2UNet(inp_shape=inp_shape)\n\n\ndef define_log(log_path_experiment, algorithm):\n if not os.path.exists(log_path_experiment):\n print(\"DIRECTORY Created\")\n os.makedirs(log_path_experiment)\n\n f = open(log_path_experiment + algorithm + '.log', 'a')\n sys.stdout = Tee(sys.stdout, f)\n\n\n# because the keras bug. if para we must use the origion model to save the shared weights\nclass ModelCallBackForMultiGPU(Callback):\n def __init__(self, model):\n self.model_to_save = model\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch % 1 == 0:\n self.model_to_save.save(log_path_experiment + '/model_at_epoch_%05d.hdf5' % epoch)\n print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))\n\n\nclass LossHistory(Callback):\n def on_train_begin(self, logs={}):\n self.losses = []\n self.accs = []\n\n def on_epoch_end(self, batch, logs={}):\n self.losses.append(logs.get('val_loss'))\n self.accs.append(logs.get('val_acc'))\n print('learning rate:' + str(logs.get('lr')))\n\n\nclass SGDLearningRateTracker(Callback):\n def on_epoch_end(self, epoch, logs={}):\n optimizer = self.model.optimizer\n lr = K.eval(optimizer.lr * (1. / (1. + optimizer.decay * optimizer.iterations)))\n print('\\nLR: {:.6f}\\n'.format(lr))\n\n\n# ========= Load settings from Config file\nconfig.read('configuration.txt')\nfine_tuning = False\nalgorithm = config.get('experiment name', 'name')\ndataset = config.get('data attributes', 'dataset')\nlog_path_experiment = './log/experiments/' + algorithm + '/' + dataset + '/'\n# log_path_experiment = './log/experiments/STARE/' + algorithm + '/'\n\n# ========= Load settings from Config file\npath_data = config.get('data paths', 'path_local')\nmodel_path = config.get('data paths', 'model_path')\n# training settings\nN_epochs = int(config.get('training settings', 'N_epochs'))\nbatch_size = int(config.get('training settings', 'batch_size'))\ninp_shape = (int(config.get('data attributes', 'patch_width')), int(config.get('data attributes', 'patch_height')), 1)\ngpu = 3\nfcn = True\nif algorithm == 'deform':\n fcn = False\n model = get_net(inp_shape=inp_shape, algorithm=algorithm)\nelse:\n fcn = True\n model = get_net(inp_shape=inp_shape, algorithm=algorithm)\n\ndefine_log(log_path_experiment, algorithm)\n\npatches_imgs_train, patches_masks_train = get_data_training(\n train_imgs_original=path_data + config.get('data paths', 'train_imgs_original'),\n train_groudTruth=path_data + config.get('data paths', 'train_groundTruth'), # masks\n patch_height=inp_shape[0],\n patch_width=inp_shape[1],\n N_subimgs=int(config.get('training settings', 'N_subimgs')),\n inside_FOV=config.getboolean('training settings', 'inside_FOV'),\n dataset=dataset,\n path_experiment=log_path_experiment,\n fcn=fcn\n)\n\npatches_imgs_train = np.transpose(patches_imgs_train, (0, 2, 3, 1))\nif fcn:\n patches_masks_train = np.transpose(patches_masks_train, (0, 2, 3, 1))\nprint(\"Check: final output of the network:\")\nprint(model.output_shape)\nmodel.summary()\nplot_model(model, to_file=log_path_experiment + algorithm + '_model.png',\n show_shapes=True) # check how the model looks like\njson_string = model.to_json()\nopen(log_path_experiment + algorithm + '_architecture.json', 'w').write(json_string)\ncheckpointer = ModelCallBackForMultiGPU(model)\nearly_stopping = EarlyStopping(monitor='val_loss', patience=20, mode='auto')\nreduce = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, verbose=0, mode='auto', epsilon=0.0001,\n cooldown=0, min_lr=0)\ncsv_logger = CSVLogger(log_path_experiment + 'training.csv', append=True)\nhist = model.fit(patches_imgs_train, patches_masks_train, epochs=N_epochs, batch_size=batch_size, validation_split=0.2,\n callbacks=[checkpointer, reduce, csv_logger, early_stopping], verbose=2)\n\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"433312513","text":"def is_balanced(root):\n\tdepths = [] #to keep track of depths that you havent seen\n\n\t#need a stack for dfs\n\tnodes = Stack()\n\tnodes.push((root, 0))\n\n\twhile(not nodes.is_empty()):\n\t\t#pop node and depth\n\t\tnode,depth = nodes.pop()\n\n\t\t#basically if its a leaf\n\t\tif(not nodes.left) and (not nodes.right):\n\t\t\tif depth not in depths:\n\t\t\t\tdepths.append(depth)\n\n\t\t\t#two ways you can unbalanced tree\n\t\t\t#1 - more than 2 different leaf depths\n\t\t\t#2 - 2 leaf depths and more than 1 apart\n\n\t\t\telif(len(depths) > 2) or (len(depths) == 2 and abs(depths[0] - depths[1]) > 1):\n\t\t\t\treturn False\n\n\t\t\telse:\n\t\t\t\tif node.left:\n\t\t\t\t\tnodes.push((node.left,depth+1))\n\t\t\t\tif node.right:\n\t\t\t\t\tnodes.push((node.right, depth+1))\n\treturn True \n\n\n","sub_path":"Python/Solutions/binary_tree_balanced.py","file_name":"binary_tree_balanced.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"485301211","text":"# -- coding = 'utf-8' -- \n# Author Kylin\n# Python Version 3.7.3\n# OS macOS\n\"\"\"\nNo. 978 最长湍流子数组\n\n需求:\n 给定一个整数数组arr,返回arr的最大湍流子数组的长度。\n 如果比较符号在子数组中的每个相邻元素对之间翻转,则该子数组是\"湍流子数组\"。\n 更正式地来说,当arr的子数组A[i], A[i+1], ..., A[j]满足仅满足下列条件时,我们称其为湍流子数组:\n · 若 i <= k < j :\n 当 k 为奇数时, A[k] > A[k+1],且\n 当 k 为偶数时,A[k] < A[k+1];\n · 或 若 i <= k < j :\n 当 k 为偶数时,A[k] > A[k+1] ,且\n 当 k 为奇数时, A[k] < A[k+1]。\n\"\"\"\n\n\ndef maxTurbulenceSize(arr):\n \"\"\"\n 双指针\n 右指针根据前后元素确定左指针的位置\n 时间复杂度:O(n)\n 空间复杂度:O(1)\n :type arr: List[int]\n :rtype: int\n \"\"\"\n n = len(arr)\n left, right = 0, 1\n\n # 用于记录长度\n ans = 1\n\n while right < n:\n if arr[right - 1] == arr[right]:\n # 考虑窗口长度为1(即left和right相等的情况)\n left = right\n elif right != 1 and arr[right-2] < arr[right-1] < arr[right]:\n # 表明数组是递增的,left从right-1重新设置\n left = right - 1\n elif right != 1 and arr[right-2] > arr[right-1] > arr[right]:\n # 表明数据是递减的,left从right-1重新设置\n left = right - 1\n\n ans = max(ans, right - left + 1)\n right += 1\n\n return ans\n\n\nif __name__ == \"__main__\":\n arr = [9, 4, 2, 10, 7, 8, 8, 1, 9]\n size = maxTurbulenceSize(arr)\n print(size)","sub_path":"LeetCode/src/calculate08/max_turbulence_size.py","file_name":"max_turbulence_size.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"311781314","text":"from enum import Enum\n\n__all__ = [\"ALPHA\", \"OMEGA\", \"SPLITABLES\", \"DataSetType\"]\n\nALPHA = chr(2) # Start of text\nOMEGA = chr(3) # End of text\nSPLITABLES = {\n ALPHA,\n OMEGA,\n \" \",\n \".\",\n \",\",\n \":\",\n \"-\",\n \"'\",\n \"(\",\n \")\",\n \"?\",\n \"!\",\n \"&\",\n \";\",\n '\"',\n}\n\n\nclass DataSetType(Enum):\n TEST = \"test\"\n TRAIN = \"train\"\n DEV = \"dev\"\n","sub_path":"webnlg2_reader/patterns/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"4385688","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\n\nfrom deploytodotaskerapp.forms import UserForm, RegistrationForm, UserFormForEdit, MealForm\nfrom django.contrib.auth import authenticate, login\n\nfrom django.contrib.auth.models import User\nfrom deploytodotaskerapp.models import Meal, Order, Driver\n\nfrom django.db.models import Sum, Count, Case, When\n\n\n# Create your views here.\ndef home(request):\n return redirect(registration_home)\n\n\n@login_required(login_url='/registration/login/')\ndef registration_home(request):\n return redirect(registration_order)\n\n\n@login_required(login_url='/registration/login/')\ndef registration_account(request):\n user_form = UserFormForEdit(instance=request.user)\n registration_form = RegistrationForm(instance=request.user.registration)\n\n if request.method == \"POST\":\n user_form = UserFormForEdit(request.POST, instance=request.user)\n registration_form = RegistrationForm(request.POST, request.FILES, instance=request.user.registration)\n\n if user_form.is_valid() and registration_form.is_valid():\n user_form.save()\n registration_form.save()\n\n return render(request, 'registration/account.html', {\n \"user_form\": user_form,\n \"registration_form\": registration_form\n })\n\n\n# DOUBT changed filter according to video 32 at 1:21\n\n@login_required(login_url='/registration/login/')\ndef registration_meal(request):\n meals = Meal.objects.filter(registration=request.user.registration).order_by(\"-id\")\n return render(request, 'registration/meal.html', {\"meals\": meals})\n\n\n@login_required(login_url='/registration/login/')\ndef registration_add_meal(request):\n form = MealForm()\n\n if request.method == \"POST\":\n form = MealForm(request.POST, request.FILES)\n\n if form.is_valid():\n meal = form.save(commit=False)\n meal.registration = request.user.registration\n meal.save()\n return redirect(registration_meal)\n\n return render(request, 'registration/add_meal.html', {\n \"form\": form\n })\n\n\n@login_required(login_url='/registration/login/')\ndef registration_edit_meal(request, meal_id):\n form = MealForm(instance=Meal.objects.get(id=meal_id))\n\n if request.method == \"POST\":\n form = MealForm(request.POST, request.FILES, instance=Meal.objects.get(id=meal_id))\n\n if form.is_valid():\n form.save()\n return redirect(registration_meal)\n return render(request, 'registration/edit_meal.html', {\n \"form\": form\n })\n\n\n@login_required(login_url='/registration/login/')\ndef registration_order(request):\n \"\"\"\n :param request:\n :return:\n \"\"\"\n if request.method == \"POST\":\n\n order = Order.objects.get(id=request.POST[\"id\"], registration=request.user.registration)\n\n if order.status == Order.COOKING:\n order.status = Order.READY\n order.save()\n\n orders = Order.objects.filter(registration=request.user.registration).order_by(\"-id\")\n return render(request, 'registration/order.html', {\"orders\": orders})\n\n\n@login_required(login_url='/registration/login/')\ndef registration_report(request):\n \"\"\"\n :param request:\n :return:\n \"\"\"\n # Calculate revenue and number of order by current week\n from datetime import datetime, timedelta\n\n revenue = []\n orders = []\n\n # Calculate weekdays\n today = datetime.now()\n current_weekdays = [today + timedelta(days=i) for i in range(0 - today.weekday(), 7 - today.weekday())]\n\n for day in current_weekdays:\n delivered_orders = Order.objects.filter(\n registration=request.user.registration,\n status=Order.DELIVERED,\n created_at__year=day.year,\n created_at__month=day.month,\n created_at__day=day.day\n )\n revenue.append(sum(order.total for order in delivered_orders))\n orders.append(delivered_orders.count())\n\n # Top 3 Meals\n top3_meals = Meal.objects.filter(registration=request.user.registration) \\\n .annotate(total_order=Sum('orderdetails__quantity')) \\\n .order_by(\"-total_order\")[:3]\n\n meal = {\n \"labels\": [meal.name for meal in top3_meals],\n \"data\": [meal.total_order or 0 for meal in top3_meals]\n }\n\n # Top 3 Drivers\n top3_drivers = Driver.objects.annotate(\n total_order=Count(\n Case(\n When(order__registration=request.user.registration, then=1)\n )\n )\n ).order_by(\"-total_order\")[:3]\n\n driver = {\n \"labels\": [driver.user.get_full_name() for driver in top3_drivers],\n \"data\": [driver.total_order for driver in top3_drivers]\n }\n\n return render(request, 'registration/report.html', {\n \"revenue\": revenue,\n \"orders\": orders,\n \"meal\": meal,\n \"driver\": driver\n })\n\n\ndef registration_sign_up(request):\n user_form = UserForm()\n registration_form = RegistrationForm()\n\n if request.method == \"POST\":\n user_form = UserForm(request.POST)\n registration_form = RegistrationForm(request.POST, request.FILES)\n\n if user_form.is_valid() and registration_form.is_valid():\n new_user = User.objects.create_user(**user_form.cleaned_data)\n new_registration = registration_form.save(commit=False)\n new_registration.user = new_user\n new_registration.save()\n\n login(request, authenticate(\n username=user_form.cleaned_data[\"username\"],\n password=user_form.cleaned_data[\"password\"]\n ))\n\n return redirect(registration_home)\n\n return render(request, \"registration/sign_up.html\", {\n \"user_form\": user_form,\n \"registration_form\": registration_form\n })\n","sub_path":"deploytodotaskerapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"565501203","text":"import logging\nimport random\nimport string\nfrom csv import DictReader\nfrom typing import List\n\nimport pytest\n\nfrom . import common\n\nENDPOINT = common.BASE_URL + \"/demand\"\n\n\n@pytest.fixture()\ndef sample_demand():\n \"\"\"Return rows of sample demand from csv file\"\"\"\n\n # Loading data from sample csv\n with open(\"tests/vrp_testing_data.csv\") as sample_demand_file:\n sample_demand_rows = list(DictReader(sample_demand_file))\n\n NUM_CLUSTERS: int = 10\n\n # Cleaning individual objects in-place\n for demand in sample_demand_rows:\n demand.pop(\"zipcode\")\n demand[\"latitude\"] = float(demand[\"latitude\"])\n demand[\"longitude\"] = float(demand[\"longitude\"])\n demand[\"quantity\"] = float(demand.pop(\"weight\")) / 10\n demand[\"unit\"] = \"kilograms\"\n demand[\"cluster_id\"] = int(demand.pop(\"pallets\")) % NUM_CLUSTERS\n\n return sample_demand_rows\n\n\n@pytest.fixture()\ndef random_demand():\n \"\"\"Return random generated demand\"\"\"\n\n return {\n \"latitude\": random.uniform(-90, 90),\n \"longitude\": random.uniform(-180, 180),\n \"quantity\": random.uniform(0, 20000),\n \"cluster_id\": random.randint(0, 100),\n \"unit\": \"\".join(\n random.choices(string.ascii_lowercase, k=random.randint(1, 10))\n ),\n }\n\n\n@pytest.mark.parametrize(\n \"content_type\",\n [\n \"audio/aac\",\n \"application/x-abiword\",\n \"application/x-freearc\",\n \"video/x-msvideo\",\n \"application/vnd.amazon.ebook\",\n \"application/octet-stream\",\n \"image/bmp\",\n \"application/x-bzip\",\n \"application/x-bzip2\",\n \"application/x-csh\",\n \"text/css\",\n \"text/csv\",\n \"application/msword\",\n (\n \"application/vnd.openxmlformats-officedocument.wordprocessingml\"\n \".document\"\n ),\n \"application/vnd.ms-fontobject\",\n \"application/epub+zip\",\n \"application/gzip\",\n \"image/gif\",\n \"text/html\",\n \"image/vnd.microsoft.icon\",\n \"text/calendar\",\n \"application/java-archive\",\n \"image/jpeg\",\n \"text/javascript, per the following specifications:\",\n \"audio/midi\",\n \"text/javascript\",\n \"audio/mpeg\",\n \"video/mpeg\",\n \"application/vnd.apple.installer+xml\",\n \"application/vnd.oasis.opendocument.presentation\",\n \"application/vnd.oasis.opendocument.spreadsheet\",\n \"application/vnd.oasis.opendocument.text\",\n \"audio/ogg\",\n \"video/ogg\",\n \"application/ogg\",\n \"audio/opus\",\n \"font/otf\",\n \"image/png\",\n \"application/pdf\",\n \"application/x-httpd-php\",\n \"application/vnd.ms-powerpoint\",\n (\n \"application/vnd.openxmlformats-officedocument.presentationml\"\n \".presentation\"\n ),\n \"application/vnd.rar\",\n \"application/rtf\",\n \"application/x-sh\",\n \"image/svg+xml\",\n \"application/x-shockwave-flash\",\n \"application/x-tar\",\n \"image/tiff\",\n \"video/mp2t\",\n \"font/ttf\",\n \"text/plain\",\n \"application/vnd.visio\",\n \"audio/wav\",\n \"audio/webm\",\n \"video/webm\",\n \"image/webp\",\n \"font/woff\",\n \"font/woff2\",\n \"application/xhtml+xml\",\n \"application/vnd.ms-excel\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n \"application/xml \",\n \"application/vnd.mozilla.xul+xml\",\n \"application/zip\",\n \"video/3gpp\",\n \"video/3gpp2\",\n \"application/x-7z-compressed\",\n ],\n)\ndef test_non_json_request(client, content_type: str, auth_header: dict):\n \"\"\"Test with content types other than 'application/json'\"\"\"\n\n logging.info(f\"Testing with content-type : {content_type}\")\n\n headers = dict(auth_header, **{\"Content-Type\": content_type})\n\n res = client.post(ENDPOINT, headers=headers, data=\"\")\n\n logging.debug(f\"Response : {res}\")\n logging.debug(f\"Response Data : {res.data}\")\n\n assert res.status_code == 400\n assert res.headers[\"Content-Type\"] == \"application/json\"\n assert (\n res.json[\"message\"]\n == \"Incorrect request format! Request data must be JSON\"\n )\n\n\ndef test_invalid_json(client, auth_header: dict):\n \"\"\"Test with invalid JSON in request\"\"\"\n\n logging.info(\"Testing with invalid JSON\")\n logging.debug(f'Sending request to \"{ENDPOINT}\"')\n\n headers = dict(auth_header, **{\"Content-Type\": \"application/json\"})\n\n res = client.post(\n ENDPOINT,\n headers=headers,\n data=\"\".join(\n random.choices(\n string.ascii_letters + \"\".join([\"{\", \"}\", '\"', \"'\"]),\n k=random.randint(1, 27),\n )\n ),\n )\n\n logging.debug(f\"Response : {res}\")\n logging.debug(f\"Response Data : {res.data}\")\n\n assert res.status_code == 400\n assert res.headers[\"Content-Type\"] == \"application/json\"\n assert (\n res.json[\"message\"]\n == \"Invalid JSON received! Request data must be JSON\"\n )\n\n\ndef test_empty_demand(client, auth_header):\n \"\"\"Test by sending empty demand array\"\"\"\n input_data = {\"demand\": []}\n logging.info(\"Testing with empty demand array\")\n\n headers = dict(auth_header, **{\"Content-Type\": \"application/json\"})\n\n res = client.post(ENDPOINT, headers=headers, json=input_data)\n\n logging.debug(f\"Response : {res}\")\n logging.debug(f\"Response Data : {res.data}\")\n\n assert res.status_code == 400\n assert res.headers[\"Content-Type\"] == \"application/json\"\n\n error_message = res.json[\"message\"]\n assert error_message == \"'demand' is empty\"\n\n\n@pytest.mark.parametrize(\n \"param, value\",\n [\n (\"latitude\", -101.536),\n (\"latitude\", \"-101.536\"),\n (\"latitude\", -846),\n (\"latitude\", \"-846\"),\n (\"latitude\", 507.305),\n (\"latitude\", \"1.04\"),\n (\"latitude\", 643),\n (\"latitude\", \"75\"),\n (\"latitude\", \"abl{s\"),\n (\"latitude\", \"\"),\n (\"longitude\", -967.895),\n (\"longitude\", \"-967.895\"),\n (\"longitude\", -816),\n (\"longitude\", \"-816\"),\n (\"longitude\", 2131.114),\n (\"longitude\", \"2131.114\"),\n (\"longitude\", 137),\n (\"longitude\", \"137\"),\n (\"longitude\", \"itKv{a\"),\n (\"longitude\", \"\"),\n (\"cluster_id\", -4830.546),\n (\"cluster_id\", -2113),\n (\"cluster_id\", 9326.594),\n (\"cluster_id\", \"uHNHjdeb2\"),\n (\"cluster_id\", \"\"),\n (\"unit\", -6813.875),\n (\"unit\", -3942),\n (\"unit\", 2959.333),\n (\"unit\", 1769),\n (\"unit\", \"-23\"),\n (\"unit\", \"1832\"),\n (\"unit\", \"faf2\"),\n (\"unit\", \"knuw{\"),\n (\"unit\", \"}knuw\"),\n (\"unit\", \"!dead\"),\n (\"unit\", \"\"),\n (\"quantity\", -1391.151),\n (\"quantity\", \"-1391.151\"),\n (\"quantity\", -4921),\n (\"quantity\", \"-4921\"),\n (\"quantity\", \" bsgj\"),\n (\"quantity\", \"hfuo6542w\"),\n (\"quantity\", \"\"),\n ],\n)\ndef test_invalid_demand(\n client, auth_header: dict, param: str, value: any, random_demand: dict\n):\n \"\"\"Test with invalid parameters in demand\"\"\"\n\n demand = random_demand\n input_data = {\"demand\": [demand], \"stack_id\": 1}\n logging.debug(f\"Demand : {demand}\")\n logging.debug(f\"Input data : {input_data}\")\n\n demand[param] = value\n logging.debug(f\"Invalid demand : {demand}\")\n\n headers = dict(auth_header, **{\"Content-Type\": \"application/json\"})\n\n res = client.post(ENDPOINT, headers=headers, json=input_data)\n\n assert res.status_code == 400\n assert f\"Invalid {param}\" in res.json[\"message\"]\n\n\ndef test_single_insert(client, auth_header: dict, random_demand: dict):\n \"\"\"Test with single demand\"\"\"\n demand = random_demand\n input_data = {\"demand\": [demand], \"stack_id\": 1}\n logging.debug(f\"demand : {demand}\")\n\n headers = dict(auth_header, **{\"Content-Type\": \"application/json\"})\n\n res = client.post(ENDPOINT, headers=headers, json=input_data)\n\n logging.debug(f\"Response : {res}\")\n logging.debug(f\"Response data : {res.data}\")\n\n assert res.status_code == 201\n assert res.headers[\"Content-Type\"] == \"application/json\"\n\n for demand, response in zip([demand], res.json[\"demand\"]):\n id = response.pop(\"id\")\n assert isinstance(id, int)\n assert demand == response\n response[\"id\"] = id\n\n\ndef test_batch_insert(client, auth_header: dict, sample_demand: List[dict]):\n \"\"\"Test with multiple demand\"\"\"\n\n input_data = {\"demand\": sample_demand, \"stack_id\": 1}\n logging.info(\"Testing with multiple demand in one request\")\n\n headers = dict(auth_header, **{\"Content-Type\": \"application/json\"})\n\n res = client.post(ENDPOINT, headers=headers, json=input_data)\n\n assert res.status_code == 201\n assert len(res.json[\"demand\"]) == len(sample_demand)\n\n for demand, response in zip(sample_demand, res.json[\"demand\"]):\n id = response.pop(\"id\")\n assert isinstance(id, int)\n assert demand == response\n response[\"id\"] = id\n","sub_path":"solverstack-crud/tests/test_demand.py","file_name":"test_demand.py","file_ext":"py","file_size_in_byte":9015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"587490060","text":"__author__ = 'johnbritti'\nimport pickle, os\n\nfrom PyQt5.QtCore import (\n QAbstractItemModel,\n QModelIndex,\n Qt,\n QVariant,\n QMimeData\n)\nfrom PyQt5 import QtGui\n\nfrom item_classes import *\n\n\nclass EntryModel(QAbstractItemModel):\n def __init__(self):\n super(EntryModel, self).__init__()\n self.root = EntryRoot()\n self.setup()\n\n def setup(self):\n '''self.root.append_child(EntryCategory('Untitled'))\n self.root.append_child(EntryCategory('Untitled'))\n self.root.append_child(EntryCategory('Untitled'))'''\n\n def rowCount(self, parent=None, *args, **kwargs):\n \"\"\"\n Returns number of rows after a given item\n :rtype : int\n \"\"\"\n if parent.column() > 0:\n return 0\n if not parent.isValid():\n p_item = self.root\n else:\n p_item = parent.internalPointer()\n return p_item.child_count()\n\n def columnCount(self, parent=None, *args, **kwargs):\n \"\"\"\n Returns Number of columns\n :rtype : int\n \"\"\"\n return self.root.column_count()\n\n def data(self, index, role=None):\n \"\"\"\n Returns data stored in an entry at a given column\n :rtype : string\n \"\"\"\n if not index.isValid():\n return QVariant()\n\n item = index.internalPointer()\n if role == Qt.DisplayRole:\n return item.data(index.column())\n if role == Qt.UserRole:\n if item:\n return item.content\n if role == Qt.CheckStateRole and index.column() == 0:\n return item.check_state\n if role == Qt.BackgroundColorRole:\n if item.col_data[1] == '':\n return QtGui.QColor(227, 250, 190)\n\n return QVariant()\n\n def setData(self, index, value, role=None):\n \"\"\"\n Sets the data at an index (called when you double click-edit a cell)\n :rtype : bool\n \"\"\"\n if not index.isValid():\n return False\n\n item = index.internalPointer()\n if role == Qt.EditRole:\n item.setData(index.column(), value)\n self.dataChanged.emit(index, index)\n return True\n if role == Qt.CheckStateRole:\n item.check_state = value\n return False\n\n def headerData(self, column, orientation, role=None):\n \"\"\"\n Returns the data at the column of the root item\n :rtype : string\n \"\"\"\n if orientation == Qt.Horizontal and role == Qt.DisplayRole:\n return QVariant(self.root.data(column))\n return QVariant()\n\n def index(self, row, col, parent=QModelIndex(), *args, **kwargs):\n \"\"\"\n Returns an index in a format that Qt can understand\n :rtype : QModelIndex\n \"\"\"\n if not self.hasIndex(row, col, parent):\n return QModelIndex()\n\n if not parent.isValid():\n parent_item = self.root\n\n else:\n parent_item = parent.internalPointer()\n\n child_item = parent_item.children[row]\n\n if child_item:\n return self.createIndex(row, col, child_item)\n else:\n return QModelIndex()\n\n def parent(self, index=None):\n \"\"\"\n Returns index of the parent node of the index node\n :rtype : QModelIndex\n \"\"\"\n if not index.isValid():\n return index\n\n child_item = index.internalPointer()\n if not child_item:\n return QModelIndex()\n parent_item = child_item.parent\n\n if parent_item == self.root:\n return QModelIndex()\n\n return self.createIndex(parent_item.row(), 0, parent_item)\n\n def flags(self, index):\n \"\"\"\n Returns the flags of an entry as bytes\n :rtype : bytes\n \"\"\"\n if not index.isValid():\n return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDropEnabled\n\n return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDropEnabled | QtCore.Qt.ItemIsDragEnabled | \\\n QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable\n\n def item_from_index(self, index):\n \"\"\"\n Returns an actual item from a given QModelIndex\n :rtype : item\n \"\"\"\n return index.internalPointer() if index.isValid() else self.root\n\n def mimeTypes(self):\n \"\"\"\n Returns all the MIME types available to this program\n What are MIME types? Fuck you, that's what\n :rtype: list of strings\n \"\"\"\n types = ['application/item_instance.txt']\n return types\n\n def mimeData(self, indices):\n \"\"\"\n Returns serialized entry, because that's obviously the mos efficient way to move things\n :rtype : bytearray\n \"\"\"\n data = b''\n num_items = len(indices) // self.root.column_count()\n items = [self.item_from_index(indices[i * 4]) for i in range(num_items)]\n for item in items:\n if item.movable == False:\n return None\n try:\n data += pickle.dumps(items)\n except(RuntimeError):\n print('!!!Failed to copy MIME data!!!')\n\n mime_data = QMimeData()\n mime_data.setData('application/item_instance.txt', data)\n return mime_data\n\n def dropMimeData(self, mime_data, action, row, column, parent_index):\n \"\"\"\n Pastes serialized data from mimeData() function\n :rtype : bool\n \"\"\"\n if not mime_data.hasFormat('application/item_instance.txt'):\n return False\n items = pickle.loads(mime_data.data('application/item_instance.txt'))\n for item in items:\n if item.col_data == self.item_from_index(parent_index).col_data:\n return False\n drop_parent = self.item_from_index(parent_index)\n self.move_rows([self.match(0, Qt.DisplayRole, i.col_data)[0] for i in items], drop_parent, row)\n self.layoutChanged.emit()\n return True\n\n def remove_rows(self, items):\n \"\"\"\n Removes list of sequential items\n :rtype : bool\n \"\"\"\n self.beginRemoveRows(self.index(items[0].parent.row(), 0), items[0].parent.child_index(items[0]),\n items[-1].parent.child_index(items[-1]))\n for item in items:\n item.parent.remove_child(item)\n self.endRemoveRows()\n return True\n\n def insert_rows(self, items, parent, row):\n \"\"\"\n Insert items at a specific row inside of a parent\n :rtype : bool\n \"\"\"\n parent_index = self.index(parent.row(), 0)\n self.beginInsertRows(parent_index, row, row - 1)\n for item in items:\n parent.insert_child(item, row)\n self.endInsertRows()\n return True\n\n def move_rows(self, items, parent, row):\n \"\"\"\n Removes the list of items and then inserts them at the row of a parent\n :rtype : bool\n \"\"\"\n self.remove_rows(items)\n self.insert_rows(items, parent, row)\n return True\n\n def supportedDropActions(self):\n \"\"\"\n Tells Qt what you can do with this model drop-wise\n :rtype : bytes\n \"\"\"\n return Qt.MoveAction | Qt.CopyAction\n\n def match(self, start_row, role, value, num=1, match_flags=Qt.MatchExactly, *args, **kwargs):\n \"\"\"\n Returns list of Entries that match the data entered\n :rtype : list of Entry\n \"\"\"\n entries = self.root.list_all_entries()\n if role == Qt.DisplayRole:\n return [entry for entry in entries if entry.col_data == value][0:num]\n return []\n\n def export_mod_list(self):\n file = open('modlist.txt', 'w')\n root = self.root\n for mod in [root.children[i] for i in range(root.child_count())]:\n file.write(mod.export())\n file.flush()\n\n def import_mod_list(self):\n if not os.path.exists('modlist.txt'):\n return\n file = open('modlist.txt', 'r')\n items = [i.strip('\\n') for i in file if len(i) > 2]\n for item in items:\n data = item.split(',')\n drop_parent = self.item_from_index(self.index(int(data[1]),0))\n self.insert_rows([EntryCategory(data[0])], drop_parent, drop_parent.child_count())","sub_path":"entry_model.py","file_name":"entry_model.py","file_ext":"py","file_size_in_byte":8247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"434700190","text":"from torch.nn.modules import TransformerEncoderLayer,TransformerEncoder,TransformerDecoder,TransformerDecoderLayer\nimport math\nimport torch\nfrom torch import nn\nfrom torch.nn.modules import Transformer\nfrom torch.nn.modules.normalization import LayerNorm\nfrom torch.nn.init import xavier_uniform_\nfrom torch.nn.modules import Linear\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\n#Slightly extend the transformer model to embed encoder and decoder initial inputs\n#and use positional encodings as well \n#some code here copied from https://pytorch.org/docs/master/_modules/torch/nn/modules/transformer.html#Transformer\nclass TransformerModel(nn.Module):\n\n def __init__(self,d_model,nhead,num_encoder_layers,num_decoder_layers,\n dim_feedforward,dropout,activation,src_vocab_size,tgt_vocab_size):\n super(TransformerModel,self).__init__()\n self.pos_encoder = PositionalEncoding(d_model=d_model,dropout=0.1) #, max_len=100)\n encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout, activation)\n encoder_norm = LayerNorm(d_model)\n self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)\n decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout, activation)\n decoder_norm = LayerNorm(d_model)\n self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, decoder_norm)\n \n self.d_model = d_model\n self.nhead = nhead\n self.linear = Linear(d_model,tgt_vocab_size)\n self.transformer = Transformer(d_model=d_model,nhead=nhead,num_encoder_layers=num_encoder_layers,\n num_decoder_layers=num_decoder_layers,dim_feedforward=dim_feedforward,\n dropout=dropout,activation=activation)\n \n self.encoder_embedding = nn.Embedding(src_vocab_size,d_model)\n self.decoder_embedding = nn.Embedding(tgt_vocab_size,d_model)\n\n self._reset_parameters() #initialize all the parameters randomly\n\n\n def _reset_parameters(self):\n #Initiate parameters in the transformer model.\n for p in self.parameters():\n if p.dim() > 1:\n xavier_uniform_(p)\n \n def change_to_value_net(self):\n self.linear = Linear(self.d_model, 1) #now doing regression\n torch.nn.init.xavier_uniform(self.linear.weight) #initialize new weights\n \n \n '''\n args:\n src_key_padding_mask: mask out padded portion of src (is (N,S))\n tgt_mask: mask out future target words (I think usually just a square triangular matrix)\n tgt_key_padding_mask: mask out padded portion of tgt\n memory: (is the encoder output) in the case of testing or policy gradients, \n we reuse this output so want to give option to give it here\n '''\n def forward(self, src, tgt, src_key_padding_mask=None,tgt_mask=None, tgt_key_padding_mask=None,\n memory_key_padding_mask=None,memory=None,only_return_last_col=False):\n \n '''\n First embed src and tgt, then add positional encoding, then run encoder,\n then decoder.\n '''\n if memory is None:\n #here we reuse encoder output from previous decoding step\n memory = self.encoder_embedding(src).double() * math.sqrt(self.d_model)\n memory = self.pos_encoder(memory).double()\n memory = self.encoder(memory,src_key_padding_mask=src_key_padding_mask)\n\n tgt2 = self.decoder_embedding(tgt).double() * math.sqrt(self.d_model)\n tgt2 = self.pos_encoder(tgt2)\n\n output = self.decoder(tgt2, memory, tgt_mask=tgt_mask,\n tgt_key_padding_mask=tgt_key_padding_mask,\n memory_key_padding_mask=memory_key_padding_mask)\n\n #linear layer increases embedding dimension to size of vocab (then can feed through softmax)\n #If value_net, then linear layer will reduce embedding dim to size 1 since just regression\n output = self.linear(output) #The cross entropy loss will take in the unnormalized outputs \n return output,memory\n \n\ndef generate_square_subsequent_mask(sz):\n #Generate a square mask for the sequence. The masked positions are filled with float('-inf').\n #Unmasked positions are filled with float(0.0).\n mask = (torch.triu(torch.ones(sz, sz)) == 1).float().transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n\n\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len,dtype=torch.float64).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).double() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n\n def forward(self, x): \n x = x + Variable(self.pe.transpose(0,1)[:x.size(0), :],requires_grad=False)\n return self.dropout(x)\n\n\n#now our optimizer (uses adam but changes learning rate over time)\n#is in paper and http://nlp.seas.harvard.edu/2018/04/03/attention.html#optimizer\nclass NoamOpt:\n \"Optim wrapper that implements rate.\"\n def __init__(self, model_size, factor, warmup, optimizer):\n self.optimizer = optimizer\n self._step = 0 \n self.warmup = warmup\n self.factor = factor\n self.model_size = model_size\n self._rate = 0\n \n def step(self):\n \"Update parameters and rate\"\n self._step += 1\n rate = self.rate()\n for p in self.optimizer.param_groups:\n p['lr'] = rate\n self._rate = rate\n self.optimizer.step()\n \n def rate(self, step = None):\n \"Implement `lrate` above\"\n if step is None:\n step = self._step\n return self.factor * \\\n (self.model_size ** (-0.5) *\n min(step ** (-0.5), step * self.warmup ** (-1.5)))\n \n\n\ndef get_std_opt(model):\n return NoamOpt(model.d_model, 1, 4000,\n torch.optim.Adam(model.parameters(), lr=5e-4, betas=(0.9, 0.98), eps=1e-9))\n \n\n\n#taken from https://nlp.seas.harvard.edu/2018/04/03/attention.html#label-smoothing\n#CURRENTLY NOT USING THIS\nclass LabelSmoothing(nn.Module):\n \"Implement label smoothing.\"\n #size is output vocab size\n\n def __init__(self, size, padding_idx, smoothing=0.0):\n super(LabelSmoothing, self).__init__()\n self.criterion = nn.KLDivLoss(reduction='sum') #want to then divide by #tokens. \n self.criterion2 = nn.KLDivLoss(reduction='none')\n self.padding_idx = padding_idx\n self.confidence = 1.0 - smoothing\n self.smoothing = smoothing\n self.size = size\n self.true_dist = None\n\n #x is log(probs of predictions) and target are indices of true values \n def forward(self, x, target):\n #(output of decoder has dim [T, vocab_size, batch_size] so this will be same and target will be (T,batch_size)\n true_dist = x.data.clone()\n true_dist.fill_(self.smoothing / (self.size - 2)) #just fills matrix with self.smoothing / (self.size - 2)\n #print('true dist shape: {}, unsqueezed shape: {}'.format(true_dist.shape,target.data.unsqueeze(1).shape))\n true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence) #places confidence in correct locations (so if confidence=0.9 then true indice has val 0.9\n true_dist[:, self.padding_idx] = 0 #Makes prob of getting blank space 0\n #mask = torch.nonzero(target.data == self.padding_idx) #gets indices of where target is padding\n \n #NEED TO CREATE MASK THAT MULTIPLIES\n mask = (~(target.data == self.padding_idx)).unsqueeze(1) # is now (T,1,N)\n #now mask is (T,N) now insert middle dimension then multiply\n true_dist = mask * true_dist\n \n self.true_dist = true_dist\n #want to return both the sum of kl div over all tokens and keep track of kl per token\n \n return self.criterion(x, Variable(true_dist, requires_grad=False)), mask.sum()\n\n\n\n\n","sub_path":"BaselineCode/transformerModel.py","file_name":"transformerModel.py","file_ext":"py","file_size_in_byte":8409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"508696767","text":"import math\nimport random\n\nif __name__ == '__main__':\n\n M = input('请输入一个较大的整数')\n N = 0\n for i in range(int(M)):\n x = random.random()\n y = random.random()\n if math.sqrt(x ** 2 + y ** 2) < 1:\n N += 1\n pi = 4 * N / int(M)\n # print(pi)\n print(pi)\n","sub_path":"PythonLearning/MathematicalModeling/蒙特卡罗/get_pi.py","file_name":"get_pi.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"554870012","text":"import requests\nfrom django import template\n\nregister = template.Library()\n\n@register.simple_tag\ndef tweet_tags(url):\n twtjson = requests.get('https://publish.twitter.com/oembed?url=' + url + '&omit_script=true')\n twtparse = twtjson.json()\n twthtml = twtparse['html']\n return twthtml","sub_path":"blog/templatetags/tweet_tags.py","file_name":"tweet_tags.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"430796645","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 15 08:42:28 2020\n\n@author: gongmeiting\n\"\"\"\n\n#read thefile \n#extract the sequences of mitochondria genes\n#simplify the sequence name \n#output resulst in a new fasta file\n\n#change the working directory to where the Saccharomyces_cerevisiae.R64-1-1.cdna.all.fa is stored\nimport os\nos.chdir(\"/Users/gongmeiting/Downloads\")\nimport re\n#read the file\nsacc=open('Saccharomyces_cerevisiae.R64-1-1.cdna.all.fa')\n#creat the newfile mito_gene.fa\nnewfile=open('mito_gene.fa',\"w\")\n#Read file into a single string\ns=sacc.read()\n#use re.findall() to extract the matching strings\n#*? Repeats the previous element zero or moretimes(non-greedy)\nseq_mito=re.findall(r'(>.*?:Mito:[\\d\\D]+?gene:.*\\n[\\d\\D]+?)>',s)\n\nfor gene in seq_mito:\n #delete the unnecessary part\n #r'>.*?(gene:.*? ).*?]',r'\\1' to select only genen name and the length of the sequence\n simplify_seq_mito=re.sub(r'>.*?(gene:.*? ).*?]',r'\\1',gene)\n #delete the '\\n' and '>'\n new=simplify_seq_mito.replace('\\n','')\n #-11 because we find that the lengths of genen name in Mito are the same\n length=len(new)-11\n sacc=\">\"+'gene length:'+str(length)+' '+new+\"\\n\"\nl1=[]\nl1.append(sacc)\nnewfile.write(sacc)\n#close mewfile\nnewfile.close()\nprint(open('mito_gene.fa').read())","sub_path":"Practical8/get_mito_gene.py","file_name":"get_mito_gene.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"123411517","text":"import numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport rotations\nimport math\n\n# Sorting the directory\ndef sorting_dir(load_data_folder):\n sorting_folder_list = os.listdir(load_data_folder)\n sorted_folder_list = []\n for i in range(len(sorting_folder_list)+1):\n for sorting_folder in sorting_folder_list:\n if i == int(sorting_folder[-5:-4]):\n sorted_folder_list.append(sorting_folder)\n return sorted_folder_list\n\n# Set up the table \ncube_x =[1,2,3,4,5,6,7,8,9,10]\ncube_y =[5,6,2,3,13,4,1,2,4,8]\ncube_z =[2,3,3,3,5,7,9,11,9,10]\ndef get_cube(cube_x,cube_y,cube_z): \n phi = np.arange(1,10,2)*np.pi/4\n Phi, Theta = np.meshgrid(phi, phi)\n\n cube_x = np.cos(Phi)*np.sin(Theta)\n cube_y = np.sin(Phi)*np.sin(Theta)\n cube_z = np.cos(Theta)/np.sqrt(2)\n return cube_x,cube_y,cube_z\nx_length = 0.5\ny_length = 0.7\nz_length = 0.4\ncube_x,cube_y,cube_z = get_cube(cube_x,cube_y,cube_z)\n\n# Extract the directories.\nload_traj_folder = '/Users/bourne/Downloads/mirror learning/data_plot/all_n_rsym_trajs/'\n# Sorting the files in the list: 0,1,2,3..., for plotting the label legends in right orders.\ntraj_sorted_folder_list = sorting_dir(load_traj_folder)\n\nds = []\nfor file in traj_sorted_folder_list:\n file = os.path.join(load_traj_folder,file)\n d = np.load(file)\n ds.append(d)\n\n\n\n\n# Begin===================Extract the trajectories from observation from transition.\nall_xs =[]\nall_ys =[]\nall_zs =[]\nfor d in ds:\n xs =[]\n ys =[]\n zs = []\n for transitions in d:\n x =[]\n y =[]\n z = []\n for ob in transitions[0]:\n x.append(ob[0][0])\n y.append(ob[0][1])\n z.append(ob[0][2])\n x = np.array(x)\n y = np.array(y)\n z = np.array(z)\n xs.append(x)\n ys.append(y)\n zs.append(z)\n all_xs.append(xs)\n all_ys.append(ys)\n all_zs.append(zs)\n# End===================Extract the trajectories from observation from transition.\n\n\n# Begin===================Extract the thetas.\nload_theta_folder = '/Users/bourne/Downloads/mirror learning/data_plot/all_n_rsym_thetas/'\n# Sorting the files in the list: 0,1,2,3..., for plotting the label legends in right orders.\nthetas_sorted_folder_list = sorting_dir(load_theta_folder)\n\nall_thetas = []\nall_thetas.append('None')\nfor file in thetas_sorted_folder_list:\n file = os.path.join(load_theta_folder,file)\n thetas_in_each_file = np.load(file)\n all_thetas.append(thetas_in_each_file)\n\n# End===================Extract the thetas.\n\n# Prepare the color for plot\nprepared_color = ['c','m','gold','g','b']\nplane_colors = prepared_color.copy()\noriginal_colors = []\n# The original traj is red\noriginal_colors.append('r')\nfor i in range(4):\n n = 2**i\n pop_color = prepared_color.pop()\n for _ in range(n):\n original_colors.append(pop_color)\noriginal_colors.reverse()\n\n\n \n\n\n\n# plot each n_rsym trajectories\nfor (xs,ys,zs,n_rsym_thetas) in zip(all_xs,all_ys,all_zs,all_thetas):\n \n colour = original_colors.copy()\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n n_rsym_thetas_list = list(n_rsym_thetas)\n n_rsym_thetas_list.reverse()\n plane_colours = plane_colors.copy()\n for i,(x,y,z) in enumerate(zip(xs,ys,zs)):\n \n ax.plot(x, y, z, c=colour.pop())\n if i == 1 or i == 3 or i == 7 or i == 15:\n #Begin===================== show the kaleidoscope plane\n # Given the normal vector and the point in that plane\n point = np.array([0, 0,0 ]) + np.array([0.695, 0.75, 0.4])\n normal = np.array([0, 1, 0]) \n # for i in range(360):\n theta = n_rsym_thetas_list.pop()\n rot_vec = np.array([0, 0, theta ])\n rot_mat = rotations.euler2mat(rot_vec)\n normal = np.dot(rot_mat,normal)\n # a plane is a*x+b*y+c*z+d=0\n # [a,b,c] is the normal. Thus, we have to calculate\n # d and we're set\n d = -point.dot(normal)\n # create x,z , the plane range\n xx, zz = np.meshgrid(range(695,1800), range(0,8))\n xx = xx * 0.001\n zz = zz * 0.1\n \n # calculate corresponding z\n y = (-normal[0] * xx - normal[2] * zz - d) * 1. /normal[1]\n # plot the surface\n plane_color = plane_colours.pop()\n ax.plot_surface(xx, y, zz, alpha=0.2, color = plane_color)\n #End===================== show the kaleidoscope plane\n # robot base poiont\n ax.scatter(0.695, 0.75, 0.4, c='r')\n\n # plot the table\n ax.plot_surface(cube_x*x_length+1.3, cube_y*y_length+0.75, cube_z*z_length+0.2,alpha = 0.2, color = 'white')\n\n\n\n\n # setup the axis inf\n ax.set_xlim(0.6,1.5)\n ax.set_ylim(0.4,1)\n ax.set_zlim(0,0.8)\n ax.set_xlabel('X Label')\n ax.set_ylabel('Y Label')\n ax.set_zlabel('Z Label')\nplt.show()\n\n\n\n","sub_path":"visualized_plot_ker_traj/plot_ker_traj.py","file_name":"plot_ker_traj.py","file_ext":"py","file_size_in_byte":4952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"643579491","text":"\"\"\"Decision Tree.\"\"\"\n# import json\nimport pickle\nimport click\n# import numpy as np\n# from sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeClassifier\n# from sklearn.model_selection import train_test_split\n# from sklearn import metrics\n\n\n@click.command()\n@click.argument('x1', type=int)\ndef reg(x1):\n \"\"\"Reqression.\"\"\"\n # Import X and Y datasets\n X = pickle.load(open('/home/bee/cwl2/MyX.p', 'rb'))\n Y = pickle.load(open('/home/bee/cwl2/MyY.p', 'rb'))\n\n X = X.values\n\n print(\"My pickle X is\", X)\n Y = Y.values\n print(\"My pickle Y is\", Y)\n for i in range(x1):\n clf = DecisionTreeClassifier()\n clf1 = clf.fit(X, Y)\n print(\"Decision tree parameters\")\n print(clf1)\n pickle.dump(clf1, open('clf1.p', 'wb'))\n\n\nif __name__ == '__main__':\n reg(x1=1)\n# Ignores preserving code for now\n# pylama:ignore=C0103,R1732,W0612,W0621\n","sub_path":"beeflow/data/cwl/cwl_validation/ml-workflow/machine_learning/decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"17832296","text":"import sys\nimport os\nmyPath = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.join(myPath, '../post/'))\n\n\ndef test_parse_nodoutR61():\n \"\"\"correctly parse data from R6.1 nodout files\n \"\"\"\n from create_disp_dat import parse_line\n\n nodout = open(\"tests/nodout\", \"r\")\n n = nodout.readlines()\n line = n[8]\n raw_data = parse_line(line)\n\n assert raw_data[0] == 6\n assert raw_data[1] == 0.0\n assert raw_data[3] == -1.5\n\n\ndef test_parse_nodoutR8():\n \"\"\"correctly parse data from R8 nodout files\n \"\"\"\n from create_disp_dat import parse_line\n\n nodout = open(\"tests/nodout\", \"r\")\n n = nodout.readlines()\n line = n[10]\n raw_data = parse_line(line)\n\n assert raw_data[0] == 8\n assert raw_data[1] == 0.0\n assert raw_data[3] == -1.5\n\n\ndef test_correct_Enot():\n \"\"\"test fix -??? -> E-100\n \"\"\"\n from create_disp_dat import parse_line\n\n nodout = open(\"tests/nodout\", \"r\")\n n = nodout.readlines()\n line = n[9]\n\n raw_data = parse_line(line)\n\n assert raw_data[3] == 0.0\n\n\ndef test_count_timesteps():\n \"\"\"test counting time steps in nodout\n \"\"\"\n from create_disp_dat import count_timesteps\n\n ts_count = count_timesteps(\"tests/nodout\")\n\n assert ts_count == 2\n\n\ndef test_write_header(tmpdir):\n \"\"\"test writing disp.dat header\n \"\"\"\n from create_disp_dat import open_dispout\n from create_disp_dat import write_headers\n import struct\n\n header = {'numnodes': 4,\n 'numdims': 3,\n 'numtimesteps': 2\n }\n\n fname = tmpdir.join('testheader.dat')\n dispout = open_dispout(fname.strpath)\n write_headers(dispout, header)\n dispout.close()\n\n with open(fname, 'rb') as dispout:\n h = struct.unpack('fff', dispout.read(4 * 3))\n\n assert h[0] == 4.0\n assert h[1] == 3.0\n assert h[2] == 2.0\n\n\ndef test_write_data(tmpdir):\n \"\"\"test writing data to disp.dat\n \"\"\"\n from create_disp_dat import open_dispout\n from create_disp_dat import process_timestep_data\n import struct\n from pytest import approx\n\n fname = tmpdir.join('testdata.dat')\n dispout = open_dispout(fname.strpath)\n data = []\n data.append([float(0.0), float(0.1), float(0.2), float(0.3)])\n data.append([float(1.0), float(1.1), float(1.2), float(1.3)])\n process_timestep_data(data, dispout, writenode=True)\n dispout.close()\n\n with open(fname, 'rb') as f:\n d = struct.unpack(8 * 'f', f.read(4 * 8))\n\n assert d[0] == 0.0\n assert d[1] == 1.0\n assert d[2] == approx(0.1)\n assert d[3] == approx(1.1)\n assert d[7] == approx(1.3)\n","sub_path":"tests/test_create_disp_dat.py","file_name":"test_create_disp_dat.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"229242954","text":"# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack import *\n\n\nclass Gtensor(CMakePackage):\n \"\"\"The gtensor performance portability library.\"\"\"\n\n homepage = \"https://github.com/wdmapp/gtensor\"\n url = \"https://github.com/wdmapp/gtensor/fake.tar.gz\"\n git = \"https://github.com/wdmapp/gtensor\"\n\n maintainers = ['germasch', 'bd4']\n\n version('develop', branch='main')\n\n variant('device', default='host',\n description='Default device backend',\n values=('host', 'cuda', 'hip', 'sycl'),\n multi=False)\n variant('tests', default=False,\n description='Build with unit testing')\n\n depends_on('cmake@3.18.0:')\n\n depends_on('googletest@1.10.0:', when='+tests')\n\n depends_on('cuda', when='device=cuda')\n depends_on('thrust@1.10.0:', when='device=cuda')\n\n def cmake_args(self):\n spec = self.spec\n\n args = ['-DCPM_USE_LOCAL_PACKAGES=ON']\n args += ['-DGTENSOR_DEVICE={}'.format(\n self.spec.variants['device'].value)]\n args += ['-DBUILD_TESTING={}'.format(\n 'ON' if '+tests' in self.spec else 'OFF')]\n\n return args\n","sub_path":"spack/psc/packages/gtensor/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"442803448","text":"import argparse\nimport json\nimport mimetypes\nimport os\nimport socket\nimport sys\nimport threading\nimport traceback\nfrom email.utils import formatdate\nfrom http.server import BaseHTTPRequestHandler\nfrom io import BytesIO\n\nfrom lockfile import LockFile\n\nfrom COMP6461_LA2.bgcolor import BgColor\nfrom reliable_socket import reliable_socket\n\n\nclass response_code(enumerate):\n NOT_FOUND = 404\n OK = 200\n BAD_REQUEST = 400\n UNAUTHORIZED = 401\n INTERNAL_SERVER_ERROR = 500\n\n\nclass logger(enumerate):\n DEBUG = \"DEBUG\"\n ERROR = \"ERROR\"\n\n\nclass server:\n debugging = None\n port = None\n directory = None\n\n def __init__(self, debugging, port, directory):\n server.debugging = debugging\n server.port = port\n server.directory = os.path.abspath(directory)\n\n def configure_and_start_server(self):\n tcp_socket = reliable_socket()\n try:\n tcp_socket.bind('localhost', server.port)\n tcp_socket.enable_debugging(True)\n tcp_socket.listen(10)\n if server.debugging:\n print(BgColor.color_green_wrapper(\"\\n Server started on DEBUG mode\"))\n print(BgColor.color_green_wrapper(\"\\n Server started at port: \" + str(server.port)))\n print(BgColor.color_green_wrapper(\" Server's working directory set to: \" + server.directory + \"\\n\"))\n except socket.error:\n print(\"Socket Error : \", traceback.format_exc())\n while True:\n try:\n connection, client_address = tcp_socket.accept()\n self.print_if_debugging_is_enabled(None, \"\\n\")\n self.print_if_debugging_is_enabled(logger.DEBUG, \"client connected from \" + str(client_address))\n threading.Thread(target=httpfs().handle_client_request, args=(connection, client_address)).start()\n except (KeyboardInterrupt, Exception):\n server.print_if_debugging_is_enabled(logger.ERROR, traceback.format_exc())\n break\n\n @staticmethod\n def print_if_debugging_is_enabled(type, message):\n if args.debugging:\n if type is logger.DEBUG:\n print(BgColor.color_yellow_wrapper(\"DEBUG: \" + message))\n elif type is logger.ERROR:\n print(BgColor.color_red_wrapper(\"ERROR: \" + message))\n elif type is None:\n print(message)\n\n\nclass httpfs:\n\n def __init__(self):\n self._connection = None\n self._client_address = None\n\n self._request_type = None\n self._request_path = None\n self._request_headers = {}\n self._request_query_parameters = None\n self._request_body = None\n\n self._response_status = {}\n self._response_headers = {}\n self._response_body = None\n\n @property\n def connection(self):\n return self._connection\n\n @connection.setter\n def set_connection(self, connection):\n self._connection = connection\n\n @property\n def client_address(self):\n return self._client_address\n\n @client_address.setter\n def set_client_address(self, client_address):\n self._client_address = client_address\n\n @property\n def request_type(self):\n return self._request_type\n\n @request_type.setter\n def set_request_type(self, request_type):\n self._request_type = request_type\n\n @property\n def request_path(self):\n return self._request_path\n\n @request_path.setter\n def set_request_path(self, request_path):\n self._request_path = request_path\n\n @property\n def request_headers(self):\n return self._request_headers\n\n @request_headers.setter\n def set_request_headers(self, request_headers):\n self._request_headers.update(request_headers)\n\n @property\n def get_request_header_as_string(self):\n header = \"\"\n for key, val in self.request_headers.items():\n header = header + (key + \": \" + val + \"\\n\")\n return header\n\n @property\n def request_query_parameters(self):\n return self._request_query_parameters\n\n @request_query_parameters.setter\n def set_request_query_parameters(self, request_query_parameters):\n self._request_query_parameters = request_query_parameters\n\n @property\n def request_body(self):\n return self._request_body\n\n @request_body.setter\n def set_request_body(self, request_body):\n self._request_body = request_body\n\n @property\n def response_status(self):\n return self._response_status\n\n @response_status.setter\n def set_response_status(self, response_status):\n self._response_status = response_status\n\n @property\n def response_headers(self):\n return self._response_headers\n\n @response_headers.setter\n def set_response_headers(self, response_headers):\n self._response_headers.update(response_headers)\n\n @property\n def get_response_header_as_string(self):\n header = \"\"\n for key, val in self.response_headers.items():\n header = header + (key + \": \" + str(val) + \"\\r\\n\")\n return header\n\n @property\n def response_body(self):\n return self._response_body\n\n @response_body.setter\n def set_response_body(self, response_body):\n self._response_body = response_body\n\n def get_byte_length_of_object(self, object):\n return sys.getsizeof(object.encode(\"utf-8\"))\n\n def handle_client_request(self, connection, client_address):\n try:\n self.set_connection = connection\n self.set_client_address = str(client_address)\n while True:\n request = connection.recv()\n if len(request) > 0:\n self.parse_request(request)\n self.generate_response()\n self.send_response()\n break\n except Exception as e:\n if not self.response_status:\n self.set_response_status = {\"Internal Server Error\": response_code.INTERNAL_SERVER_ERROR}\n self.set_response_body = json.dumps({\"Message: \": \"Internal Server Error \" + self.request_path})\n self.set_response_headers = {\"Content-Type\": \"application/json\"}\n self.set_response_headers = {\"Content-Length\": self.get_byte_length_of_object(self.response_body)}\n self.send_response()\n server.print_if_debugging_is_enabled(logger.ERROR, traceback.format_exc())\n finally:\n connection.close()\n\n \"\"\"\n For HTTP Request Parsing \n see (https://stackoverflow.com/a/5955949/14375140)\n \"\"\"\n\n def parse_request(self, request):\n request = HTTPRequest(request)\n server.print_if_debugging_is_enabled(logger.DEBUG, \"Received Request from client: \" + self.client_address)\n if not request.error_code:\n self.set_request_type = request.command\n self.set_request_headers = request.headers\n self.set_request_path = request.path\n content_length = self.request_headers.get('Content-Length')\n if content_length:\n self.set_request_body = request.rfile.read(int(content_length)).decode(\"utf-8\")\n server.print_if_debugging_is_enabled(logger.DEBUG,\n \"Parsing \" + self.request_type + \" request from client: \" + self.client_address)\n else:\n self.set_request_type = request.command\n self.set_response_status = {\"Bad Request\": response_code.BAD_REQUEST}\n self.set_response_body = json.dumps(\"Invalid Request Format\")\n self.set_response_headers = {\"Content-Type\": \"application/json\"}\n self.set_response_headers = {\"Content-Length\": self.get_byte_length_of_object(self.response_body)}\n server.print_if_debugging_is_enabled(logger.DEBUG, \"Bad Request: Invalid Request Format\"\n + str(request.error_code) + \"From\" + self.client_address)\n raise SyntaxError(\"Invalid Request Format: \" + str(request.error_code))\n\n def generate_response(self):\n if \"..\" in self.request_path:\n self.set_response_status = {\"Unauthorized\": response_code.UNAUTHORIZED}\n self.set_response_body = json.dumps(\"Access denied\")\n self.set_response_headers = {\"Content-Type\": \"application/json\"}\n self.set_response_headers = {\"Content-Length\": self.get_byte_length_of_object(self.response_body)}\n server.print_if_debugging_is_enabled(logger.DEBUG,\n \"Access denied at path: \" + server.directory + self.request_path +\n \" for client: \" + self.client_address)\n else:\n if self.request_type == \"GET\":\n if self.request_path == \"/\":\n list_of_files = os.listdir(server.directory)\n self.set_response_status = {\"OK\": response_code.OK}\n self.set_response_body = json.dumps({\"list\": list_of_files})\n self.set_response_headers = {\"Content-Type\": \"application/json\"}\n self.set_response_headers = {\"Content-Length\": self.get_byte_length_of_object(self.response_body)}\n elif os.path.exists(server.directory + self.request_path):\n with open(server.directory + self.request_path) as f:\n file_content = f.read()\n mime_type = mimetypes.guess_type(self.request_path)\n self.set_response_status = {\"OK\": response_code.OK}\n self.set_response_body = file_content\n self.set_response_headers = {\"Content-Type\": mime_type[0]}\n self.set_response_headers = {\n \"Content-Length\": self.get_byte_length_of_object(self.response_body)}\n if mime_type[0] != \"application/json\":\n self.set_response_headers = {\n \"Content-Disposition\": \"attachment; filename=\" + os.path.basename(f.name)}\n else:\n self.set_response_headers = {\"Content-Disposition\": \"inline\"}\n else:\n self.set_response_status = {\"Not Found\": response_code.NOT_FOUND}\n self.set_response_body = json.dumps({\"message: \": \"requested file does not exist or invalid path\"})\n self.set_response_headers = {\"Content-Type\": \"application/json\"}\n self.set_response_headers = {\"Content-Length\": self.get_byte_length_of_object(self.response_body)}\n server.print_if_debugging_is_enabled(logger.DEBUG,\n \"requested file does not exist or invalid path at \" + self._request_path + \" for client: \" + self.client_address)\n\n elif self.request_type == \"POST\":\n \"\"\"\n Preprocessing: If path has /post attached to it first than remove it, if path does't start \n with '/' than append it as well.\n \"\"\"\n self.set_request_path = self.request_path.replace(\"/post\", \"\", 1)\n if not self.request_path.startswith(\"/\"):\n self.set_request_path = \"/\" + self.request_path\n\n os.makedirs(os.path.dirname(server.directory + self.request_path), exist_ok=True)\n\n if os.path.isdir(server.directory + self.request_path):\n self.set_response_status = {\"Bad Request\": response_code.BAD_REQUEST}\n self.set_response_body = json.dumps({\"Message: \": \"requested path is directory\"})\n self.set_response_headers = {\"Content-Type\": \"application/json\"}\n self.set_response_headers = {\"Content-Length\": self.get_byte_length_of_object(self.response_body)}\n server.print_if_debugging_is_enabled(logger.DEBUG,\n \"requested path is Directory for client \" + self.client_address)\n raise IsADirectoryError(self)\n\n if self.request_body:\n lock = LockFile(server.directory + self.request_path)\n lock.acquire()\n mode = \"w\"\n if \"Overwrite\" in self.request_headers.keys() and self.request_headers[\"Overwrite\"]:\n if self.request_headers[\"Overwrite\"].lower() == \"false\":\n mode = \"a\"\n file = open(server.directory + self.request_path, mode)\n file.write(self.request_body)\n file.close()\n lock.release()\n self.set_response_status = {\"OK\": response_code.OK}\n self.set_response_body = json.dumps({\"Success: \": \"true\"})\n self.set_response_headers = {\"Content-Type\": \"application/json\"}\n self.set_response_headers = {\"Content-Length\": self.get_byte_length_of_object(self.response_body)}\n else:\n self.set_response_status = {\"OK\": response_code.OK}\n self.set_response_body = json.dumps({\"Message: \": \"No Content to Write\"})\n self.set_response_headers = {\"Content-Type\": \"application/json\"}\n self.set_response_headers = {\"Content-Length\": self.get_byte_length_of_object(self.response_body)}\n\n def send_response(self):\n response_status = list(self.response_status.keys())[0]\n response_code = str(self.response_status[response_status])\n date = str(formatdate(timeval=None, localtime=False, usegmt=True))\n\n server.print_if_debugging_is_enabled(logger.DEBUG,\n \"sending response of \" + self.request_type + \" request with status \" +\n response_code + \" at time: \"\n + date + \" to client: \" + self.client_address)\n\n response = \"HTTP/1.0 \" + response_code + \" \" + response_status + \"\\r\\n\" + \\\n \"Date: \" + date + \"\\r\\n\" + \\\n \"Server: \" + \"COMP6461_LA1 (Unix)\" + \"\\r\\n\" + \\\n self.get_response_header_as_string + \"\\r\\n\" + \\\n self.response_body\n\n self.connection.sendall(response.encode('utf-8'))\n\n\nclass HTTPRequest(BaseHTTPRequestHandler):\n def __init__(self, request_text):\n self.rfile = BytesIO(request_text)\n self.raw_requestline = self.rfile.readline()\n self.error_code = self.error_message = None\n self.parse_request()\n\n def send_error(self, code, message):\n self.error_code = code\n self.error_message = message\n\n\nparser = argparse.ArgumentParser(description=\"http server\")\n\nparser.add_argument(\"-v\", dest=\"debugging\",\n help=\"Prints debugging messages if enabled\",\n action=\"store_true\")\nparser.add_argument(\"-p\",\n dest=\"port\",\n default=\"8080\",\n type=int,\n help=\"Specifies the port number that the server will listen and serve at \\\n Default is 8080.\",\n action=\"store\")\nparser.add_argument(\"-d\",\n dest=\"directory\",\n help=\"Specifies the directory that the server will use to read/write requested files. Default is \"\n \"the current directory when launching the application.\",\n default=\"./\")\n\nargs = parser.parse_args()\nserver_instance = server(args.debugging, args.port, args.directory)\nserver_instance.configure_and_start_server()\n","sub_path":"COMP6461_LA2/httpfs.py","file_name":"httpfs.py","file_ext":"py","file_size_in_byte":15826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"284190623","text":"# -*- coding: utf-8 -*-\n\nimport preprocess\nimport model\nimport os\nimport lightgbm\nimport pandas as pd\nimport pickle\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\ndef train():\n for station in range(1, 5):\n ld = preprocess.LoadData(station)\n fe = preprocess.FeatureEngineering()\n lgb = model.LGBModel()\n \n data = ld.load_data()\n #print(data.shape)\n data = fe.feature_extract(data)\n #print(data.shape)\n \n x = data.drop(['实际功率', '实发辐照度'], axis = 1)\n y = data['实际功率']\n y = data['实发辐照度']\n x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=0.1, random_state=678)\n #print(x_train.shape, x_val.shape)\n \n #print(x_train.head(5))\n gbm = lgb.train(x_train, y_train, x_val ,y_val)\n '''\n dumpPath = 'model/'\n if not os.path.exists(dumpPath):\n os.makedirs(dumpPath)\n with open(dumpPath+'lgb_{}.model'.format(station), 'wb') as f:\n pickle.dump(gbm, f)\n #gbm.save_model(, num_iteration=gbm.best_iteration)\n '''\n\ndef predict():\n for station in range(1 ,5):\n ld = preprocess.LoadData(station, 'test')\n fe = preprocess.FeatureEngineering()\n with open('model/lgb_{}.model'.format(station), 'rb') as f:\n gbm = pickle.load(f)\n #gbm = lightgbm.Booster(model_file=)\n data = ld.load_data()\n data = fe.feature_extract(data, 'test')\n \n test_id = data['id']\n del_id = data[data['辐照度'].isin([-1.0])]['id']\n test = data.drop(['id'], axis=1)\n \n republish_pred = gbm.predict(test, num_iteration=gbm.best_iteration)\n republish_pred = pd.DataFrame(republish_pred)\n sub = pd.concat([test_id, republish_pred], axis=1)\n print(sub.shape)\n sub.columns = ['id', 'predicition']\n sub.loc[sub['id'].isin(del_id), 'predicition'] = 0.0\n sub.to_csv('submit/version_{}.csv'.format(station), index=False, sep=',', encoding='UTF-8') \n\n\nif __name__ == '__main__':\n train()\n '''\n predict()\n data1 = pd.read_csv('submit/version_1.csv')\n data2 = pd.read_csv('submit/version_2.csv')\n data3 = pd.read_csv('submit/version_3.csv')\n data4 = pd.read_csv('submit/version_4.csv')\n res = pd.concat([data1, data2, data3, data4], axis = 0)\n res.to_csv('submit/res.csv', index=False, encoding='utf-8')\n '''\n\n\n\n","sub_path":"version_02/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"237728894","text":"import pdftotext\n\npdf_file = open(\"report.pdf\", \"rb\")\n\npdf = pdftotext.PDF(pdf_file)\n\nfor page in pdf:\n print(page)\n\nprint(pdf[0])\n\n# Resize the Window - Non Pep8 Compliant, mandated by Kivy\nfrom kivy.config import Config\nimport face_recognition\nConfig.set('graphics', 'width', '400')\nConfig.set('graphics', 'height', '200')\n\nfrom kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.label import Label\nfrom kivy.properties import *\nimport pyttsx3\nimport time\nfrom kivy.lang import Builder\nfrom kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition\n\n\nBuilder.load_string(\"\"\"\n#:kivy 1.0.9\n#:import FadeTransition kivy.uix.screenmanager.FadeTransition\n\n\n\n name: \"home_page\"\n GridLayout:\n cols:1\n size: root.width, root.height\n GridLayout:\n cols:2\n Button:\n text: \"Open\"\n on_press: app.home_page.open_file\n Button:\n text:\"Convert\"\n size_hint: 1, 0.2\n on_press: app.screen_manager.current = \"login_page\"\n\n\n\n\"\"\")\n\n\n# defined in builder at top\nclass HomePage(Screen):\n def open_file(self):\n print(\"hello\")\n\n\n\nclass FaceApp(App):\n\n def build(self):\n self.screen_manager = ScreenManager()\n self.home_page = HomePage()\n self.screen_manager.add_widget(home_page(name='home_page'))\n return self.screen_manager\n\n\nif __name__ == '__main__':\n FaceApp().run()","sub_path":"miscellaneous/converter_app.py","file_name":"converter_app.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"239206308","text":"import math\nimport sys_IO as io\nimport picamera\nimport picamera.array\nimport numpy\nimport time\n\n\n###################### INITIALISE ######################\n\n#parameters\nfield_width = 182 #cm\nfield_length = 243 #cm\n\nus_offset = 10 #cm\n\nturning_memory = 100;\n\ndirection_correction_amount = 1\nno_ball_in_sight_threshold = 200\n\ncam_fov = 40 #camera's field of view in degrees\navoiding_stuff_distance = 10\n\ngoal_dir = io.get_comp(True, 20)\nheading = goal_dir\npre_ball_direction = 0;\nultrasonics = [0,0,0,0]\n\n#capturing photos\nphoto_width = 32\nphoto_height = 32\ny_total = []\n\ncamera = picamera.PiCamera()\noutput = picamera.array.PiRGBArray(camera)\ncamera.rotation = 90\ncamera.resolution = (photo_width, photo_height)\n\ndef get_difference(goal, current):\n if goal > 360 or goal < 0 or current > 360 or current < 0:\n raise Exception(\"out of range\")\n diff = current - goal\n absDiff = abs(diff)\n\n if absDiff == 180:\n return -(absDiff)\n elif absDiff < 180:\n return -(diff)\n elif current > goal:\n return -(absDiff - 360)\n else:\n return -(360 - absDiff)\n \ndef get_coords():\n #Finds coordinates on the feild\n offset = get_difference(goal_dir, heading)\n\n ultrasonics[0] = io.get_ultrasonic_val(0) + us_offset\n ultrasonics[1] = io.get_ultrasonic_val(1) + us_offset\n ultrasonics[2] = io.get_ultrasonic_val(2) + us_offset\n ultrasonics[3] = io.get_ultrasonic_val(3) + us_offset\n right = ultrasoncis[1]/field_width\n left = ultrasoncis[3]/field_width\n \n x = 0.\n \n if left <= right:\n right += 1-left\n right = right/2\n x = 1 - right\n else:\n left += 1-right\n left = left/2\n x = left\n \n y = ultrasonics[2]/field_length\n return x , y\n\ndef get_ball_dir():\n y_total = []\n cam_array = io.get_camera_array(camera, output)\n\n for x in range(photo_width):\n column = 0\n for y in range(photo_height):\n r = cam_array[x,y,0]\n g = cam_array[x,y,1]\n b = cam_array[x,y,2]\n\n if r > 70 and g < 70 and b < 70:\n column += 1\n y_total.append(column)\n\n index = y_total.index(max(y_total))\n \n if index >= 10:#threshold\n percent = 1-(((index+1)/photo_width))\n else:\n percent = None\n return percent\n\n#################################### MAIN LOOP #####################################\nwhile True:\n heading = io.get_comp(True, 4)\n ball_dir = get_ball_dir()\n\n m1 = 0.\n m2 = 0.\n m3 = 0.\n kicker = 0.\n\n if io.get_ultrasonic_val(0) < 15:\n #turn to goal\n offset = get_difference(goal_dir,heading)#goal dir yet to be changed\n kicker = -100\n if abs(offset) < 10:\n print(\"charging\")\n m3 -= 100\n m1 += 100\n time.sleep(1.5)\n #TODO: make something here that reverses the kicker if it's the robot is on the far side of the field\n else:\n print(abs(offset))\n #face north\n m2 += 80*offset\n else:\n if ball_dir == None:\n #turn to ball\n m1, m2 , m3 = turning_memory , turning_memory , turning_memory\n else:\n #drive to ball\n m1 += 80 + (ball_dir-0.5)*20\n m3 = - m1\n turning_memory = 100 * numpy.sign(ball_dir-0.5)\n\n\n\n #output\n io.change_motor(m1,0)\n io.change_motor(m2,1)\n io.change_motor(m3,2)\n io.change_motor(kicker,3)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"507250065","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\nclass SinglyLinkedListNode:\n def __init__(self, node_data):\n self.data = node_data\n self.next = None\n\nclass SinglyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert_node(self, node_data):\n node = SinglyLinkedListNode(node_data)\n\n if not self.head:\n self.head = node\n else:\n self.tail.next = node\n\n\n self.tail = node\n\ndef print_singly_linked_list(node, sep, fptr):\n while node:\n fptr.write(str(node.data))\n\n node = node.next\n\n if node:\n fptr.write(sep)\n\n# Complete the mergeLists function below.\n\n#\n# For your reference:\n#\n# SinglyLinkedListNode:\n# int data\n# SinglyLinkedListNode next\n#\n#\nsys.setrecursionlimit(10000)\ndef mergeLists(head1, head2):\n if head1 is None and head2 is None:\n return None\n elif head1 is None: \n return head2\n elif head2 is None: \n return head1\n\n if head1.data <= head2.data:\n smaller = head1\n smaller.next = mergeLists(head1.next, head2)\n else:\n smaller = head2\n smaller.next = mergeLists(head1, head2.next)\n return smaller","sub_path":"merge2sortedll.py","file_name":"merge2sortedll.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"337818604","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 21 14:20:56 2016\n\n@author: bartja02\n\"\"\"\n\n#TODO: function to append impressions\n\n\nimport numpy as np\nimport pandas as pd\nimport os as os\nfrom datetime import datetime, timedelta\nimport random\n\n#some functions\n\ndef combine_ids(hhids, pids):\n hh_p_id = []\n if len(hhids) == len(pids):\n for i in range(len(pids)):\n h_id = str(hhids[i]) \n p_id = str(pids[i])\n if len(p_id) > 2:\n print(\"HH too large\")\n break\n elif len(p_id) == 1:\n p_id = '0'+p_id\n combined_id = h_id + p_id\n hh_p_id.append(int(combined_id))\n return hh_p_id\n\ndef random_date(start, end):\n length_in_days = (end - start)\n random_days = random.randint(0,length_in_days.days)\n return start + timedelta(days = random_days)\n\n#import files\nos.chdir('C:\\\\Users\\\\bartja02\\\\Documents\\\\GitHub\\\\MA_Audience_Link\\\\data')\ntv_inputs = pd.read_csv('pilot_sample_data.csv')\ndig_inputs = pd.read_csv('digital_exposures.csv')\n\n\"\"\"\nClean TV data\n\"\"\"\n\n#combine id columns\ntv_hh_p_ids = combine_ids(tv_inputs['household_id'].tolist(), tv_inputs['person_id'].tolist())\ntv_inputs.insert(0, 'hh_p_ids', tv_hh_p_ids)\n\n\n#remove columns\ntv_inputs.drop(['Unnamed: 0', 'household_id', 'person_id'], axis = 1, inplace = True)\n\n#rename column to something useful\ntv_inputs.rename(columns = {'9 N/A':'exposure_time', \n 'air_date_6_to_6' : 'exposure_date', }, inplace = True)\n#convert string to date\ntv_inputs['exposure_date'] = pd.to_datetime(tv_inputs['exposure_date']) \n\n\"\"\"\nclean digital data\n\"\"\"\n\n#combine id columns\ndig_hh_p_ids = combine_ids(dig_inputs['household_id'].tolist(), dig_inputs['person_id'].tolist())\ndig_inputs.insert(0, 'hh_p_ids', dig_hh_p_ids)\n\n#remove unneeded columns\ndig_inputs.drop(['Unnamed: 0','HHPID','household_id','Total Digital', 'person_id','age','sex','intab','AEN Prime Viewers','Local Spot'], axis = 1, inplace = True)\n\n#remove superfluous words from title\nfor i in range(len(dig_inputs.columns)):\n old = dig_inputs.columns[i] \n new = dig_inputs.columns[i].replace('Digital ','')\n dig_inputs.rename(columns = {old : new}, inplace = True)\n\n#unpivot data\nsite_list = ['AOL', 'MSN', 'IMDb', 'Huffington Post',\n 'NYTimes', 'THR', 'All Other', 'Hulu', 'NCM Portfolio of Sites',\n 'New York Magazine', 'TremorVideo', 'Turn Network', 'Undertone',\n 'Variety', 'Weather Channel']\ndig_unpivoted = pd.melt(dig_inputs, id_vars = ['hh_p_ids'], var_name = 'site', value_vars = site_list, value_name = 'impressions')\n\n#remove zero exposure lines\ndig_imps_summed = dig_unpivoted[dig_unpivoted['impressions'].ne(0)]\n\ncampaign_start = tv_inputs.exposure_date.min()\ncampaign_end = tv_inputs.exposure_date.max()\n\n#generate mock exposures\nmock_data = []\n\nfor index, row in dig_imps_summed.iterrows(): #iterates over the rows\n impression_count = row['impressions']\n for i in range(impression_count): #generates over the count of impressions from the input file\n mock_date = random_date(campaign_start, campaign_end) #random date\n mock_impression = [row['hh_p_ids'],row['site'],mock_date] #generates a line for the impression with a made up date\n mock_data.append(mock_impression)\n\nmock_digital_impressions = pd.DataFrame(mock_data, columns = ['hh_p_ids', 'site', 'impression_date'])\n\nmock_digital_impressions.to_csv('mock_digital_impressions.csv', sep = '\\t')","sub_path":"mock_digital_exposures.py","file_name":"mock_digital_exposures.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"579201265","text":"import threading, logging, time\n\n\ndef daemon():\n logging.debug('starting')\n time.sleep(2)\n logging.debug('exiting')\n\ndef nonDaemon():\n logging.debug('starting')\n logging.debug('exiting')\n\nlogging.basicConfig(level = logging.DEBUG, format='(%(threadName)-10s) %(message)s',)\n\nd = threading.Thread(name = 'daemon', target = daemon)\nd.setDaemon(True)\n\nn = threading.Thread(name = 'non-daemon', target = nonDaemon)\n\nd.start()\nn.start()\n\nd.join(1)\nprint('d.isAlive() %s'%(d.isAlive()))\nn.join()\n\n","sub_path":"V_threading.py","file_name":"V_threading.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"643909160","text":"def repeat(n, sym):\n s = ''\n while n > 0:\n s = s + sym\n n = n - 1\n return s\n\ndef line(n):\n return repeat(n, '*')\n\ndef triangle(n):\n s = ''\n while n > 0 :\n s = line(n) + '\\n' + s\n n = n - 1\n return s\n\nret = repeat(3, '#')\nl = line(5)\nt = triangle(6)\nt2 = triangle(3)\nprint()","sub_path":"2020-2021/DEV2/Chapter 2/BA07.py","file_name":"BA07.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"271408167","text":"import pygame\nfrom Menu import *\nfrom Jugador import *\nfrom Levels import *\nfrom Maps import *\n\n#setup\npygame.init()\n\nclass New_Game():\n def __init__(self,width,height,FPS,Title,Image_Bg):\n\n self.width = width\n self.height = height\n self.fps = FPS\n self.title = Title\n self.window = pygame.display.set_mode((self.width,self.height))\n pygame.display.set_caption(self.title) \n\n image = pygame.image.load(Image_Bg).convert()\n self.Background = pygame.transform.scale(image,(self.width,self.height)).convert()\n self.Background_rect = self.Background.get_rect()\n\n self.Screens= {}\n self.Run = True\n self.Controlador_Interfaz = Controlador_Interfaz(self)\n\n #crear los menus\n self.Main_Menu = Main_Menu(self,\"./Runner_Game/Images/Background_Menu.png\",\"Main\")\n self.Pause_Menu = Pause_Menu(self,\"Pause\")\n self.Levels_Menu = Levels_Menu(self,\"./Runner_Game/Images/stage.jpg\",\"Levels\")\n \n #Agregar los controladores \n self.Controlador_Interfaz.Add_Menu(self.Main_Menu)\n self.Controlador_Interfaz.Add_Menu(self.Pause_Menu)\n self.Controlador_Interfaz.Add_Menu(self.Levels_Menu)\n \n #activar main como pantalla activo\n self.Controlador_Interfaz.Active_screen = self.Controlador_Interfaz.Menus[\"Main\"]\n\n #activar el boton play inicial\n self.Controlador_Interfaz.Positioned = self.Main_Menu.buttons[0]\n\n #Creo el jugador, el parametro self hace referencia al mismo objeto \"New_Game\" que estoy creando en este init\n self.Player = Player(self,x=200)\n\n #creo los niveles y añado el nivel inicial\n self.Levels = []\n self.Levels.append(level(Map_1,self.width+6450,self.height,self,\"./Runner_Game/Images/stage.jpg\",\"Nivel_1\",(50,50)))\n self.Levels.append(level(Map_2,self.width+4000,self.height,self,\"./Runner_Game/Images/Background_Lvl.png\",\"Nivel_2\",(325,50)))\n self.Levels.append(level(Map_3,self.width+4000,self.height,self,\"./Runner_Game/Images/Locked2.png\",\"Nivel_3\",(600,50)))\n self.Levels.append(level(Map_3,self.width+4000,self.height,self,\"./Runner_Game/Images/Background_Lvl.png\",\"Nivel_4\",(50,50+175+10)))\n self.Levels.append(level(Map_3,self.width+4000,self.height,self,\"./Runner_Game/Images/Background_Lvl.png\",\"Nivel_5\",(325,50+175+10)))\n self.Levels.append(level(Map_3,self.width+4000,self.height,self,\"./Runner_Game/Images/Background_Lvl.png\",\"Nivel_6\",(600,50+175+10)))\n \n #siempre dejo desbloqueado solo el primer nivel\n self.Levels[0].locked = False\n ","sub_path":"Setups.py","file_name":"Setups.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"613382319","text":"#!/usr/bin/env python3\r\n\r\nfrom flask import Flask, abort, redirect, request\r\nfrom flask_restful import Api, Resource, reqparse\r\nfrom random import randint\r\nimport requests\r\n\r\napp = Flask(__name__)\r\napi = Api(app)\r\n\r\nclass Rerouter(Resource):\r\n\r\n def get(self, id):\r\n pass\r\n\r\n def post(self, id):\r\n pass\r\n\r\n def put(self, id):\r\n pass\r\n\r\n def delete(self, id):\r\n pass\r\n\r\n def __init__(self):\r\n self.get= self.catch_all\r\n self.patch= self.catch_all\r\n self.post= self.catch_all\r\n self.put= self.catch_all\r\n self.delete= self.catch_all\r\n self.copy= self.catch_all\r\n self.head= self.catch_all\r\n self.options= self.catch_all\r\n self.link= self.catch_all\r\n self.unlink= self.catch_all\r\n self.purge= self.catch_all\r\n self.lock= self.catch_all\r\n self.unlock= self.catch_all\r\n self.propfind= self.catch_all\r\n self.view= self.catch_all\r\n\r\n Resource.__init__(self)\r\n\r\n def get_ips(self):\r\n with open('active_ips.txt', 'r') as f:\r\n ips= []\r\n print(\"IPs ativos:\")\r\n for line in f:\r\n ips.append(line.strip())\r\n print(ips[-1])\r\n return ips\r\n\r\n def choose_ip_randomly(self, ips):\r\n chosen_index= randint(0, len(ips)-1)\r\n print(\"IP a ser redirecionado: \"+ips[chosen_index])\r\n return ips[chosen_index]\r\n\r\n def reroute(self, url, body, method):\r\n\r\n reroute_dict={\r\n 'GET': requests.get,\r\n 'PUT': requests.put,\r\n 'POST': requests.post,\r\n 'DELETE': requests.delete\r\n }\r\n\r\n response= reroute_dict[method](url, json=body)\r\n\r\n return response.json(), response.status_code\r\n\r\nclass RerouteTaskID(Rerouter):\r\n\r\n def catch_all(self, id):\r\n print(\"Redirecionando chamada.\")\r\n ips= self.get_ips()\r\n if ips:\r\n ip= self.choose_ip_randomly(ips)\r\n\r\n id_url= '/'+str(id)\r\n url=\"http://\"+ip+':5000'+'/Tarefa'+id_url\r\n\r\n return self.reroute(url, request.get_json(), request.method)\r\n return '', 423\r\n\r\n\r\nclass RerouteTask(Rerouter):\r\n\r\n def catch_all(self):\r\n print(\"Redirecionando chamada.\")\r\n ips= self.get_ips()\r\n if ips:\r\n ip= self.choose_ip_randomly(ips)\r\n\r\n url=\"http://\"+ip+':5000'+'/Tarefa'\r\n\r\n return self.reroute(url, request.get_json(), request.method)\r\n return '', 423\r\n\r\nclass RerouteHealthCheck (Rerouter):\r\n\r\n def catch_all(self):\r\n print(\"Redirecionando chamada.\")\r\n ips= self.get_ips()\r\n if ips:\r\n ip= self.choose_ip_randomly(ips)\r\n\r\n url=\"http://\"+ip+':5000'+'/healthcheck'\r\n\r\n return self.reroute(url, request.get_json(), request.method)\r\n return '', 423\r\n\r\n\r\napi.add_resource(RerouteTaskID, '/Tarefa/')\r\napi.add_resource(RerouteTask, '/Tarefa')\r\napi.add_resource(RerouteHealthCheck, '/healthcheck')\r\n\r\napp.run(debug=True,host=\"0.0.0.0\",port = 5000)\r\n","sub_path":"projeto/load_balancer/lb_service.py","file_name":"lb_service.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"384236762","text":"from fbchat import Client\nfrom fbchat.models import *\nfrom time import strftime\nimport configparser\nimport requests\n\n\nclass Config():\n def __init__(self):\n config = configparser.ConfigParser()\n config.read('config.cfg')\n self.login = config['credentials']['nickname']\n self.password = config['credentials']['password']\n self.conversation_id = config['settings']['conversation_id']\n self.api_key = config['openweathermap']['api_key']\n\n\nclass Bot(Client):\n conversation_id = Config().conversation_id\n\n def most(self):\n time = int(strftime('%H')+strftime('%M'))\n if 0000 <= time <= 1030 or 1100 <= time <= 1200 or 1300 <= time <= 1330 or 1430 <= time <= 1600 or 1730 <= time <= 2359:\n return \"Most jest otwarty.\"\n else:\n return \"Most jest zamknięty.\"\n\n def pogoda(self, city):\n api_key = Config().api_key\n params = {'q': city, 'APPID': api_key, 'units': 'metric'}\n r = requests.get(\n \"https://api.openweathermap.org/data/2.5/weather\", params)\n if r.status_code == 200:\n r_json = r.json()\n temp = r_json['main']['temp']\n status = r_json['weather'][0]['description']\n wind_speed = r_json['wind']['speed']\n return (\"Pogoda w {}\\r\\n\"\n \"Temperatura: {}°C\\r\\n\"\n \"Status: {}\\r\\n\"\n \"Prędkość wiatru {} m/s\".format(city, temp, status, wind_speed))\n else:\n return \"Something went wrong... correct command usage example: pogoda Gizycko,pl\"\n\n def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):\n commands = {}\n self.markAsDelivered(thread_id, thread_type)\n msg = message_object.text.lower()\n print(\"{} said: {}\".format(author_id, message_object.text))\n for command_name in dir(self):\n commands[command_name] = getattr(self, command_name)\n command, args = (msg.split(\" \", 1) + [\" \"])[:2]\n if command in commands and author_id != self.uid:\n if len(args) > 1:\n self.send(Message(commands[command](\n args)), thread_id=self.conversation_id)\n else:\n self.send(Message(commands[command]()),\n thread_id=self.conversation_id)\n\n\nif __name__ == \"__main__\":\n cfg = Config()\n bot = Bot(cfg.login, cfg.password)\n bot.listen()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"613130889","text":"# MIT License\n#\n# Copyright (c) 2021 Soohwan Kim\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom omegaconf import DictConfig\n\nfrom openspeech.models import register_model\nfrom openspeech.models import OpenspeechCTCModel\nfrom openspeech.encoders.quartznet import QuartzNet\nfrom openspeech.tokenizers.tokenizer import Tokenizer\nfrom openspeech.models.quartznet.configurations import (\n QuartzNet5x5Configs,\n QuartzNet10x5Configs,\n QuartzNet15x5Configs,\n)\n\n\n@register_model('quartznet5x5', dataclass=QuartzNet5x5Configs)\nclass QuartzNet5x5Model(OpenspeechCTCModel):\n r\"\"\"\n QUARTZNET: DEEP AUTOMATIC SPEECH RECOGNITION WITH 1D TIME-CHANNEL SEPARABLE CONVOLUTIONS\n Paper: https://arxiv.org/abs/1910.10261.pdf\n\n Args:\n configs (DictConfig): configuration set.\n tokenizer (Tokeizer): tokenizer is in charge of preparing the inputs for a model.\n\n Inputs:\n inputs (torch.FloatTensor): A input sequence passed to encoders. Typically for inputs this will be a padded `FloatTensor` of size ``(batch, seq_length, dimension)``.\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\n\n Returns:\n outputs (dict): Result of model predictions that contains `y_hats`, `logits`, `output_lengths`\n \"\"\"\n\n def __init__(self, configs: DictConfig, tokenizer: Tokenizer) -> None:\n super(QuartzNet5x5Model, self).__init__(configs, tokenizer)\n\n def build_model(self):\n self.encoder = QuartzNet(\n configs=self.configs,\n input_dim=self.configs.audio.num_mels,\n num_classes=self.num_classes,\n )\n\n\n@register_model('quartznet10x5', dataclass=QuartzNet10x5Configs)\nclass QuartzNet10x5Model(QuartzNet5x5Model):\n r\"\"\"\n QUARTZNET: DEEP AUTOMATIC SPEECH RECOGNITION WITH 1D TIME-CHANNEL SEPARABLE CONVOLUTIONS\n Paper: https://arxiv.org/abs/1910.10261.pdf\n\n Args:\n configs (DictConfig): configuration set.\n tokenizer (Tokeizer): tokenizer is in charge of preparing the inputs for a model.\n\n Inputs:\n inputs (torch.FloatTensor): A input sequence passed to encoders. Typically for inputs this will be a padded `FloatTensor` of size ``(batch, seq_length, dimension)``.\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\n\n Returns:\n outputs (dict): Result of model predictions that contains `y_hats`, `logits`, `output_lengths`\n \"\"\"\n def __init__(self, configs: DictConfig, tokenizer: Tokenizer) -> None:\n super(QuartzNet10x5Model, self).__init__(configs, tokenizer)\n\n\n@register_model('quartznet15x5', dataclass=QuartzNet15x5Configs)\nclass QuartzNet15x5Model(QuartzNet5x5Model):\n r\"\"\"\n QUARTZNET: DEEP AUTOMATIC SPEECH RECOGNITION WITH 1D TIME-CHANNEL SEPARABLE CONVOLUTIONS\n Paper: https://arxiv.org/abs/1910.10261.pdf\n\n Args:\n configs (DictConfig): configuration set.\n tokenizer (Tokeizer): tokenizer is in charge of preparing the inputs for a model.\n\n Inputs:\n inputs (torch.FloatTensor): A input sequence passed to encoders. Typically for inputs this will be a padded `FloatTensor` of size ``(batch, seq_length, dimension)``.\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\n\n Returns:\n outputs (dict): Result of model predictions that contains `y_hats`, `logits`, `output_lengths`\n \"\"\"\n def __init__(self, configs: DictConfig, tokenizer: Tokenizer) -> None:\n super(QuartzNet15x5Model, self).__init__(configs, tokenizer)\n","sub_path":"openspeech/models/quartznet/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"557608325","text":"import pytest\nfrom selenium import webdriver\n\n\ndef pytest_addoption(parser):\n parser.addoption('--language', action='store', default='en',\n help=\"Choose language, for example: ru or es or fr\")\n\n\n@pytest.fixture(scope=\"function\")\ndef browser(request):\n # de-DE\n browser_language = request.config.getoption(\"language\")\n print(\"\\nstart browser for test..\", browser_language)\n option = webdriver.ChromeOptions()\n option.add_experimental_option(\"excludeSwitches\", ['enable-automation', 'enable-logging'])\n option.add_argument(f\"--lang={browser_language}\")\n browser = webdriver.Chrome(options=option)\n yield browser\n print(\"\\nquit browser..\")\n browser.quit()\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"151004780","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport pytest\nfrom io import StringIO\nimport html_render as hr\n\ndef test_element():\n out_element = hr.Element(\"content message\")\n assert out_element.content == [\"content message\"]\n\ndef test_append():\n append_element = hr.Element(\"append message1\")\n append_element.append(\"append message2\")\n assert append_element.content == [\"append message1\", \"append message2\"]\n\ndef test_render():\n render_element = hr.Element(\"render text\")\n render_element.tag = 'html'\n f = StringIO()\n render_element.render(f)\n assert f.getvalue() == \"\\n\" + render_element.indent + \"render text\\n\\n\"\n\ndef test_OneLineTag():\n out_OneLineTag = hr.OneLineTag(\"create title\")\n out_OneLineTag.tag = 'title'\n f = StringIO()\n out_OneLineTag.render(f)\n assert f.getvalue() == 'create title\\n'\n\ndef test_SelfClosingTag():\n out_SelfClosingTag = hr.SelfClosingTag()\n out_SelfClosingTag.tag = 'meta'\n f = StringIO()\n out_SelfClosingTag.render(f)\n assert f.getvalue() == '\\n'\n\ndef test_A():\n out_A = hr.A(\"http://google.com\", \"Link\")\n f = StringIO()\n out_A.render(f)\n assert f.getvalue() == '\\n Link\\n\\n'\n\ndef test_H():\n out_H = hr.H(2, \"Header2\")\n f = StringIO()\n out_H.render(f)\n assert f.getvalue() == '

    Header2

    \\n'\n","sub_path":"students/Net_Michael/lesson7/test_html_render.py","file_name":"test_html_render.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"376086559","text":"from tkinter import *\nfrom tkinter import messagebox\nimport random\nimport datetime\n\ndate = datetime.date.today()\n\n\nclass Media:\n \"\"\"This is my media class that will init the title, author and rating\"\"\"\n all_movies = [] # The list where i store all the movie objects\n all_books = [] # The list where i will store all the book objects\n\n def __init__(self, title, author, rating):\n self.title = title\n self.author = author\n self.rating = rating\n\n if self.rating != \"Awesome\" and self.rating != \"Bad\":\n self.rating = \"N/R\"\n\n\nclass Book(Media):\n \"\"\"The book class is a subclass from the mainclass Media\"\"\"\n def __init__(self, title, author, rating):\n super().__init__(title, author, rating)\n self.sort = \"Bok\"\n\n def show_book(self):\n return '{} skriven av {}'.format(self.title, self.author)\n\n def show_title_grade(self):\n return 'Boken {} har fått \"{}\" av dig'.format(self.title, self.rating)\n\n def show_tips(self):\n return 'Vi tipsar om {} skriven av {}'.format(self.title, self.author)\n\n\nclass Movie(Media):\n \"\"\"The movie class is also a subclass to Media class\"\"\"\n def __init__(self, title, author, rating):\n super().__init__(title, author, rating)\n self.sort = \"Film\"\n\n def show_movie(self):\n return '{} regisserad av {}'.format(self.title, self.author)\n\n def show_title_grade(self):\n return 'Filmen {} har fått \"{}\" av dig'.format(self.title, self.rating)\n\n def show_tips(self):\n return 'Vi tipsar om {} regisserad av {}'.format(self.title, self.author)\n\n\ndef add_movie():\n \"\"\"A function that i will call when the user wants to add a new book\"\"\"\n bg_color = \"LightSteelBlue3\"\n movie_frame = Toplevel(root)\n movie_frame.title(\"Lägg till film\")\n movie_frame.resizable(0, 0)\n movie_frame.configure(bg=bg_color)\n\n title_label = Label(movie_frame, text=\"Titel\", bg=bg_color, bd=3)\n title_label.grid(row=0, column=0, sticky=W)\n author_label = Label(movie_frame, text=\"Författare\", bg=bg_color, bd=3)\n author_label.grid(row=1, column=0, sticky=W)\n rating_label = Label(movie_frame, text=\"Rating\", bg=bg_color, bd=3)\n rating_label.grid(row=2, column=0, sticky=W)\n\n title_text = StringVar()\n title_entry = Entry(movie_frame, text=title_text)\n title_entry.grid(row=0, column=1)\n title_entry.delete(0, END)\n\n author_text = StringVar()\n author_entry = Entry(movie_frame, text=author_text)\n author_entry.grid(row=1, column=1)\n author_entry.delete(0, END)\n\n rating_text = StringVar()\n rating_entry = Entry(movie_frame, text=rating_text)\n rating_entry.grid(row=2, column=1)\n rating_entry.delete(0, END)\n\n save_button = Button(movie_frame, text=\"Spara\", width=11,\n command=lambda: save_movie(title_entry.get(), author_entry.get(), rating_entry.get()))\n save_button.grid(row=3, column=0)\n back_button = Button(movie_frame, text=\"Tillbaka\", width=11, command=movie_frame.destroy)\n back_button.grid(row=3, column=1)\n\n\ndef save_movie(a, b, c,):\n \"\"\"A function that will save the users input as a new book\"\"\"\n if a != \"\" and b != \"\" and c != \"\":\n if c != \"Awesome\" and c != \"Bad\":\n messagebox.showinfo('Error', 'Betyg anges \"Awesome\" eller \"Bad\"')\n else:\n new_movie = Movie(a, b, c)\n Media.all_movies.append(new_movie)\n messagebox.showinfo('Sparad', new_movie.show_movie())\n else:\n messagebox.showinfo('Error', 'Var god ange titel, författare och betyg tack!')\n\n\ndef show_movie():\n \"\"\"A function that will add all my books to my listbox\"\"\"\n list_of_movies.delete(0, END)\n for movie in Media.all_movies:\n list_of_movies.insert(0, movie.show_movie())\n\n\ndef sort_movie():\n \"\"\"This function will sort out all the books that have bad rating\"\"\"\n list_of_movies.delete(0, END)\n for movie in Media.all_movies:\n if movie.rating == \"Awesome\":\n list_of_movies.insert(0, movie.show_title_grade())\n\n\ndef tips_movie():\n \"\"\"This function will take a book that has good rating and return it as a tips\"\"\"\n list_of_movies.delete(0, END)\n for movie in Media.all_movies:\n if movie.rating == \"Awesome\":\n value = random.choice(Media.all_movies)\n list_of_movies.insert(0, value.show_tips())\n break\n else:\n novalue = \"Tyvärr så hittade vi ingen med bra betyg!\"\n list_of_movies.insert(0, novalue)\n\n\ndef add_book():\n \"\"\"A function that i will call when the user wants to add a new book\"\"\"\n bg_color = \"LightBlue3\"\n book_frame = Toplevel(root)\n book_frame.title(\"Lägg till bok\")\n book_frame.resizable(0, 0)\n book_frame.configure(bg=bg_color)\n\n title_label = Label(book_frame, text=\"Titel\", bg=bg_color, bd=3)\n title_label.grid(row=0, column=0, sticky=W)\n author_label = Label(book_frame, text=\"Författare\", bg=bg_color, bd=3)\n author_label.grid(row=1, column=0, sticky=W)\n rating_label = Label(book_frame, text=\"Rating\", bg=bg_color, bd=3)\n rating_label.grid(row=2, column=0, sticky=W)\n\n title_text = StringVar()\n title_entry = Entry(book_frame, text=title_text)\n title_entry.grid(row=0, column=1)\n title_entry.delete(0, END)\n\n author_text = StringVar()\n author_entry = Entry(book_frame, text=author_text)\n author_entry.grid(row=1, column=1)\n author_entry.delete(0, END)\n\n rating_text = StringVar()\n rating_entry = Entry(book_frame, text=rating_text)\n rating_entry.grid(row=2, column=1)\n rating_entry.delete(0, END)\n\n save_button = Button(book_frame, text=\"Spara\", width=11,\n command=lambda: save_book(title_entry.get(), author_entry.get(), rating_entry.get()))\n save_button.grid(row=3, column=0)\n back_button = Button(book_frame, text=\"Tillbaka\", width=11, command=book_frame.destroy)\n back_button.grid(row=3, column=1)\n\n\ndef save_book(a, b, c):\n \"\"\"A function that will save the users input as a new book\"\"\"\n if a != \"\" and b != \"\" and c != \"\":\n if c != \"Awesome\" and c != \"Bad\":\n messagebox.showinfo('Error', 'Betyg anges \"Awesome\" eller \"Bad\"')\n else:\n new_book = Book(a, b, c)\n Media.all_books.append(new_book)\n messagebox.showinfo('Sparad', new_book.show_book())\n else:\n messagebox.showinfo('Error', 'Var god ange titel, författare och betyg tack!')\n\n\ndef show_books():\n \"\"\"A function that will add all my books to my listbox\"\"\"\n list_of_books.delete(0, END)\n for book in Media.all_books:\n list_of_books.insert(0, book.show_book())\n\n\ndef sort_books():\n \"\"\"This function will sort out all the books that have bad rating\"\"\"\n list_of_books.delete(0, END)\n for book in Media.all_books:\n if book.rating == \"Awesome\":\n list_of_books.insert(0, book.show_title_grade())\n\n\ndef tips_book():\n \"\"\"This function will take a book that has good rating and return it as a tips\"\"\"\n list_of_books.delete(0, END)\n for book in Media.all_books:\n if book.rating == \"Awesome\":\n value = random.choice(Media.all_books)\n list_of_books.insert(0, value.show_tips())\n break\n else:\n novalue = \"Tyvärr så hittade vi ingen med bra betyg!\"\n list_of_books.insert(0, novalue)\n\n\n'''Adding som books to my list for testing the program'''\nbook1 = Book(\"Pippi Långstrump\", \"Astrid Lindgren\", \"Awesome\")\nbook2 = Book(\"Brott och straff\", \"Fjodor Dostojevski\", \"Awesome\")\nbook3 = Book(\"Infiltratören\", \"Lars Wierup\", \"Awesome\")\nbook4 = Book(\"Programmering 2\", \"Magnus Lilja\", \"Bad\")\n\n'''Adding some movies too my list for testing the program'''\nmovie1 = Movie(\"Harry Potter\", \"JK Rowling\", \"Awesome\")\nmovie2 = Movie(\"Sagan om ringen\", \"Peter Jackson\", \"Awesome\")\nmovie3 = Movie(\"Höstlegender\", \"Edward Zwick\", \"Bad\")\nmovie4 = Movie(\"Pippi Långstrump\", \"Astrid Lindgren\", \"Awesome\")\n\n\n'''Appending my hard coded books to my list'''\nMedia.all_books.append(book1)\nMedia.all_books.append(book2)\nMedia.all_books.append(book3)\nMedia.all_books.append(book4)\n\n'''Appending my hard coded movies to my list'''\nMedia.all_movies.append(movie1)\nMedia.all_movies.append(movie2)\nMedia.all_movies.append(movie3)\nMedia.all_movies.append(movie4)\n\nroot = Tk()\nroot.title(\"Mediabibliotek\")\nroot.resizable(0, 0)\nroot.configure(bg=\"lightsteelblue1\")\n\n'''CREATING THE MENU BAR WITH DROPDOWNMENUS'''\nmenubar = Menu(root)\nbook_menu = Menu(menubar, tearoff=0)\nbook_menu.add_command(label=\"Lägg till bok\", command=add_book)\nbook_menu.add_command(label=\"Visa böcker\", command=show_books)\nbook_menu.add_command(label=\"Awesome böcker\", command=sort_books)\nbook_menu.add_command(label=\"Tipsa om bok\", command=tips_book)\nbook_menu.add_separator()\nbook_menu.add_command(label=\"Avsluta\", command=root.quit)\nmenubar.add_cascade(label=\"Böcker\", menu=book_menu)\n\nmovie_menu = Menu(menubar, tearoff=0)\nmovie_menu.add_command(label=\"Lägg till film\", command=add_movie)\nmovie_menu.add_command(label=\"Visa filmer\", command=show_movie)\nmovie_menu.add_command(label=\"Awesome filmer\", command=sort_movie)\nmovie_menu.add_command(label=\"Tipsa om film\", command=tips_movie)\nmovie_menu.add_separator()\nmovie_menu.add_command(label=\"Avsluta\", command=root.quit)\nmenubar.add_cascade(label=\"Filmer\", menu=movie_menu)\n\n'''CREATING THE WELCOMELABEL THAT WILL BE DISPLAYED AND STATUSBAR'''\nstatus_bar = Label(root, text=str(date) + \" Copyright by Sonny.Svensson@yh.nackademin.se\", bd=2, relief=SUNKEN)\nstatus_bar.pack(side=BOTTOM, fill=X)\nheader = Label(root, text=\"Välkommen till ditt mediabibliotek\", font=\"time 19\", bd=2, relief=SUNKEN, bg=\"ivory\")\nheader.pack(fill=X)\nbook_label = Label(root, text=\"Böcker\", bg=\"LightSteelBlue2\", font=\"times 15\")\nbook_label.place(x=200, y=50)\nmovie_label = Label(root, text=\"Filmer\", bg=\"LightSteelBlue2\", font=\"times 15\")\nmovie_label.place(x=700, y=50)\n\n'''Creating the left frame that will be displayed in the main window'''\nleft_frame = LabelFrame(root, width=300, height=300, bd=3, relief=SUNKEN)\nleft_frame.pack(pady=50, side=LEFT)\nlist_of_books = Listbox(left_frame, width=80, height=20)\nlist_of_books.pack()\n\n'''Creating the right frame that will be displayed in the main window'''\nright_frame = LabelFrame(root, width=300, height=300, bd=3, relief=SUNKEN)\nright_frame.pack(pady=50, side=LEFT)\nlist_of_movies = Listbox(right_frame, width=80, height=20)\nlist_of_movies.pack()\n\n\ndef delete_all_books():\n \"\"\"The function to delete all the books both from the listbox and the list\"\"\"\n list_of_books.delete(0, END)\n Media.all_books.clear()\n\n\ndef delete_selected_book():\n \"\"\"Function to delete selected item in the listbox\"\"\"\n cursor = list_of_books.get(ANCHOR)\n list_of_books.delete(ANCHOR)\n for i in Media.all_books:\n if cursor == i.show_book():\n Media.all_books.remove(i)\n\n\ndef delete_all_movies():\n \"\"\"Same function for the movies to delete everything\"\"\"\n list_of_movies.delete(0, END)\n Media.all_movies.clear()\n\n\ndef delete_selected_movie():\n \"\"\"Delete selected item from the listbox\"\"\"\n cursor = list_of_movies.get(ANCHOR)\n list_of_movies.delete(ANCHOR)\n for i in Media.all_movies:\n if cursor == i.show_movie():\n Media.all_movies.remove(i)\n\n\n'''Making a choice if the user wants to delete a book or a movie'''\ndelete_books = Button(root, text=\"Radera alla böcker\", command=delete_all_books)\ndelete_books.place(x=30, y=420)\nremovebook_button = Button(root, text=\"Ta bort bok\", command=delete_selected_book)\nremovebook_button.place(x=150, y=420)\n\ndelete_movies = Button(root, text=\"Radera alla filmer\", command=delete_all_movies)\ndelete_movies.place(x=780, y=420)\nremovemovie_button = Button(root, text=\"Ta bort film\", command=delete_selected_movie)\nremovemovie_button.place(x=900, y=420)\n\nquit_button = Button(root, text=\"Avsluta\", width=11, bg=\"red\", command=root.quit)\nquit_button.place(x=445, y=420)\nroot.configure(menu=menubar)\nroot.mainloop()\n","sub_path":"Projektarbete/Mediabibliotek.py","file_name":"Mediabibliotek.py","file_ext":"py","file_size_in_byte":12016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"206520848","text":"\"\"\"\nTranslate QIF file into Ledger file\n\nQIF Files Represent transactions with entries from many \"target\"\naccounts that apply to a single \"source\" account (an asset account)\n\"\"\"\n\nimport argparse\nimport datetime\nimport mmap\nimport re\nfrom qif_parser import QIFParser\n\ndef ledger_account_name(name):\n \"\"\"\n ensure account complies with ledger format\n \"\"\"\n # replace 'hard separators' in the name\n pattern = re.compile(r'[ ]{2,}|[\\t]')\n return pattern.sub(\" \", name)\n\ndef ledger_amount(amount):\n \"\"\"\n Convert amount to ledger format from QIF\n\n An amount in QIF is in \"source\" account terms which is implied\n to be an asset account\n\n We need to negate the amount to apply it to the \"target\" account\n \n e.g. Expenses:Tax would be negative in QIF (as it subtracts directly \n from the asset account). But it's a positive in Ledger as it adds to\n the Tax account and subtracts from the asset account\n \"\"\"\n if amount != 0.0:\n return -amount\n else:\n return amount\n\n \ndef qif2ledger(qif_transaction, asset_account):\n \"\"\"\n return a dict with ledger attributes suitable for \n use in writing a ledger file\n \"\"\"\n\n l = {}\n postings = []\n for r in qif_transaction.records:\n d = r.value_dict\n if r.type == 'DATE':\n l['date'] = d['date'].strftime(\"%Y/%m/%d\")\n if r.type == 'PAYEE':\n l['payee'] = d['value']\n if r.type in ['U_AMOUNT', 'T_AMOUNT']:\n amount = ledger_amount(d['amount'])\n if r.type == 'CATEGORY':\n account = ledger_account_name(d['value'])\n if r.type == 'MEMO':\n l['memo'] = d['value']\n if r.type == 'SPLIT':\n posting = {\n 'account': ledger_account_name(d['category']),\n 'amount': ledger_amount(d['amount'])\n }\n if 'memo' in d:\n posting['memo'] = d['memo']\n postings.append(posting)\n \n if len(postings) == 0:\n posting = {\n 'account': ledger_account_name(account),\n 'amount': ledger_amount(amount)\n }\n postings.append(posting)\n\n postings.append({'account': asset_account})\n l['postings'] = postings\n return l\n \ndef print_ledger_dict(d):\n MEMO_TEMPLATE = \" ;{memo}\"\n SPLIT_TEMPLATE = \" {account} ${amount}\"\"\"\n SPLIT_TEMPLATE_MEMO = \" {account} ${amount} ;{memo}\"\"\"\n SPLIT_TEMPLATE_MEMO_NO_AMOUNT = \" {account} ;{memo}\"\"\"\n SPLIT_TEMPLATE_NO_AMOUNT = \" {account}\"\"\"\n \n print(\"{date} {payee}\".format(**d))\n if 'memo' in d:\n print(MEMO_TEMPLATE.format(**d))\n\n for p in d['postings']:\n if 'memo' in p:\n if 'amount' in p:\n print(SPLIT_TEMPLATE_MEMO.format(**p))\n else:\n print(SPLIT_TEMPLATE_MEMO_NO_AMOUNT.format(**p))\n elif 'amount' in p:\n print(SPLIT_TEMPLATE.format(**p))\n else: \n print(SPLIT_TEMPLATE_NO_AMOUNT.format(**p))\n\n print(\"\")\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Translate QIF to ledger\")\n parser.add_argument(\"-a\", \"--asset_account\", help=\"Account transactions apply to\")\n parser.add_argument(\"qif\", help=\"QIF filename to be parsed\")\n\n args = parser.parse_args()\n\n with open(args.qif, 'r', encoding=\"utf-8\") as f: \n text_map = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n qif_parser = QIFParser()\n for transaction in qif_parser.parse(text_map):\n # TODO: Output more useful format\n ledger_dict = qif2ledger(transaction, args.asset_account)\n print_ledger_dict(ledger_dict)\n text_map.close()\n","sub_path":"qif2ledger.py","file_name":"qif2ledger.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"266159171","text":"import numpy as np\nfrom misc.policies import EpsilonGreedy\nfrom approximators.mlp_torch import MLPQFunction\nfrom misc.buffer import Buffer\nfrom misc import utils\nimport time\n\nimport torch\n\nprior_eigen = None\ncholesky_mask = None\nprior_normal = None\nposterior_normal = None\nsigma_inv = None\n\ndef unpack(params, C, K):\n \"\"\"Unpacks a parameter vector into c, mu, L\"\"\"\n c = params[:C]\n mus = params[C:C + C * K]\n mu = mus.reshape(C, K)\n Ls = params[C + C * K:]\n L = Ls.reshape(C, K, K)\n return c, mu, L\n\n\ndef pack(c, mu, L):\n \"\"\"Packs c and mu and L into a parameter vector\"\"\"\n params = np.concatenate((c, mu.flatten(), L.flatten()), axis=0)\n return params\n\n\ndef clip(params, cholesky_clip, C, K):\n \"\"\"Makes sure the Cholesky factor L is well-defined\"\"\"\n global cholesky_mask\n c, mu, L = unpack(params, C, K)\n cholesky_mask = np.eye(K, dtype=bool) if cholesky_mask is None else cholesky_mask\n for i in range(C):\n mask = np.logical_and(L[i, :, :] < cholesky_clip, cholesky_mask)\n L[i, :, :][mask] = cholesky_clip\n L[i, :, :][np.triu_indices(K, 1)] = 0\n return pack(c, mu, L)\n\n\ndef sample_posterior(params, C, K):\n \"\"\"Samples a Q function from the posterior distribution\"\"\"\n c, mu, L = unpack(params, C, K)\n cluster = np.random.choice(np.arange(C), p=c)\n return np.dot(L[cluster, : , :], np.random.randn(K,)) + mu[cluster, :]\n\n\ndef normal_KL(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, L=None, precision=None):\n \"\"\" Computes the KL between normals for two GMMs \"\"\"\n global prior_eigen\n Sigma_bar_inv = np.linalg.inv(Sigma_bar) if precision is None else precision\n inv_b = Sigma_bar_inv[np.newaxis]\n if prior_eigen is None:\n prior_eigen, _ = np.linalg.eig(Sigma_bar[np.newaxis])\n\n if L is None:\n posterior_eigen, _ = np.linalg.eig(Sigma[:, np.newaxis])\n else:\n posterior_eigen = np.diagonal(L[:, np.newaxis], axis1=2, axis2=3)**2\n posterior_eigen = np.real(posterior_eigen)\n posterior_eigen[posterior_eigen < 0] = 1e-10\n mu_diff = mu[:, np.newaxis] - mu_bar[np.newaxis]\n\n return 0.5 * (np.sum(np.log(prior_eigen / posterior_eigen) + posterior_eigen / prior_eigen, axis=2) +\n np.matmul(np.matmul(mu_diff[:, :, np.newaxis], inv_b), mu_diff[:, :, :, np.newaxis])[:, :, 0, 0] -\n mu.shape[1])\n\n\ndef normal_KL3(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, L=None, precision=None):\n \"\"\" Computes the KL between normals for two GMMs using pytorch tensors \"\"\"\n #mu, sigma, L must be torch tensors\n global prior_eigen\n Sigma_bar_inv = np.linalg.inv(Sigma_bar) if precision is None else precision\n inv_b = torch.from_numpy(Sigma_bar_inv[np.newaxis])\n if prior_eigen is None:\n prior_eigen_torch = torch.from_numpy(np.real(np.linalg.eig(Sigma_bar[np.newaxis])[0]))\n else:\n prior_eigen_torch = torch.from_numpy(prior_eigen)\n\n diag_mask = torch.eye(mu.shape[1]).unsqueeze(0).unsqueeze(0).double()\n posterior_eigen = ((L.unsqueeze(1)*diag_mask).sum(dim=-1))**2\n posterior_eigen[posterior_eigen < 0] = 1e-10\n mu_diff = mu.unsqueeze(1) - torch.from_numpy(mu_bar[np.newaxis])\n return 0.5 * (((prior_eigen_torch / posterior_eigen).log() + posterior_eigen / prior_eigen_torch).sum(dim=2) +\n torch.matmul(torch.matmul(mu_diff.unsqueeze(2), inv_b), mu_diff.unsqueeze(3))[:, :, 0, 0] -\n mu.shape[1])\n\n\ndef tight_ukl(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, phi, psi, L=None,eps=0.01, max_iter=100, normalkl=None):\n \"\"\" Solves Variational problem to tight the upper bound\"\"\"\n\n kl = normal_KL(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, L=L) if normalkl is None else normalkl\n # Constants\n e_kl = np.exp(-kl) + 1e-10\n i = 0\n done = False\n while i < max_iter and not done:\n\n psi_bar = c_bar[np.newaxis] * phi / np.sum(phi, axis=0, keepdims=True)\n done = np.max(np.abs(psi - psi_bar)) < eps\n psi = psi_bar\n\n phi_bar = c[:, np.newaxis] * psi * e_kl / np.sum(psi * e_kl, axis=1, keepdims=True)\n done = done and np.max(np.abs(phi-phi_bar)) < eps\n phi = phi_bar\n\n i += 1\n\n return phi, psi\n\n\ndef UKL(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, phi, psi, precision=None, L=None):\n \"\"\"Computes an upper bound to the KL\"\"\"\n kl = normal_KL(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, L=L, precision=precision) # (posterior, prior)\n\n kl_var = np.sum(phi * np.log(phi/psi))\n kl_gaussian = np.sum(phi * kl)\n return kl_var + kl_gaussian\n\ndef UKL3(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, phi, psi, precision=None, L=None, normalkl=None):\n \"\"\"Computes an upper bound to the KL\"\"\"\n kl = normal_KL3(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, L=L, precision=precision) if normalkl is None \\\n else normalkl # (posterior, prior)\n kl_var = np.sum(phi * np.log(phi/psi))\n kl_gaussian = (torch.from_numpy(phi) * kl).sum()\n return kl_var.item() + kl_gaussian\n\n\ndef sample_gmm(n_samples, c, mu, L):\n \"\"\" Samples a mixture of Gaussians \"\"\"\n vs = np.random.randn(n_samples, mu.shape[1])\n clusters = np.random.choice(np.arange(c.size), n_samples, p=c)\n ws = np.matmul(vs[:,np.newaxis], np.transpose(L[clusters], (0,2,1)))[:,0,:] + mu[clusters]\n return ws, vs\n\n\ndef objective(samples, params, Q, c_bar, mu_bar, Sigma_bar, operator, n_samples, phi, psi, n_weights, lambda_, C, K,\n precision=None):\n \"\"\"Computes the negative ELBO\"\"\"\n c, mu, L = unpack(params, C, K)\n # We add a small constant to make sure Sigma is always positive definite\n L_reg = L+0.1*np.eye(K)[np.newaxis]\n weights, _ = sample_gmm(n_weights, c, mu, L)\n likelihood = operator.expected_bellman_error(Q, samples, weights)\n assert likelihood >= 0\n kl = UKL(c, mu, None, c_bar, mu_bar, Sigma_bar, phi, psi, L=L_reg, precision=precision)\n assert kl >= 0\n return likelihood + lambda_ * kl / n_samples\n\n\ndef gradient_KL(c, mu, L, c_bar, mu_bar, Sigma_bar, phi, psi, max_iter_ukl, C, K, precision=None, tight_bound=True):\n # Cache the pairwise KL\n mu = torch.from_numpy(mu).requires_grad_()\n L = torch.from_numpy(L).requires_grad_()\n normalkl = normal_KL3(c, mu, None, c_bar, mu_bar, Sigma_bar, L=L, precision=precision)\n\n if tight_bound:\n psi = c[:, np.newaxis] * c_bar[np.newaxis]\n phi = np.array(psi)\n phi, psi = tight_ukl(c, mu, None, c_bar, mu_bar, Sigma_bar, phi, psi,\n L=L,\n max_iter=max_iter_ukl,\n normalkl=normalkl.detach().numpy())\n\n assert np.all(np.logical_and(phi >= 0, psi >= 0))\n\n grad_c = np.zeros(C)\n ukl = UKL3(c, mu, None, c_bar, mu_bar, Sigma_bar, phi, psi, precision=precision, L=L, normalkl=normalkl)\n ukl.backward()\n grad_mu = mu.grad.data.numpy()\n grad_L = L.grad.data.numpy()\n return grad_c, grad_mu, grad_L, phi, psi\n\n\ndef init_posterior(c, mu, L, c_bar, mu_bar, Sigma_bar, phi, psi, C, K, cholesky_clip, max_iter_ukl, precision=None,\n max_iter=10000, eta=1e-5, eps=0.00001, ukl_tight_freq=100):\n i = 0\n ukl_prev = UKL(c, mu, None, c_bar, mu_bar, Sigma_bar, phi, psi, L=L)\n done = False\n params = pack(c, mu, L)\n while not done and i < max_iter:\n if i % ukl_tight_freq == 0:\n grad_c, grad_mu, grad_L, phi, psi = gradient_KL(c, mu, L, c_bar, mu_bar, Sigma_bar, phi, psi,\n max_iter_ukl, C, K, precision=precision)\n else:\n grad_c, grad_mu, grad_L, phi, psi = gradient_KL(c, mu, L, c_bar, mu_bar, Sigma_bar, phi, psi, max_iter_ukl,\n C, K, precision=precision, tight_bound=False)\n params = clip(params - eta * pack(grad_c, grad_mu, grad_L), cholesky_clip, C, K)\n c, mu, L = unpack(params, C, K)\n ukl = UKL(c, mu, None, c_bar, mu_bar, Sigma_bar, phi, psi, L=L, precision=precision)\n done = np.abs(ukl-ukl_prev) < eps\n ukl_prev = ukl\n i += 1\n print(\"Initializing prior %d... UKL: %f\" % (i, ukl))\n return params, phi, psi\n\n\ndef gradient(samples, params, Q, c_bar, mu_bar, Sigma_bar, operator, n_samples, phi, psi, n_weights, lambda_,\n max_iter_ukl, C, K, precision=None, t_step=0, ukl_tight_freq=1):\n \"\"\"Computes the objective function gradient\"\"\"\n c, mu, L = unpack(params, C, K)\n grad_c = np.zeros(c.shape)\n\n _, vs = utils.sample_mvn(n_weights * C, mu[0, :], L[0, :, :])\n\n ws = np.matmul(vs.reshape(C,n_weights,K), np.transpose(L, (0,2,1))) + mu[:, np.newaxis]\n be_grad = operator.gradient_be(Q, samples, ws.reshape(C*n_weights, K)).reshape(C, n_weights, K)\n # Gradient of the expected Bellman error wrt mu\n ebe_grad_mu = np.average(be_grad, axis=1)\n # Gradient of the expected Bellman error wrt L.\n ebe_grad_L = np.average(np.matmul(be_grad[:, :, :, np.newaxis], vs.reshape(C, n_weights, K)[:,:,np.newaxis]), axis=1)\n ebe_grad_mu = c[:, np.newaxis] * ebe_grad_mu\n ebe_grad_L = c[:, np.newaxis, np.newaxis] * ebe_grad_L\n\n kl_grad_c, kl_grad_mu, kl_grad_L, phi, psi = gradient_KL(c, mu, L, c_bar, mu_bar, Sigma_bar, phi, psi,\n max_iter_ukl, C, K, precision=precision,\n tight_bound=(t_step % ukl_tight_freq == 0))\n grad_mu = ebe_grad_mu + lambda_ * kl_grad_mu / n_samples\n grad_L = ebe_grad_L + lambda_ * kl_grad_L / n_samples\n\n return pack(grad_c, grad_mu, grad_L)\n\n\ndef learn(mdp,\n Q,\n operator,\n max_iter=5000,\n buffer_size=10000,\n batch_size=50,\n alpha_adam=0.001,\n alpha_sgd=0.1,\n lambda_=0.001,\n n_weights=10,\n train_freq=1,\n eval_freq=50,\n random_episodes=0,\n eval_states=None,\n eval_episodes=1,\n mean_episodes=50,\n preprocess=lambda x: x,\n cholesky_clip=0.0001,\n bandwidth=0.00001,\n post_components=1,\n max_iter_ukl=60,\n eps=0.001,\n eta=1e-6,\n time_coherent=False,\n n_source=10,\n source_file=None,\n seed=None,\n render=False,\n verbose=True,\n ukl_tight_freq=1,\n sources=None):\n\n if seed is not None:\n np.random.seed(seed)\n\n # Randomly initialize the weights in case an MLP is used\n if isinstance(Q, MLPQFunction):\n Q.init_weights()\n\n # Reset global variables\n global prior_eigen\n prior_eigen = None\n global cholesky_mask\n cholesky_mask = None\n global prior_normal\n prior_normal = None\n global posterior_normal\n posterior_normal = None\n\n # Initialize policies\n pi_g = EpsilonGreedy(Q, np.arange(mdp.action_space.n), epsilon=0)\n\n # Get number of features\n K = Q._w.size\n C = post_components\n\n # Load weights and construct prior distribution\n weights = utils.load_object(source_file) if sources is None else sources\n ws = np.array([w[1] for w in weights])\n np.random.shuffle(ws)\n # Take only the first n_source weights\n ws = ws[:n_source, :]\n mu_bar = ws\n Sigma_bar = np.tile(np.eye(K) * bandwidth, (n_source,1,1))\n Sigma_bar_inv = np.tile((1/bandwidth * np.eye(K))[np.newaxis], (n_source, 1, 1))\n c_bar = np.ones(n_source)/n_source\n\n # We initialize the parameters of the posterior to the best approximation of the posterior family to the prior\n c = np.ones(C) / C\n psi = c[:, np.newaxis] * c_bar[np.newaxis]\n phi = np.array(psi)\n\n mu = np.array([100 * np.random.randn(K) for _ in range(C)])\n Sigma = np.array([np.eye(K) for _ in range(C)])\n\n phi, psi = tight_ukl(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, phi, psi, max_iter=max_iter_ukl, eps=eps)\n params, phi, psi = init_posterior(c, mu, Sigma, c_bar, mu_bar, Sigma_bar, phi, psi, C, K, cholesky_clip,\n max_iter_ukl, max_iter=max_iter_ukl * 10, precision=Sigma_bar_inv, eta=eta, eps=eps)\n\n # Add random episodes if needed\n init_samples = list()\n if random_episodes > 0:\n w, _ = sample_gmm(random_episodes, c_bar, mu_bar, np.sqrt(Sigma_bar))\n for i in range(random_episodes):\n Q._w = w[i]\n init_samples.append(utils.generate_episodes(mdp, pi_g, n_episodes=1, preprocess=preprocess))\n init_samples = np.concatenate(init_samples)\n\n t, s, a, r, s_prime, absorbing, sa = utils.split_data(init_samples, mdp.state_dim, mdp.action_dim)\n init_samples = np.concatenate((t[:, np.newaxis], preprocess(s), a, r[:, np.newaxis], preprocess(s_prime),\n absorbing[:, np.newaxis]), axis=1)\n\n # Figure out the effective state-dimension after preprocessing is applied\n eff_state_dim = preprocess(np.zeros(mdp.state_dim)).size\n\n # Create replay buffer\n buffer = Buffer(buffer_size, eff_state_dim)\n n_init_samples = buffer.add_all(init_samples) if random_episodes > 0 else 0\n\n # Results\n iterations = []\n episodes = []\n n_samples = []\n evaluation_rewards = []\n learning_rewards = []\n episode_rewards = [0.0]\n l_2 = []\n l_inf = []\n fvals = []\n episode_t = []\n\n # Create masks for ADAM and SGD\n adam_mask = pack(np.zeros(C), np.ones((C,K)) * alpha_adam, np.zeros((C,K,K))) # ADAM learns only \\mu\n sgd_mask = pack(np.zeros(C), np.zeros((C,K)), np.ones((C,K,K)) * alpha_sgd) # SGD learns only L\n\n # Adam initial params\n m_t = 0\n v_t = 0\n t = 0\n\n # Init env\n s = mdp.reset()\n h = 0\n Q._w = sample_posterior(params, C, K)\n\n start_time = time.time()\n\n # Learning\n for i in range(max_iter):\n\n # If we do not use time coherent exploration, resample parameters\n Q._w = sample_posterior(params, C, K) if not time_coherent else Q._w\n # Take greedy action wrt current Q-function\n s_prep = preprocess(s)\n a = np.argmax(Q.value_actions(s_prep))\n # Step\n s_prime, r, done, _ = mdp.step(a)\n # Build the new sample and add it to the dataset\n buffer.add_sample(h, s_prep, a, r, preprocess(s_prime), done)\n\n # Take a step of gradient if needed\n if i % train_freq == 0:\n # Estimate gradient\n g = gradient(buffer.sample_batch(batch_size), params, Q, c_bar, mu_bar, Sigma_bar, operator,\n i + 1, phi, psi, n_weights, lambda_, max_iter_ukl, C, K, precision=Sigma_bar_inv,\n t_step=i, ukl_tight_freq=ukl_tight_freq)\n\n # Take a gradient step for \\mu\n params, t, m_t, v_t = utils.adam(params, g, t, m_t, v_t, alpha=adam_mask)\n # Take a gradient step for L\n params = utils.sgd(params, g, alpha=sgd_mask)\n # Clip parameters\n params = clip(params, cholesky_clip, C, K)\n\n # Add reward to last episode\n episode_rewards[-1] += r * mdp.gamma ** h\n\n s = s_prime\n h += 1\n if done or h >= mdp.horizon:\n\n episode_rewards.append(0.0)\n s = mdp.reset()\n h = 0\n Q._w = sample_posterior(params, C, K)\n episode_t.append(i)\n\n # Evaluate model\n if i % eval_freq == 0:\n\n #Save current weights\n current_w = np.array(Q._w)\n\n # Evaluate MAP Q-function\n c, mu, _ = unpack(params, C, K)\n rew = 0\n for j in range(C):\n Q._w = mu[j]\n rew += utils.evaluate_policy(mdp, pi_g, render=render, initial_states=eval_states,\n n_episodes=eval_episodes, preprocess=preprocess)[0]\n rew /= C\n\n learning_rew = np.mean(episode_rewards[-mean_episodes - 1:-1]) if len(episode_rewards) > 1 else 0.0\n br = operator.bellman_residual(Q, buffer.sample_batch(batch_size)) ** 2\n l_2_err = np.average(br)\n l_inf_err = np.max(br)\n fval = objective(buffer.sample_batch(batch_size), params, Q, c_bar, mu_bar, Sigma_bar, operator,\n i + 1, phi, psi, n_weights, lambda_, C, K, precision=Sigma_bar_inv)\n\n # Append results\n iterations.append(i)\n episodes.append(len(episode_rewards) - 1)\n n_samples.append(n_init_samples + i + 1)\n evaluation_rewards.append(rew)\n learning_rewards.append(learning_rew)\n l_2.append(l_2_err)\n l_inf.append(l_inf_err)\n fvals.append(fval)\n\n # Make sure we restart from s\n mdp.reset(s)\n\n # Restore weights\n Q._w = current_w\n\n end_time = time.time()\n elapsed_time = end_time - start_time\n start_time = end_time\n\n if verbose:\n print(\"Iter {} Episodes {} Rew(G) {} Rew(L) {} Fval {} L2 {} L_inf {} time {:.1f} s\".format(\n i, episodes[-1], rew, learning_rew, fval, l_2_err, l_inf_err, elapsed_time))\n\n run_info = [iterations, episodes, n_samples, learning_rewards, evaluation_rewards, l_2, l_inf, fvals, episode_rewards[:len(episode_t)], episode_t]\n weights = np.array(mu)\n\n return [mdp.get_info(), weights, run_info]\n","sub_path":"algorithms/mgvt_torch.py","file_name":"mgvt_torch.py","file_ext":"py","file_size_in_byte":17259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"387649259","text":"import json, re, os\n\ndef build_envvars_file(envvars_file=None, config_file=None):\n if envvars_file is None:\n envvars_file = os.path.join(os.path.dirname(__file__), 'envvars.d', 'sysenv')\n if config_file is None:\n config_file = open(os.getenv('EB_CONFIG_FILE'))\n data = ''\n try:\n data = json.load(config_file)\n except ValueError:\n return\n\n with open(envvars_file, 'w') as fd:\n write_json_key_values(fd, data)\n\ndef write_json_key_values(file, json, prefix = 'EB_CONFIG'):\n for key, value in json.iteritems():\n key = re.sub('\\\\W', '_', key)\n if prefix == 'EB_CONFIG_PLUGINS_RDS_ENV' or \\\n prefix == 'EB_CONFIG_ENV' or prefix == 'EB_CONFIG_PHP_ENV':\n prefix = None\n elif prefix is not None:\n key = key.upper()\n if isinstance(value, dict):\n write_json_key_values(file, value, '_'.join((prefix, key)))\n elif key == 'ENV' and isinstance(value, list):\n for val in value:\n file.write('export %s\\n' % (val))\n else:\n if value is None:\n value = ''\n value = str(value).encode(\"string_escape\")\n if prefix is None:\n pdata = ''\n else:\n pdata = prefix + '_'\n file.write('export %s%s=\"%s\"\\n' % (pdata, key, value))\n\nif __name__ == '__main__':\n build_envvars_file()\n","sub_path":"php5.4_x64/support/build_envvars.py","file_name":"build_envvars.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"141224774","text":"# Copyright (c) 2015-2016 Kyle Lopin (Naresuan University) \n# Licensed under the Creative Commons Attribution-ShareAlike 3.0 (CC BY-SA 3.0 US) License\n\n\"\"\" Graphical user interface to control PSoC electrochemical device main file\n\"\"\"\n# standard libraries\nimport csv\nimport ctypes\nimport time\nimport logging\nimport os\nimport sys\nimport tkinter.font\nimport tkinter as tk\nfrom tkinter import filedialog\nfrom tkinter import ttk\n# local files\nimport amp_frame\nimport asv_frame\nimport change_toplevel as change_top\nimport cv_frame\nimport graph_properties\nimport option_menu\nimport properties\nimport usb_comm\n\n__author__ = 'Kyle Vitautas Lopin'\n\nOPTIONS_BACKGROUND = 'LightCyan4'\nlogging.getLogger('PIL').setLevel(logging.WARNING)\n\ntry: # works for windows 8.1 and newer\n ctypes.windll.shcore.SetProcessDpiAwareness(2)\n print(\"Set DPI awareness\")\nexcept:\n pass\n\n\nclass ElectroChemGUI(tk.Tk):\n \"\"\" Graphical User Interface to interact with the PSoC electrochemical device\n \"\"\"\n\n def __init__(self, parent=None):\n if not os.path.exists('logging'): # make a directory to store logging files\n os.makedirs('logging')\n date = time.strftime(\"%Y_%m_%d\")\n for handler in logging.root.handlers[:]:\n logging.root.removeHandler(handler)\n logging.basicConfig(level=logging.DEBUG, filename=\"logging/\" + date + \"_logging_file.log\",\n format=\"%(asctime)-15s %(levelname)s %(module)s %(lineno)d: %(message)s\")\n\n self.data_save_type = \"Converted\"\n self.device_params = properties.DeviceParameters()\n self.display_type = check_display_type()\n tk.Tk.__init__(self, parent)\n self.parent = parent\n self.voltage_source_label = tk.StringVar()\n # let the user see if the device is set for 2 or 3 electrodes\n self.electrode_config_label = tk.StringVar()\n # device starts in 3 electrode config\n self.electrode_config_label.set(\"3 electrode configuration\")\n self.device = usb_comm.AmpUsb(self, self.device_params)\n graph_props = graph_properties.GraphProps()\n # frame to put the connection button, graph toolbar and label for VDAC source\n self.frames = self.make_bottom_frames()\n\n # Make Notebooks to separate the CV and amperometry methods\n self.notebook = ttk.Notebook(self)\n self.cv = cv_frame.CVFrame(self, self.notebook, graph_props)\n self.amp = amp_frame.AmpFrame(self, self.notebook, graph_props)\n self.asv = asv_frame.ASVFrame(self, self.notebook, graph_props)\n\n self.notebook.add(self.cv, text=\"Cyclic Voltammetry\")\n self.notebook.add(self.amp, text=\"Amperometry\")\n self.notebook.add(self.asv, text=\"Anode Stripping Voltammetry\")\n\n self.notebook.pack(side='top', expand=True, fill=tk.BOTH)\n tk.Label(self.frames[2], textvariable=self.voltage_source_label, font=(\"Bookman\", 10)\n ).pack(side='top')\n tk.Label(self.frames[2], textvariable=self.electrode_config_label, font=(\"Bookman\", 10)\n ).pack(side='top')\n # make a button to display connection settings and allow user to try to reconnect\n self.connect_button = tk.Button(self.frames[1], command=self.connect)\n self.update_connect_button()\n self.connect_button.pack(side='bottom')\n option_menu.OptionMenu(self)\n\n def set_data_type(self, _type):\n \"\"\" Developer option to have the device not convert the incoming data and just report and\n save the raw numbers\n :param _type: string of either \"Raw Counts\", or \"Converted\"\n \"\"\"\n logging.info(\"Developer option to save raw adc counts selected\")\n self.data_save_type = _type\n\n def update_connect_button(self):\n \"\"\" Update the connect button to red if no device is connected yellow if found but not\n connected and green if it is connected, except on Mac devices as there tcl (or something)\n does not allow the buttons to be colored\n \"\"\"\n if self.device.connected:\n self.connect_button.config(text=\"Connected\", bg='green')\n elif self.device.device.found:\n self.connect_button.config(text=\"Found but not connected\", bg='yellow')\n else:\n self.connect_button.config(text=\"Device Not Found\", bg='red')\n\n def change_data_labels(self):\n \"\"\" Call a toplevel to allow the user to change data labels in the legend\n \"\"\"\n change_top.ChangeDataLegend(self)\n\n def set_voltage_source_label(self, message):\n \"\"\" Give a message to the user about what voltage source is being used\n :param message: message to give the user\n \"\"\"\n self.voltage_source_label.set(message)\n\n def update_current_range(self, _value, current_limit):\n self.cv.set_tia_current_lim(_value, current_limit)\n self.amp.set_tia_current_lim(_value, current_limit)\n self.asv.set_tia_current_lim(_value, current_limit)\n\n def open_data(self):\n \"\"\" Open a csv file that has the data saved in it, in the same format as this program\n saves the data. Check what type of\n NOTE:\n _data_hold - holds the data as its being pulled from the file with the structure\n _data_hold = [ [x-data-array], [y1-data-array], [y2-data-array], .., [yn-data] ]\n \"\"\"\n logging.debug(\"opening data\")\n _file_name = cv_frame.open_file('open') # get a filename\n # Confirm that the user supplied a file\n if _file_name:\n\n logging.debug(\"a file named %s opened\", _file_name)\n with open(_file_name, 'rb') as _file:\n _reader = csv.reader(_file) # create reader from file\n\n first_array = _reader.next() # get the first line that has the data labels\n\n # figure out what type of data was opened\n if first_array[0] == 'voltage':\n # this is a cyclic voltammetry data\n self.cv.open_data(_reader, first_array)\n _file.close()\n\n def user_select_delete_some_data(self):\n change_top.UserSelectDataDelete(self)\n\n def delete_all_data_user_prompt(self):\n change_top.UserDeleteDataWarning(self)\n\n def delete_all_data(self):\n \"\"\" Delete all the data collected so far and clear the lines from the plot area\n :return:\n \"\"\"\n logging.debug(\"deletinga all data\")\n # Delete all displayed lines\n self.cv.delete_all_data()\n\n def quit(self):\n \"\"\" Destroy the master \"\"\"\n # self.destroy()\n destroyer()\n\n def set_adc_channel(self, _channel):\n \"\"\" Used to debug the device by storing info in the other adc channels that can be gathered\n :param _channel: what adc channel in the device to get\n \"\"\"\n self.device_params.adc_tia.adc_channel = _channel\n\n def connect(self, button=None):\n \"\"\" Function the connect button is attached to, to try to connect an amperometry PSoC device\n and display if the device is connected or not\n :param button: button the user clicks to try to connect the device\n \"\"\"\n logging.debug(\"trying connecting\")\n\n if self.device.connected:\n logging.info(\"device is connected\")\n else:\n logging.debug(\"attempting to connect\")\n self.device = usb_comm.AmpUsb(self, self.device_params)\n # If no device then try to connect\n self.update_connect_button()\n\n def failed_connection(self): # this is not working now\n logging.info(\"failed connection\")\n\n # usb.util.dispose_resources()\n if hasattr(self, \"device\"):\n # self.device.destroy()\n pass\n if hasattr(self, \"connect_button\"):\n self.connect_button.config(text=\"Not Connected\", bg='red')\n\n def make_bottom_frames(self):\n \"\"\" To pack the matplotlib toolbar and connect button in a nice layout make a frame along\n the bottom of the GUI and fill it with 3 'evenly' spaced frames\n :return: list of 3 frames to put toolbar, button, and VDAC label\n \"\"\"\n # make frame to line the bottom of the GUI\n main_bottom = tk.Frame(self)\n main_bottom.pack(side='bottom', fill=tk.X)\n # make a list to fill with the 3 frames and pack them\n bottom_frame = []\n for i in range(3):\n bottom_frame.append(tk.Frame(main_bottom, width=220, height=35))\n bottom_frame[i].pack(side='left', fill=tk.X, expand=1)\n return bottom_frame\n\n\ndef destroyer():\n # app.quit()\n app.destroy()\n sys.exit()\n\n\ndef get_data_from_csv_file(_filename):\n with open(_filename, 'rb') as _file:\n _reader = csv.reader(_file) # create reader from file\n\n first_array = _reader.next() # get the first line that has the data labels\n _data_hold = [] # create a list to hold the data\n # Make lists to hold the voltage and data arrays\n for i in range(len(first_array)): # make as many list as there columns in the csv file\n _data_hold.append([])\n\n for row in _reader:\n for i, data in enumerate(row):\n _data_hold[i].append(float(data))\n _file.close()\n return _data_hold\n\n\ndef check_display_type():\n \"\"\" Check if matplotlib graph can be used,\n :return: type that can be used to make display graph, matplotlib or canvas as a string\n \"\"\"\n try:\n import matplotlib\n import matplotlib.pyplot as plt\n from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n return \"matplotlib\"\n except ImportError as e:\n return \"canvas\"\n\nif __name__ == '__main__':\n app = ElectroChemGUI()\n app.protocol(\"WM_DELETE_WINDOW\", destroyer)\n app.title(\"Amperometry Device\")\n app.geometry(\"950x600\")\n app.mainloop()\n\n","sub_path":"amp_gui.py","file_name":"amp_gui.py","file_ext":"py","file_size_in_byte":9877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"255894309","text":"#!/usr/bin/env python\n#-*-coding:utf8 -*-\n\n\"\"\"\nAuteur : Julien Roziere \nDate : 20/03/2017\nDescription : Programme contenant toutes les fonctions reliées à l'analyse de fichiers .pdb.\n\"\"\"\nimport math, string\n\n\ndef parsePDBMultiChains(infile) :\n\n # lecture du fichier PDB \n f = open(infile, \"r\")\n lines = f.readlines()\n f.close()\n\n\n # var init\n chaine = True\n firstline = True\n prevres = None\n dPDB = {}\n dPDB[\"reslist\"] = []\n dPDB[\"chains\"] = []\n \n # parcoure le PDB \n for line in lines :\n if line[0:4] == \"ATOM\" :\n chain = line[21]\n if not chain in dPDB[\"chains\"] :\n dPDB[\"chains\"].append(chain)\n dPDB[chain] = {}\n dPDB[chain][\"reslist\"] = []\n curres = \"%s\"%(line[22:26]).strip()\n if not curres in dPDB[chain][\"reslist\"] :\n dPDB[chain][\"reslist\"].append(curres)\n dPDB[chain][curres] = {}\n dPDB[chain][curres][\"resname\"] = string.strip(line[17:20])\n dPDB[chain][curres][\"atomlist\"] = []\n atomtype = string.strip(line[12:16])\n dPDB[chain][curres][\"atomlist\"].append(atomtype)\n dPDB[chain][curres][atomtype] = {}\n #print \"cures \", curres\n #print dPDB[chain][curres]\n \n dPDB[chain][curres][atomtype][\"x\"] = float(line[30:38])\n dPDB[chain][curres][atomtype][\"y\"] = float(line[38:46])\n dPDB[chain][curres][atomtype][\"z\"] = float(line[46:54])\n dPDB[chain][curres][atomtype][\"id\"] = line[6:11].strip()\n\n return dPDB\n","sub_path":"testCommit/structureTools_JulienRoziere.py","file_name":"structureTools_JulienRoziere.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"281065403","text":"import datetime\nfrom django.contrib import admin\nfrom shoppy.shop.models import *\nfrom shoppy.shop.mail import sendOrderSendMail\n\nclass OrderAdmin(admin.ModelAdmin):\n list_display = ['billnumber', 'user', 'order_date', 'state_of_order', 'overview_link']\n list_display_links = ['billnumber']\n list_filter = ['order_date']\n search_fields = ['id']\n actions = ['make_send']\n\n def make_send(self, request, queryset):\n rows_updated = 0\n for order in queryset:\n if order.order_date and not order.send_date and (not order.paymenttype.pay_first or order.paid_date):\n order.send_date = datetime.datetime.now()\n order.save()\n rows_updated += 1\n sendOrderSendMail(order)\n #sendOrderSendMailAdmin(order)\n if rows_updated == 1:\n message_bit = \"1 Bestellung wurde\"\n else:\n message_bit = \"%s Bestellungen wurden\" % rows_updated\n self.message_user(request, \"%s erfolgreich als versendet markiert.\" % message_bit)\n make_send.short_description = \"Markiere Auswahl als versendet\"\n\nadmin.site.register(Order, OrderAdmin)","sub_path":"shoppy/shop/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"322976254","text":"from util import *\n# from nltk.tokenize import word_tokenize \n# Add your import statements here\n\n\n\n\nclass Tokenization():\n\n\tdef naive(self, text):\n\t\t\"\"\"\n\t\tTokenization using a Naive Approach\n\n\t\tParameters\n\t\t----------\n\t\targ1 : list\n\t\t\tA list of strings where each string is a single sentence\n\n\t\tReturns\n\t\t-------\n\t\tlist\n\t\t\tA list of lists where each sub-list is a sequence of tokens\n\t\t\"\"\"\n\n\t\ttokenizedText = None\n\n\t\t#Fill in code here\n\t\tlst=[]\n\t\tfor i in text:\n\t\t\ti.replace(\"\\n\",\" \")\n\t\t\tlst.append(i.split(\" \"))\n\t\t\n\t\ttokenizedText=lst\n\t\treturn tokenizedText\n\n\n\n\tdef pennTreeBank(self, text):\n\t\t\"\"\"\n\t\tTokenization using the Penn Tree Bank Tokenizer\n\n\t\tParameters\n\t\t----------\n\t\targ1 : list\n\t\t\tA list of strings where each string is a single sentence\n\n\t\tReturns\n\t\t-------\n\t\tlist\n\t\t\tA list of lists where each sub-list is a sequence of tokens\n\t\t\"\"\"\n\t\tl = []\n\t\tfor i in text:\n\t\t\tw = word_tokenize(i)\n\t\t\tl.append(w)\n\t\t\t\n\t\ttokenizedText=l\n\t\treturn tokenizedText\n","sub_path":"A1-P1/code_folder/tokenization.py","file_name":"tokenization.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"590004064","text":"import cv2\nimport numpy as np\n\ndef FeatureMatching(img2, img1):\n gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n sift = cv2.xfeatures2d.SIFT_create()\n kp1, des1 = sift.detectAndCompute(gray1, None)\n kp2, des2 = sift.detectAndCompute(gray2, None)\n bf = cv2.BFMatcher()\n matches = bf.knnMatch(des1,des2, k=2) \n good = []\n for m in matches:\n if m[0].distance < 0.5*m[1].distance: \n good.append(m)\n matches = np.asarray(good)\n if len(matches[:,0]) >= 4:\n src = np.float32([ kp1[m.queryIdx].pt for m in matches[:,0] ]).reshape(-1,1,2)\n dst = np.float32([ kp2[m.trainIdx].pt for m in matches[:,0] ]).reshape(-1,1,2)\n H, masked = cv2.findHomography(src, dst, cv2.RANSAC, 5.0)\n else:\n pass\n dst = cv2.warpPerspective(img1,H,(img2.shape[1] + img1.shape[1], img2.shape[0]))\n dst[0:img1.shape[0], 0:img2.shape[1]-10] = img2[:,:img2.shape[1]-10]\n return CropBlackSpace(dst)\n\ndef CropBlackSpace(img):\n gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n mask = gray>0\n gray = gray[np.ix_(mask.any(1),mask.any(0))]\n return img[:gray.shape[0],:gray.shape[1]]\n\nimg1 = cv2.imread('Database/fig1.png')\nimg2 = cv2.imread('Database/fig2.png')\nimg3 = cv2.imread('Database/fig3.png')\nimg4 = cv2.imread('Database/fig4.png')\nout1_2 = FeatureMatching(img1,img2)\nout3_4 = FeatureMatching(img3,img4)\nout = FeatureMatching(out1_2,out3_4)\ncv2.imwrite('out.png',out)\n##cv2.imwrite('out3_4.png',out3_4)\n# cv2.imshow('out2_3',out2_3)\n# cv2.imshow('out3_4',out3_4)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"ejc2Test.py","file_name":"ejc2Test.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"306832324","text":"# class ParenthesesError(Exception):\n# def __init__(self, msg):\n# self.msg = msg\n\nfrom enum import Enum\n\n\nclass Operation(Enum):\n ADD = 1\n CONCAT = 2\n NONE = 3\n\n\nclass Iteration(Enum):\n POSITIVE = 1\n GENERAL = 2\n NONE = 3\n\n\nclass BasePart:\n def __init__(self):\n self.automaton = None\n self.reg_string = ''\n self.operation = Operation.NONE\n self.iteration = Iteration.NONE\n\n def print(self):\n print(self.reg_string)\n self.automaton.print()\n\n def wrap_in_parentheses(self):\n return '({})'.format(self.reg_string)\n\n def add_iter_reg_str(self, symbol):\n if len(self.reg_string) == 1:\n self.reg_string += symbol\n else:\n self.reg_string = self.wrap_in_parentheses() + symbol\n\n def make_iteration(self):\n if self.iteration == Iteration.GENERAL:\n self.add_iter_reg_str('*')\n self.automaton.iteration()\n print('General iteration:')\n self.print()\n elif self.iteration == Iteration.POSITIVE:\n self.add_iter_reg_str('+')\n self.automaton.positive_iteration()\n print('Positive iteration:')\n self.print()\n\n\nclass Part(BasePart):\n def __init__(self, operation, reg_string):\n super().__init__()\n self.operation = operation\n self.reg_string = reg_string\n\n\nclass Parts(BasePart):\n def __init__(self):\n super().__init__()\n self.values = []\n\n def __iter__(self):\n for val in self.values:\n yield val\n\n def __delitem__(self, index):\n del self.values[index]\n\n def __getitem__(self, index):\n return self.values[index]\n\n def __setitem__(self, index, value):\n self.values[index] = value\n\n def add_part(self, part):\n if isinstance(part, Part):\n if len(part.reg_string) != 0:\n self.values.append(part)\n else:\n self.values.append(part)\n\n def add_part_reg_str(self, part):\n if part.operation == Operation.ADD:\n self.reg_string += '+'\n\n if isinstance(part, Part) or part.iteration != Iteration.NONE:\n self.reg_string += part.reg_string\n else:\n self.reg_string += part.wrap_in_parentheses()\n\n\ndef detect_oper(exp, start_ind):\n prev_ind = start_ind - 1\n if prev_ind >= 0:\n if exp[prev_ind] == '(':\n return Operation.NONE\n elif exp[prev_ind] == '+':\n return Operation.ADD\n else:\n return Operation.CONCAT\n else:\n return Operation.NONE\n\n\ndef separate_concat(parts):\n inner_parts = Parts()\n is_concat = False\n for idx in range(len(parts.values) - 1, -1, -1):\n # TODO: check this for work with recursion\n if isinstance(parts[idx], Parts):\n separate_concat(parts[idx])\n\n if parts[idx].operation == Operation.CONCAT:\n inner_parts.values.insert(0, parts[idx])\n del parts[idx]\n is_concat = True\n elif is_concat:\n inner_parts.values.insert(0, parts[idx])\n del parts[idx]\n inner_parts.operation = inner_parts[0].operation\n inner_parts[0] = Operation.NONE\n\n parts.values.insert(idx, inner_parts)\n inner_parts = Parts()\n is_concat = False\n\n\ndef parse_reg_exp(exp, ind):\n parts = Parts()\n start = ind\n\n while ind < len(exp):\n if exp[ind] == '+':\n parts.add_part(Part(detect_oper(exp, start), exp[start:ind:]))\n start = ind + 1\n\n elif exp[ind] == '*' or exp[ind] == 'p':\n parts.add_part(Part(detect_oper(exp, start), exp[start:ind - 1:]))\n start = ind - 1\n parts.add_part(Part(detect_oper(exp, start), exp[start:ind:]))\n start = ind + 1\n if exp[ind] == '*':\n parts[-1].iteration = Iteration.GENERAL\n else:\n parts[-1].iteration = Iteration.POSITIVE\n\n elif exp[ind] == '(':\n parts.add_part(Part(detect_oper(exp, start), exp[start:ind:]))\n start = ind\n parts.add_part(parse_reg_exp(exp, ind + 1))\n parts[-1].operation = detect_oper(exp, start)\n\n if ind + 1 < len(exp) and \\\n (exp[ind + 1] == '*' or exp[ind + 1] == 'p'):\n ind += 1\n if exp[ind + 1] == '*':\n parts[-1].iteration = Iteration.GENERAL\n else:\n parts[-1].iteration = Iteration.POSITIVE\n\n start = ind + 1\n\n elif exp[ind] == ')':\n parts.add_part(Part(detect_oper(exp, start), exp[start:ind:]))\n return parts\n\n ind += 1\n\n parts.add_part(Part(detect_oper(exp, start), exp[start:ind:]))\n separate_concat(parts)\n\n return parts\n","sub_path":"parsing_exp.py","file_name":"parsing_exp.py","file_ext":"py","file_size_in_byte":4853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"590668403","text":"##\n## Construya una tabla que contenga _c0 y una lista\n## separada por ',' de los valores de la columna _c4\n## de la tabla tbl1.tsv\n## \nimport pandas as pd\n\n\ndf = pd.read_csv('tbl1.tsv', sep='\\t')\ndf2 = pd.DataFrame({'lista': df.groupby(['_c0']).apply(lambda x: ','.join(sorted(x['_c4'])))}).reset_index()\nprint(df2)\n","sub_path":"q10.py","file_name":"q10.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"352263260","text":"# -*- encoding: UTF-8 -*-\r\n# 此脚本的作用是以“zm_deleting.txt\"为参照,删除词库中的一些不常用词组,以让词库更加高效,不会出现一些无谓的词条。\r\n# usage:delete_redundant_words.py filename (脚本和zm_deleting.txt要在同一目录下)\r\n# \"zm_deleting.txt\"我放在gsealine的gist上以便随时更新:https://gist.github.com/gsealine/d4e566441a9948c7b0f49fd44cb5a06e\r\n\r\nimport re\r\nimport os\r\nimport sys\r\nimport codecs\r\n# 用codecs以指定编码打开文件很有效,不然有时会有错误\r\nfilepath = sys.argv[1]\r\nf = codecs.open(filepath, \"r\", 'utf-8')\r\nlines = f.readlines() #readlines()能生成一个list\r\nf.close()\r\n\r\nf_redundant = codecs.open(r'rudundant_words_in_jd.txt', \"r\", 'utf-8')\r\nrdlines = f_redundant.readlines()\r\nf_redundant.close()\r\n\r\nfilename = os.path.basename(filepath)\r\nnewFilename = \"new_\" + filename\r\nnewf = codecs.open(newFilename, \"w\", 'utf-8')\r\n\r\n\r\n# 考虑到词库开头可能有rime特有的说明语句,先记录下词库真正开始的行数 beginrow\r\nfor i,line in enumerate(lines):\r\n beginrow = i\r\n if re.match(u'^\\u4e00\\ta', line):\r\n break\r\n\r\n# wblines 是词库文件的所有字词组成的列表\r\nwbwords = [line.split()[0] for line in lines[beginrow:]] # 这是列表生成器的用法,速度更快\r\n\r\n# rdwords 是所有待删词组成的列表\r\nrdwords = [rdline.split()[0] for rdline in rdlines]\r\nsetrdwords = set(rdwords)\r\n# 将其转化为集合后再用 if …… in …… 语句查找会快很多\r\n\r\nfor line in lines[:beginrow]:\r\n newf.write(line)\r\n\r\nfor i,wbword in enumerate(wbwords):\r\n if (wbword in setrdwords):\r\n continue\r\n newf.write(lines[i + beginrow])\r\n# wbwords 和 lines 两个列表的顺序要对应\r\n\r\nnewf.close()\r\n","sub_path":"delete_redundant_words_v2.0.py","file_name":"delete_redundant_words_v2.0.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"606949700","text":"from typing import List\n\nclass Solution:\n def twoSum1(self, nums: List[int], target: int) -> List[int]:\n nums_to_target_pair = {}\n for i, num in enumerate(nums):\n target_num = target - num\n if target_num in nums_to_target_pair:\n return [nums.index(target_num), i]\n nums_to_target_pair[num] = target_num\n for num, complement in nums_to_target_pair.items():\n index_of_num = nums.index(num)\n if num == complement:\n if nums.count(num) > 1:\n return [index_of_num, nums[index_of_num+1:].index(complement) + index_of_num + 1]\n else:\n continue\n elif complement in nums:\n return [index_of_num, nums.index(complement)]\n\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n sum_map = {}\n for i in range(len(nums)):\n complement = target - nums[i]\n if complement in sum_map.keys():\n return [sum_map[complement], i]\n sum_map[nums[i]] = i\n\n\nsolution = Solution()\nnums = [2, 7, 11, 15]\ntarget = 9\nprint(\"Expecting [0, 1]: \" + str(solution.twoSum(nums, target)))\nnums = [3, 2, 4]\ntarget = 6\nprint(\"Expecting [1, 2]: \" + str(solution.twoSum(nums, target)))\nnums = [3, 3]\ntarget = 6\nprint(\"Expecting [0, 1]: \" + str(solution.twoSum(nums, target)))\nnums = [2, 5, 5, 11]\ntarget = 10\nprint(\"Expecting [1, 2]: \" + str(solution.twoSum(nums, target)))\n","sub_path":"Easy/1-TwoSum/TwoSum.py","file_name":"TwoSum.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"164035363","text":"import sys\nfrom random import randint\nfrom heapq import heappush,heappop\nfrom time import clock\nsize = 100000\nt1 = clock()\na = [(randint(1, 30), randint(1, 60)) for i in range (size)]\nk = sorted(a, key=lambda x:x[1])\nt2 = clock()\nsys.stdout.write(\"builtin sorting : \"+ str(t2-t1)+\"\\n\")\n\nt3 = clock()\nh = []\nfor i in range(size):\n a, b = randint(1, 30), randint(1, 60)\n heappush(h, (b, a))\n\nkk = []\nfor i in range(size):\n b, a = heappop(h)\n kk.append((a, b))\n\nt4 = clock()\n\n\nsys.stdout.write(\"using heap : \"+str(t4-t3)) ","sub_path":"sorting/sorting_performance.py","file_name":"sorting_performance.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"485918811","text":"\"\"\"\n===============\nact.io.armfiles\n===============\n\nThis module contains I/O operations for loading files that were created for the\nAtmospheric Radiation Measurement program supported by the Department of Energy\nOffice of Science.\n\n\"\"\"\n# import standard modules\nimport glob\nimport xarray as xr\nimport warnings\n\nfrom .dataset import ACTAccessor\nfrom enum import Flag, auto\n\n\nclass ARMStandardsFlag(Flag):\n \"\"\"\n This class stores a flag that is returned by\n :ref:act.io.armfiles.check_arm_standards.\n\n Attributes\n ----------\n OK:\n This flag is set if the dataset conforms to ARM standards\n NO_DATASTREAM:\n This flag is set if the dataset does not have a datastream\n field.\n\n Examples\n --------\n .. code-block:: python\n\n my_flag = act.io.armfiles.ARMStandardsFlag(\n act.io.armfiles.ARMStandardsFlag.OK)\n assert my_flag.OK\n \"\"\"\n\n OK = auto()\n \"\"\"The dataset conforms to ARM standards.\"\"\"\n NO_DATASTREAM = auto()\n \"\"\"The dataset does not have a datastream field.\"\"\"\n\n\ndef read_netcdf(filenames, variables=None):\n\n \"\"\"\n Returns `xarray.Dataset` with stored data and metadata from a user-defined\n query of ARM-standard netCDF files from a single datastream.\n\n Parameters\n ----------\n filenames : str or list\n Name of file(s) to read\n variables : list, optional\n List of variable name(s) to read\n\n Returns\n -------\n act_obj : Object\n ACT dataset\n\n Examples\n --------\n This example will load the example sounding data used for unit testing.\n\n .. code-block:: python\n\n import act\n\n the_ds, the_flag = act.io.armfiles.read_netcdf(\n act.tests.sample_files.EXAMPLE_SONDE_WILDCARD)\n print(the_ds.act.datastream)\n \"\"\"\n\n file_dates = []\n file_times = []\n arm_ds = xr.open_mfdataset(filenames, parallel=True, concat_dim='time')\n\n # Adding support for wildcards\n if isinstance(filenames, str):\n filenames = glob.glob(filenames)\n\n filenames.sort()\n for n, f in enumerate(filenames):\n file_dates.append(f.split('.')[-3])\n file_times.append(f.split('.')[-2])\n\n arm_ds.act.file_dates = file_dates\n arm_ds.act.file_times = file_times\n is_arm_file_flag = check_arm_standards(arm_ds)\n if is_arm_file_flag.NO_DATASTREAM is True:\n arm_ds.act.datastream = \"act_datastream\"\n else:\n arm_ds.act.datastream = arm_ds.attrs[\"datastream\"]\n arm_ds.act.site = str(arm_ds.act.datastream)[0:3]\n arm_ds.act.arm_standards_flag = is_arm_file_flag\n\n return arm_ds\n\n\ndef check_arm_standards(ds):\n \"\"\"\n Checks to see if an xarray dataset conforms to ARM standards.\n\n Parameters\n ----------\n ds: xarray dataset\n The dataset to check.\n\n Returns\n -------\n flag: ARMStandardsFlag\n The flag corresponding to whether or not the file conforms\n to ARM standards.\n \"\"\"\n\n the_flag = ARMStandardsFlag(ARMStandardsFlag.OK)\n\n if 'datastream' not in ds.attrs.keys():\n warnings.warn((\"ARM standards require that the datastream name\" +\n \" be defined, currently using a default\" +\n \" of act_datastream.\"), UserWarning)\n the_flag.OK = False\n the_flag.NO_DATASTREAM = True\n\n return the_flag\n","sub_path":"act/io/armfiles.py","file_name":"armfiles.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"554074702","text":"#! /usr/bin/env python\n\nimport networkx as nx\nimport sentics\nimport SenticParser\nimport os\n\nclass SenticsParser(object):\n\n\tdef __init__(self):\n\t\tdirname = os.path.dirname(__file__)\n\t\tself.G = nx.read_gpickle(os.path.join(dirname, \"test.gpickle\"))\n\t\tself.sn = sentics.Sentics()\n\n\tdef get_sentics_of_sentence(self, sentence):\n\n\t\twords = sentence.split()\n\n\t\tlist_concepts = []\n\t\tconc = []\n\n\t\tto_add = \"\"\n\n\t\tfor word in words:\n\t\t\tif (word in self.G):\n\t\t\t\tconc.append(word)\n\t\t\t\tto_add += word + \" \"\n\t\t\telif(to_add != \"\"):\n\t\t\t\tlist_concepts.append(to_add[:-1])\n\t\t\t\tto_add = \"\"\n\n\t\tif(to_add != \"\"):\n\t\t\tlist_concepts.append(to_add[:-1])\n\n\t\tparserList = SenticParser.getOutputConcepts(sentence)\n\n\t\tlist_concept = list(set(list_concepts) | \tset(parserList))\n\n\t\tlist_concept = filter(bool, list_concept)\n\n\t\tlist_concept = set(list(list_concepts))\n\n\t\tto_search = []\n\n\n\t\tfor phrase in list_concepts:\n\t\t\tconcepts = phrase.split()\n\t\t\tto_search = to_search + concepts\n\t\t\tfor i in range(len(concepts) - 1):\n\t\t\t\tfor j in range(i + 1, len(concepts)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tk = nx.dijkstra_path(self.G, concepts[i], concepts[j])\n\t\t\t\t\t\tif(len(k) == j - i + 1 and k == concepts[i:j + 1]):\n\t\t\t\t\t\t\tto_search = list(set(to_search) - set(k))\n\t\t\t\t\t\t\tword_to_add = \"_\".join(k)\n\t\t\t\t\t\t\tto_search.append(word_to_add)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tcontinue\n\n\t\tto_search = list(set(to_search))\n\n\t\tsorted_by_length = sorted(to_search, key=lambda tup:len(tup.split(\"_\")))\n\t\treturn filter(lambda x: x is not None, [self.sn.lookup(concept) for concept in to_search])\n","sub_path":"parser/senticsparser.py","file_name":"senticsparser.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"210779151","text":"\ndef ListsIntersection(first_list, second_list): \n new_list = [value for value in first_list if value in second_list] \n return new_list\n\n\ndef ListsIntersection2(first_list, second_list):\n return list(set(first_list) & set(second_list)) \n \n\n\n\nlist1=[1,2,3,4,5,6,7,8,9,10]\nlist2=[5,6,7,8,9,10,11,12,13,15,15]\nintersect_list=ListsIntersection(list1,list2)\nintersect_list2=ListsIntersection2(list1,list2)\nprint(intersect_list)\nprint(intersect_list2)\n","sub_path":"Day Five/task 2.py","file_name":"task 2.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"56689815","text":"# -*- coding: utf-8 -*-\nfrom functools import wraps as _wraps\nfrom functools import partial\nimport weakref\nfrom hashlib import md5\nfrom base64 import b64encode\nimport time\nimport logging\nimport random\nimport pydoc\nfrom .clients import base, asyncache, tiered\n\ntry:\n from .mq import coherence\n from .clients import coherent\n no_coherence = False\nexcept ImportError:\n no_coherence = True\n\nfrom .clients.base import CacheMissError\n\ntry:\n import cython\nexcept ImportError:\n # Make cython annotations work without cython\n _cy_noop = lambda f: f\n class _cython:\n locals = lambda **kw: _cy_noop\n globals()['cython'] = _cython\n\nclass NO_NAMESPACE:\n pass\n\nclass _NONE:\n pass\n\ntry:\n import multiprocessing\nexcept ImportError:\n class multiprocessing:\n @staticmethod\n def cpu_count():\n return 1\n\ndef wraps(wrapped):\n w = _wraps(wrapped)\n def decor(wrapper):\n wrapper = w(wrapper)\n wrapper.__doc__ = \"\\n\".join(\n pydoc.render_doc(wrapped, 'cached %s:').split('\\n', 4)[:3]\n + list(filter(bool, [wrapper.__doc__])))\n return wrapper\n return decor\n\ndef _make_namespace(f, salt = None, salt2 = None):\n f = getattr(f, 'im_func', f)\n fname = getattr(f, '__name__', None)\n if fname is None:\n fname = getattr(f, 'func_name', None)\n if fname is None:\n # FTW\n return repr(f)\n\n mname = getattr(f, '__module__', '')\n\n fcode = getattr(f, '__code__', None)\n if fcode is None:\n fcode = getattr(f, 'func_code', None)\n if fcode is not None:\n fpath = '%s:%d' % (fcode.co_filename, fcode.co_firstlineno)\n else:\n fpath = ''\n\n try:\n body_digest = md5(fpath.encode(\"utf8\"))\n if salt:\n body_digest.update(salt.encode(\"utf8\"))\n if salt2:\n body_digest.update(salt2.encode(\"utf8\"))\n if fcode:\n body_digest.update(getattr(fcode, 'co_code', b''))\n return \"%s.%s#%s\" % (mname,fname,b64encode(body_digest.digest()).rstrip(b\"=\\n\"))\n except Exception as e:\n return repr(f)\n\ndef _simple_put_deferred(future, client, f, key, ttl, *p, **kw):\n defer = asyncache.Defer(f, *p, **kw)\n if future is not None:\n defer.future = future\n return client.put(key, defer, ttl)\n\ndef _coherent_put_deferred(shared, async_ttl, future, client, f, key, ttl, *p, **kw):\n return client.put_coherently(key, ttl,\n lambda : not shared.contains(key, async_ttl),\n future,\n f, *p, **kw)\n\nclass CacheStats(object):\n __slots__ = (\n 'hits', 'misses', 'errors',\n 'sync_misses', 'sync_errors',\n 'min_miss_time', 'max_miss_time', 'sum_miss_time', 'sum_miss_time_sq',\n 'miss_time_histogram', 'miss_time_histogram_bins', 'miss_time_histogram_max', 'wait_time',\n )\n\n def __init__(self):\n self.clear()\n self.set_histogram_bins(0, None)\n\n def clear(self):\n self.hits = self.misses = self.errors = self.sync_misses = self.sync_errors = 0\n self.max_miss_time = self.sum_miss_time = self.sum_miss_time_sq = self.wait_time = 0\n self.min_miss_time = -1\n\n def set_histogram_bins(self, bins, maxtime):\n if bins <= 0:\n self.miss_time_histogram_bins = self.miss_time_histogram_max = 0\n self.miss_time_histogram = None\n else:\n self.miss_time_histogram = [0] * bins\n self.miss_time_histogram_bins = bins\n self.miss_time_histogram_max = maxtime\n\n def add_histo(self, time):\n if self.miss_time_histogram:\n hmax = self.miss_time_histogram_max\n hbins = self.miss_time_histogram_bins\n hbin = min(hbins-1, min(hmax, time) * hbins / hmax)\n self.miss_time_histogram[hbin] += 1\n\ndecorated_functions = weakref.WeakSet()\n\ndef cached(client, ttl,\n key = lambda *p, **kw:(p,frozenset(kw.items()) or ()),\n namespace = None,\n value_serialization_function = None,\n value_deserialization_function = None,\n async_writer_queue_size = None,\n async_writer_workers = None,\n async_writer_threadpool = None,\n async_writer_kwargs = None,\n async_ttl = None,\n async_client = None,\n async_expire = None,\n lazy_kwargs = {},\n async_lazy_recheck = False,\n async_lazy_recheck_kwargs = {},\n async_processor = None,\n async_processor_workers = None,\n async_processor_threadpool = None,\n async_processor_kwargs = None,\n renew_time = None,\n future_sync_check = None,\n initialize = None,\n decorate = None,\n timings = True,\n ttl_spread = True,\n autonamespace_version_salt = None,\n _eff_async_ttl = None,\n _put_deferred = None,\n _fput_deferred = None,\n _lazy_recheck_put_deferred = None,\n _flazy_recheck_put_deferred = None ):\n \"\"\"\n This decorator provides cacheability to suitable functions.\n\n To be considered suitable, the values received on parameters must be immutable types (otherwise caching will\n be unreliable).\n\n Caches are thread-safe only if the provided clients are thread-safe, no additional safety is provided. If you\n have a thread-unsafe client you want to make safe, use a (ReadWrite)SyncAdapter. Since synchronization adapters\n only apply to store manipuation functions, and not the wrapped function, deadlocks cannot occur.\n\n The decorated function will provide additional behavior through\n\n Attributes\n ----------\n\n client: the backing cache client. The provided client is never used as-is, and instead is wrapped in a\n NamespaceWrapper. This is it.\n\n ttl: The configured TTL\n\n async_ttl: The configured async TTL\n\n clear(): forget all cached values. Since the client might be shared, it will only increase an internal\n revision mark used to decorate keys, so the cache will not be immediately purged. For that, use\n client.clear() (but beware that it will also clear other caches sharing the same client).\n\n invalidate(...): mimicking the underlying function's signature, it will, instead of invoking the function,\n invalidate cached entries sharing the call's key.\n\n expire(...): like invalidate, but the key is just marked as out-of-date, requiring immediate refresh,\n but not completely invalid.\n\n put(_cache_put, ...): mimicking the underlying function's signature after the first positional argument,\n except for one keyword argument _cache_put, it will forcibly set the cached value for that key to\n be what's supplied in _cache_put. Although there will be no invocation of the target function,\n the write will be synchronous unless the underlying cache client is async, and for external caches\n this might still mean a significant delay.\n\n refresh(...): mimicking the underlying function's signature, it will forcefully invoke the function,\n regardless of cache status, and refresh the cache with the returned value.\n\n uncached(...): this is the underlying function, undecorated.\n\n peek(...): mimicking the underlying function's signature, it will query the cache without ever invoking\n the underlying function. If the cache doesn't contain the key, a CacheMissError will be raised.\n\n get_ttl(...): mimicking the underlying function's signature, it will query the cache without ever invoking\n the underlying function, and return both the result and the ttl. Misses return NONE as value and\n a negative ttl, instead of raising a CacheMissError.\n\n lazy(...): mimicking the underlying function's signature, it will behave just like a cached function call,\n except that if there is no value, instead of waiting for one to be computed, it will just raise\n a CacheMissError. If the access is async, it will start a background computation. Otherwise, it will\n behave just as peek.\n\n future(...): probably the preferred way of accessing the cache on an asynchronous app, it will return\n a decorated function that will return futures that will receive the value when done.\n For straight calls, if lazy would not raise a CacheMissError, the future will already contain the value,\n resulting in no delays. If the client is tiered and has remote tiers, it's recommendable to add proper\n lazy_kwargs to avoid this synchronous call blocking. Other forms of access perform similarly, always\n returning a future immediately without blocking. Alternatively, setting future_sync_check to False\n will disable this check and always do it through the processor.\n\n async(): if the underlying client is async, it will return the decorated function (self). Otherwise, it will\n be another decorated function, created on demand, backed by the same client wrapped in an async adapter.\n As such, it can be used to perform asynchronous operations on an otherwise synchronous function.\n\n on_promote: subdecorator that registers callbacks that will receive promotion events from this function.\n\n on_value: subdecorator that registers callbacks that will receive freshly computed values from this function.\n The callback will receive the value as its first argument, and all the original arguments for the call\n that initiated the computation following that argument (including keyword arguments).\n\n stats: cache statistics, containing:\n hits - number of cache hits\n misses - number of cache misses\n errors - number of exceptions caught\n sync_misses - number of synchronous (blocking) misses\n sync_errors - number of synchronous exceptions (propagated to caller)\n\n min_miss_time - minimum time spent computing a miss\n max_miss_time - maximum time spent computing a miss\n sum_miss_time - total time spent computing a miss (divide by misses and get an average)\n sum_miss_time_sq - sum of squared times spent computing a miss (to compute standard deviation)\n\n miss_time_histogram - histogram of times spent computing misses, computed only if histogram\n bins and limits are set.\n miss_time_histogram_bins - number of bins configured\n miss_time_histogram_max - maximum histogram time configured\n\n wait_time - time spent waiting for async updates, that's sync miss time on async queries\n\n reset(): clear all statistics\n set_histogram_bins(bins, max): configure histogram collection to use \"bins\" bins spanning\n from 0 to max. If bins is set to 0, max is ignored, and histogram collection is disabled\n\n All values are approximate, as no synchroniation is attempted while updating.\n\n sync_misses and sync_errors are caller-visible misses or exceptions. The difference with\n misses and errors respectively are the number of caller-invisible misses or errors.\n\n Parameters\n ----------\n\n client: the cache store client to be used\n\n ttl: the time, in seconds, during which values remain valid.\n\n callkey: the given key-computing callable\n\n renew_time: if not None, the time, in seconds, to add to the TTL when an item is scheduled for\n refresh. This renews the current item at a cost, but prevents concurrent readers from attempting\n their own refresh in a rather simple way, short of using a coherence protocol. Roughly\n equivalent to the dogpile pattern with a timeout as specified.\n\n key: (optional) A key derivation function, that will take the same arguments as the underlying function,\n and should return a key suitable to the client. If not provided, a default implementation that will\n usually work for most primitive argument types will be used.\n\n namespace: (optional) If provided, the namespace used to identify cache entries will be the one provided.\n If not, a default one will be derived out of the function's module and name, which may differ between\n platforms, so you'll want to provide a stable one for shared caches. If NO_NAMEPSACE is given,\n no namespace decoration will be applied. Specify if somehow collisions are certain not to occur.\n\n autonamespace_version_salt: (optional) If provided, it will alter the automatically generated namespace\n in a predictable and stable way. Can be used to force version upgrades when the automatic namespace\n is not able to pick up code changes.\n\n value_serialization_function: (optional) If provided, values will not be stored directly into the cache,\n but the result of applying this function to them. Use if the cache is remote and does not natively\n support the results given by the underlying function, or if stripping of runtime-specific data is\n required.\n\n value_deserialization_function: (optional) Counterpart to value_serialization_function, it will be applied\n on values coming from the cache, before returning them as cached function calls.\n\n async_writer_queue_size: (optional) Writer queue size used for the async() client. Default is 100.\n\n async_writer_workers: (optional) Number of async workers for the async() client.\n Default is multiprocessing.cpu_count\n\n async_writer_threadpool: (optional) Threadpool to be used for the async writer, instead of\n workers, this can specify a specific thread pool to use (perhaps shared among other writers).\n It can also be a callable, in which case it must be a factory function that takes the number\n of workers as argument and returns a threadpool to be used. It's recommendable to always use\n factories instead of instances, to avoid premature thread initialization.\n\n async_writer_kwargs: (optional) Optional arguments to be used when constructing AsyncWriteCacheClient\n wrappers. Ignored if an explicit async_client is given.\n\n async_client: (optional) Alternatively to async_writer_queue_size and async_writer_workers, a specific\n async client may be specified. It is expected this client will be an async wrapper of the 'client'\n mandatorily specified, that can be shared among decorated functions (to avoid multiplying writer\n threads).\n\n async_ttl: (optional) The TTL at which an async refresh starts. For example, async_ttl=1 means to start\n a refresh just 1 second before the entry expires. It must be smaller than ttl. Default is half the TTL.\n If negative, it means ttl - async_ttl, which reverses the logic to mean \"async_ttl\" seconds after\n creation of the cache entry.\n\n async_processor_workers: (optional) Number of threads used for async cache operations (only applies to\n future() calls, other async operations are configured with async_writer args). Only matters if the\n clients perform expensive serialization (there's no computation involved otherwise). Default is\n multiprocessing.cpu_count\n\n async_processor_threadpool: (optional) Threadpool to be used for the async processor, instead of\n workers, this can specify a specific thread pool to use (perhaps shared among other processors).\n It can also be a callable, in which case it must be a factory function that takes the number\n of workers as argument and returns a threadpool to be used. It's recommendable to always use\n factories instead of instances, to avoid premature thread initialization.\n\n async_processor_kwargs: (optional) Optional arguments to be used when constructing AsyncCacheProcessors.\n Ignored if an explicit async_processor is given.\n\n async_processor: (optional) Shared processor to utilize in future() calls.\n\n future_sync_check: (optional) Whether to perform a quick synchronous check of the cache with lazy_kwargs\n in order to avoid stalling on the processor for cached access. Set to False if there's no non-blocking\n tier in the given cache client.\n\n async_expire: (optional) A callable that will get an expired key, when TTL falls below async_ttl.\n Common use case is to pass a first-tier's expire bound method, thus initiating a refresh.\n\n lazy_kwargs: (optional) kwargs to send to the client's getTtl when doing lazy requests. Useful for\n tiered clients, that can accept access modifiers through kwargs\n\n async_lazy_recheck: (optional) when sending lazy_kwargs that may result in spurious CacheMissError,\n specifying this on True will trigger an async re-check of the cache (to verify the need for an\n async refresh).\n\n async_lazy_recheck_kwargs: (optional) when setting async_lazy_recheck, recheck kwargs can be specified\n here (default empty).\n\n initialize: (optional) A callable hook to be called right before all accesses. It should initialize whatever\n is needed initialized (like daemon threads), and only once (it should be a no-op after it's called once).\n It can return True to avoid being called again (any return value that doesn't evaluate to True will\n be ignored).\n\n decorate: (optional) A decorator to apply to all call-like decorated functions. Since @cached creates many\n variants of the function, this is a convenience over manually decorating all variants.\n\n timings: (optional) Whether to gather timing statistics. If true, misses will be timed, and timing data\n will be included in the stats attribute. It does imply some overhead. Default is True.\n\n ttl_spread: (optional - default True). If None, the TTL will be used as-is for cache insertions.\n If True, an automatic TTL spread will be computed so insertions and recomputatins are better distributed\n in time. If a number (float or int), an equal-type random amount between [-ttl_spread, ttl_spread]\n will be added.\n \"\"\"\n if value_serialization_function or value_deserialization_function:\n client = base.DecoratedWrapper(client,\n value_decorator = value_serialization_function,\n value_undecorator = value_deserialization_function )\n if namespace is not None and namespace is not NO_NAMESPACE:\n client = base.NamespaceWrapper(namespace, client)\n if async_client:\n async_client = base.NamespaceMirrorWrapper(client, async_client)\n\n if not client.is_async:\n if async_writer_queue_size is None:\n async_writer_queue_size = 100\n if async_writer_workers is None:\n async_writer_workers = multiprocessing.cpu_count()\n\n if async_ttl is None:\n async_ttl = ttl / 2\n elif async_ttl < 0:\n async_ttl = ttl + async_ttl\n\n if ttl_spread is True:\n ttl_spread = min(ttl, async_ttl, abs(ttl-async_ttl)) / 2\n if ttl_spread:\n spread_type = type(ttl_spread)\n eff_ttl = lambda r = random.random : ttl + spread_type(ttl_spread * (r() - 0.5))\n else:\n eff_ttl = lambda : ttl\n\n if _put_deferred is None:\n _fput_deferred = _simple_put_deferred\n _put_deferred = partial(_fput_deferred, None)\n if _lazy_recheck_put_deferred is None:\n _flazy_recheck_put_deferred = _simple_put_deferred\n _lazy_recheck_put_deferred = partial(_flazy_recheck_put_deferred, None)\n\n if async_processor is not None and async_processor_workers is None:\n async_processor_workers = multiprocessing.cpu_count()\n\n if async_writer_kwargs is None:\n async_writer_kwargs = {}\n async_writer_kwargs.setdefault('threadpool', async_writer_threadpool)\n\n if async_processor_kwargs is None:\n async_processor_kwargs = {}\n async_processor_kwargs.setdefault('threadpool', async_processor_threadpool)\n\n # Copy to avoid modifying references to caller objects\n elazy_kwargs = lazy_kwargs.copy()\n easync_lazy_recheck_kwargs = async_lazy_recheck_kwargs.copy()\n eget_async_lazy_recheck_kwargs = easync_lazy_recheck_kwargs.copy()\n\n EMPTY_KWARGS = {}\n _NONE_ = _NONE\n Future = asyncache.Future\n\n def decor(f):\n if namespace is None:\n salt2 = repr((ttl,))\n nclient = base.NamespaceWrapper(_make_namespace(\n f, salt = autonamespace_version_salt, salt2 = salt2), client)\n if async_client:\n nasync_client = base.NamespaceMirrorWrapper(nclient, async_client)\n else:\n nasync_client = async_client\n else:\n nclient = client\n nasync_client = async_client\n\n stats = CacheStats()\n\n if initialize is not None:\n def _initialize():\n nonlocal _initialize\n stop_initializing = initialize()\n if stop_initializing:\n _initialize = None\n else:\n _initialize = None\n\n # static async ttl spread, to avoid inter-process contention\n if ttl_spread:\n if _eff_async_ttl:\n eff_async_ttl = _eff_async_ttl\n else:\n eff_async_ttl = max(async_ttl / 2, async_ttl - spread_type(ttl_spread * 0.25 * random.random()))\n else:\n eff_async_ttl = async_ttl\n\n # Wrap and track misses and timings\n if timings:\n of = f\n @wraps(of)\n @cython.locals(t0=cython.double, t1=cython.double, t=cython.double)\n def af(*p, **kw):\n stats.misses += 1\n try:\n t0 = time.time()\n rv = of(*p, **kw)\n t1 = time.time()\n t = t1-t0\n try:\n if t > stats.max_miss_time:\n stats.max_miss_time = t\n if stats.min_miss_time < 0 or stats.min_miss_time > t:\n stats.min_miss_time = t\n stats.sum_miss_time += t\n stats.sum_miss_time_sq += t*t\n if stats.miss_time_histogram:\n stats.add_histo(t)\n except:\n # Ignore stats collection exceptions.\n # Quite possible since there is no thread synchronization.\n pass\n if value_callbacks:\n try:\n _value_callback(rv, *p, **kw)\n except:\n # Just log callback exceptions, orthogonal behavior shouldn't propagate to the caller\n logging.getLogger('chorde').error(\"Error on value callback\", exc_info = True)\n pass\n return rv\n except:\n stats.errors += 1\n raise\n @wraps(of)\n def f(*p, **kw):\n stats.sync_misses += 1\n return af(*p, **kw)\n else:\n of = f\n @wraps(of)\n def af(*p, **kw): # lint:ok\n stats.misses += 1\n try:\n rv = of(*p, **kw)\n if value_callbacks:\n try:\n _value_callback(rv, *p, **kw)\n except:\n # Just log callback exceptions, orthogonal behavior shouldn't propagate to the caller\n logging.getLogger('chorde').getLogger('chorde').error(\"Error on value callback\", exc_info = True)\n pass\n return rv\n except:\n stats.errors += 1\n raise\n @wraps(of)\n def f(*p, **kw): # lint:ok\n stats.sync_misses += 1\n rv = af(*p, **kw)\n if value_callbacks:\n try:\n _value_callback(rv, *p, **kw)\n except:\n # Just log callback exceptions, orthogonal behavior shouldn't propagate to the caller\n logging.getLogger('chorde').error(\"Error on value callback\", exc_info = True)\n pass\n return rv\n\n @wraps(of)\n def cached_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return f(*p, **kw)\n\n try:\n rv = nclient.get(callkey, **get_kwargs)\n stats.hits += 1\n except CacheMissError:\n rv = f(*p, **kw)\n nclient.put(callkey, rv, eff_ttl())\n return rv\n if decorate is not None:\n cached_f = decorate(cached_f)\n\n @wraps(of)\n def get_ttl_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return f(*p, **kw)\n rv = nclient.getTtl(callkey, **get_kwargs)\n if rv[1] < 0:\n stats.misses += 1\n else:\n stats.hits += 1\n return rv\n if decorate is not None:\n get_ttl_f = decorate(get_ttl_f)\n\n @wraps(of)\n @cython.locals(t0=cython.double, t1=cython.double, t=cython.double)\n def async_cached_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return f(*p, **kw)\n\n client = aclient\n __NONE = _NONE_\n rv, rvttl = client.getTtl(callkey, __NONE, **get_kwargs)\n\n if (rv is __NONE or rvttl < eff_async_ttl) and not client.contains(callkey, eff_async_ttl):\n if renew_time is not None:\n if rv is not __NONE:\n nclient.renew(callkey, eff_async_ttl + renew_time)\n elif placeholder_value_fn_cell:\n placeholder = placeholder_value_fn_cell[0](*p, **kw)\n nclient.add(callkey, placeholder, eff_async_ttl + renew_time)\n rv = placeholder\n rvttl = eff_async_ttl + renew_time\n # Launch background update\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n elif rv is not __NONE:\n if rvttl < eff_async_ttl:\n client.promote(callkey, ttl_skip = eff_async_ttl, **get_kwargs)\n stats.hits += 1\n\n if rv is __NONE:\n # Must wait for it\n if timings:\n t0 = time.time()\n client.wait(callkey)\n rv, rvttl = client.getTtl(callkey, __NONE, **get_kwargs)\n if rv is __NONE or rvttl < eff_async_ttl:\n # FUUUUU\n rv = f(*p, **kw)\n stats.sync_misses += 1\n if timings:\n t1 = time.time()\n t = t1-t0\n stats.wait_time += t\n\n return rv\n if decorate is not None:\n async_cached_f = decorate(async_cached_f)\n\n @wraps(of)\n def future_cached_f(*p, **kw):\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return fclient.do_async(f, *p, **kw)\n\n client = aclient\n clientf = fclient\n frv = Future()\n __NONE = _NONE_\n\n if future_sync_check:\n # Quick sync call with lazy_kwargs\n rv, rvttl = client.getTtl(callkey, __NONE, **elazy_kwargs)\n else:\n rv = __NONE\n rvttl = -1\n\n if (rv is __NONE or rvttl < eff_async_ttl):\n # The hard way\n if rv is __NONE:\n # It was a miss, so wait for setting the value\n def on_value(value):\n stats.hits += 1\n frv.set(value[0])\n # If it's stale, though, start an async refresh\n if value[1] < eff_async_ttl and not nclient.contains(callkey, eff_async_ttl,\n **easync_lazy_recheck_kwargs):\n if renew_time is not None and (rv is not __NONE or lazy_kwargs):\n nclient.renew(callkey, eff_async_ttl + renew_time)\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n def on_miss():\n if renew_time is not None and placeholder_value_fn_cell:\n placeholder = placeholder_value_fn_cell[0](*p, **kw)\n nclient.add(callkey, placeholder, eff_async_ttl + renew_time)\n _fput_deferred(frv, client, af, callkey, eff_ttl(), *p, **kw)\n def on_exc(exc_info):\n stats.errors += 1\n return frv.exc(exc_info)\n clientf.getTtl(callkey, ttl_skip = eff_async_ttl, **eget_async_lazy_recheck_kwargs)\\\n .on_any(on_value, on_miss, on_exc)\n else:\n # It was a stale hit, so set the value now, but start a touch-refresh\n stats.hits += 1\n frv._set_nothreads(rv)\n def on_value(contains): # lint:ok\n if not contains:\n if renew_time is not None and (rv is not __NONE or lazy_kwargs):\n nclient.renew(callkey, eff_async_ttl + renew_time)\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n else:\n # just promote\n nclient.promote(callkey, ttl_skip = eff_async_ttl, **get_kwargs)\n def on_miss(): # lint:ok\n if renew_time is not None and placeholder_value_fn_cell:\n placeholder = placeholder_value_fn_cell[0](*p, **kw)\n nclient.add(callkey, placeholder, eff_async_ttl + renew_time)\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n def on_exc(exc_info): # lint:ok\n stats.errors += 1\n clientf.contains(callkey, eff_async_ttl, **easync_lazy_recheck_kwargs)\\\n .on_any_once(on_value, on_miss, on_exc)\n else:\n stats.hits += 1\n frv._set_nothreads(rv)\n return frv\n if decorate is not None:\n future_cached_f = decorate(future_cached_f)\n\n @wraps(of)\n def lazy_cached_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n raise CacheMissError\n\n try:\n rv = nclient.get(callkey, **elazy_kwargs)\n stats.hits += 1\n return rv\n except CacheMissError:\n stats.misses += 1\n raise\n if decorate is not None:\n lazy_cached_f = decorate(lazy_cached_f)\n peek_cached_f = lazy_cached_f\n\n @wraps(of)\n def future_lazy_cached_f(*p, **kw):\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n raise CacheMissError\n\n client = aclient\n frv = Future()\n __NONE = _NONE_\n\n if future_sync_check:\n # Quick sync call with lazy_kwargs\n rv, rvttl = client.getTtl(callkey, __NONE, **elazy_kwargs)\n else:\n rv = __NONE\n rvttl = -1\n\n if (rv is __NONE or rvttl < eff_async_ttl):\n # The hard way\n clientf = fclient\n if rv is __NONE and (not future_sync_check or async_lazy_recheck):\n # It was a preliminar miss, so wait for a recheck to set the value\n def on_value(value):\n if value[1] >= 0:\n stats.hits += 1\n frv.set(value[0])\n else:\n # Too stale\n frv.miss()\n # If it's stale, though, start an async refresh\n if value[1] < eff_async_ttl and not client.contains(callkey, eff_async_ttl,\n **easync_lazy_recheck_kwargs):\n if renew_time is not None and (rv is not __NONE or lazy_kwargs):\n nclient.renew(callkey, eff_async_ttl + renew_time)\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n def on_miss():\n # Ok, real miss, report it and start the computation\n frv.miss()\n if renew_time is not None and placeholder_value_fn_cell:\n placeholder = placeholder_value_fn_cell[0](*p, **kw)\n nclient.add(callkey, placeholder, eff_async_ttl + renew_time)\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n def on_exc(exc_info):\n stats.errors += 1\n frv.exc(exc_info)\n clientf.getTtl(callkey, ttl_skip = eff_async_ttl, **eget_async_lazy_recheck_kwargs)\\\n .on_any(on_value, on_miss, on_exc)\n else:\n # It was a stale hit or permanent miss, so set the value now, but start a touch-refresh\n if rv is __NONE:\n stats.misses += 1\n frv._miss_nothreads()\n else:\n stats.hits += 1\n frv._set_nothreads(rv)\n def on_value(contains): # lint:ok\n if not contains:\n if renew_time is not None and (rv is not __NONE or lazy_kwargs):\n nclient.renew(callkey, eff_async_ttl + renew_time)\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n else:\n # just promote\n nclient.promote(callkey, ttl_skip = eff_async_ttl, **get_kwargs)\n def on_miss(): # lint:ok\n if renew_time is not None and placeholder_value_fn_cell:\n placeholder = placeholder_value_fn_cell[0](*p, **kw)\n nclient.add(callkey, placeholder, eff_async_ttl + renew_time)\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n def on_exc(exc_info): # lint:ok\n stats.errors += 1\n clientf.contains(callkey, eff_async_ttl, **easync_lazy_recheck_kwargs)\\\n .on_any_once(on_value, on_miss, on_exc)\n else:\n stats.hits += 1\n frv._set_nothreads(rv)\n return frv\n if decorate is not None:\n future_lazy_cached_f = decorate(future_lazy_cached_f)\n\n @wraps(of)\n def future_peek_cached_f(*p, **kw):\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n raise CacheMissError\n\n client = aclient\n clientf = fclient\n frv = Future()\n __NONE = _NONE_\n\n if future_sync_check:\n # Quick sync call with lazy_kwargs\n rv, rvttl = client.getTtl(callkey, __NONE, **elazy_kwargs)\n else:\n rv = __NONE\n rvttl = -1\n\n if (rv is __NONE or rvttl < eff_async_ttl):\n # The hard way\n if rv is __NONE and (not future_sync_check or async_lazy_recheck):\n # It was a miss, so wait for setting the value\n def on_value(value):\n if value[1] >= 0:\n stats.hits += 1\n return frv.set(value[0])\n else:\n # Too stale\n stats.misses += 1\n return frv.miss()\n def on_miss():\n # Ok, real miss, report it\n stats.misses += 1\n return frv.miss()\n def on_exc(exc_info):\n stats.errors += 1\n return frv.exc(exc_info)\n clientf.getTtl(callkey, ttl_skip = eff_async_ttl, **eget_async_lazy_recheck_kwargs)\\\n .on_any(on_value, on_miss, on_exc)\n else:\n # It was a stale hit or permanent miss\n if rv is __NONE or rvttl < 0:\n stats.misses += 1\n frv._miss_nothreads()\n else:\n stats.hits += 1\n frv._set_nothreads(rv)\n else:\n stats.hits += 1\n frv._set_nothreads(rv)\n return frv\n if decorate is not None:\n future_peek_cached_f = decorate(future_peek_cached_f)\n\n @wraps(of)\n def future_get_ttl_f(*p, **kw):\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n raise CacheMissError\n\n # To-Do: intercept hits/misses and update stats?\n # (involves considerable overhead...)\n return fclient.getTtl(callkey, **get_kwargs)\n if decorate is not None:\n future_get_ttl_f = decorate(future_get_ttl_f)\n\n @wraps(of)\n def invalidate_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n nclient.delete(callkey)\n if decorate is not None:\n invalidate_f = decorate(invalidate_f)\n\n @wraps(of)\n def future_invalidate_f(*p, **kw):\n try:\n callkey = key(*p, **kw)\n except:\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n return fclient.delete(callkey)\n if decorate is not None:\n future_invalidate_f = decorate(future_invalidate_f)\n\n @wraps(of)\n def expire_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n nclient.expire(callkey)\n if decorate is not None:\n expire_f = decorate(expire_f)\n\n @wraps(of)\n def async_expire_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n aclient.expire(callkey)\n if decorate is not None:\n async_expire_f = decorate(async_expire_f)\n\n @wraps(of)\n def future_expire_f(*p, **kw):\n try:\n callkey = key(*p, **kw)\n except:\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n return fclient.expire(callkey)\n if decorate is not None:\n future_expire_f = decorate(future_expire_f)\n\n @wraps(of)\n def put_f(*p, **kw):\n value = kw.pop('_cache_put')\n put_kwargs = kw.pop('_cache_put_kwargs', None)\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n nclient.put(callkey, value, eff_ttl(), **(put_kwargs or EMPTY_KWARGS))\n if decorate is not None:\n put_f = decorate(put_f)\n\n @wraps(of)\n def async_put_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n value = kw.pop('_cache_put')\n put_kwargs = kw.pop('_cache_put_kwargs', None)\n try:\n callkey = key(*p, **kw)\n except:\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n aclient.put(callkey, value, eff_ttl(), **(put_kwargs or EMPTY_KWARGS))\n if decorate is not None:\n async_put_f = decorate(async_put_f)\n\n @wraps(of)\n def future_put_f(*p, **kw):\n value = kw.pop('_cache_put')\n put_kwargs = kw.pop('_cache_put_kwargs', None)\n try:\n callkey = key(*p, **kw)\n except:\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n return fclient.put(callkey, value, eff_ttl(), **(put_kwargs or EMPTY_KWARGS))\n if decorate is not None:\n future_put_f = decorate(future_put_f)\n\n @wraps(of)\n def async_lazy_cached_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n raise CacheMissError\n\n __NONE = _NONE_\n client = aclient\n\n rv, rvttl = client.getTtl(callkey, __NONE, **elazy_kwargs)\n\n if (rv is __NONE or rvttl < eff_async_ttl) and not client.contains(callkey, eff_async_ttl, **elazy_kwargs):\n if async_lazy_recheck:\n stats.misses += 1\n\n # send a Defer that touches the client with recheck kwargs\n # before doing the refresh. Needs not be coherent.\n def touch_key(*p, **kw):\n rv, rvttl = nclient.getTtl(callkey, __NONE, ttl_skip = eff_async_ttl,\n **eget_async_lazy_recheck_kwargs)\n if (rv is __NONE or rvttl < eff_async_ttl) and not nclient.contains(callkey, eff_async_ttl,\n **easync_lazy_recheck_kwargs):\n if renew_time is not None and (rv is not __NONE or lazy_kwargs):\n nclient.renew(callkey, eff_async_ttl + renew_time)\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n return base.NONE\n\n # This will make contains return True for this key, until touch_key returns\n # This is actually good, since it'll result in immediate misses from now on,\n # avoiding trying to queue up touch after touch\n _lazy_recheck_put_deferred(client, touch_key, callkey, ttl, *p, **kw)\n else:\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n elif rv is not __NONE:\n if rvttl < eff_async_ttl:\n if async_expire:\n async_expire(callkey)\n else:\n # means client.contains(callkey, eff_async_ttl), so promote\n client.promote(callkey, ttl_skip = eff_async_ttl, **get_kwargs)\n stats.hits += 1\n else:\n stats.misses += 1\n\n if rv is __NONE:\n raise CacheMissError(callkey)\n else:\n return rv\n if decorate is not None:\n async_lazy_cached_f = decorate(async_lazy_cached_f)\n\n @wraps(of)\n def refresh_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n\n rv = f(*p, **kw)\n nclient.put(callkey, rv, eff_ttl())\n return rv\n if decorate is not None:\n refresh_f = decorate(refresh_f)\n\n @wraps(of)\n def async_refresh_f(*p, **kw):\n if _initialize is not None:\n _initialize()\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n\n client = aclient\n if not client.contains(callkey, 0):\n _put_deferred(client, af, callkey, eff_ttl(), *p, **kw)\n if decorate is not None:\n async_refresh_f = decorate(async_refresh_f)\n\n @wraps(of)\n def future_refresh_f(*p, **kw):\n try:\n callkey = key(*p, **kw)\n except:\n # Bummer\n logging.getLogger('chorde').error(\"Error evaluating callkey\", exc_info = True)\n stats.errors += 1\n return\n\n frv = Future()\n _fput_deferred(frv, aclient, af, callkey, eff_ttl(), *p, **kw)\n return frv\n if decorate is not None:\n future_refresh_f = decorate(future_refresh_f)\n\n if client.is_async:\n cached_f = async_cached_f\n lazy_cached_f = async_lazy_cached_f\n elif nasync_client:\n aclient = nasync_client\n else:\n aclient = None\n\n promote_callbacks = []\n value_callbacks = []\n get_kwargs = {}\n def _promote_callback(*p, **kw):\n for cb in promote_callbacks:\n cb(*p, **kw)\n def _value_callback(*p, **kw):\n for cb in value_callbacks:\n cb(*p, **kw)\n def on_promote_f(callback):\n promote_callbacks.append(callback)\n get_kwargs.setdefault('promote_callback', _promote_callback)\n elazy_kwargs.setdefault('promote_callback', _promote_callback)\n eget_async_lazy_recheck_kwargs.setdefault('promote_callback', _promote_callback)\n return callback\n def on_value_f(callback):\n value_callbacks.append(callback)\n return callback\n\n placeholder_value_fn_cell = []\n def placeholder_value_f(fn):\n placeholder_value_fn_cell[:] = [fn]\n\n fclient = None\n def future_f(initialize = True):\n nonlocal fclient\n if _initialize is not None:\n _initialize()\n if fclient is None and initialize:\n if aclient:\n _client = aclient\n else:\n async_f() # initializes aclient\n _client = aclient\n\n if async_processor:\n _client = async_processor.bound(_client)\n else:\n _client = asyncache.AsyncCacheProcessor(async_processor_workers, _client,\n **async_processor_kwargs)\n # atomic\n fclient = _client\n future_cached_f.client = fclient\n return future_cached_f\n\n if not client.is_async:\n def async_f(initialize = True):\n nonlocal aclient\n if _initialize is not None:\n _initialize()\n if aclient is None and initialize:\n # atomic\n aclient = asyncache.AsyncWriteCacheClient(nclient,\n async_writer_queue_size,\n async_writer_workers,\n **async_writer_kwargs)\n async_cached_f.client = aclient\n return async_cached_f\n async_cached_f.clear = nclient.clear\n async_cached_f.client = aclient if aclient is not None else None\n async_cached_f.bg = weakref.ref(async_cached_f)\n async_cached_f.lazy = async_lazy_cached_f\n async_cached_f.refresh = async_refresh_f\n async_cached_f.peek = peek_cached_f\n async_cached_f.invalidate = invalidate_f\n async_cached_f.expire = async_expire_f\n async_cached_f.uncached = of\n async_cached_f.put = async_put_f\n async_cached_f.ttl = ttl\n async_cached_f.async_ttl = async_ttl\n async_cached_f.callkey = key\n async_cached_f.stats = stats\n async_cached_f.get_ttl = get_ttl_f\n async_cached_f._promote_callbacks = promote_callbacks\n async_cached_f._value_callbacks = value_callbacks\n async_cached_f.on_promote = on_promote_f\n async_cached_f.on_value = on_value_f\n async_cached_f.placeholder_value = placeholder_value_f\n cached_f.bg = async_f\n cached_f.lazy = lazy_cached_f\n cached_f.refresh = refresh_f\n cached_f.peek = peek_cached_f\n cached_f.invalidate = invalidate_f\n cached_f.expire = expire_f\n cached_f.put = put_f\n else:\n aclient = nclient\n cached_f.bg = async_f = weakref.ref(cached_f)\n cached_f.lazy = async_lazy_cached_f\n cached_f.refresh = async_refresh_f\n cached_f.peek = peek_cached_f\n cached_f.invalidate = invalidate_f\n cached_f.expire = expire_f\n cached_f.put = async_put_f\n\n cached_f.future = future_f\n cached_f.clear = nclient.clear\n cached_f.client = nclient\n cached_f.ttl = ttl\n cached_f.async_ttl = async_ttl or ttl\n cached_f.callkey = key\n cached_f.stats = stats\n cached_f.uncached = of\n cached_f.get_ttl = get_ttl_f\n cached_f._promote_callbacks = promote_callbacks\n cached_f._value_callbacks = value_callbacks\n cached_f.on_promote = on_promote_f\n cached_f.on_value = on_value_f\n cached_f.placeholder_value = placeholder_value_f\n\n future_cached_f.clear = lambda : fclient.clear()\n future_cached_f.client = None\n future_cached_f.bg = cached_f.bg\n future_cached_f.lazy = future_lazy_cached_f\n future_cached_f.refresh = future_refresh_f\n future_cached_f.peek = future_peek_cached_f\n future_cached_f.invalidate = future_invalidate_f\n future_cached_f.expire = future_expire_f\n future_cached_f.put = future_put_f\n future_cached_f.ttl = ttl\n future_cached_f.async_ttl = async_ttl\n future_cached_f.callkey = key\n future_cached_f.stats = stats\n future_cached_f.uncached = of\n future_cached_f.get_ttl = future_get_ttl_f\n future_cached_f._promote_callbacks = promote_callbacks\n future_cached_f._value_callbacks = value_callbacks\n future_cached_f.on_promote = on_promote_f\n future_cached_f.on_value = on_value_f\n future_cached_f.placeholder_value = placeholder_value_f\n\n decorated_functions.add(cached_f)\n return cached_f\n return decor\n\nif not no_coherence:\n\n def coherent_cached(private, shared, ipsub, ttl,\n key = lambda *p, **kw:(p,frozenset(kw.items()) or ()),\n tiered_ = None,\n namespace = None,\n coherence_namespace = None,\n coherence_encoding = 'pyobj',\n coherence_timeout = None,\n value_serialization_function = None,\n value_deserialization_function = None,\n async_writer_queue_size = None,\n async_writer_workers = None,\n async_writer_threadpool = None,\n async_writer_kwargs = None,\n async_ttl = None,\n async_expire = None,\n lazy_kwargs = {},\n async_lazy_recheck = False,\n async_lazy_recheck_kwargs = {},\n async_processor = None,\n async_processor_workers = None,\n async_processor_threadpool = None,\n async_processor_kwargs = None,\n renew_time = None,\n future_sync_check = None,\n initialize = None,\n decorate = None,\n tiered_opts = None,\n ttl_spread = True,\n wait_time = None,\n autonamespace_version_salt = None,\n **coherence_kwargs ):\n \"\"\"\n This decorator provides cacheability to suitable functions, in a way that maintains coherency across\n multiple compute nodes.\n\n For suitability considerations and common parameters, refer to cached. The following describes the\n aspects specific to the coherent version.\n\n The decorated function will provide additional behavior through attributes:\n coherence: the coherence manager created for this purpse\n\n ipsub: the given IPSub channel\n\n Params\n ipsub: An IPSub channel that will be used to publish and subscribe to update events.\n\n private: The private (local) cache client, the one that needs coherence.\n\n shared: The shared cache client, that reflects changes made by other nodes, or a tuple\n to specify multiple shared tiers.\n\n tiered_: (optional) A client that queries both, private and shared. By default, a TieredInclusiveClient\n is created with private and shared as first and second tier, which should be the most common case.\n The private client will be wrapped in an async wrapper if not async already, to be able to execute\n the coherence protocol asynchronously. This should be adequate for most cases, but in some,\n it may be beneficial to provide a custom client.\n\n tiered_opts: (optional) When using the default-constructed tiered client, you can pass additional (keyword)\n arguments here.\n\n coherence_namespace: (optional) There is usually no need to specify this value, the namespace in use\n by caching will be used for messaging as well, or if caching uses NO_NAMESPACE, the default that\n would be used instead. However, for really high-volume channels, sometimes it is beneficial to pick\n a more compact namespace (an id formatted with struct.pack for example).\n\n coherence_encoding: (optional) Keys will have to be transmitted accross the channel, and this specifies\n the encoding that will be used. The default 'pyobj' should work most of the time, but it has to\n be initialized, and 'json' or others could be more compact, depending on keys.\n (see CoherenceManager for details on encodings)\n\n coherence_timeout: (optional) Time (in ms) of peer silence that will be considered abnormal. Default\n is 2000ms, which is sensible given the IPSub protocol. You may want to increase it if node load\n creates longer hiccups.\n\n wait_time: (optional) Time (in ms) a call that is being computed externally will wait blocking for\n a result. Waiting forever (None, the default) could block the writer threadpool, so it's best to\n specify a reasonably adequate (for the application) timeout.\n\n Any extra argument are passed verbatim to CoherenceManager's constructor.\n \"\"\"\n if async_ttl is None:\n async_ttl = ttl / 2\n elif async_ttl < 0:\n async_ttl = ttl + async_ttl\n\n if ttl_spread is True:\n ttl_spread = min(ttl, async_ttl, abs(ttl-async_ttl)) / 2\n\n if not private.is_async:\n if async_writer_queue_size is None:\n async_writer_queue_size = 100\n if async_writer_workers is None:\n async_writer_workers = multiprocessing.cpu_count()\n\n if async_writer_kwargs is None:\n async_writer_kwargs = {}\n async_writer_kwargs.setdefault('threadpool', async_writer_threadpool)\n\n def decor(f):\n if ttl_spread:\n spread_type = type(ttl_spread)\n eff_async_ttl = max(async_ttl / 2, async_ttl - spread_type(ttl_spread * 0.25 * random.random()))\n else:\n eff_async_ttl = None\n\n salt2 = repr((ttl,))\n if coherence_namespace is None:\n _coherence_namespace = _make_namespace(f, salt = autonamespace_version_salt, salt2 = salt2)\n else:\n _coherence_namespace = coherence_namespace\n\n if namespace is None:\n _namespace = _make_namespace(f, salt = autonamespace_version_salt, salt2 = salt2)\n else:\n _namespace = namespace\n\n if not private.is_async:\n nprivate = asyncache.AsyncWriteCacheClient(private,\n async_writer_queue_size,\n async_writer_workers,\n **async_writer_kwargs)\n else:\n nprivate = private\n\n if not isinstance(shared, tuple):\n shareds = (shared,)\n sharedt = shared\n elif len(shared) == 1:\n shareds = shared\n sharedt = shared[0]\n else:\n shareds = shared\n sharedt = tiered.TieredInclusiveClient(*shareds, **(tiered_opts or {}))\n\n if tiered_ is None:\n ntiered = tiered.TieredInclusiveClient(nprivate, *shareds, **(tiered_opts or {}))\n else:\n ntiered = tiered_\n\n if _namespace is not NO_NAMESPACE:\n ntiered = base.NamespaceWrapper(_namespace, ntiered)\n nprivate = base.NamespaceMirrorWrapper(ntiered, nprivate)\n nshared = base.NamespaceMirrorWrapper(ntiered, sharedt)\n else:\n nshared = sharedt\n\n coherence_manager = coherence.CoherenceManager(\n _coherence_namespace, nprivate, nshared, ipsub,\n encoding = coherence_encoding,\n **coherence_kwargs)\n\n nclient = coherent.CoherentWrapperClient(ntiered, coherence_manager, coherence_timeout)\n\n expired_ttl = async_ttl\n if eff_async_ttl:\n expired_ttl = max(expired_ttl, eff_async_ttl)\n if renew_time:\n expired_ttl = max(expired_ttl, (eff_async_ttl or async_ttl) + renew_time)\n\n rv = cached(nclient, ttl,\n namespace = NO_NAMESPACE, # Already covered\n key = key,\n value_serialization_function = value_serialization_function,\n value_deserialization_function = value_deserialization_function,\n async_writer_queue_size = async_writer_queue_size,\n async_writer_workers = async_writer_workers,\n async_writer_threadpool = async_writer_threadpool,\n async_writer_kwargs = async_writer_kwargs,\n async_ttl = async_ttl,\n async_expire = async_expire,\n initialize = initialize,\n decorate = decorate,\n lazy_kwargs = lazy_kwargs,\n async_lazy_recheck = async_lazy_recheck,\n async_lazy_recheck_kwargs = async_lazy_recheck_kwargs,\n async_processor = async_processor,\n async_processor_workers = async_processor_workers,\n async_processor_threadpool = async_processor_threadpool,\n async_processor_kwargs = async_processor_kwargs,\n renew_time = renew_time,\n future_sync_check = future_sync_check,\n ttl_spread = ttl_spread,\n _eff_async_ttl = eff_async_ttl,\n _put_deferred = partial(_coherent_put_deferred, nshared, expired_ttl, None,\n expire_private = nprivate.expire),\n _fput_deferred = partial(_coherent_put_deferred, nshared, expired_ttl,\n wait_time=wait_time,\n expire_private = nprivate.expire) )(f)\n rv.coherence = coherence_manager\n rv.ipsub = ipsub\n return rv\n return decor\n","sub_path":"lib/chorde/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":62984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"364107187","text":"from __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nsys.path.append(os.path.join('.', '..'))\nimport utils\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\n\n(embedding_test,embedding_labels_test) = utils.tfRead('test')\nprint(\"tfRecord test uploaded!\")\n\nembedding_labels_test = utils.labelMinimizer(embedding_labels_test)\nembedding_list = embedding_test\n\ngpu_opts = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)\n # load the trained network from a local drive\nwith tf.Session(config=tf.ConfigProto(gpu_options=gpu_opts)) as sess:\n#First let's load meta graph and restore weights\n saver = tf.train.import_meta_graph(\"C:/tmp/audio_classifier.meta\")\n saver.restore(sess,tf.train.latest_checkpoint('C:/tmp/'))\n# Now, let's access and create placeholders variables and\n# create feed-dict to feed new data\n\n graph = tf.get_default_graph()\n x_pl = graph.get_tensor_by_name(\"xPlaceholder:0\")\n feed_dict = {x_pl: embedding_list}\n\n #Now, access the op that you want to run.\n op_to_restore = graph.get_tensor_by_name(\"op_to_restore:0\")\n\n y_pred = sess.run(op_to_restore, feed_dict)\n\n pred = sess.run(tf.argmax(y_pred, axis=1))\n #print(\"class predicion embedding 1:\", pred)\n #print(\"real label: \",embedding_labels_test[0:100])\n\ncorrect_pred = 0;\nfor i in range(0,len(pred)):\n if pred[i] == embedding_labels_test[i]:\n correct_pred+=1\n\nacc = correct_pred/len(pred)\nprint(\"Test accuracy: \", acc)\n\n\n# majority vote test:\nfrom collections import Counter\n\ncorrect_pred = 0;\nidx = 0;\nfor n in range(1,round(len(pred)/10)):\n majorLabel= embedding_labels_test[idx:idx+9]\n majorPred = pred[idx:idx+9]\n cntLabel = Counter(majorLabel)\n cntPred = Counter(majorPred)\n\n idx = idx+10\n cLabel = cntLabel.most_common(1)[0]\n cPred = cntPred.most_common(1)[0]\n #print(cnt.most_common(1)[0])\n #print(cLabel[0])\n #print(cPred[0])\n if cLabel[0] == cPred[0]:\n correct_pred+=1\n\nacc = correct_pred/round(len(pred)/10)\nprint(\"Test accuracy (major): \", acc)\n\nconf_mat = confusion_matrix(embedding_labels_test,pred)\nnp.set_printoptions(precision=2)\nconf_norm = conf_mat.astype('float')/conf_mat.sum(axis=1)[:,np.newaxis]\nprint(conf_norm*100)\nprint(sum(conf_mat))\nprint(sum(conf_mat)[1])\n\n# 0 outdoor, 1 indoor, 2 vehicle\nclassName = [\"Outdoor\",\"Indoor\",\"Vehicle\"]\n# Plot normalized confusion matrix\nplt.figure()\nutils.plot_confusion_matrix(conf_mat, classes=className, normalize=True,\n title='Normalized confusion matrix')\n\nplt.savefig('myfig')\nplt.show()\n","sub_path":"restoreTest3Classes.py","file_name":"restoreTest3Classes.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"277985247","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport os\nimport io\nimport json\nimport pytest\nfrom copy import deepcopy\nfrom tabulator import Stream\nfrom jsontableschema import Schema\nfrom sqlalchemy import create_engine\nfrom jsontableschema_sql import Storage\nfrom dotenv import load_dotenv; load_dotenv('.env')\n\n\n# Tests\n\ndef test_storage():\n\n # Get resources\n articles_descriptor = json.load(io.open('data/articles.json', encoding='utf-8'))\n comments_descriptor = json.load(io.open('data/comments.json', encoding='utf-8'))\n articles_rows = Stream('data/articles.csv', headers=1).open().read()\n comments_rows = Stream('data/comments.csv', headers=1).open().read()\n\n # Engine\n engine = create_engine(os.environ['DATABASE_URL'])\n\n # Storage\n storage = Storage(engine=engine, prefix='test_storage_')\n\n # Delete buckets\n storage.delete()\n\n # Create buckets\n storage.create(\n ['articles', 'comments'],\n [articles_descriptor, comments_descriptor],\n indexes_fields=[[['rating'], ['name'], ['created_datetime']], []])\n\n # Recreate bucket\n storage.create('comments', comments_descriptor, force=True)\n\n # Write data to buckets\n storage.write('articles', articles_rows)\n gen = storage.write('comments', comments_rows, as_generator=True)\n lst = list(gen)\n assert len(lst) == 1\n\n # Create new storage to use reflection only\n storage = Storage(engine=engine, prefix='test_storage_')\n\n # Create existent bucket\n with pytest.raises(RuntimeError):\n storage.create('articles', articles_descriptor)\n\n # Assert representation\n assert repr(storage).startswith('Storage')\n\n # Assert buckets\n assert storage.buckets == ['articles', 'comments']\n\n # Assert descriptors\n assert storage.describe('articles') == sync_descriptor(articles_descriptor)\n assert storage.describe('comments') == sync_descriptor(comments_descriptor)\n\n # Assert rows\n assert list(storage.read('articles')) == sync_rows(articles_descriptor, articles_rows)\n assert list(storage.read('comments')) == sync_rows(comments_descriptor, comments_rows)\n\n # Delete non existent bucket\n with pytest.raises(RuntimeError):\n storage.delete('non_existent')\n\n\n # Delete buckets\n storage.delete()\n\n\ndef test_update():\n\n\n # Get resources\n descriptor = json.load(io.open('data/original.json', encoding='utf-8'))\n original_rows = Stream('data/original.csv', headers=1).open().read()\n update_rows = Stream('data/update.csv', headers=1).open().read()\n update_keys = ['person_id', 'name']\n\n # Engine\n engine = create_engine(os.environ['DATABASE_URL'])\n\n # Storage\n storage = Storage(engine=engine, prefix='test_update_', autoincrement='__id')\n\n # Delete buckets\n storage.delete()\n\n # Create buckets\n storage.create('colors', descriptor)\n\n\n # Write data to buckets\n storage.write('colors', original_rows, update_keys=update_keys)\n\n gen = storage.write('colors', update_rows, update_keys=update_keys, as_generator=True)\n gen = list(gen)\n assert len(gen) == 5\n assert len(list(filter(lambda i: i.updated, gen))) == 3\n assert list(map(lambda i: i.updated_id, gen)) == [5, 3, 6, 4, 5]\n\n storage = Storage(engine=engine, prefix='test_update_', autoincrement='__id')\n gen = storage.write('colors', update_rows, update_keys=update_keys, as_generator=True)\n gen = list(gen)\n assert len(gen) == 5\n assert len(list(filter(lambda i: i.updated, gen))) == 5\n assert list(map(lambda i: i.updated_id, gen)) == [5, 3, 6, 4, 5]\n\n # Create new storage to use reflection only\n storage = Storage(engine=engine, prefix='test_update_')\n\n rows = list(storage.iter('colors'))\n\n assert len(rows) == 6\n color_by_person = dict(\n (row[1], row[3])\n for row in rows\n )\n assert color_by_person == {\n 1: 'blue',\n 2: 'green',\n 3: 'magenta',\n 4: 'sunshine',\n 5: 'peach',\n 6: 'grey'\n }\n\n # Storage without autoincrement\n storage = Storage(engine=engine, prefix='test_update_')\n storage.delete()\n storage.create('colors', descriptor)\n\n storage.write('colors', original_rows, update_keys=update_keys)\n gen = storage.write('colors', update_rows, update_keys=update_keys, as_generator=True)\n gen = list(gen)\n assert len(gen) == 5\n assert len(list(filter(lambda i: i.updated, gen))) == 3\n assert list(map(lambda i: i.updated_id, gen)) == [None, None, None, None, None]\n\n\ndef test_bad_type():\n\n # Engine\n engine = create_engine(os.environ['DATABASE_URL'])\n\n # Storage\n storage = Storage(engine=engine, prefix='test_bad_type_')\n with pytest.raises(TypeError):\n storage.create('bad_type', {\n 'fields': [\n {\n 'name': 'bad_field',\n 'type': 'any'\n }\n ]\n })\n\n\ndef test_only_parameter():\n # Check the 'only' parameter\n\n # Get resources\n simple_descriptor = json.load(io.open('data/simple.json', encoding='utf-8'))\n\n # Engine\n engine = create_engine(os.environ['DATABASE_URL'], echo=True)\n\n # Storage\n storage = Storage(engine=engine, prefix='test_only_')\n\n # Delete buckets\n storage.delete()\n\n # Create buckets\n storage.create(\n 'names',\n simple_descriptor,\n indexes_fields=[['person_id']])\n\n def only(table):\n ret = 'name' not in table\n return ret\n engine = create_engine(os.environ['DATABASE_URL'], echo=True)\n storage = Storage(engine=engine, prefix='test_only_', reflect_only=only)\n # Delete non existent bucket\n with pytest.raises(RuntimeError):\n storage.delete('names')\n\n\ndef test_storage_bigdata():\n\n # Generate schema/data\n descriptor = {'fields': [{'name': 'id', 'type': 'integer'}]}\n rows = [{'id': value} for value in range(0, 2500)]\n\n # Push rows\n engine = create_engine(os.environ['DATABASE_URL'])\n storage = Storage(engine=engine, prefix='test_storage_bigdata_')\n storage.create('bucket', descriptor, force=True)\n storage.write('bucket', rows, keyed=True)\n\n # Pull rows\n assert list(storage.read('bucket')) == list(map(lambda x: [x['id']], rows))\n\n\ndef test_storage_bigdata_rollback():\n\n # Generate schema/data\n descriptor = {'fields': [{'name': 'id', 'type': 'integer'}]}\n rows = [(value,) for value in range(0, 2500)] + [('bad-value',)]\n\n # Push rows\n engine = create_engine(os.environ['DATABASE_URL'])\n storage = Storage(engine=engine, prefix='test_storage_bigdata_rollback_')\n storage.create('bucket', descriptor, force=True)\n try:\n storage.write('bucket', rows)\n except Exception:\n pass\n\n # Pull rows\n assert list(storage.read('bucket')) == []\n\n\n# Helpers\n\ndef sync_descriptor(descriptor):\n descriptor = deepcopy(descriptor)\n for field in descriptor['fields']:\n if field['type'] in ['array', 'geojson']:\n field['type'] = 'object'\n if 'format' in field:\n del field['format']\n return descriptor\n\n\ndef sync_rows(descriptor, rows):\n result = []\n schema = Schema(descriptor)\n for row in rows:\n result.append(schema.cast_row(row))\n return result\n","sub_path":"tests/test_storage.py","file_name":"test_storage.py","file_ext":"py","file_size_in_byte":7372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"527817364","text":"from math import isnan\n\nimport numpy as np\nfrom mosfit.constants import DAY_CGS\nfrom mosfit.modules.engines.engine import Engine\n\nCLASS_NAME = 'Magnetar'\n\n\nclass Magnetar(Engine):\n \"\"\"Magnetar spin-down engine\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def process(self, **kwargs):\n if 'dense_times' in kwargs:\n self._times = kwargs['dense_times']\n else:\n self._times = kwargs['rest_times']\n self._Pspin = kwargs['Pspin']\n self._Bfield = kwargs['Bfield']\n self._Mns = kwargs['Mns']\n self._thetaPB = kwargs['thetaPB']\n self._rest_t_explosion = kwargs['resttexplosion']\n\n Ep = 2.6e52 * (self._Mns / 1.4)**(3. / 2.) * self._Pspin**(-2)\n\n tp = 1.3e5 * self._Bfield**(-2) * self._Pspin**2 * (self._Mns / 1.4)**(\n 3. / 2.) * (np.sin(self._thetaPB))**(-2)\n\n ts = [\n np.inf\n if self._rest_t_explosion > x else (x - self._rest_t_explosion)\n for x in self._times\n ]\n\n # print(ts)\n #\n # raise SystemExit\n #\n luminosities = [Ep / tp / (1. + t * DAY_CGS / tp)**2 for t in ts]\n luminosities = [0.0 if isnan(x) else x for x in luminosities]\n\n # Add on to any existing luminosity\n luminosities = self.add_to_existing_lums(luminosities)\n\n return {'luminosities': luminosities}\n","sub_path":"mosfit/modules/engines/magnetar.py","file_name":"magnetar.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"197902763","text":"data = [ [int(a) for a in i.split(\" \")] for i in open(\"B-large.in\",\"rU\").read()[:-1].split(\"\\n\")]\ncount = 0\nfor line in data[1:]:\n\tcount += 1\n\tsupps = line[1]\n\tscore = line[2]\n\tmaxes = 0\n\tnonsuptot = (score*3)-2\n\tsuptot = (score*3)-4\n\tif suptot < 0:\n\t\tsuptot = 1\n\tfor i in range(3,(len(line))):\n\t\tif line[i] >= nonsuptot:\n\t\t\tmaxes += 1\n\t\t\tcontinue\n\t\tif (line[i] >= suptot) and (supps > 0):\n\t\t\tmaxes += 1\n\t\t\tsupps -= 1\n\tif score == 0:\n\t\tmaxes = line[0]\n\tprint (\"Case #\"+str(count)+\":\", maxes)\n\t\t\n\t\t\t\n\n\n\n\n","sub_path":"solutions_1595491_1/Python/Entropy/Dancing.py","file_name":"Dancing.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"629154694","text":"\"\"\"\nNow try a repeating-key XOR cipher. E.g. it should take a string \"hello world\"\nand, given the key is \"key\", xor the first letter \"h\" with \"k\", then xor \"e\"\nwith \"e\", then \"l\" with \"y\", and then xor next char \"l\" with \"k\" again, then \"o\"\nwith \"e\" and so on. You may use index of coincidence, Hamming distance, Kasiski\nexamination, statistical tests or whatever method you feel would show the best\nresult.\n\"\"\"\nimport textwrap\nfrom collections import defaultdict, Counter, OrderedDict\nfrom itertools import cycle, permutations\nimport binascii\nimport time\n\ntask3 = '1c41023f564b2a130824570e6b47046b521f3f5208201318245e0e6b40022643072e13183e51183f5a1f3e4702245d4b285a1b23561965133f2413192e571e28564b3f5b0e6b50042643072e4b023f4a4b24554b3f5b0238130425564b3c564b3c5a0727131e38564b245d0732131e3b430e39500a38564b27561f3f5619381f4b385c4b3f5b0e6b580e32401b2a500e6b5a186b5c05274a4b79054a6b67046b540e3f131f235a186b5c052e13192254033f130a3e470426521f22500a275f126b4a043e131c225f076b431924510a295f126b5d0e2e574b3f5c4b3e400e6b400426564b385c193f13042d130c2e5d0e3f5a086b52072c5c192247032613433c5b02285b4b3c5c1920560f6b47032e13092e401f6b5f0a38474b32560a391a476b40022646072a470e2f130a255d0e2a5f0225544b24414b2c410a2f5a0e25474b2f56182856053f1d4b185619225c1e385f1267131c395a1f2e13023f13192254033f13052444476b4a043e131c225f076b5d0e2e574b22474b3f5c4b2f56082243032e414b3f5b0e6b5d0e33474b245d0e6b52186b440e275f456b710e2a414b225d4b265a052f1f4b3f5b0e395689cbaa186b5d046b401b2a500e381d61'\ntask3_bytes = binascii.unhexlify(bytes(task3, 'ascii'))\n\nYELLOW_COLOR = \"\\033[93m\"\nBLUE_COLOR = \"\\033[94m\"\nWHITE_COLOR = \"\\033[0m\"\n\nENGLISH_WORDS_FREQEUNCIES = [\n ord(' '),\n ord('e'), # \n ord('t'), # \n ord('a'), # \n ord('o'), # \n ord('i'), # \n ord('n'), # \n ord('s'), # \n ord('r'), # \n ord('h'), # \n \n]\n\n\ndef count_frequencies(text):\n occurencies = Counter(text)\n frequencies = [(k, round(v / len(text), 5)) for k, v in occurencies.items()]\n return OrderedDict(sorted(frequencies, key=lambda x: -(x[1])))\n\ndef apply_key(text, key):\n result = b''\n for char, key_letter in zip(text, cycle(key)):\n result += bytes([(char ^ key_letter), ])\n\n return result\n\ndef find_possible_symbols(frequencies, pos):\n # Try to change with first 5 symbols\n top_english_freqs_perms = permutations(ENGLISH_WORDS_FREQEUNCIES)\n top_english_freqs_perms = set(map(\n lambda letters: letters[:5],\n top_english_freqs_perms\n ))\n top_text_freqs = list(frequencies.keys())[:5]\n\n minimum_coincided = 5\n possible_keys = set()\n for perm in top_english_freqs_perms:\n \n keys = set(map(\n lambda chars: chars[0] ^ chars[1],\n zip(top_text_freqs, perm)\n ))\n # print(perm, top_text_freqs, len(keys), minimum_coincided, keys)\n\n if len(keys) < minimum_coincided:\n minimum_coincided = len(keys)\n possible_keys = keys\n elif len(keys) == minimum_coincided:\n possible_keys = possible_keys | keys\n\n print(\n f'{BLUE_COLOR} Position {pos}: '\n f'{WHITE_COLOR}symbols {possible_keys} produce '\n f'{YELLOW_COLOR}{minimum_coincided}{WHITE_COLOR} variants of mapping'\n )\n \n return possible_keys\n\n\ndef form_all_possible_mappings(possible_key_mappings):\n if not possible_key_mappings:\n return []\n\n mapping_copy = possible_key_mappings.copy()\n random_position = list(mapping_copy.keys())[0]\n random_position_symbols = mapping_copy.pop(random_position)\n\n other_possible_mappings = form_all_possible_mappings(mapping_copy)\n if not other_possible_mappings:\n return [{random_position: symbol} for symbol in random_position_symbols]\n \n results = []\n for symbol in random_position_symbols:\n for result in other_possible_mappings:\n results.append({random_position: symbol, **result})\n \n return results\n\ndef mapping_to_key(mapping):\n sorted_keys = sorted(mapping.items(), key=lambda pair: pair[0]) # By key\n return [x[1] for x in sorted_keys]\n\n\ndef try_decipher_for_key_length(text_bytes, key_length, possible_words=None):\n possible_words = [] if possible_words is None else possible_words\n\n same_pos_chars = defaultdict(list)\n for i, char in enumerate(text_bytes): \n same_pos_chars[i % key_length].append(char)\n \n same_pos_frequencies = {\n position: count_frequencies(chars)\n for position, chars in same_pos_chars.items()\n }\n\n possible_keys = {}\n for position, freqs in same_pos_frequencies.items():\n possible_keys[position] = find_possible_symbols(freqs, position)\n\n all_possible_mappings = form_all_possible_mappings(possible_keys)\n len_mapping = len(all_possible_mappings)\n print('\\n##### Total possible keys: ', len_mapping)\n\n for mapping in all_possible_mappings:\n key = mapping_to_key(mapping)\n \n result_bytes = apply_key(text_bytes, key).lower()\n all_words_present = True\n for word in possible_words:\n if bytes(word, 'ascii') not in result_bytes:\n all_words_present = False\n break\n\n if all_words_present:\n key_str = bytes(key).decode('ascii')\n print(f'{YELLOW_COLOR}Key {key_str} result: {WHITE_COLOR}')\n print(result_bytes)\n\n\n\n\ntry_decipher_for_key_length(task3_bytes, 6, ['the', 'genetic'])\n","sub_path":"lab1_2.py","file_name":"lab1_2.py","file_ext":"py","file_size_in_byte":5522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"523978122","text":"#!/usr/local/bin/python\n# coding: utf-8\n\nfrom __future__ import unicode_literals\nfrom nutritionapp import forms as nutrition_forms\nfrom django.shortcuts import render\nfrom healthylife import settings\nfrom healthylifeapp import views as general_views\nfrom shop import views as shop_views\n\nimport requests\nimport json\n\n# Nutrition views\ndef nutrition(request):\n \"\"\"\n View for nutrition section\n Search nutritional information\n \"\"\"\n food_information = None\n\n nutrition_filter_form = getNutritionFilterForm(request)\n\n if nutrition_filter_form.is_valid():\n food_name = nutrition_filter_form.cleaned_data['name']\n print(food_name)\n else:\n food_name = None\n\n if food_name is not None:\n food_information = getNutritionixApiInformation(food_name)\n #food_information = json.loads(food_information)\n print(food_information)\n\n return render(request, 'nutrition.html', {\n \"search_form\": general_views.getSearchForm(),\n 'subscribe_form': general_views.getSubscribeForm(),\n 'search_food_form': getNutritionFilterForm(request),\n 'food_information': food_information,\n 'shoppingcart': shop_views.getShoppingCart(request),\n })\n\n\n# Common Functions\ndef getNutritionFilterForm(request):\n \"\"\"\n Method to get search food form\n depends that get or post request\n \"\"\"\n if request.method == 'POST':\n nutrition_filter_form = nutrition_forms.NutritionFilter(request.POST)\n else:\n nutrition_filter_form = nutrition_forms.NutritionFilter()\n\n return nutrition_filter_form\n\n\ndef getNutritionixApiInformation(food):\n \"\"\"\n Method that request on nutrition api\n \"\"\"\n\n url = \"https://trackapi.nutritionix.com/v2/search/instant?\"\n \"\"\"\n Populate any search interface, including autocomplete, with common foods and branded foods from Nutritionix. This searches our entire database of 600K+ foods. Once a user selects the food from the autocomplete interface, make a separate API request to look up the nutrients of the food.\n https://gist.github.com/mattsilv/6d19997bbdd02cf5337e9d4806b4f464\n \"\"\"\n\n url2 = \"https://trackapi.nutritionix.com/v2/natural/nutrients?\"\n \"\"\"\n Get detailed nutrient breakdown of any natural language text\n https://gist.github.com/mattsilv/9dfb709e7609537ffd3b1b8c097e9bfb\n https://gist.github.com/mattsilv/95f94dd1378d4747fb68ebb2d042a4a6\n \"\"\"\n\n url3 = \"https://trackapi.nutritionix.com/v2/search/item?\"\n \"\"\"\n Look up the nutrition information for any branded food item by the nix_item_id (from /search/instant endpoint) or UPC scanned from a branded grocery product.\n https://gist.github.com/mattsilv/478c9288f213ce5333399a41bd6da5a4\n \"\"\"\n\n body = {\n 'query': food,\n }\n headers = {\n 'x-app-id': settings.X_APP_ID,\n 'x-app-key': settings.X_APP_KEY,\n #'x-remote-user-id': \"7a43c5ba-50e7-44fb-b2b4-bbd1b7d22632\",\n }\n response = requests.request(\"GET\", url, params=body, headers=headers)\n #content = response.json()['common']\n content = response.json()\n # revisar aparte del common\n\n return content\n","sub_path":"healthylife/nutritionapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"533371950","text":"import requests ,time\nfrom scanprice import changeTime\nrequests.packages.urllib3.disable_warnings()\nrequests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100) \ns = requests.Session()\nr1=s.get('https://k.apiairasia.com/availabledates/api/v1/pricecalendar/0/0/CKG/DMK/2018-09-17/1/99',verify=False)\ntime_start = time.time()\nr2=s.get('https://k.apiairasia.com/availabledates/api/v1/pricecalendar/0/0/DMK/CKG/2018-09-17/1/99',verify=False)\n\ntime_end = time.time()\nprint (changeTime(time_end-time_start))\nprint(r1.text)\nprint(r2.text)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"302822956","text":"'''\n19.二叉树的镜像\n递归,每个子树上左右结点位置互换\n先考虑两种base case情况:\n(1)根结点为空\n(2)左右子结点都为空\n之后:\n(1)调换左右结点位置;\n(2)递归将左右子树分别做镜像\n'''\nclass TreeNode():\n\tdef __init__(self, x):\n\t\tself.val = x\n\t\tself.left = None\n\t\tself.right = None\ndef Mirror(root):\n\tif not root:\n\t\treturn\n\troot.left, root.right = root.right, root.left\n\tMirror(root.left)\n\tMirror(root.right)\n\treturn root\n'''\n循环法:若不用递归的方式,用栈\n中序遍历后用栈逆序打出来的序列,就是镜像二叉树的中序遍历\n或者先序遍历把左和右调换次序\n'''\n","sub_path":"数据结构与算法/剑指offer/19.二叉树的镜像.py","file_name":"19.二叉树的镜像.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"440005269","text":"import AppKit\nimport objc\n\nclass ImageMapImageCell(AppKit.NSTextFieldCell):\n \n @objc.python_method\n def setImages(self, imageMap):\n self._imageMap = imageMap\n \n def drawWithFrame_inView_(self, frame, view):\n value = self.objectValue()\n if value in self._imageMap:\n image = self._imageMap[value]\n srcWidth, srcHeight = image.size()\n viewHeight = view.rowHeight()\n scaledWidth = srcWidth / (srcHeight / viewHeight)\n x, y = frame.origin\n image.drawInRect_(((x, y), (scaledWidth, view.rowHeight())))\n","sub_path":"lib/imageMapImageCell.py","file_name":"imageMapImageCell.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"362116554","text":"################################################################################\n# attraction.py\n# Noah Ansel\n# 2015-11-03\n# --------------\n# An application of Vector3\n# to simulate attractive forces.\n################################################################################\n\n# Built-in Python includes\nfrom math import *\nfrom tkinter import *\n\n# External includes\nfrom vector3 import Vector3\n\n\n\"███████████████████████████████ Constants ████████████████████████████████\"\n\n# 6.67 * 10**-11\nGRAVITATIONAL_CONSTANT = 1\n\n\n\"███████████████████████████ External Functions ███████████████████████████\"\n\ndef getForce(target,other):\n \"\"\"\n (Entity, Entity) -> (Vector3)\n Finds the force upon target as result of other.\n \"\"\"\n\n radius = Vector3(other.center[0] - target.center[0],\n other.center[1] - target.center[1],\n other.center[2] - target.center[2])\n if radius.magnitude() == 0: # already in steady state\n return Vector3(0, 0, 0)\n else:\n magnitude = ((GRAVITATIONAL_CONSTANT * target.mass * other.mass) /\n (radius.magnitude()**2))\n theta, phi = radius.angles()\n return Vector3(magnitude = magnitude, theta = theta, phi = phi)\n\n\n\"████████████████████████████████ Objects █████████████████████████████████\"\n\n################################\n# Entity\n# --------------\n# An entity for the engine.\n################################\nclass Entity:\n\n id = 0\n\n def __init__(self, mass = 1, radius = 1, center= [0, 0, 0], velocity = None):\n self.id = Entity.id\n self.mass = mass # kg\n self.radius = radius # m\n self.center = center\n\n if velocity == None:\n self.velocity = Vector3(0,0,0) # m/s\n else:\n self.velocity = velocity # m/s\n Entity.id += 1\n\n def __str__(self):\n toRet = \"\".format(self.center[0],\n self.center[1],\n self.center[2],\n self.velocity)\n return toRet\n\n\n################################\n# Engine\n# --------------\n# Contains interacting entities.\n################################\nclass Engine:\n\n def __init__(self, dimensions = [10, 10, 10], canvas = None):\n self.entities = []\n self.dimensions = dimensions\n self.canvas = canvas\n\n def __str__(self):\n toRet = \"\"\n return toRet\n\n def add(self, mass = 1, radius = 1, center = [0, 0, 0], velocity = None):\n \"\"\"\n (args) -> (None)\n Creates a new entity with args and adds it to the list of entities\n \"\"\"\n ent = Entity(mass = mass,\n radius = radius,\n center = center,\n velocity = velocity)\n self.entities.append(ent)\n # update sectors\n\n def find(self, id):\n \"\"\"\n (id) -> (Entity)\n Finds an entity with the given id, if it exists.\n \"\"\"\n for item in self.entities:\n if item.id == id:\n return item\n\n def netForce(self, id):\n \"\"\"\n (id) -> (Vector3)\n Finds the net force on a given entity id.\n \"\"\"\n netForce = Vector3(0,0,0)\n\n me = self.find(id)\n for item in self.entities:\n if item.id != id:\n netForce += getForce(me,item)\n\n return netForce\n\n\n\"████████████████████████████████ Display █████████████████████████████████\"\n\n\n\"████████████████████████████████ Testing █████████████████████████████████\"\n\nif __name__==\"__main__\":\n eng = Engine()\n eng.add()\n eng.add(10,2,[5,4,3],Vector3(10,3,2.413))\n eng.add()\n print(eng)\n print(eng.netForce(0))","sub_path":"attract.py","file_name":"attract.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"366037471","text":"import logging\nfrom logging.handlers import RotatingFileHandler\nimport config\n\nclass RssLog(object):\n def __init__(self):\n self.rss_log_file = config.get_other_config()[\"log_file\"]\n\n self.rss_logger = logging.getLogger(\"rss\")\n self.rss_logger.setLevel(logging.INFO)\n\n file_handler = RotatingFileHandler(self.rss_log_file,\n mode='w',\n maxBytes=1000,\n backupCount=3,\n encoding='utf-8')\n\n formatter = logging.Formatter('%(asctime)s - %(lineno)d - %(levelname)s - %(message)s')\n file_handler.setFormatter(formatter)\n\n self.rss_logger.addHandler(file_handler)\n\n #useage\n #self.rss_logger.info('info messages')","sub_path":"rsslog.py","file_name":"rsslog.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"255751005","text":"\nimport decimal\nimport logging\n\nimport io\n\nfrom ..serialize.bitcoin_streamer import parse_struct, stream_struct\nfrom ..serialize import b2h, b2h_rev\nfrom ..encoding import bitcoin_address_to_ripemd160_sha_sec, double_sha256, public_pair_to_ripemd160_sha_sec\nfrom .script.tools import disassemble, compile\nfrom .script.signing import sign_signature\nfrom .script.vm import verify_script\nfrom .. import ecdsa\n\nCOIN_FACTOR = decimal.Decimal(100000000)\n\nclass ValidationFailureError(Exception): pass\n\nclass TxIn(object):\n \"\"\"\n The part of a Tx that specifies where the BitCoin comes from.\n \"\"\"\n def __init__(self, previous_hash, previous_index, script=b'', sequence=4294967295):\n self.previous_hash = previous_hash\n self.previous_index = previous_index\n self.script = script\n self.sequence = sequence\n\n def stream(self, f):\n stream_struct(\"#LSL\", f, self.previous_hash, self.previous_index, self.script, self.sequence)\n\n @classmethod\n def parse(self, f):\n return self(*parse_struct(\"#LSL\", f))\n\n def __str__(self):\n return 'TxIn<%s[%d] \"%s\">' % (b2h_rev(self.previous_hash), self.previous_index, disassemble(self.script))\n\nclass TxInGeneration(TxIn):\n def __str__(self):\n return 'TxIn' % b2h(self.script)\n\nclass TxOut(object):\n \"\"\"\n The part of a Tx that specifies where the BitCoin goes to.\n \"\"\"\n def __init__(self, coin_value, script):\n self.coin_value = int(coin_value)\n self.script = script\n\n def stream(self, f):\n stream_struct(\"QS\", f, self.coin_value, self.script)\n\n @classmethod\n def parse(self, f):\n return self(*parse_struct(\"QS\", f))\n\n def __str__(self):\n return 'TxOut<%s \"%s\">' % (decimal.Decimal(self.coin_value)/COIN_FACTOR, disassemble(self.script))\n\nclass Tx(object):\n\n @classmethod\n def coinbase_tx(class_, public_key_sec, coin_value, coinbase_bytes=b''):\n tx_in = TxInGeneration(previous_hash=bytes([0] * 32), previous_index=(1<<32)-1, script=coinbase_bytes)\n COINBASE_SCRIPT_OUT = \"%s OP_CHECKSIG\"\n script_text = COINBASE_SCRIPT_OUT % b2h(public_key_sec)\n script_bin = compile(script_text)\n tx_out = TxOut(coin_value, script_bin)\n # TODO: what is this?\n version = 1\n # TODO: what is this?\n lock_timestamp = 0\n return class_(version, [tx_in], [tx_out], lock_timestamp)\n\n @classmethod\n def standard_tx(class_, previous_hash_index__tuple_list, coin_value__bitcoin_address__tuple_list, tx_db=None, secret_exponent_key_for_public_pair_lookup=None):\n # TODO: what is this?\n version = 1\n # TODO: what is this?\n lock_timestamp = 0\n tx_in_list = [TxIn(h, idx) for h, idx in previous_hash_index__tuple_list]\n tx_out_list = []\n STANDARD_SCRIPT_OUT = \"OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG\"\n for coin_value, bitcoin_address in coin_value__bitcoin_address__tuple_list:\n ripemd160_sha = bitcoin_address_to_ripemd160_sha_sec(bitcoin_address)\n script_text = STANDARD_SCRIPT_OUT % b2h(ripemd160_sha)\n script_bin = compile(script_text)\n tx_out_list.append(TxOut(coin_value, script_bin))\n tx = Tx(version, tx_in_list, tx_out_list, lock_timestamp)\n if tx_db and secret_exponent_key_for_public_pair_lookup:\n tx = tx.sign(tx_db, secret_exponent_key_for_public_pair_lookup)\n return tx\n\n @classmethod\n def parse(self, f, is_first_in_block=False):\n version, count = parse_struct(\"LI\", f)\n txs_in = []\n if is_first_in_block:\n txs_in.append(TxInGeneration.parse(f))\n count = count - 1\n for i in range(count):\n txs_in.append(TxIn.parse(f))\n count, = parse_struct(\"I\", f)\n txs_out = []\n for i in range(count):\n txs_out.append(TxOut.parse(f))\n lock_timestamp, = parse_struct(\"L\", f)\n return self(version, txs_in, txs_out, lock_timestamp)\n\n def __init__(self, version, txs_in, txs_out, lock_timestamp=0):\n self.version = version\n self.txs_in = txs_in\n self.txs_out = txs_out\n self.lock_timestamp = lock_timestamp\n\n def stream(self, f):\n stream_struct(\"LI\", f, self.version, len(self.txs_in))\n for t in self.txs_in:\n t.stream(f)\n stream_struct(\"I\", f, len(self.txs_out))\n for t in self.txs_out:\n t.stream(f)\n stream_struct(\"L\", f, self.lock_timestamp)\n\n def hash(self):\n s = io.BytesIO()\n self.stream(s)\n return double_sha256(s.getvalue())\n\n def id(self):\n return b2h_rev(self.hash())\n\n def validate(self, tx_db):\n for idx, tx_in in enumerate(self.txs_in):\n tx_from = tx_db.get(tx_in.previous_hash)\n if not tx_from:\n raise ValidationFailureError(\"missing source transaction %s\" % b2h_rev(tx_in.previous_hash))\n if tx_in.previous_hash != tx_from.hash():\n raise ValidationFailureError(\"source transaction %s has incorrect hash (actually %s)\" % (b2h_rev(tx_in.previous_hash), b2h_rev(tx_from.hash())))\n tx_out = tx_from.txs_out[tx_in.previous_index]\n if not verify_script(tx_in.script, tx_out.script, self, idx):\n raise ValidationFailureError(\"Tx %s TxIn index %d did not verify\" % (b2h_rev(tx_in.previous_hash), idx))\n\n def sign(self, tx_db, secret_exponents, public_pair_compressed_for_ripemd160_sha_key_lookup=None):\n # if secret_exponents is a list, we generate the lookup\n # build secret_exponent_key_for_public_pair_lookup\n if hasattr(secret_exponents, \"get\"):\n secret_exponent_key_for_public_pair_lookup = secret_exponents\n else:\n secret_exponent_key_for_public_pair_lookup = {}\n public_pair_compressed_for_ripemd160_sha_key_lookup = {}\n for secret_exponent in secret_exponents:\n public_pair = ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, secret_exponent)\n secret_exponent_key_for_public_pair_lookup[public_pair] = secret_exponent\n public_pair_compressed_for_ripemd160_sha_key_lookup[public_pair_to_ripemd160_sha_sec(public_pair, compressed=True)] = (public_pair, True)\n public_pair_compressed_for_ripemd160_sha_key_lookup[public_pair_to_ripemd160_sha_sec(public_pair, compressed=False)] = (public_pair, False)\n\n new_txs_in = []\n for tx_in in self.txs_in:\n tx_from = tx_db.get(tx_in.previous_hash)\n new_script = sign_signature(tx_from, self, tx_in.previous_index, secret_exponent_key_for_public_pair_lookup.get, public_pair_compressed_for_ripemd160_sha_key_lookup.get)\n if not new_script: raise Exception(\"bad signature\")\n new_txs_in.append(TxIn(tx_in.previous_hash, tx_in.previous_index, new_script))\n tx = Tx(self.version, new_txs_in, self.txs_out, self.lock_timestamp)\n tx.validate(tx_db)\n return tx\n\n def __str__(self):\n return \"Tx [%s]\" % self.id()\n\n def __repr__(self):\n return \"Tx [%s] (v:%d) [%s] [%s]\" % (self.id(), self.version, \", \".join(str(t) for t in self.txs_in), \", \".join(str(t) for t in self.txs_out))\n","sub_path":"pycoin/tx/Tx.py","file_name":"Tx.py","file_ext":"py","file_size_in_byte":7289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"186544318","text":"from tkinter import *\r\nfrom tkinter import ttk\r\n\r\npos = Tk()\r\npos.title(\"Lo's Concessions\")\r\npos.geometry(\"1920x1080\")\r\n\r\n# making the function for the command option of the food button\r\n\r\n\r\ndef hb_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(3.00)\r\n order_panel.insert(END, \"Hamburger \\t\\t\\t\\t3.00\\n\")\r\n\r\n\r\ndef cb_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(4.50)\r\n order_panel.insert(END, \"Cheeseburger \\t\\t\\t\\t4.50\\n\")\r\n\r\n\r\ndef hd_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(3.00)\r\n order_panel.insert(END, \"Hotdog \\t\\t\\t\\t3.00\\n\")\r\n\r\n\r\ndef ccd_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(5.00)\r\n order_panel.insert(END, \"Chili Cheese Dog \\t\\t\\t\\t5.00\\n\")\r\n\r\n\r\ndef cpizza_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(3.50)\r\n order_panel.insert(END, \"Cheese Pizza \\t\\t\\t\\t3.50\\n\")\r\n\r\n\r\ndef ppizza_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(4.50)\r\n order_panel.insert(END, \"Pepperoni Pizza \\t\\t\\t\\t4.50\\n\")\r\n\r\n\r\ndef nachos_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(6.00)\r\n order_panel.insert(END, \"Nachos \\t\\t\\t\\t6.00\\n\")\r\n\r\n\r\ndef pretzel_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(3.00)\r\n order_panel.insert(END, \"Salted Pretzel \\t\\t\\t\\t3.00\\n\")\r\n\r\n\r\ndef popcorn_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(2.50)\r\n order_panel.insert(END, \"Popcorn \\t\\t\\t\\t2.50\\n\")\r\n\r\n\r\ndef candy_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(4.00)\r\n order_panel.insert(END, \"Boxed Candy \\t\\t\\t\\t4.00\\n\")\r\n\r\n\r\ndef soda_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(3.00)\r\n order_panel.insert(END, \"Bottled Soda \\t\\t\\t\\t3.00\\n\")\r\n\r\n\r\ndef water_order_taking():\r\n total = 0.00\r\n price = lambda a: a\r\n total += price(3.00)\r\n order_panel.insert(END, \"Bottled Water \\t\\t\\t\\t3.00\\n\")\r\n\r\n\r\ndef clear_button():\r\n order_panel.delete(1.0, END)\r\n\r\n\r\nreceipt = open(\"receipts.txt\", \"a\")\r\n\r\n# this function will grab the order from the order panel and write it to the receipts text file\r\n\r\n\r\ndef print_receipt():\r\n receipt.write(order_panel.get(1.0, END))\r\n receipt.close()\r\n order_panel.delete(1.0, END)\r\n# this allows another order to be taken after the previous order has been completed\r\n pos.mainloop()\r\n\r\n# opening all the photos for the buttons\r\n\r\n\r\nhamburger = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\burger.png\").subsample(2, 2)\r\ncheeseburger = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\cheeseburger.png\").subsample(2, 2)\r\nhotdog = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\hotdog.png\").subsample(2, 2)\r\nccdog = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\chilidog.png\").subsample(5, 5)\r\ncpizza = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\cpizza.png\").subsample(4, 4)\r\nppizza = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\ppizza.png\").subsample(2, 2)\r\nnachos = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\nachos.png\").subsample(2, 2)\r\npretzel = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\pretzel.png\").subsample(6, 6)\r\npopcorn = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\popcorn.png\").subsample(2, 2)\r\ncandy = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\candy.png\").subsample(6, 6)\r\nsoda = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\soda.png\").subsample(2, 2)\r\nwater = PhotoImage(file=r\"D:\\PycharmProjects\\PersonalProjects\\water.png\").subsample(2, 2)\r\n\r\nbutton = Button(pos, text=\"Hamburger\", image=hamburger, compound=TOP, bg=\"#FFFFFF\", command=hb_order_taking).grid(row=2, column=1, columnspan=1, padx=5, pady=5)\r\nbutton = Button(pos, text=\"Cheeseburger\", image=cheeseburger, compound=TOP, bg=\"#FFFFFF\", command=cb_order_taking).grid(row=2, column=3, columnspan=1)\r\nbutton = Button(pos, text=\"Hotdog\", image=hotdog, compound=TOP, bg=\"#FFFFFF\", command=hd_order_taking).grid(row=2, column=5, columnspan=1)\r\nbutton = Button(pos, text=\"Chili Cheese Dog\", image=ccdog, compound=TOP, bg=\"#FFFFFF\", command=ccd_order_taking).grid(row=2, column=7, columnspan=1)\r\nbutton = Button(pos, text=\"Cheese Pizza\", image=cpizza, compound=TOP, bg=\"#FFFFFF\", command=cpizza_order_taking).grid(row=3, column=1, columnspan=1)\r\nbutton = Button(pos, text=\"Pepperoni Pizza\", image=ppizza, compound=TOP, bg=\"#FFFFFF\", command=ppizza_order_taking).grid(row=3, column=3, columnspan=1)\r\nbutton = Button(pos, text=\"Nachos\", image=nachos, compound=TOP, bg=\"#FFFFFF\", command=nachos_order_taking).grid(row=3, column=5, columnspan=1)\r\nbutton = Button(pos, text=\"Salted Pretzel\", image=pretzel, compound=TOP, bg=\"#FFFFFF\", command=pretzel_order_taking).grid(row=3, column=7, columnspan=1)\r\nbutton = Button(pos, text=\"Popcorn\", image=popcorn, compound=TOP, bg=\"#FFFFFF\", command=popcorn_order_taking).grid(row=4, column=1, columnspan=1)\r\nbutton = Button(pos, text=\"Boxed Candy\", image=candy, compound=TOP, bg=\"#FFFFFF\", command=candy_order_taking).grid(row=4, column=3, columnspan=1)\r\nbutton = Button(pos, text=\"Bottled Soda\", image=soda, compound=TOP, bg=\"#FFFFFF\", command=soda_order_taking).grid(row=4, column=5, columnspan=1)\r\nbutton = Button(pos, text=\"Bottled Water\", image=water, compound=TOP, bg=\"#FFFFFF\", command=water_order_taking).grid(row=4, column=7, columnspan=1)\r\n\r\n\r\nclear_button = Button(pos, text=\"Clear\", command=clear_button, fg=\"#FFFFFF\", bg=\"#FF0800\", activebackground=\"#B31717\", width=\"25\", height=\"5\", font=\"Impact 18\").grid(row=5, column=1, columnspan=2)\r\n\r\ndone_button = Button(pos, text=\"Done\", command=print_receipt, fg=\"#FFFFFF\", bg=\"#00FF2A\", activebackground=\"#08A813\", width=\"25\", height=\"5\", font=\"Impact 18\").grid(row=5, column=5, columnspan=2)\r\n\r\norder_panel = Text(pos)\r\norder_panel.grid(row=2, rowspan=3, column=9)\r\n\r\n# undo_button = Button(pos, text=\"Undo\", fg=\"#000000\", command=order_panel.edit_undo).grid(row=9, column=1)\r\n\r\npos.mainloop()\r\n","sub_path":"POS Terminal_GUI.py","file_name":"POS Terminal_GUI.py","file_ext":"py","file_size_in_byte":6098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"440068326","text":"import numpy as np\nfrom prml.feature_extractions.pca import PCA\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nfrom sklearn.preprocessing import StandardScaler\n\nclass BayesianPCA_SVI(PCA):\n def __init__(self, n_components, learning_decay=0.7):\n \"\"\"\n construct principal component analysis\n\n Parameters\n ----------\n n_components : int\n number of components\n \"\"\"\n assert isinstance(n_components, int)\n self.n_components = n_components\n self.learning_decay=learning_decay\n\n def _batch(self, X, total_size):\n weights = np.repeat(total_size/X.shape[0],X.shape[0])\n D=X.shape[1]\n self.X_dr = {'X': X, 'XX': X**2, 'W': weights}\n\n def eigen(self, X_dr, *arg):\n sample_size = int(np.sum(X_dr['W']))\n X = self.X_dr['W'][:,None]*self.X_dr['X']\n n_features = X.shape[1]\n if sample_size >= n_features:\n cov = np.cov(X, rowvar=False)\n values, vectors = np.linalg.eigh(cov)\n index = n_features - self.n_components\n else:\n cov = np.cov(X)\n values, vectors = np.linalg.eigh(cov)\n vectors = (X.T @ vectors) / np.sqrt(sample_size * values)\n index = sample_size - self.n_components\n self.I = np.eye(self.n_components)\n if index == 0:\n self.var = 0\n else:\n self.var = np.mean(values[:index])\n\n self.W = vectors[:, index:].dot(np.sqrt(np.diag(values[index:]) - self.var * self.I))\n self.__M = self.W.T @ self.W + self.var * self.I\n self.C = self.W @ self.W.T + self.var * np.eye(n_features)\n if index == 0:\n self.Cinv = np.linalg.inv(self.C)\n else:\n self.Cinv = np.eye(n_features) / np.sqrt(self.var) - self.W @ np.linalg.inv(self.__M) @ self.W.T / self.var\n\n def fit(self, X, iter_max=100, initial=\"random\", batch_size=10, testset = None):\n \"\"\"\n empirical bayes estimation of pca parameters\n\n Parameters\n ----------\n X : (sample_size, n_features) ndarray\n input data\n iter_max : int\n maximum number of em steps\n\n Returns\n -------\n mean : (n_features,) ndarray\n sample mean fo the input data\n W : (n_features, n_components) ndarray\n projection matrix\n var : float\n variance of observation noise\n \"\"\"\n import time\n start = time.time()\n\n self._batch(np.array_split(X, int(X.shape[0]/batch_size))[0], X.shape[0])\n\n initial_list = [\"random\", \"eigen\"]\n self.mean = np.sum(self.X_dr['W'][:,None]*self.X_dr['X'], axis=0)/sum(self.X_dr['W'])\n self.I = np.eye(self.n_components)\n if initial not in initial_list:\n print(\"availabel initializations are {}\".format(initial_list))\n if initial == \"random\":\n self.W = np.eye(np.size(self.X_dr['X'], 1), self.n_components)\n self.var = 1.\n elif initial == \"eigen\":\n self.eigen(self.X_dr)\n self.alpha = len(self.mean) / np.sum(self.W ** 2, axis=0).clip(min=1e-10)\n\n self.n_batch_iter_=1\n\n ll = np.zeros(iter_max)\n time_s = np.zeros(iter_max)\n for i in range(iter_max):\n W = np.copy(self.W)\n np.take(X, np.random.permutation(X.shape[0]), axis=0, out=X)\n for batch in np.array_split(X, int(X.shape[0]/batch_size), axis=0):\n self.n_batch_iter_ += 1\n self._batch(batch, X.shape[0])\n Ez, Ezz = self._expectation(self.X_dr['X']-self.mean)\n self._maximization(self.X_dr, Ez, Ezz)\n #self.alpha = len(self.mean) / np.sum(self.W ** 2, axis=0).clip(min=1e-10)\n if np.allclose(W, self.W):\n break\n print(i)\n self.n_iter = i + 1\n self.C = self.W @ self.W.T + self.var * np.eye(np.size(self.X_dr['X'], 1))\n self.Cinv = np.linalg.inv(self.C)\n ll[i]=sum(self.log_proba(testset))\n time_s[i]= time.time() - start\n print(ll[i])\n print(time_s[i])\n\n return ll, time_s\n\n def _maximization(self, X_dr, Ez, Ezz):\n X_mean = (X_dr['X']-self.mean)\n self.new_W = (X_mean*X_dr['W'][:,None]).T @ Ez @ np.linalg.inv(np.sum(Ezz*X_dr['W'][:,None,None], axis=0) + self.var * np.diag(self.alpha))\n self.new_var = np.sum(\n (np.mean((X_dr['XX'] - 2*X_dr['X']*self.mean + self.mean ** 2), axis=-1)\n - 2 * np.mean(Ez @ self.W.T * X_mean, axis=-1)\n + np.trace((Ezz @ self.W.T @ self.W).T)/ len(self.mean))*X_dr['W'])/sum(X_dr['W'])\n\n self.learning_offset = 10\n learning_rate = np.power(self.learning_offset + self.n_batch_iter_,\n -self.learning_decay)\n\n self.W = (1-learning_rate)*self.W + learning_rate*self.new_W\n self.var = (1-learning_rate)*self.var + learning_rate*self.new_var\n self.var=max(self.var,0.000001)\n\n","sub_path":"datareduction/bayesian_pca_SVI.py","file_name":"bayesian_pca_SVI.py","file_ext":"py","file_size_in_byte":5036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"284069010","text":"\"\"\"smtp\"\"\"\n\nimport os\nimport traceback\n\nfrom datacontract.iscoutdataset import IscoutTask\nfrom .zgrab2scannerbase import Zgrab2ScannerBase\nfrom ..zgrab2parser import Zgrab2ParserSMTP\nfrom .....clientdatafeedback.scoutdatafeedback import PortInfo\n\n\nclass Zgrab2ScannerSMTP(Zgrab2ScannerBase):\n \"\"\"zgrab2 http scanner\"\"\"\n\n def __init__(self, zgrab_path: str):\n Zgrab2ScannerBase.__init__(self, \"zgrab2smtp\")\n self._parser: Zgrab2ParserSMTP = Zgrab2ParserSMTP()\n\n def get_banner_smtp(\n self,\n task: IscoutTask,\n level,\n portinfo: PortInfo,\n *args,\n zgrab2path: str = \"zgrab2\",\n sudo: bool = False,\n timeout: float = 600,\n ) -> iter:\n \"\"\"scan smtp services and get the banner\"\"\"\n hostfi = None\n outfi = None\n try:\n port: int = portinfo._port\n if not isinstance(port, int) or port < 0 or port > 65535:\n raise Exception(\"Invalid port: {}\".format(port))\n\n hosts: list = [portinfo._host]\n for h in portinfo.hostnames:\n if h not in hosts:\n hosts.append(h)\n for d in portinfo.domains:\n if d not in hosts:\n hosts.append(d)\n\n hostfi = self._write_hosts_to_file(task, hosts)\n if hostfi is None:\n return\n\n outfi = self._scan_smtp(\n task,\n level,\n hostfi,\n port,\n *args,\n zgrab2path=zgrab2path,\n sudo=sudo,\n timeout=timeout,\n )\n if outfi is None or not os.path.isfile(outfi):\n return\n\n self._parser.parse_banner(task, level, portinfo, outfi)\n\n except Exception:\n self._logger.error(\"Scan mssql error: {}\".format(traceback.format_exc()))\n finally:\n if not hostfi is None and os.path.isfile(hostfi):\n os.remove(hostfi)\n if not outfi is None and os.path.isfile(outfi):\n os.remove(outfi)\n\n def _scan_smtp(\n self,\n task: IscoutTask,\n level,\n host_file: str,\n port: int,\n *args,\n zgrab2path: str = \"zgrab2\",\n sudo: bool = False,\n timeout: float = 600,\n ) -> str:\n \"\"\"scan smtp\n \"\"\"\n outfi: str = None\n try:\n enhanced_args = []\n\n # add hosts and ports to args\n enhanced_args.append(\"smtp\")\n enhanced_args.append(f\"-p {port}\")\n # zgrab2 smtp --send-ehlo --ehlo-domain=\"mail.example.com\" --starttls --keep-client-logs -f host.txt -o smtp3.json\n enhanced_args.append(f\"-t {timeout}\")\n\n if not \"--send-ehlo\" in args:\n enhanced_args.append(\"--send-ehlo\")\n if not \"--ehlo-domain=\" in args:\n enhanced_args.append('--ehlo-domain=\"mail.example.com\"')\n if not \"--keep-client-logs\" in args:\n enhanced_args.append(\"--keep-client-logs\")\n\n # 这个args里面几乎没有东西,除非真的是外面有特殊说明这个才有值,所以还是先留在这里\n enhanced_args.extend(args)\n\n if port == 25 and not \"--starttls\" in enhanced_args:\n enhanced_args.append(\"--starttls\")\n if \"--smtps\" in enhanced_args:\n enhanced_args.remove(\"--smtps\")\n elif port == 465 and not \"--smtps\" in enhanced_args:\n # although it have scanned tls certificate in advance,\n # here should scan it again in order to check if the\n # certificate is different from the one previously scanned.\n enhanced_args.append(\"--smtps\")\n if \"--starttls\" in enhanced_args:\n enhanced_args.remove(\"--starttls\")\n\n if \"--input-file=\" not in args or \"-f\" not in args:\n enhanced_args.append(f\"-f {host_file}\") # input file\n\n outfi = os.path.join(self._tmpdir, \"{}_{}.smtp\".format(task.batchid, port))\n if \"--output-file=\" not in args or \"-o\" not in args:\n # here must use -o, use '--output-file' will cause exception 'No such file or directory'\n # this may be a bug\n # 人家没说可以用--output-file\n enhanced_args.append(f\"-o {outfi}\") # output file\n\n # 如果没有当前文件夹那么就创建当前文件夹\n outdir = os.path.dirname(outfi)\n if not os.path.exists(outdir) or not os.path.isdir(outdir):\n os.makedirs(outdir)\n\n curr_process = None\n try:\n\n curr_process = self._run_process(\n zgrab2path, *enhanced_args, rootDir=outdir, sudo=sudo\n )\n stdout, stderr = curr_process.communicate(timeout=timeout)\n exitcode = curr_process.wait(timeout=timeout)\n if stdout is not None:\n self._logger.trace(stdout)\n if stderr is not None:\n self._logger.trace(stderr)\n if exitcode != 0:\n raise Exception(f\"Scan smtp error: {stdout}\\n{stderr}\")\n self._logger.info(\n f\"Scan smtp exitcode={str(exitcode)}\\ntaskid:{task.taskid}\\nbatchid:{task.batchid}\\nport:{port}\"\n )\n finally:\n if curr_process is not None:\n curr_process.kill()\n except Exception:\n if outfi is not None and os.path.isfile(outfi):\n os.remove(outfi)\n outfi = None\n self._logger.info(\n f\"Scan smtp exitcode={str(exitcode)}\\ntaskid:{task.taskid}\\nbatchid:{task.batchid}\\nport:{port}\"\n )\n\n return outfi\n","sub_path":"savecode/threeyears/idownclient/scout/plugin/zgrab2/zgrab2scanner/zgrab2scannersmtp.py","file_name":"zgrab2scannersmtp.py","file_ext":"py","file_size_in_byte":5894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"72692360","text":"from cryptography.fernet import Fernet as dpsisbad\r\nimport os as pp\r\nimport pygame as hotshit\r\n#from playsound import playsound as sexy\r\n#sexy('https://cdn.discordapp.com/attachments/831569914535739393/877087237743996938/y2mate.com_-_Jonas_Brothers_Hesitate_Lyrics.mp3', False)\r\n\r\n\r\nhotshit.mixer.init()\r\nhotshit.mixer.music.load('bis.wav')\r\nhotshit.mixer.music.play(999)\r\n\r\n\r\npp.system(\"color 0E\")\r\npp.system(\"cls\")\r\nprint(\"Thank you for using AbhiQ Encrytor\")\r\ndpsreadschats = input(\"Do You Have A Key? (yes - y and no - n)\\n\")\r\nif dpsreadschats == \"y\":\r\n key = input(\"Enter Your Key Here \\n\").encode()\r\n print(\"This is Your Key : \"+ (key.decode()))\r\nelse:\r\n key = dpsisbad.generate_key() \r\n print(\"Please Keep this Key Safely.\\n\")\r\n print(\"-------------------------------------------\")\r\n print((key.decode()))\r\n print(\"-------------------------------------------\\n\")\r\ndpsstalks = dpsisbad(key)\r\n\r\npp.system(\"color 0B\")\r\nwhile True:\r\n dpshacksyou = input(\"Do You Want to Encode Or Decode The Message? \\n(Encode = e, Decode = d, quit = q) \\n\")\r\n if dpshacksyou == \"e\":\r\n gg = input(\"Enter the text you want to encode. \\n\")\r\n encoded_text = gg.encode()#https://stackoverflow.com/a/69043349/14836433\r\n token = dpsstalks.encrypt(encoded_text)\r\n print(\"This is Your Encrypted Message. \\n\"+(token.decode()))\r\n ghost = input(\"\\n Press Enter To Continue\")\r\n pp.system(\"cls\")\r\n elif dpshacksyou == \"d\":\r\n text1 = input(\"Enter the encrypted text to decode. \\n\").encode()\r\n token = dpsstalks.decrypt(text1)\r\n print(\"This was your secret message \\n\"+(token.decode)())\r\n ghost = input(\"\\n Press Enter To Continue\")\r\n pp.system(\"cls\")\r\n elif dpshacksyou in (\"q\", \"exit\", \"quit\"):\r\n pp.system(\"color 0F\")\r\n pp.system(\"cls\")\r\n ghost = input(\"Thanks For Using AbhiQ services. \\n\")\r\n break\r\n\r\n\r\n\r\n","sub_path":"encryptor.py","file_name":"encryptor.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"574240862","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2015, ParaTools, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# (1) Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# (2) Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# (3) Neither the name of ParaTools, Inc. nor the names of its contributors may\n# be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\"\"\"TAU Commander command line interface (CLI).\n\nThe TAU Commander CLI is composed of a single top-level command that invokes\nsubcommands, much like `git`_. For example, the command line \n``tau project create my_new_project`` invokes the `create` subcommand of the\n`project` subcommand with the arguments `my_new_project`. \n\nEvery package in :py:mod:`tau.cli.commands` is a TAU Commander subcommand. Modules\nin the package are that subcommand's subcommands. This can be nested as deep as\nyou like. Subcommand modules must set the following module attributes:\n\n * COMMAND (str): The subcommand name as returned by :any:`get_command`.\n * SHORT_DESCRIPTION (str): A one-line description of the subcommand. \n * HELP (str): The subcommand's help page. Should be long and detailed.\n * parser: A function that returns an argument parser for the command.\n * main: The subprogram entry point.\n \nSubcommand modules may optionally set the following module attributes:\n\n * GROUP (str): List this subcommand in a group named `GROUP` in help messages.\n\n.. _git: https://git-scm.com/\n\"\"\"\n\nimport os\nimport sys\nfrom pkgutil import walk_packages\nfrom tau import TAU_SCRIPT, TAU_HOME\nfrom tau import logger\nfrom tau.error import ConfigurationError, InternalError\n\n\nLOGGER = logger.get_logger(__name__)\n\nSCRIPT_COMMAND = os.path.basename(TAU_SCRIPT)\n\n_COMMANDS = {SCRIPT_COMMAND: {}}\n\n_COMMANDS_PACKAGE = __name__ + '.commands'\n\n\nclass UnknownCommandError(ConfigurationError):\n \"\"\"Indicates that a specified command is unknown.\"\"\"\n message_fmt = \"\"\"\n%(value)r is not a valid TAU command.\n\n%(hint)s\"\"\"\n def __init__(self, value, hint=\"Try 'tau --help'.\"):\n super(UnknownCommandError, self).__init__(value, hint)\n\n\nclass AmbiguousCommandError(ConfigurationError):\n \"\"\"Indicates that a specified partial command is ambiguous.\"\"\"\n message_fmt = \"\"\"\nCommand '%(value)s' is ambiguous: %(matches)s\n\n%(hint)s\"\"\"\n def __init__(self, value, matches, hint=\"Try 'tau --help'.\"):\n super(AmbiguousCommandError, self).__init__(value, hint)\n self.message_fields['matches'] = ', '.join(matches)\n\n\ndef get_command(module_name):\n \"\"\"Converts a module name to a command name string.\n \n Maps command module names to their command line equivilants, e.g.\n 'tau.cli.commands.target.create' => 'tau target create'\n \n Args:\n module_name (str): Name of a module.\n \n Returns:\n str: A string that identifies the command.\n \"\"\"\n return ' '.join(_command_as_list(module_name))\n\n\ndef _command_as_list(module_name):\n \"\"\"Converts a module name to a command name list.\n \n Maps command module names to their command line equivilants, e.g.\n 'tau.cli.commands.target.create' => ['tau', 'target', 'create']\n\n Args:\n module_name (str): Name of a module.\n\n Returns:\n list: Strings that identify the command.\n \"\"\"\n parts = module_name.split('.')\n for part in _COMMANDS_PACKAGE.split('.'):\n if parts[0] == part:\n parts = parts[1:]\n return [SCRIPT_COMMAND] + parts\n\n\ndef get_commands(root=_COMMANDS_PACKAGE):\n # pylint: disable=line-too-long\n \"\"\"Returns a dictionary mapping commands to Python modules.\n \n Given a root module name, return a dictionary that maps commands and their\n subcommands to Python modules. The special key ``__module__`` maps to the\n command module. Other strings map to subcommands of the command.\n \n Args:\n root (str): A string naming the module to search for cli.\n \n Returns:\n dict: Strings mapping to dictionaries or modules.\n \n Example:\n ::\n\n get_commands('tau.cli.commands.target') ==>\n {'__module__': ,\n 'create': {'__module__': },\n 'delete': {'__module__': },\n 'edit': {'__module__': },\n 'list': {'__module__': }}\n \"\"\"\n def lookup(cmd, dct):\n if not cmd:\n return dct\n elif len(cmd) == 1:\n return dct[cmd[0]]\n else:\n return lookup(cmd[1:], dct[cmd[0]])\n\n def walking_import(module, cmd, dct):\n car, cdr = cmd[0], cmd[1:]\n if cdr:\n walking_import(module, cdr, dct[car])\n elif not car in dct:\n dct[car] = {}\n __import__(module)\n dct[car]['__module__'] = sys.modules[module]\n\n command_module = sys.modules[_COMMANDS_PACKAGE]\n for _, module, _ in walk_packages(command_module.__path__, \n command_module.__name__ + '.'):\n try:\n lookup(_command_as_list(module), _COMMANDS)\n except KeyError:\n walking_import(module, _command_as_list(module), _COMMANDS)\n\n return lookup(_command_as_list(root), _COMMANDS)\n\n\ndef get_commands_description(root=_COMMANDS_PACKAGE):\n \"\"\"Builds listing of command names with short description.\n \n Args:\n root (str): A dot-seperated string naming the module to search for cli.\n \n Returns:\n str: Help string describing all commands found at or below `root`.\n \"\"\"\n groups = {}\n commands = sorted([i for i in get_commands(root).iteritems() if i[0] != '__module__'])\n for cmd, topcmd in commands:\n module = topcmd['__module__']\n descr = getattr(module, 'SHORT_DESCRIPTION', \"FIXME: No description\")\n group = getattr(module, 'GROUP', None)\n name = '{:<12}'.format(cmd)\n groups.setdefault(group, []).append(' %s %s' % (name, descr))\n\n parts = []\n for group, members in groups.iteritems():\n if group:\n parts.append(group + ' subcommands:')\n else:\n parts.append('subcommands:')\n parts.extend(members)\n parts.append('')\n return '\\n'.join(parts)\n\n\ndef execute_command(cmd, cmd_args=None, parent_module=None):\n \"\"\"Import the command module and run its main routine.\n \n Args:\n cmd (list): List of strings identifying the command, i.e. from :any:`_command_as_list`.\n cmd_args (list): Command line arguments to be parsed by command.\n parent_module (str): Dot-seperated name of the command's parent.\n \n Raises:\n UnknownCommandError: `cmd` is invalid.\n AmbiguousCommandError: `cmd` is ambiguous.\n \n Returns:\n int: Command return code.\n \"\"\"\n # pylint: disable=invalid-name\n def _resolve(c, d):\n if not c:\n return []\n car, cdr = c[0], c[1:]\n try:\n matches = [(car, d[car])]\n except KeyError:\n matches = [i for i in d.iteritems() if i[0].startswith(car)]\n if len(matches) == 1:\n return [matches[0][0]] + _resolve(cdr, matches[0][1])\n elif len(matches) == 0:\n raise UnknownCommandError(' '.join(cmd))\n elif len(matches) > 1:\n raise AmbiguousCommandError(' '.join(cmd), [m[0] for m in matches])\n\n if parent_module:\n parent = _command_as_list(parent_module)[1:]\n cmd = parent + cmd\n\n while len(cmd):\n root = '.'.join([_COMMANDS_PACKAGE] + cmd)\n try:\n main = get_commands(root)['__module__'].main\n except KeyError:\n LOGGER.debug('%r not recognized as a TAU command', cmd)\n try:\n resolved = _resolve(cmd, _COMMANDS[SCRIPT_COMMAND])\n except UnknownCommandError:\n if len(cmd) <= 1:\n raise # We finally give up\n if not parent_module:\n parent = cmd[:-1]\n LOGGER.debug('Getting help from parent command %r', parent)\n return execute_command(parent, ['--help'])\n else:\n LOGGER.debug('Resolved ambiguous command %r to %r', cmd, resolved)\n return execute_command(resolved, cmd_args)\n except AttributeError:\n raise InternalError(\"'main(argv)' undefined in command %r\", cmd)\n else:\n if not cmd_args:\n cmd_args = []\n return main(cmd_args)\n","sub_path":"packages/tau/cli/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"534297993","text":"\r\nimport math\r\nimport random\r\nimport numpy as np\r\nimport io\r\nfrom io import StringIO\r\nimport numpy as np\r\nfrom io import StringIO\r\n\r\ninput_string = '''\r\n25 2 50 1 500 127900\r\n39 3 10 1 1000 222100\r\n13 2 13 1 1000 143750\r\n82 5 20 2 120 268000\r\n130 6 10 2 600 460700\r\n115 6 10 1 550 407000\r\n'''\r\n\r\nnp.set_printoptions(precision=1) # this just changes the output settings for easier reading\r\n \r\ndef fit_model(input_file):\r\n x = np.genfromtxt(input_file, skip_header=1)\r\n # read the data in and fit it. the values below are placeholder values\r\n c = np.linalg.lstsq(x[:,:-1] , x[:,-1])[0] # coefficients of the linear regression\r\n x = x[:,:-1] # input data to the linear regression\r\n print(c)\r\n print(x @ c)\r\n\r\n# simulate reading a file\r\ninput_file = StringIO(input_string)\r\nfit_model(input_file)\r\n\r\n ","sub_path":"Scripts/C3E13_Linear_Regression.py","file_name":"C3E13_Linear_Regression.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"52869002","text":"from io import TextIOWrapper\nimport sqlite3\nimport json\n\n\nqtys = {\n 1: \"$1\",\n 2: \"$2\",\n 3: \"$3\",\n 4: \"$4\",\n 5: \"$5\",\n 6: \"$7\",\n 7: \"$7\",\n 8: \"$8\",\n 9: \"$9\",\n 10: \"$9\",\n 11: \"$$$1\",\n 12: \"$12\",\n 13: \"$$$2\",\n 14: \"$$$3\",\n 15: \"$$$1\",\n 16: \"$$$2\",\n 17: \"$$$3\",\n 18: \"$18\",\n 19: \"$19\",\n 20: \"$4\"\n}\n\nfor i in range(21, 29):\n qtys.update({i: f\"${i}\"})\n\n\nfilter_type = {\n 1: \"$7\",\n 2: \"$2\",\n 3: \"$7\",\n 4: \"$18\",\n 5: \"$7\" # only this type exist in current db\n}\n\n\ndef generate_installed_equipment(db: str, file: TextIOWrapper):\n conn = sqlite3.connect(db)\n rows = conn.execute(\"\"\"select site_id, sensor_type, sensor_type_name, sensor_id, bus_channel, baud_rate from sensor s\n join sensor_type_desc std on std.sensor_type_id = s.sensor_type\n order by site_id\"\"\").fetchall()\n used_up_stations = []\n for row in rows:\n # only once for every distinct site\n if row[0] not in used_up_stations and row[0] != -1:\n used_up_stations.append(row[0])\n file.write(f\"CNF SEQ-${row[0]} {json.dumps(generate_data(row, rows, db, file))}\" + \"\\n\")\n\n\ndef generate_data(input_row, rows, db, file: TextIOWrapper):\n '''\n installed eqt communicator data, instruments data, postprocessing is called from here\n logger id to site mapping is also done here\n '''\n site_id = input_row[0]\n instruments = []\n for row in rows:\n # search for rows that match this site\n if row[0] == site_id:\n conn = sqlite3.connect(db)\n msr_types = conn.execute(f\"\"\"select distinct measurement_type_id from sensor_data where sensor_id={row[3]}\"\"\").fetchall()\n msr =[]\n for msr_type in msr_types:\n if msr_type[0] != -1:\n data = {\n \"qty_id\": f\"{qtys[msr_type[0]]}\",\n \"msr_id\": f\"${row[3]}${msr_type[0]}\" # $sensor_id$msr_type\n }\n msr.append(data)\n communicator_ports = {\n 2: \"#modbus-1\", 3: \"#modbus-2\", 5: \"#sdi12-1\", 4:\"#4-20ma-1\", 100: \"#rs232-1\"\n }\n bus_channel = row[4]\n if row[1] != 6: # if it is not a camera\n instruments.append({\n \"type_id\": f\"${row[1]}\",\n \"name\": row[2],\n \"active\": True,\n \"connection\": {\n \"communicator_port\": communicator_ports[bus_channel],\n \"settings\": {\n \"#baud-rate\": \"#\" + str(row[5])\n }\n },\n \"settings\": {},\n \"measurements\": msr\n })\n else: # if it is a camera add blobs field\n instruments.append({\n \"type_id\": f\"${row[1]}\",\n \"name\": row[2],\n \"active\": True,\n \"connection\": {\n \"communicator_port\": communicator_ports[bus_channel],\n \"settings\": {\n \"#baud-rate\": \"#\" + str(row[5])\n }\n },\n \"settings\": {},\n \"measurements\": msr,\n \"blobs\": [\n {\n \"blob_type_id\": \"$1\",\n \"msr_id\": f\"${row[3]}\"\n }\n ]\n })\n comm_msr = []\n for i in range(1, 7):\n comm_msr.append({\n \"qty_id\": f\"$${i}\",\n \"msr_id\": f\"${site_id}$${i}\"\n })\n settings = conn.execute(f\"select logger_id, low_voltage, scan_duration_sec from site where site_id={site_id}\").fetchone()\n logger_id = settings[0]\n lowest_voltage = settings[1]\n warmup_time = settings[2]\n data = {\n \"communicator\": {\n \"type_id\": \"$$1\",\n \"settings\": {\n \"warmup_time\": str(warmup_time),\n \"lowest_voltage\": str(lowest_voltage),\n \"#logger_id\": logger_id\n },\n \"measurements\": comm_msr,\n \"endpoint\": \"\"\n },\n \"instruments\": instruments,\n \"postprocessing\": generate_postprocessing(site_id, db)\n }\n\n # make logger_id to site mapping\n file.write(f\"CNF LOG-{logger_id} ${site_id}\\n\")\n return data\n\n\ndef generate_postprocessing(site_id, db):\n '''\n postprocessing for virtual instruments - filter functions are also called from here\n '''\n conn = sqlite3.connect(db)\n rows = conn.execute(f\"\"\"select instrument_id, json from virtual_instrument where site_id={site_id}\"\"\").fetchall()\n virtual_instruments = []\n for row in rows:\n settings_data = json.loads(row[1])\n msr_level = None\n msr_velocity = None\n level_offset = None\n k_coeff = []\n calibration_points = []\n geometry = []\n v_notch = {}\n if 'level_sensor' in settings_data:\n msr_level = f\"${settings_data['level_sensor']}$7\" # $7 is Average Water Level\n if 'velocity_sensor' in settings_data:\n msr_velocity = f\"${settings_data['velocity_sensor']}$2\" # $2 is Average Surface Velocity\n if 'level_offset' in settings_data:\n level_offset = settings_data[\"level_offset\"]\n if 'k_coeffs' in settings_data:\n k_coeff = settings_data[\"k_coeffs\"]\n if 'calibration' in settings_data:\n calibration_points = settings_data[\"calibration\"]\n if 'geometry' in settings_data:\n geometry = settings_data[\"geometry\"]\n if 'v-notch' in settings_data:\n v_notch = settings_data[\"v-notch\"]\n instrument = {\n \"qty_id\": \"$5\",\n \"msr_id\": f\"${row[0]}\",\n \"pipeline\": [\n {\n \"script_id\": \"#index-velocity-discharge\",\n \"settings\": {\n \"msr_level\": msr_level,\n \"msr_velocity\": msr_velocity, \n \"level_offset\": level_offset,\n \"k_coeffs\": k_coeff,\n \"calibration_points\": calibration_points,\n \"geometry\": geometry,\n \"v_notch\": v_notch\n }\n }\n ]\n }\n virtual_instruments.append(instrument)\n postprocessing = generate_filters(site_id, db, virtual_instruments)\n return postprocessing\n\n\ndef generate_filters(site_id, db, virtual_instruments: list):\n '''\n searches for sensors that have filters on them\n '''\n conn = sqlite3.connect(db)\n sensors_with_filter = conn.execute(f\"\"\"select filter_id, filter_type_id, f.sensor_id, params_json from sensor s\n join filter f on s.sensor_id=f.sensor_id\n where s.site_id={site_id}\"\"\").fetchall()\n used_up_sensors = []\n for row in sensors_with_filter:\n qty = filter_type[row[1]] # get what qty this sensor is measuring\n sensor_id = row[2]\n if (sensor_id, qty) not in used_up_sensors: # (sensor_id, measured qty) should only be written once per filter\n used_up_sensors.append((sensor_id,qty))\n filter = {\n \"qty_id\": f\"{qty}\",\n \"msr_id\": f\"$0{sensor_id}{qty}\",\n \"pipeline\": pipeline_for_sensors(qty, row, sensors_with_filter)\n }\n virtual_instruments.append(filter)\n return virtual_instruments\n\n\ndef pipeline_for_sensors(qty, row, sensors_with_filter):\n '''\n generates an array with filters (pipeline) for this specific sensor\n '''\n filters = []\n sensor_id = row[2]\n for sensor in sensors_with_filter:\n if sensor[2] == sensor_id and qty == filter_type[sensor[1]]:\n options = json.loads(sensor[3])\n if options[0][\"name\"] == \"compare_operator\":\n compare_operators = {\n \"less than\": \"#less-than\",\n \"greater than\": \"#greater-than\"\n }\n filter = {\n \"script_id\": \"#range-filter\",\n \"settings\": {\n \"msr_input\": \"place holder\",\n \"limit\": options[1][\"value\"],\n \"compare_operator\": compare_operators[options[0][\"value\"]]\n }\n }\n\n elif options[0][\"name\"] == \"change\":\n filter = {\n \"script_id\": \"#max-change-filter\",\n \"settings\": {\n \"msr_input\": \"place holder\",\n \"limit\": options[0][\"value\"],\n }\n }\n else:\n filter = {\n \"script_id\": \"#snr-filter\",\n \"settings\": {\n \"msr_input\": \"place holder\",\n \"msr_snr_input\": f\"${sensor_id}$9\",\n \"limit\": options[0][\"value\"],\n \"snr_soft_limit\": options[1][\"value\"]\n }\n }\n filters.append(filter)\n # so snr-filter comes last in the array, and only the first element in the array\n # has a specific \"msr_input\", others have it set to \"#last-result\"\n filters = sorted(filters, key=lambda x: x[\"script_id\"])\n first_iteration_flag = True\n for filter in filters:\n if first_iteration_flag:\n msr_input = f\"${sensor_id}{qty}\"\n first_iteration_flag = False\n else:\n msr_input = \"#last-result\"\n filter[\"settings\"][\"msr_input\"] = msr_input\n return filters \n\n\nif __name__ == '__main__':\n with open(\"temp/temp.txt\", 'w') as file:\n generate_installed_equipment(\"database/old_database_geolux.db\", file)\n","sub_path":"Migration/installed_equipment_import.py","file_name":"installed_equipment_import.py","file_ext":"py","file_size_in_byte":9963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"468253920","text":"\nclass HelpersNoMagic(object):\n \"\"\"\n Access helper.functions as attributes, but raise AttributeError\n for missing functions instead of returning null_function\n\n adapted from ckan/config/environment.py:_HelpersNoMagic\n \"\"\"\n def __getattr__(self, name):\n import pylons\n h = pylons.config['pylons.h']\n\n fn = getattr(h, name)\n if fn == h.null_function:\n raise AttributeError(\"No helper found named '%s'\" % name)\n return fn\n","sub_path":"ckantoolkit/shims.py","file_name":"shims.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"278285711","text":"from utils import build_dataset,save_pickle\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--dataset', dest='dataset', default='Clipart', help='dataset name')\n\nargs = parser.parse_args()\n\ndef main():\n if args.dataset == 'Clipart':\n build_dataset(\"expdata/Clipart\",\"prosessed_data/Clipart\",args.dataset,weight=64,hight=64)\n\n elif args.dataset == 'RealWorld':\n build_dataset(\"expdata/RealWorld\", \"prosessed_data/RealWorld\",args.dataset, weight=64, hight=64)\n\n elif args.dataset == 'mnist':\n mnist = input_data.read_data_sets(train_dir='mnist')\n\n train = {'X': mnist.train.images.reshape(-1, 28, 28),\n 'y': mnist.train.labels}\n\n test = {'X': mnist.test.images.reshape(-1, 28, 28),\n 'y': mnist.test.labels}\n\n save_path='prosessed_data/mnist'\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n save_pickle(train, save_path+'/train.pkl')\n save_pickle(test, save_path+'/test.pkl')\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"build_dataset.py","file_name":"build_dataset.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"485569464","text":"import matplotlib.pyplot as plt\nfrom scipy.stats import multivariate_normal\nimport numpy as np\nimport support_code\n\n\ndef likelihood_func(w, X, y, likelihood_var):\n '''\n Implement likelihood_func. This function returns the data likelihood\n given f(y | X; w) ~ Normal(y; Xw, likelihood_var).\n\n Args:\n w: Weights\n X: Training design matrix with first col all ones\n y: Training response vector\n likelihood_var: likelihood variance\n\n Returns:\n likelihood: Data likelihood (float)\n '''\n\n likelihood = multivariate_normal.pdf(y.flatten(), (X@w).flatten(), likelihood_var)\n return likelihood\n\n\ndef get_posterior_params(X, y, prior: dict, likelihood_var=0.2 ** 2):\n \"\"\"\n Implement get_posterior_params. This function returns the posterior\n mean vector \\mu_p and posterior covariance matrix \\Sigma_p for\n Bayesian regression (normal likelihood and prior).\n\n Note support_code.make_plots takes this completed function as an argument.\n\n Args:\n X: Training design matrix with first col all ones\n y: Training response vector\n prior: Prior parameters; dict with 'mean' (prior mean)\n and 'var' (prior covariance)\n likelihood_var: likelihood variance- default (0.2**2) per the lecture slides\n\n Returns:\n post_mean: Posterior mean\n post_var: Posterior var\n \"\"\"\n\n prior_mean, prior_precision = prior['mean'], np.linalg.inv(prior['var'])\n trans_product = X.T @ X\n post_mean = np.linalg.inv(trans_product + likelihood_var * prior_precision) @ X.T @ y\n post_var = np.linalg.inv(trans_product/likelihood_var + prior_precision)\n return post_mean, post_var\n\n\ndef get_predictive_params(x_new, post_mean, post_var, likelihood_var=0.2 ** 2):\n \"\"\"\n Implement get_predictive_params. This function returns the predictive\n distribution parameters (mean and variance) given the posterior mean\n and covariance matrix (returned from get_posterior_params) and the\n likelihood variance (default value from lecture).\n\n Args:\n x_new: New observation\n post_mean, post_var: Returned from get_posterior_params\n likelihood_var: likelihood variance (0.2**2) per the lecture slides\n\n Returns:\n - pred_mean: Mean of predictive distribution\n - pred_var: Variance of predictive distribution\n \"\"\"\n\n pred_mean = np.dot(post_mean.T, x_new)\n pred_var = x_new.T @ post_var @ x_new + likelihood_var\n return pred_mean, pred_var\n\n\nif __name__ == '__main__':\n\n '''\n If your implementations are correct, running\n python problem.py\n inside the Bayesian Regression directory will, for each sigma in sigmas_to-test generates plots\n '''\n\n np.random.seed(46134)\n actual_weights = np.asarray([0.3, 0.5])\n data_size = 40\n noise = {\"mean\": 0, \"var\": 0.2 ** 2}\n likelihood_var = noise[\"var\"]\n x_train, y_train = support_code.generate_data(data_size, noise, actual_weights)\n\n # Question (b)\n sigmas_to_test = [1/2, 1/(2**5), 1/(2**10)]\n for sigma_squared in sigmas_to_test:\n prior = {\"mean\": np.asarray([0, 0]),\n \"var\": np.identity(2) * sigma_squared}\n\n support_code.make_plots(actual_weights,\n x_train,\n y_train,\n likelihood_var,\n prior,\n likelihood_func,\n get_posterior_params,\n get_predictive_params)\n","sub_path":"hw5/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"540396430","text":"from __future__ import print_function\nimport tempfile\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.functions import col\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import StringType,BooleanType,DateType\nfrom pyspark.sql.types import DateType\nfrom pyspark.sql.types import StructType,StructField, StringType, IntegerType\n\nprint(\"Start the Spark Job \")\nspark = SparkSession.builder.appName('spark_job_logs_data_IAC_POC').enableHiveSupport().getOrCreate()\n\nINPUT_PATH='gs://iwinner-data/data/input/'\nOUTPUT_PATH='gs://iwinner-data/data/output'\n\nschema = StructType([ \\\n StructField(\"Country\",StringType(),True), \\\n StructField(\"Age\",IntegerType(),True), \\\n StructField(\"Salary\",IntegerType(),True), \\\n StructField(\"Purchased\", StringType(), True), \\\n StructField(\"ts\", StringType(), True) ])\n\nprint(\"Schema Info: \"+schema)\n\nprint(\"Input File Path :\"+INPUT_PATH)\n\ninput_df = spark.read.format(\"csv\") \\\n .option(\"header\", True) \\\n .schema(schema) \\\n .load(INPUT_PATH)\nprint(\"OUTPUT_PATH: \"+OUTPUT_PATH)\n\nprint(\"Display the input data frame schema \")\ninput_df.printSchema()\n\nprint(\"Display the input data 20 records\")\ninput_df.show(10,False)\n\n\nprint(\"Write dataframe to parquet files\")\ninput_df.write.format(\"parquet\").mode('overwrite').save(OUTPUT_PATH)\n\nprint(\"END the Spark Job\")\n","sub_path":"dataproc/spark_job.py","file_name":"spark_job.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"15739809","text":"\"\"\"\nСистемные модели демона парсера\n\"\"\"\n\nfrom django.db import models\n\nMODELS_CHOICES = (\n ('TAG', 'Теги'),\n ('RELEASE', 'Релиз'),\n ('ARTIST', 'Исполнитель'),\n ('TRACK', 'Композиция')\n)\nACT_CHOICES = (\n ('NEW', 'Поиск новых'),\n ('EDITING', 'Осмотр существующих'),\n ('FIND', 'Найдено')\n)\n\nclass SysActions(models.Model):\n \"\"\"\n Логирование действий \n \"\"\"\n model = models.CharField(\n max_length = 128,\n choices = MODELS_CHOICES,\n verbose_name = 'Модель')\n act = models.CharField(\n max_length = 128,\n choices = ACT_CHOICES,\n verbose_name = 'Действие')\n value = models.CharField(\n max_length = 128,\n blank = True,\n verbose_name = 'Значение')\n date = models.DateTimeField(\n auto_now_add = True,\n verbose_name = 'Время действия')\n\n def __str__(self):\n return \"%s - %s\" % (self.model, self.act)\n \n class Meta:\n verbose_name = 'Действие'\n verbose_name_plural = 'Действия'\n\nclass SysQueue(models.Model):\n \"\"\"\n Очередь выполняемых действий\n \"\"\"\n id = models.AutoField(primary_key = True)\n model = models.CharField(\n max_length = 128,\n choices = MODELS_CHOICES,\n verbose_name = 'Модель')\n act = models.CharField(\n max_length = 128,\n choices = ACT_CHOICES,\n verbose_name = 'Действие')\n value = models.CharField(\n max_length = 128,\n default = '{}',\n verbose_name = 'Значение (Опционально)')\n scheduled = models.DateTimeField(\n null = True,\n verbose_name = 'Назначено на')\n created = models.DateTimeField(\n auto_now_add = True,\n verbose_name = 'Создано')\n \n class Meta:\n verbose_name = 'Участник очереди'\n verbose_name_plural = 'Участники очереди'","sub_path":"api/system_models.py","file_name":"system_models.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"558571374","text":"# keep these three import statements\r\nimport game_API\r\nimport fileinput\r\nimport json\r\n\r\n# your import statements here\r\nimport random\r\n\r\nfirst_line = True # DO NOT REMOVE\r\n\r\n# global variables or other functions can go here\r\nstances = [\"Rock\", \"Paper\", \"Scissors\"]\r\n\r\nenemyStance = \"\"\r\ncounter = 0\r\n\r\n# Check if monster will be arrive by the time we arrive\r\ndef shouldAttack(monster, shift):\r\n if not monster.dead:\r\n return True\r\n turnsToRespawn = monster.respawn_counter - shift\r\n totalTurnsToMove = get_distance(me.location, monster.location, me.speed)\r\n return totalTurnsToMove >= turnsToRespawn\r\n\r\n# Find the attack stat which is lowest\r\ndef get_lowest_attack():\r\n me = game.get_self()\r\n lowest_attack = \"rock\"\r\n lowest_damage = me.rock;\r\n if (me.paper < lowest_damage):\r\n lowest_damage = me.paper\r\n lowest_attack = \"paper\"\r\n if (me.scissors < lowest_damage):\r\n lowest_damage = me.scissors\r\n lowest_attack = \"scissors\"\r\n if (me.speed < 2):\r\n lowest_attack = \"speed\"\r\n return lowest_attack\r\n\r\n# Find the monster who would increase lowest attack stat\r\ndef get_monster_node_for_attack_balance():\r\n lowest_attack = get_lowest_attack()\r\n node = 0\r\n highest = -1000\r\n max_distance = 0\r\n if me.health < 60:\r\n max_distance = 1;\r\n elif me.health < 100:\r\n max_distance = 2\r\n else:\r\n max_distance = 3\r\n for monster in game.get_all_monsters():\r\n paths = game.shortest_paths(me.location, monster.location)\r\n if (len(paths[0]) <= max_distance):\r\n if (lowest_attack == \"rock\"):\r\n if (monster.death_effects.rock > highest and shouldAttack(monster, 0)):\r\n highest = monster.death_effects.rock\r\n node = monster.location\r\n elif (lowest_attack == \"paper\" and shouldAttack(monster, 0)):\r\n if (monster.death_effects.paper > highest):\r\n highest = monster.death_effects.paper\r\n node = monster.location\r\n elif (lowest_attack == \"scissors\" and shouldAttack(monster, 0)):\r\n if (monster.death_effects.scissors > highest and shouldAttack(monster, 0)):\r\n highest = monster.death_effects.scissors\r\n node = monster.location\r\n else:\r\n node = 3\r\n return node\r\n\r\n# Find the path that would increase the lowest attack stat\r\ndef get_best_path_for_attack_balance():\r\n highest_total = -1000\r\n best_path = []\r\n for path in game.shortest_paths(game.get_self().location, get_monster_node_for_attack_balance()):\r\n total = 0\r\n for node in path:\r\n lowest_attack = get_lowest_attack()\r\n if (not game.has_monster(node)):\r\n continue\r\n weight = 0\r\n if (shouldAttack(game.get_monster(node), 0)):\r\n weight = 1\r\n if (lowest_attack == \"rock\" and game.get_monster(node).attack < 4):\r\n total += weight*game.get_monster(node).death_effects.rock-(game.get_monster(node).attack)**4\r\n elif (lowest_attack == \"paper\" and game.get_monster(node).attack < 4):\r\n total += weight*game.get_monster(node).death_effects.paper-(game.get_monster(node).attack)**4\r\n else:\r\n if (game.get_monster(node).attack < 4):\r\n total += weight*game.get_monster(node).death_effects.scissors-(game.get_monster(node).attack)**4\r\n if total > highest_total:\r\n highest_total = total\r\n best_path = path\r\n return best_path\r\n\r\n# Return stance that would win\r\ndef get_winning_stance(stance):\r\n if stance == \"Rock\":\r\n return \"Paper\"\r\n elif stance == \"Paper\":\r\n return \"Scissors\"\r\n elif stance == \"Scissors\":\r\n return \"Rock\"\r\n\r\n# Find number of turns to travel between 2 nodes\r\ndef get_distance(start, end, speed):\r\n path = game.shortest_paths(start, end)\r\n return len(path[0])*(7-speed)\r\n\r\n# main player script logic\r\n# DO NOT CHANGE BELOW ----------------------------\r\nfor line in fileinput.input():\r\n if first_line:\r\n game = game_API.Game(json.loads(line))\r\n first_line = False\r\n continue\r\n game.update(json.loads(line))\r\n# DO NOT CHANGE ABOVE ---------------------------\r\n\r\n # code in this block will be executed each turn of the game\r\n\r\n me = game.get_self()\r\n enemy = game.get_opponent()\r\n game.log(str(me.location))\r\n enemy_distance = min(get_distance(me.location, enemy.location, me.speed), get_distance(me.location, enemy.location, enemy.speed))\r\n \r\n current_stance = me.stance\r\n current_stance = current_stance.lower()\r\n attack_current = 0\r\n if (current_stance == \"rock\"):\r\n attack_current = me.rock\r\n elif current_stance == \"paper\":\r\n attack_current = me.paper\r\n else:\r\n attack_current = me.scissors\r\n\r\n # If health is less than 20\r\n if me.health<=20:\r\n # If my location is node 0\r\n if me.location == 0: \r\n # If monster alive and health/attack < move time \r\n if (not game.get_monster(0).dead and (game.get_monster(me.location).health/attack_current) < 7-me.speed):\r\n paths = get_best_path_for_attack_balance()\r\n destination_node = paths[0]\r\n # If monster dead\r\n else:\r\n destination_node = me.location\r\n # If I need to go to 0\r\n else:\r\n path = game.shortest_paths(me.location, 0)\r\n destination_node = path[0][0]\r\n\r\n # If health monster is alive go to 0\r\n if shouldAttack(game.get_monster(0), 10):\r\n path = game.shortest_paths(me.location, 0)\r\n destination_node = path[0][0]\r\n\r\n # Check if we have moved this turn\r\n elif me.location == me.destination:\r\n if game.has_monster(me.location):\r\n if game.get_monster(me.location).dead:\r\n # Get the path to the monster that will best balance our attack\r\n paths = get_best_path_for_attack_balance()\r\n destination_node = paths[0]\r\n else:\r\n if ((game.get_monster(me.location).health/attack_current) < 7-me.speed):\r\n paths = get_best_path_for_attack_balance()\r\n destination_node = paths[0]\r\n else:\r\n destination_node = me.location\r\n else:\r\n paths = get_best_path_for_attack_balance()\r\n destination_node = paths[0]\r\n\r\n else:\r\n destination_node = me.destination\r\n\r\n if (destination_node == 11):\r\n destination_node = 16\r\n\r\n if (destination_node == 15 or destination_node == 17):\r\n destination_node = 10\r\n \r\n monster_not_on_location = True\r\n # Logic for choosing stance\r\n \r\n # If in the same location as enemy, randomly choose stance\r\n if enemy.location == me.location:\r\n chosen_stance = stances[random.randint(0,2)]\r\n\r\n if game.has_monster(me.location) and not game.get_monster(me.location).dead:\r\n chosen_stance = get_winning_stance(get_winning_stance(game.get_monster(me.location).stance))\r\n\r\n if enemyStance == enemy.stance:\r\n counter += 1\r\n if counter >= 8:\r\n chosen_stance = get_winning_stance(enemy.stance)\r\n\r\n else:\r\n enemyStance = enemy.stance\r\n counter = 0\r\n\r\n # If in the same location of a monster who is not dead\r\n elif game.has_monster(me.location) and not game.get_monster(me.location).dead:\r\n chosen_stance = get_winning_stance(game.get_monster(me.location).stance)\r\n monster_not_on_location= False\r\n\r\n # If no monster or person then set next node\r\n if game.has_monster(destination_node) and monster_not_on_location and (enemy.location != me.location):\r\n chosen_stance = get_winning_stance(game.get_monster(destination_node).stance)\r\n\r\n # submit your decision for the turn \r\n game.submit_decision(destination_node, chosen_stance)\r\n","sub_path":"MyBot.py","file_name":"MyBot.py","file_ext":"py","file_size_in_byte":8036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"201977270","text":"from sqlalchemy.dialects.postgresql import JSONB\nfrom serious_game import db\nfrom flask import json\n\n\nclass User(db.Model):\n __tablename__ = 'user'\n\n id = db.Column(db.Integer, primary_key=True)\n vorname = db.Column(db.String(32), nullable=False)\n nachname = db.Column(db.String(32), nullable=False)\n geb = db.Column(db.Date, nullable=False)\n username = db.Column(db.String, nullable=False, unique=True)\n highscore = db.Column(db.Integer, default=0)\n savegame = db.Column(JSONB())\n\n def __init__(self, vorname, nachname, geb):\n self.vorname = vorname\n self.nachname = nachname\n self.geb = geb\n self.username = vorname + nachname + unicode(geb.date())\n self.highscore = 0\n\n def __repr__(self):\n return unicode(self.vorname + \" \" + self.nachname)\n\n @classmethod\n def get_user(cls, userid):\n new_user = db.session.query(User).get(userid)\n return new_user\n\n def make_json_data(self):\n data = {\n 'vorname': self.vorname,\n 'nachname': self.nachname,\n 'geburtstag': self.geb,\n 'userid': self.id,\n 'username': self.username,\n 'highscore': self.highscore,\n }\n if hasattr(self, \"score\"):\n data['score'] = self.score\n return json.jsonify(data)\n\n def update_user(self):\n # try - except block here?!\n db.session.add(self)\n db.session.commit()\n\n def update_highscore(self, score):\n if score > self.highscore:\n self.highscore = score\n\n def save_game(self, savegame):\n self.savegame = savegame\n\n def load_game(self):\n if self.savegame:\n return self.savegame\n","sub_path":"core/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"235989078","text":"import time\nfrom pandas import DataFrame\nfrom numpy import array as arr\nfrom random import randint\nfrom matplotlib.pyplot import *\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport mpl_toolkits.axes_grid1 as axesTool\nimport mpl_toolkits.axes_grid1\nfrom scipy.optimize import curve_fit as fit\nfrom matplotlib.patches import Ellipse\nimport IPython\nimport IPython.display as disp\n\nfrom . import MainAnalysis as ma\nfrom . import TransferAnalysis\nfrom . import Miscellaneous as misc\n\nfrom .MainAnalysis import analyzeNiawgWave, standardAssemblyAnalysis, AnalyzeRearrangeMoves\nfrom .LoadingFunctions import loadDataRay, loadCompoundBasler, loadDetailedKey\nfrom .AnalysisHelpers import (processSingleImage, orderData,\n normalizeData, getBinData, fitDoubleGaussian,\n guessGaussianPeaks, calculateAtomThreshold, getAvgPic,\n getEnsembleStatistics, processImageData,\n fitPictures, fitGaussianBeamWaist, integrateData, \n computeMotNumber, getFitsDataFrame, genAvgDiscrepancyImage, getGridDims)\n\nfrom . import TransferAnalysisOptions as tao\nfrom . import ThresholdOptions as to\nfrom . import AnalysisHelpers as ah\nfrom . import MarksConstants as mc \nfrom . import PopulationAnalysis as pa \nfrom .TimeTracker import TimeTracker\nfrom .fitters import LargeBeamMotExpansion, exponential_saturation\nfrom .fitters.Gaussian import gaussian_2d, double as double_gaussian, bump\nfrom . import ExpFile as exp\n\ndef addAxColorbar(fig, ax, im):\n cax = mpl_toolkits.axes_grid1.make_axes_locatable(ax).append_axes('right', size='5%', pad=0.05)\n return fig.colorbar(im, cax=cax, orientation='vertical'), cax\n\ndef makeAvgPlts(avgPlt1, avgPlt2, avgPics, analysisOpts, colors): \n print(\"Making Avg Plots...\")\n # Average Images\n for plt, dat, locs in zip([avgPlt1, avgPlt2], avgPics, [analysisOpts.initLocs(), analysisOpts.tferLocs()]):\n plt.imshow(dat, origin='lower', cmap='Greys_r');\n # first, create the total list\n markerTotalList = []\n for psc_s, prc, color in zip(analysisOpts.postSelectionConditions, analysisOpts.positiveResultConditions, colors ): \n for psc in psc_s:\n assert(len(psc.markerWhichPicList) == len(psc.markerLocList))\n for markernum, pic in enumerate(psc.markerWhichPicList):\n markerTotalList.append((pic, psc.markerLocList[markernum]))\n if prc is not None:\n for markernum, pic in enumerate(prc.markerWhichPicList):\n markerTotalList.append((pic, prc.markerLocList[markernum]))\n markerRunningList = []\n markerLocModList = ((0.25,0.25),(0.25,-0.25),(-0.25,-0.25),(-0.25,0.25))\n for psc_s, prc, color in zip(analysisOpts.postSelectionConditions, analysisOpts.positiveResultConditions, colors ): \n for psc in psc_s:\n for markernum, pic in enumerate(psc.markerWhichPicList):\n markerRunningList.append((pic, psc.markerLocList[markernum]))\n loc = locs[psc.markerLocList[markernum]]\n if markerTotalList.count((pic, psc.markerLocList[markernum])) == 1: \n circ = Circle((loc[1], loc[0]), 0.2, color=color)\n else: \n circNum = markerTotalList.count((pic, psc.markerLocList[markernum])) \\\n - markerRunningList.count((pic, psc.markerLocList[markernum]))\n print('circNum', circNum)\n circ = Circle((loc[1]+markerLocModList[circNum%4][0], loc[0]+markerLocModList[circNum%4][1]), 0.2, color=color)\n [avgPlt1,avgPlt2][pic].add_artist(circ)\n if prc is not None:\n for markernum, pic in enumerate(prc.markerWhichPicList):\n markerRunningList.append((pic, prc.markerLocList[markernum]))\n loc = locs[prc.markerLocList[markernum]]\n circ = Circle((loc[1], loc[0]), 0.2, color=color)\n [avgPlt1,avgPlt2][pic].add_artist(circ)\n if avgPics[0].shape[0]/avgPics[0].shape[1] < 0.3:\n avgPlt1.set_position([0.7,0.15,0.22,0.12])\n avgPlt2.set_position([0.7,0,0.22,0.12])\n else:\n avgPlt1.set_position([0.68,0,0.14,0.3])\n avgPlt2.set_position([0.83,0,0.14,0.3])\n avgPlt1.set_title('Avg Pic #1')\n avgPlt2.set_title('Avg Pic #2')\n\n \ndef fancyImshow( fig, ax, image, avgSize='20%', pad_=0, cb=True, imageArgs={}, hAvgArgs={'color':'orange'}, vAvgArgs={'color':'orange'}, \n ticklabels=True,do_vavg=True, do_havg=True, hFitParams=None, vFitParams=None, \n subplotsAdjustArgs=dict(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0), \n fitModule=bump, flipVAx = False, fitParams2D=None):\n \"\"\"\n Expand a normal image plot of the image input, giving it a colorbar, a horizontal-averaged step plot to the left\n and a vertically-averaged step plot below.\n @param fig:\n @param ax:\n @param image:\n @param avgSize: size of the averaged step plots\n @param pad_: recommended values: 0 or 0.3 to see the ticks on the image as well as the step plots.\n \"\"\"\n fig.subplots_adjust(**subplotsAdjustArgs)\n im = ax.imshow(image, **imageArgs)\n ax.grid(False)\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n #ax.axis('off')\n divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax)\n cax = hax = vax = None\n hAvg, vAvg = ah.collapseImage(image)\n if cb:\n cax = divider.append_axes('right', size='5%', pad=0)\n fig, colorbar(im, cax, orientation='vertical')\n if do_vavg:\n vAvg = [vAvg[0]] + list(vAvg)\n vax = divider.append_axes('bottom', size=avgSize, pad=pad_)\n vline = vax.step(np.arange(len(vAvg)), vAvg, **vAvgArgs)\n vax.set_yticks([])\n if not ticklabels:\n vax.set_xticks([])\n if vFitParams is not None:\n fxpts = np.linspace(0, len(vAvg), 1000)\n fypts = fitModule.f(fxpts, *vFitParams)\n vax.plot(fxpts+0.5,fypts)\n vax.set_xlim(0,len(vAvg)-1)\n if do_havg:\n # subtle difference here from the vAvg case\n hAvg = list(hAvg) + [hAvg[-1]]\n hax = divider.append_axes('left', size=avgSize, pad=pad_)\n hline = hax.step(hAvg, np.arange(len(hAvg)),**hAvgArgs)\n hax.set_ylim(0,len(hAvg)-1)\n hax.set_xticks([])\n if not ticklabels:\n hax.set_yticks([])\n if hFitParams is not None:\n fxpts = np.linspace(0, len(hAvg), 1000)\n fypts = fitModule.f(fxpts, *hFitParams)\n hax.plot(fypts, fxpts)\n if flipVAx:\n hax.invert_yaxis()\n if fitParams2D is not None:\n x = np.arange(len(image[0]))\n y = np.arange(len(image))\n X, Y = np.meshgrid(x,y)\n data_fitted = gaussian_2d.f_notheta((X,Y), *fitParams2D)\n ax.contour(x, y, data_fitted.reshape(image.shape[0],image.shape[1]), \n levels=np.linspace(min(data_fitted),max(data_fitted),4), colors='w', alpha=0.2)\n return ax, cax, hax, vax, hAvg, vAvg, im, vline, hline\n\ndef rotateTicks(plot):\n ticks = plot.get_xticklabels()\n for tickInc in range(len(ticks)):\n ticks[tickInc].set_rotation(-45)\n \ndef imageTickedColorbar(f, im, ax, lim):\n divider = axesTool.make_axes_locatable(ax)\n cax = divider.append_axes('right', size='5%', pad=0.05)\n cb = f.colorbar(im, cax, orientation='vertical')\n cb.ax.tick_params(labelsize=8)\n if lim[1] - lim[0] == 0:\n return\n for d in im.get_array().flatten():\n p = (d - lim[0]) / (lim[1] - lim[0])\n cb.ax.plot( [0, 0.25], [p, p], color='w' )\n cb.outline.set_visible(False)\n \ndef makeThresholdStatsImages(ax, thresholds, locs, shape, ims, lims, fig):\n thresholdList = [thresh.th for thresh in thresholds]\n thresholdPic, lims[0][0], lims[0][1] = genAvgDiscrepancyImage(thresholdList, shape, locs)\n ims.append(ax[0].imshow(thresholdPic, cmap=cm.get_cmap('seismic_r'), vmin=lims[0][0], vmax=lims[0][1], origin='lower'))\n ax[0].set_title('Thresholds:' + str(misc.round_sig(np.mean(thresholdList))), fontsize=12)\n imageTickedColorbar(fig, ims[-1], ax[0], lims[0])\n \n fidList = [thresh.fidelity for thresh in thresholds]\n thresholdFidPic, lims[1][0], lims[1][1] = genAvgDiscrepancyImage(fidList, shape, locs)\n ims.append(ax[1].imshow(thresholdFidPic, cmap=cm.get_cmap('seismic_r'), vmin=lims[1][0], vmax=lims[1][1], origin='lower'))\n ax[1].set_title('Threshold Fidelities:' + str(misc.round_sig(np.mean(fidList))), fontsize=12)\n imageTickedColorbar(fig, ims[-1], ax[1], lims[1])\n \n imagePeakDiff = []\n gaussFitList = [thresh.fitVals for thresh in thresholds]\n for g in gaussFitList:\n if g is not None:\n imagePeakDiff.append(abs(g[1] - g[4]))\n else:\n imagePeakDiff.append(0)\n peakDiffImage, lims[2][0], lims[2][1] = genAvgDiscrepancyImage(imagePeakDiff, shape, locs)\n ims.append(ax[2].imshow(peakDiffImage, cmap=cm.get_cmap('seismic_r'), vmin=lims[2][0], vmax=lims[2][1], origin='lower'))\n ax[2].set_title('Imaging-Signal:' + str(misc.round_sig(np.mean(imagePeakDiff))), fontsize=12)\n imageTickedColorbar(fig, ims[-1], ax[2], lims[2])\n\n residualList = [thresh.rmsResidual for thresh in thresholds]\n residualImage, _, lims[3][1] = genAvgDiscrepancyImage(residualList, shape, locs)\n lims[3][0] = 0\n ims.append(ax[3].imshow(residualImage, cmap=cm.get_cmap('inferno'), vmin=lims[3][0], vmax=lims[3][1], origin='lower'))\n ax[3].set_title('Fit Rms Residuals:' + str(misc.round_sig(np.mean(residualList))), fontsize=12)\n imageTickedColorbar(fig, ims[-1], ax[3], lims[3])\n for a in ax:\n a.tick_params(axis='both', which='major', labelsize=8)\n return imagePeakDiff\n\n\ndef plotThresholdHists( thresholds, colors, extra=None, extraname=None, thresholds_2=None, shape=(10,10), title='', minx=None, maxx=None,\n localMinMax=False, detailColor='k' ):\n fig, axs = subplots(shape[0], shape[1], figsize=(25.0, 3.0))\n if thresholds_2 is None:\n thresholds_2 = [None for _ in thresholds]\n binCenterList = [th.binCenters for th in thresholds] + [th.binCenters if th is not None else [] for th in thresholds_2]\n binCenterList = [item for sublist in binCenterList for item in sublist]\n binCenterList = [item for item in binCenterList if item] \n if minx is None:\n minx = min(binCenterList)\n if maxx is None:\n maxx = max(binCenterList)\n for tnum, (th, th2, color) in enumerate(zip(thresholds, thresholds_2, colors[1:])):\n if len(axs.shape) == 2:\n ax = axs[len(axs[0]) - tnum%len(axs[0]) - 1][int(tnum/len(axs))]\n else:\n ax = axs[tnum]\n ax.bar(th.binCenters, th.binHeights, align='center', width=th.binCenters[1] - th.binCenters[0], color=color)\n #ax.semilogy(th.binCenters, th.binHeights, color=c)\n ax.axvline(th.th, color=detailColor, ls=':')\n if localMinMax:\n minx, maxx = min(th.binCenters), max(th.binCenters)\n maxy = max(th.binHeights)\n if th2 is not None:\n ax.plot(th2.binEdges(), th2.binEdgeHeights(), color='r')\n ax.axvline(th2.th, color='r', ls='-.')\n if localMinMax:\n minx, maxx = min(list(th2.binCenters) + [minx]), max(list(th2.binCenters) + [maxx])\n maxy = max(list(th2.binHeights) + [maxy])\n if th2.fitVals is not None:\n xpts = np.linspace(min(th2.binCenters), max(th2.binCenters), 1000)\n ax.plot(xpts, double_gaussian.f(xpts, *th2.fitVals), color='r', ls='-.')\n if th.fitVals is not None:\n xpts = np.linspace(min(th.binCenters), max(th.binCenters), 1000)\n ax.plot(xpts, double_gaussian.f(xpts, *th.fitVals), detailColor)\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_xlim(minx, maxx)\n ax.set_ylim(0.1, maxy)\n ax.grid(False)\n if extra is not None:\n txt = extraname + misc.round_sig_str( np.mean(extra[tnum])) if extraname is not None else misc.round_sig_str(np.mean(extra[tnum]))\n axtxt = ax.text( (maxx + minx) / 2, maxy / 2, txt, fontsize=12 )\n axtxt.set_bbox(dict(facecolor=detailColor, alpha=0.3))\n fig.subplots_adjust(wspace=0, hspace=0)\n fig.suptitle(title, fontsize=24)\n return fig\n\ndef plotNiawg(fileIndicator, points=300, plotTogether=True, plotVolts=False):\n \"\"\"\n I have not used this function in a while. August 25th, 2019\n \n plots the first part of the niawg wave and the fourier transform of the total wave.\n \"\"\"\n t, c1, c2, fftc1, fftc2 = analyzeNiawgWave(fileIndicator, ftPts=points)\n if plotVolts:\n figure(figsize=(20,10))\n title('Niawg Output, first ' + str(points) + ' points.')\n ylabel('Relative Voltage (before NIAWG Gain)')\n xlabel('Time (s)')\n plot(t[:points], c1[:points], 'o:', label='Vertical Channel', markersize=4, linewidth=1)\n legend() \n if not plotTogether:\n figure(figsize=(20,10))\n title('Niawg Output, first ' + str(points) + ' points.')\n ylabel('Relative Voltage (before NIAWG Gain)')\n xlabel('Time (s)')\n plot(t[:points], c2[:points], 'o:', label='Horizontal Channel', markersize=4, linewidth=1)\n if not plotTogether:\n legend()\n figure(figsize=(20,10))\n title('Fourier Transform of NIAWG output')\n ylabel('Transform amplitude')\n xlabel('Frequency (Hz)')\n semilogy(fftc1['Freq'], abs(fftc1['Amp']) ** 2, 'o:', label='Vertical Channel', markersize=4, linewidth=1)\n legend()\n if not plotTogether:\n figure(figsize=(20,10))\n title('Fourier Transform of NIAWG output')\n ylabel('Transform amplitude')\n xlabel('Frequency (Hz)')\n semilogy(fftc2['Freq'], abs(fftc2['Amp']) ** 2, 'o:', label='Horizontal Channel', markersize=4, linewidth=1)\n if not plotTogether:\n legend()\n # this is half the niawg sample rate. output is mirrored around x=0.\n xlim(0, 160e6)\n show()\n\n\ndef plotImages( data, mainPlot='fits', key=None, magnification=3, showAllPics=True, plottedData=None, loadType='basler', fitPics=True, **standardImagesArgs ):\n res = ma.standardImages( data, loadType=loadType, fitPics=fitPics, manualAccumulation=True, quiet=True, key=key, plottedData=plottedData, \n **standardImagesArgs )\n (key, rawData, dataMinusBg, dataMinusAvg, avgPic, pictureFitParams, pictureFitErrors, plottedData, v_params, v_errs, h_params, h_errs, intRawData) = res\n # convert to meters\n if fitPics:\n waists = 2 * mc.baslerScoutPixelSize * np.sqrt((pictureFitParams[:, 3]**2+pictureFitParams[:, 4]**2)/2) * magnification\n # convert to s\n errs = np.sqrt(np.diag(pictureFitErrors))\n f, ax = subplots(figsize=(20,3))\n if mainPlot=='fits':\n ax.plot(key, waists, 'bo', label='Fit Waist')\n ax.yaxis.label.set_color('c')\n ax.grid( True, color='b' )\n ax2 = ax.twinx()\n ax2.plot(key, pictureFitParams[:, 0], 'ro:', marker='*', label='Fit Amp (counts)')\n ax2.yaxis.label.set_color( 'r' )\n ax.set_title('Measured atom cloud size over time')\n ax.set_ylabel('Gaussian fit waist (m)')\n ax.legend(loc='right')\n ax2.legend(loc='lower center')\n ax2.grid(True,color='r')\n elif mainPlot=='counts':\n ax.plot(key, intRawData, 'bo', label='Integrated Counts')\n ax.yaxis.label.set_color('c')\n ax.grid( True, color='b' )\n ax.set_ylabel('Integrated Counts')\n ax.legend(loc='right') \n if showAllPics:\n if 'raw' in plottedData:\n picFig = showPics(rawData, key, fitParams=pictureFitParams, hFitParams=h_params, vFitParams=v_params)\n if '-bg' in plottedData:\n picFig = showPics(dataMinusBg, key, fitParams=pictureFitParams, hFitParams=h_params, vFitParams=v_params)\n return pictureFitParams, rawData, intRawData\n \n \ndef plotMotTemperature(data, key=None, magnification=3, showAllPics=True, temperatureGuess=100e-6, plot1D=False, **standardImagesArgs):\n \"\"\"\n Calculate the mot temperature, and plot the data that led to this.\n :param data:\n :param standardImagesArgs: see the standardImages function to see the acceptable arguments here.\n :return:\n \"\"\"\n res = ah.temperatureAnalysis(data, magnification, key=key, loadType='basler',temperatureGuess=temperatureGuess, **standardImagesArgs)\n (temp, fitVals, fitCov, times, waists, rawData, pictureFitParams, key, plottedData, dataMinusBg, \n v_params, v_errs, h_params, h_errs, waists_1D, temp_1D, fitVals_1D, fitCov_1D) = res\n errs = np.sqrt(np.diag(fitCov))\n errs_1D = np.sqrt(np.diag(fitCov_1D))\n fig, ax = plt.subplots(figsize=(20,3))\n ax.plot(times, waists, 'bo', label='Fit Waist 2D')\n ax.plot(times, 2 * LargeBeamMotExpansion.f(times, *fitVals), 'c:', label='Balistic Expansion Waist 2D')\n \n if plot1D:\n ax.plot(times, waists_1D, 'go', label='x-Fit Waist 1D')\n ax.plot(times, 2 * LargeBeamMotExpansion.f(times, *fitVals_1D), 'w:', label='X-Balistic Expansion Waist 1D')\n \n ax.yaxis.label.set_color('c')\n ax.grid(True,color='b')\n\n ax2 = ax.twinx()\n ax2.plot(times, pictureFitParams[:, 0], 'ro:', marker='*', label='Fit Amp (counts)')\n ax2.yaxis.label.set_color('r')\n ax.set_title('Measured atom cloud size over time')\n ax.set_xlabel('Time (s)')\n ax.set_ylabel('Gaussian fit waist (m)')\n ax.legend(loc='right')\n ax2.legend(loc='lower center')\n ax2.grid(True,color='r')\n if showAllPics:\n if 'raw' in plottedData:\n picFig = showPics(rawData, key, fitParams=pictureFitParams, hFitParams=h_params, vFitParams=v_params)\n if '-bg' in plottedData:\n picFig = showPics(dataMinusBg, key, fitParams=pictureFitParams, hFitParams=h_params, vFitParams=v_params) \n print(\"\\nTemperture in the Large Laser Beam Approximation (2D Fits):\", misc.errString(temp * 1e6, errs[2]*1e6), 'uK')\n print(\"\\nTemperture in the Large Laser Beam Approximation (1D Fits):\", misc.errString(temp_1D * 1e6, errs_1D[2]*1e6), 'uK')\n print('2D Fit-Parameters:', fitVals)\n return pictureFitParams, rawData, temp * 1e6, errs[2]*1e6, [fig, picFig]\n \n \ndef plotMotNumberAnalysis(data, motKey, exposureTime, **fillAnalysisArgs):\n \"\"\"\n Calculate the MOT number and plot the data that resulted in the #.\n\n :param data: the number corresponding to the data set you want to analyze.\n :param motKey: the x-axis of the data. Should an array where each element corresponds to the time at which\n its corresponding picture was taken.\n :param exposureTime: the time the camera was exposed for to take the picture. Important in calculating the\n actual fluorescence rate, and this can change significantly from experiment to experiment.\n :param window: an optional specification of a subset region of the picture to analyze.\n :param cameraType: type of camera used to take the picture. Important for converting counts to photons.\n :param showStandardImages: show the images produced by the standardImages function, the actual images of the mot\n at different times.\n :param sidemotPower: measured sidemot power during the measurement.\n :param diagonalPower: measured diagonal power (of a single beam) during the experiment.\n :param motRadius: approximate radius of the MOT. Used to take into account the spread of intensity of the small\n side-mot beam across the finite area of the MOT. Default number comes from something like 8 pixels\n and 8um per pixel scaling, a calculation I don't have on me at the moment.\n :param imagingLoss: the loss in the imaging path due to filtering, imperfect reflections, etc.\n :param detuning: detuning of the mot beams during the imaging.\n \"\"\"\n (rawData, intRawData, motnumber, fitParams, fluorescence, motKey, fitErr)\\\n = ah.motFillAnalysis(data, motKey, exposureTime, loadType='basler', **fillAnalysisArgs)\n fig = plt.figure(figsize=(20,5))\n ax1 = subplot2grid((1, 4), (0, 0), colspan=3)\n ax2 = subplot2grid((1, 4), (0, 3), colspan=1)\n ax1.plot(motKey, intRawData, 'bo', label='data', color='b')\n xfitPts = np.linspace(min(motKey), max(motKey), 1000)\n ax1.plot(xfitPts, exponential_saturation.f(xfitPts, *fitParams), 'b-', label='fit', color='r', linestyle=':')\n ax1.set_xlabel('loading time (s)')\n ax1.set_ylabel('integrated counts')\n ax1.set_title('Mot Fill Curve: MOT Number:' + str(motnumber))\n res = fancyImshow(fig, ax2, rawData[-1])\n res[0].set_title('Final Image')\n print(\"integrated saturated counts subtracting background =\", -fitParams[0])\n print(\"loading time 1/e =\", fitParams[1], \"s\")\n print('Light Scattered off of full MOT:', fluorescence * mc.h * mc.Rb87_D2LineFrequency * 1e9, \"nW\")\n return motnumber, fitParams[1], rawData[-1], fitErr[1], rawData, fig\n\n\ndef singleImage(data, accumulations=1, loadType='andor', bg=arr([0]), title='Single Picture', window=(0, 0, 0, 0),\n xMin=0, xMax=0, yMin=0, yMax=0, zeroCorners=False, smartWindow=False, findMax=False,\n manualAccumulation=False, maxColor=None, key=arr([])):\n # if integer or 1D array\n if type(data) == int or (type(data) == np.array and type(data[0]) == int):\n if loadType == 'andor':\n rawData, _, _, _ = loadHDF5(data)\n elif loadType == 'scout':\n rawData = loadCompoundBasler(data, 'scout')\n elif loadType == 'ace':\n rawData = loadCompoundBasler(data, 'ace')\n elif loadType == 'dataray':\n rawData = [[] for x in range(data)]\n # assume user inputted an array of ints.\n for dataNum in data:\n rawData[keyInc][repInc] = loadDataRay(data)\n else:\n raise ValueError('Bad value for LoadType.')\n else:\n rawData = data\n\n res = processSingleImage(rawData, bg, window, xMin, xMax, yMin, yMax, accumulations, zeroCorners, smartWindow, manualAccumulation)\n rawData, dataMinusBg, xPts, yPts = res\n if not bg == arr(0):\n if findMax:\n coords = np.unravel_index(np.argmax(rawData), rawData.shape)\n print('Coordinates of maximum:', xPts[coords[0]], yPts[coords[1]])\n if maxColor is None:\n maxColor = max(dataMinusBg.flatten())\n imshow(dataMinusBg, extent=(min(xPts), max(xPts), max(yPts), min(yPts)), vmax=maxColor)\n else:\n if findMax:\n coords = np.unravel_index(np.argmax(rawData), rawData.shape)\n print('Coordinates of maximum:', xPts[coords[1]], yPts[coords[0]])\n axvline(xPts[coords[1]], linewidth=0.5)\n axhline(yPts[coords[0]], linewidth=0.5)\n if maxColor is None:\n maxColor = max(rawData.flatten())\n imshow(rawData, extent=(min(xPts), max(xPts), max(yPts), min(yPts)), vmax=maxColor)\n colorbar()\n grid(False)\n return rawData, dataMinusBg\n\n\ndef Survival(fileID, atomLocs, **TransferArgs):\n \"\"\"\n Survival is a special case of transfer where the \"transfer\" is to the original location.\n \n :param fileNumber:\n :param atomLocs:\n :param TransferArgs: See corresponding transfer function for valid TransferArgs.\n :return: see Transfer()\n \"\"\"\n return Transfer(fileID, tao.getStandardSurvivalOptions(atomLocs), atomLocs, **TransferArgs)\n\ndef Tunneling( fileID, tunnelPair1Locs, tunnelPair2Locs, dataColor=['#FF0000','#FFAAAA','#AAAAFF','#0000AA', 'k', '#00FF00', '#00AA00'], \n plotAvg=False, postSelectOnSurvival=True, includeSurvival=True, \n showFitDetails=True, includeHOM=True, **transferArgs ):\n \"\"\"\n A small wrapper for doing tunneling analysis. \n :return: see Transfer()\n \"\"\"\n t1locs = ah.unpackAtomLocations(tunnelPair1Locs)\n t2locs = ah.unpackAtomLocations(tunnelPair2Locs)\n assert(len(t1locs)==len(t2locs))\n numPairs = len(t1locs)\n \n initLocs = t1locs + t2locs\n tferLocs = t1locs + t2locs\n numConditions = 4*numPairs + int(includeHOM) + 2*int(includeSurvival)\n psConditions = [[] for _ in range(numConditions)]\n prConditions = [None for _ in range(numConditions)]\n for pairNum in range(numPairs):\n singleLoad = tao.condition(name=\"LoadL\", whichPic=[0,0], whichAtoms=[pairNum,pairNum+numPairs],\n conditions=[True,False],numRequired=-1, markerWhichPicList=(0,), markerLocList=(pairNum,))\n otherSingleLoad = tao.condition(name=\"LoadR\", whichPic=[0,0],whichAtoms=[pairNum, pairNum+numPairs],\n conditions=[False,True], numRequired=-1, markerWhichPicList=(0,), markerLocList=(pairNum+numPairs,)) \n survival = tao.condition(name=\"Sv.\", whichPic=[1,1],whichAtoms=[pairNum,pairNum+numPairs],\n conditions=[True,True], numRequired=1)\n loadBoth = tao.condition(name=\"LoadB\", whichPic=[0,0],whichAtoms=[pairNum,pairNum+numPairs],\n conditions=[True,True], numRequired=2, markerWhichPicList=(0,0), markerLocList=(pairNum,pairNum+numPairs,))\n bothOrNoneSurvive = tao.condition(name=\"evenPSv\",whichPic=[1,1],whichAtoms=[pairNum,pairNum+numPairs],\n conditions=[True,True],numRequired=[0,2])\n psConditions[pairNum].append(singleLoad)\n psConditions[pairNum+numPairs].append(singleLoad)\n psConditions[pairNum+2*numPairs].append(otherSingleLoad)\n psConditions[pairNum+3*numPairs].append(otherSingleLoad)\n if postSelectOnSurvival:\n psConditions[pairNum].append(survival)\n psConditions[pairNum+numPairs].append(survival)\n psConditions[pairNum+2*numPairs].append(survival) \n psConditions[pairNum+3*numPairs].append(survival)\n if includeHOM:\n psConditions[pairNum+4*numPairs].append(bothOrNoneSurvive)\n if includeHOM:\n psConditions[pairNum+4*numPairs].append(loadBoth)\n if includeSurvival:\n psConditions[pairNum+5*numPairs].append(singleLoad)\n psConditions[pairNum+6*numPairs].append(otherSingleLoad)\n prc1 = tao.condition(name=\"FinL\", whichPic=[1],whichAtoms=[pairNum],conditions=[True],numRequired=-1,\n markerWhichPicList=(1,), markerLocList=(pairNum,))\n prc2 = tao.condition(name=\"FinR\", whichPic=[1], whichAtoms=[pairNum+numPairs],conditions=[True],numRequired=-1,\n markerWhichPicList=(1,), markerLocList=(pairNum+numPairs,)) \n prcHom = tao.condition(name=\"P11\",whichPic=[1,1],whichAtoms=[pairNum,pairNum+numPairs],conditions=[True,True],numRequired=2,\n markerWhichPicList=(1,1), markerLocList=(pairNum, pairNum+numPairs,))\n assert(pairNum <= 1 and pairNum+numPairs <= 1)\n prConditions[pairNum] = prc1\n prConditions[pairNum+numPairs] = prc2\n prConditions[pairNum+2*numPairs] = prc1\n prConditions[pairNum+3*numPairs] = prc2\n if includeHOM:\n prConditions[pairNum+4*numPairs] = prcHom\n if includeSurvival:\n prConditions[pairNum+5*numPairs] = survival\n prConditions[pairNum+6*numPairs] = survival\n res = Transfer(fileID, tao.TransferAnalysisOptions(initLocs, tferLocs, postSelectionConditions=psConditions,\n positiveResultConditions=prConditions), \n dataColor=dataColor, plotAvg=plotAvg, showFitDetails=showFitDetails, **transferArgs)\n # currently no smarter way of handling this other than doing it manually like this.\n if includeSurvival and includeHOM:\n ax = res['Main_Axis']\n data = [np.array(dset) for dset in res['All_Transfer']]\n SP1 = data[0]\n SP2 = data[3]\n S1 = data[5]\n S2 = data[6]\n\n term1 = SP1*SP2 + (1-SP1)*(1-SP2)\n fraction2 = S1*S2/(S1*S2+(1-S1)*(1-S2))\n\n hompredict = term1 * fraction2\n\n dpdsp1 = (SP2-(1-SP2))*fraction2\n dpdsp2 = (SP1-(1-SP1))*fraction2\n dpdp1 = term1*((S1*S2+(1-S1)*(1-S2))*S2-S1*S2*(S2-(1-S2)))/(S1*S2+(1-S1)*(1-S2))**2\n dpdp2 = term1*((S1*S2+(1-S1)*(1-S2))*S1-S1*S2*(S1-(1-S1)))/(S1*S2+(1-S1)*(1-S2))**2\n homErrs = []\n for errnum in range(2):\n errs = [np.array([err[errnum] for err in dset]) for dset in res['All_Transfer_Errs']] \n homErrs.append(np.sqrt(dpdsp1**2*errs[0]**2+dpdsp2**2*errs[3]**2+dpdp1**2*errs[5]**2+dpdp2**2*errs[6]**2))\n\n ax.errorbar(res['Key'], hompredict,yerr=[homErrs[0],homErrs[1]], marker='o', linestyle='', \n color='purple', markersize=15, label='P11 Pred', capsize=5)\n #ax.plot(res['Key'], hompredict, marker='o', linestyle='', \n # color='purple', markersize=15, label='P11 Prediction')\n\n return res\n \ndef Transfer( fileNumber, anaylsisOpts, show=True, legendOption=None, fitModules=[None], \n showFitDetails=False, showFitCharacterPlot=False, showImagePlots=None, plotIndvHists=False, \n timeit=False, outputThresholds=False, plotFitGuess=False, newAnnotation=False, \n plotImagingSignal=False, expFile_version=4, plotAvg=True, countMain=False, histMain=False,\n flattenKeyDim=None, forceNoAnnotation=False, cleanOutput=True, dataColor='gist_rainbow', dataEdgeColors=None,\n tOptions=[to.ThresholdOptions()], resInput=None, countRunningAvg=None, useBase=True, **standardTransferArgs ):\n \"\"\"\n Standard data analysis function for looking at survival rates throughout an experiment. I'm very bad at keeping the \n function argument descriptions up to date.\n countMain: option is for switching which plot is the larger\n \"\"\"\n avgColor='k'\n tt = TimeTracker()\n if resInput is None:\n try:\n res = TransferAnalysis.standardTransferAnalysis( fileNumber, anaylsisOpts, fitModules=fitModules, \n expFile_version=expFile_version, tOptions=tOptions, useBase=useBase,\n **standardTransferArgs )\n except OSError as err:\n if (str(err) == \"Unable to open file (bad object header version number)\"):\n print( \"Unable to open file! (bad object header version number). This is usually a sign that the experiment \"\n \"is still in progress, or that the experiment hasn't closed the hdf5 file.\")\n else:\n print(\"OSError! Exception: \" + str(err))\n return\n else: \n res = resInput\n tt.clock('After-Standard-Analysis')\n (transferData, transferErrs, initPopulation, pic1Data, keyName, key, repetitions, initThresholds, \n fits, avgTransferData, avgTransferErr, avgFit, avgPics, genAvgs, genErrs, transVarAvg, transVarErr, \n initAtomImages, transAtomImages, pic2Data, transThresholds, fitModules, basicInfoStr, ensembleHits, \n tOptions, analysisOpts, initAtoms, tferAtoms, tferList, isAnnotated, condHitList) = res\n print('key:',key)\n if flattenKeyDim != None:\n key = key[:,flattenKeyDim]\n showImagePlots = showImagePlots if showImagePlots is not None else (False if analysisOpts.numAtoms() == 1 else True)\n legendOption = True if legendOption is None and analysisOpts.numAtoms() < 50 else False\n # set locations of plots.\n fig = figure(figsize=(25.0, 8.0))\n typeName = \"Survival\" if analysisOpts.initLocs() == analysisOpts.tferLocs() else \"Transfer\"\n grid1 = mpl.gridspec.GridSpec(12, 16,left=0.05, right=0.95, wspace=1.2, hspace=1)\n if countMain:\n countPlot = subplot(grid1[:, :11])\n elif histMain:\n countHist = subplot(grid1[:, :11])\n else:\n mainPlot = subplot(grid1[:, :11])\n initPopPlot = subplot(grid1[0:3, 12:16])\n grid1.update( left=0.1, right=0.95, wspace=0, hspace=1000 )\n if countMain:\n mainPlot = subplot(grid1[4:8, 12:15])\n countHist = subplot(grid1[4:8, 15:16], sharey=mainPlot)\n elif histMain: \n countPlot = subplot(grid1[4:8, 12:15])\n mainPlot = subplot(grid1[4:8, 15:16], sharey=countPlot)\n else:\n countPlot = subplot(grid1[4:8, 12:15])\n countHist = subplot(grid1[4:8, 15:16], sharey=countPlot)\n grid1.update( left=0.001, right=0.95, hspace=1000 )\n \n avgPlt1 = subplot(grid1[8:12, 11:13])\n avgPlt2 = subplot(grid1[8:12, 13:15])\n if type(keyName) is not type(\"a string\"):\n keyName = ' '.join([kn+',' for kn in keyName])\n titletxt = (keyName + \" \" + typeName + \"; Avg. \" + typeName + \"% = \" \n + (misc.dblAsymErrString(np.mean(transVarAvg), *avgTransferErr[0], *transVarErr[0]) \n if len( transVarAvg ) == 1 else\n misc.dblErrString(np.mean(transVarAvg), \n np.sqrt(np.sum(arr(avgTransferErr)**2)/len(avgTransferErr)), \n np.sqrt(np.sum(arr(transVarErr)**2)/len(transVarErr)))))\n # some easily parallelizable stuff\n plotList = [mainPlot, initPopPlot, countPlot, avgPlt1, avgPlt2]\n xlabels = [keyName,keyName,'Picture #','','']\n ylabels = [typeName + \" %\",\"Initial Pop %\", \"Camera Signal\",'','']\n titles = [titletxt, \"Initial Pop: Avg$ = \" + str(misc.round_sig(np.mean(arr(initPopulation)))) + '$',\n \"Thresh.=\" + str(misc.round_sig(np.mean( [initThresholds[i][j].th for i in range(len(initThresholds)) \n for j in range(len(initThresholds[i]))]))) , '', '']\n majorYTicks = [np.arange(0,1,0.1),np.arange(0,1,0.2),np.linspace(min(pic1Data[0]),max(pic1Data[0]),5),[],[]]\n minorYTicks = [np.arange(0,1,0.05),np.arange(0,1,0.1),np.linspace(min(pic1Data[0]),max(pic1Data[0]),10),[],[]]\n if len(key.shape) == 1:\n xtickKey = key if len(key) < 30 else np.linspace(min(key),max(key),30)\n if len(key.shape) == 2:\n xtickKey = key[:,0] if len(key[:,0]) < 30 else np.linspace(min(key[:,0]),max(key[:,0]),30)\n majorXTicks = [xtickKey, xtickKey, np.linspace(0,len(pic1Data[0]),10), [],[]]\n grid_options = [True,True,True,False,False]\n fontsizes = [20,10,10,10,10]\n for pltNum, (subplt, xlbl, ylbl, title, yTickMaj, yTickMin, xTickMaj, fs, grid) in \\\n enumerate(zip(plotList, xlabels, ylabels, titles, majorYTicks, minorYTicks, majorXTicks, fontsizes, grid_options)):\n subplt.set_xlabel(xlbl, fontsize=fs)\n subplt.set_ylabel(ylbl, fontsize=fs)\n subplt.set_title(title, fontsize=fs, loc='left', pad=50 if pltNum==0 else 0)\n subplt.set_yticks(yTickMaj)\n subplt.set_yticks(yTickMin, minor=True)\n subplt.set_xticks(xTickMaj)\n rotateTicks(subplt)\n subplt.grid(grid, color='#909090', which='Major', linewidth=2)\n #subplt.grid(grid, color='#AAAAAA', which='Minor')\n for item in ([subplt.title, subplt.xaxis.label, subplt.yaxis.label] + subplt.get_xticklabels() + subplt.get_yticklabels()):\n item.set_fontsize(fs)\n \n fitCharacters = []\n \n if type(dataColor) == str:\n colors, colors2 = misc.getColors(analysisOpts.numDataSets() + 1, cmStr=dataColor)\n \n else:\n colors = dataColor\n longLegend = len(transferData[0]) == 1\n markers = misc.getMarkers()\n \n # Main Plot\n if dataEdgeColors is None:\n dataEdgeColors = colors\n for dataSetInc, (atomLoc, fit, module, color, edgecolor) in enumerate(zip(range(analysisOpts.numDataSets()), fits, fitModules, colors, dataEdgeColors)):\n #leg = (r\"[%d,%d] \" % (analysisOpts.initLocs()[atomInc][0], analysisOpts.initLocs()[atomInc][1]) if typeName == \"Survival\"\n # else r\"[%d,%d]$\\rightarrow$[%d,%d] \" % (analysisOpts.initLocs()[atomInc][0], analysisOpts.initLocs()[atomInc][1], \n # analysisOpts.tferLocs()[atomInc][0], analysisOpts.tferLocs()[atomInc][1]))\n #if longLegend:\n #leg += (typeName + \" % = \" + misc.asymErrString(transferData[atomInc][0], *reversed(transferErrs[atomInc][0])))\n leg = anaylsisOpts.positiveResultConditions[dataSetInc].name + \"\\n(\"\n for ps in anaylsisOpts.postSelectionConditions[dataSetInc]:\n leg += ps.name +','\n leg += \")\"\n unevenErrs = [[err[0] for err in transferErrs[dataSetInc]], [err[1] for err in transferErrs[dataSetInc]]]\n mainPlot.errorbar ( key, transferData[dataSetInc], yerr=unevenErrs, color=color, ls='',\n capsize=6, elinewidth=3, label=leg, \n alpha=0.3 if plotAvg else 0.9, marker=markers[dataSetInc%len(markers)], markersize=15,\n markerEdgeColor=edgecolor, markerEdgeWidth=2)\n if module is not None and showFitDetails and fit['vals'] is not None:\n if module.fitCharacter(fit['vals']) is not None:\n fitCharacters.append(module.fitCharacter(fit['vals']))\n mainPlot.plot(fit['x'], fit['nom'], color=color, alpha=0.5)\n if plotFitGuess:\n mainPlot.plot(fit['x'], fit['guess'], color='r', alpha=1)\n\n mainPlot.xaxis.set_label_coords(0.95, -0.15)\n if legendOption:\n mainPlot.legend(loc=\"upper right\", bbox_to_anchor=(1, 1.1), fancybox=True, \n ncol = 4 if longLegend else 10, prop={'size': 14}, frameon=False)\n # ### Init Population Plot\n for datasetNum, _ in enumerate(analysisOpts.postSelectionConditions):\n print(np.array(initPopulation).shape)\n print(initPopulation[datasetNum])\n initPopPlot.plot(key, initPopulation[datasetNum], ls='', marker='o', color=colors[datasetNum], alpha=0.3)\n initPopPlot.axhline(np.mean(initPopulation[datasetNum]), color=colors[datasetNum], alpha=0.3)\n # some shared properties \n for plot in [mainPlot, initPopPlot]:\n if not min(key) == max(key):\n r = max(key) - min(key)\n plot.set_xlim(left = min(key) - r / len(key), right = max(key) + r / len(key))\n plot.set_ylim({0, 1})\n # ### Count Series Plot\n locColors, _ = misc.getColors(len(pic1Data)+1, cmStr='gist_earth')\n for locNum, loc in enumerate(analysisOpts.initLocs()):\n countPlot.plot(pic1Data[locNum], color=locColors[locNum], ls='', marker='.', \n markersize=2 if countMain else 1, alpha=1 if countMain else 0.05)\n if countRunningAvg is not None:\n countPlot.plot(np.convolve(pic1Data[locNum], np.ones(countRunningAvg)/countRunningAvg, mode='valid'),\n color=locColors[locNum], alpha=1 if countMain else 0.5)\n for threshInc, thresh in enumerate(initThresholds[locNum]):\n picsPerVar = int(len(pic1Data[locNum])/len(initThresholds[locNum]))\n countPlot.plot([picsPerVar*threshInc, picsPerVar*(threshInc+1)], [thresh.th, thresh.th], color=locColors[locNum], alpha=0.3)\n ticksForVis = countPlot.xaxis.get_major_ticks()\n ticksForVis[-1].label1.set_visible(False)\n # Count Histogram Plot\n for i, atomLoc in enumerate(analysisOpts.initLocs()):\n countHist.hist(pic1Data[i], 50, color=locColors[i], orientation='horizontal', alpha=0.3, histtype='stepfilled')\n countHist.axhline(initThresholds[i][0].th, color=locColors[i], alpha=0.3)\n setp(countHist.get_yticklabels(), visible=False)\n makeAvgPlts(avgPlt1, avgPlt2, avgPics, analysisOpts, locColors)\n\n avgFitCharacter = None\n if plotAvg:\n unevenErrs = [[err[0] for err in avgTransferErr], [err[1] for err in avgTransferErr]]\n (_, caps, _) = mainPlot.errorbar( key, avgTransferData, yerr=unevenErrs, color=\"#BBBBBB\", ls='',\n marker='o', capsize=12, elinewidth=5, label='Atom-Avg', markersize=10, )\n for cap in caps:\n cap.set_markeredgewidth(1.5)\n unevenErrs = [[err[0] for err in transVarErr], [err[1] for err in transVarErr]]\n (_, caps, _) = mainPlot.errorbar( key, transVarAvg, yerr=unevenErrs, color=avgColor, ls='',\n marker='o', capsize=12, elinewidth=5, label='Event-Avg', markersize=10 )\n for cap in caps:\n cap.set_markeredgewidth(1.5)\n if fitModules[-1] is not None:\n mainPlot.plot(avgFit['x'], avgFit['nom'], color=avgColor, ls=':')\n avgFitCharacter = fitModules[-1].fitCharacter(avgFit['vals'])\n if plotFitGuess:\n mainPlot.plot(fit['x'], fit['guess'], color='r', alpha=0.5)\n if fitModules[0] is not None and showFitCharacterPlot:\n f, ax = subplots()\n fitCharacterPic, vmin, vmax = genAvgDiscrepancyImage(fitCharacters, avgPics[0].shape, analysisOpts.initLocs())\n im = ax.imshow(fitCharacterPic, cmap=cm.get_cmap('seismic_r'), vmin=vmin, vmax=vmax, origin='lower')\n ax.set_title('Fit-Character (white is average)')\n #ax.grid(False)\n f.colorbar(im)\n tt.clock('After-Main-Plots')\n avgTransferPic = None\n if showImagePlots:\n imagingSignal = []\n f_imgPlots = []\n if tOptions[0].indvVariationThresholds:\n for varInc in range(len(initThresholds[0])):\n f_img, axs = subplots(1, 9 if tOptions[0].tferThresholdSame else 13, \n figsize = (36.0, 2.0) if tOptions[0].tferThresholdSame else (36.0,3))\n lims = [[None, None] for _ in range(9 if tOptions[0].tferThresholdSame else 13)]\n ims = [None for _ in range(5)]\n imagingSignal.append(np.mean(\n makeThresholdStatsImages(axs[5:9], [atomThresholds[varInc] for atomThresholds in initThresholds], \n analysisOpts.initLocs(), avgPics[0].shape, ims, lims[5:9], f_img)))\n if not tOptions[0].tferThresholdSame:\n makeThresholdStatsImages(axs[9:13], [atomThresholds[varInc] for atomThresholds in transThresholds], \n analysisOpts.tferLocs(), avgPics[0].shape, ims, lims[9:13], f_img)\n\n avgTransfers = [np.mean(s) for s in transferData]\n avgTransferPic, l20, l21 = genAvgDiscrepancyImage(avgTransfers, avgPics[0].shape, analysisOpts.initLocs())\n\n avgPops = [np.mean(l) for l in initPopulation]\n avgInitPopPic, l30, l31 = genAvgDiscrepancyImage(avgPops, avgPics[0].shape, analysisOpts.initLocs())\n \n if genAvgs is not None:\n genAtomAvgs = [np.mean(dp) for dp in genAvgs] if genAvgs[0] is not None else [0]\n genImage, _, l41 = genAvgDiscrepancyImage(genAtomAvgs, avgPics[0].shape, \n analysisOpts.initLocs()) if genAvgs[0] is not None else (np.zeros(avgPics[0].shape), 0, 1)\n else:\n genImage, l41, genAtomAvgs = (np.zeros(avgInitPopPic.shape), 1, [0])\n images = [avgPics[0], avgPics[1], avgTransferPic, avgInitPopPic, genImage]\n lims[0:5] = [[min(avgPics[0].flatten()), max(avgPics[0].flatten())], \n [min(avgPics[1].flatten()), max(avgPics[1].flatten())], \n [l20,l21],[l30,l31],[0,l41]]\n cmaps = ['viridis', 'viridis', 'seismic_r','seismic_r','inferno']\n titles = ['Avg 1st Pic', 'Avg 2nd Pic', 'Avg Trans:' + str(misc.round_sig(np.mean(avgTransfers))), \n 'Avg Load:' + str(misc.round_sig(np.mean(avgPops))),'Atom-Generation: ' + str(misc.round_sig(np.mean(genAtomAvgs)))]\n\n for i, (ax, lim, image, cmap_) in enumerate(zip(axs.flatten(), lims, images, cmaps)):\n ims[i] = ax.imshow(image, vmin=lim[0], vmax=lim[1], origin='lower', cmap=cm.get_cmap(cmap_))\n for ax, lim, title, im in zip(axs.flatten(), lims, titles, ims):\n ax.set_yticklabels([])\n ax.set_xticklabels([])\n #ax.grid(False)\n ax.set_title(title, fontsize=12)\n imageTickedColorbar(fig, im, ax, lim)\n tt.clock('After-Image-Plots')\n f_img.suptitle(keyName + ': ' + str(key[varInc]))\n f_imgPlots.append(f_img)\n else:\n f_img, axs = subplots(1, 9 if tOptions[0].tferThresholdSame else 13, figsize = (36.0, 4.0) if tOptions[0].tferThresholdSame else (36.0,3))\n lims = [[None, None] for _ in range(9 if tOptions[0].tferThresholdSame else 13)]\n ims = [None for _ in range(5)]\n imagingSignal.append(np.mean(\n makeThresholdStatsImages(axs[5:9], [atomThresholds[0] for atomThresholds in initThresholds], \n analysisOpts.initLocs(), avgPics[0].shape, ims, lims[5:9], f_img)))\n imagingSignal = [imagingSignal[0] for _ in range(len(initThresholds[0]))]\n if not tOptions[0].tferThresholdSame:\n makeThresholdStatsImages(axs[9:13], [atomThresholds[0] for atomThresholds in transThresholds], \n analysisOpts.tferLocs(), avgPics[0].shape, ims, lims[9:13], f_img)\n\n avgTransfers = [np.mean(s) for s in transferData]\n avgTransferPic, l20, l21 = genAvgDiscrepancyImage(avgTransfers, avgPics[0].shape, analysisOpts.initLocs())\n\n avgPops = [np.mean(l) for l in initPopulation]\n avgInitPopPic, l30, l31 = genAvgDiscrepancyImage(avgPops, avgPics[0].shape, analysisOpts.initLocs())\n\n if genAvgs is not None:\n genAtomAvgs = [np.mean(dp) for dp in genAvgs] if genAvgs[0] is not None else [0]\n genImage, _, l41 = genAvgDiscrepancyImage(genAtomAvgs, avgPics[0].shape, \n analysisOpts.initLocs()) if genAvgs[0] is not None else (np.zeros(avgPics[0].shape), 0, 1)\n else:\n genImage, l41, genAtomAvgs = ([[0]], 1, [0])\n images = [avgPics[0], avgPics[1], avgTransferPic, avgInitPopPic, genImage]\n lims[0:5] = [[min(avgPics[0].flatten()), max(avgPics[0].flatten())], [min(avgPics[1].flatten()), max(avgPics[1].flatten())], [l20,l21],[l30,l31],[0,l41]]\n cmaps = ['viridis', 'viridis', 'seismic_r','seismic_r','inferno']\n titles = ['Avg 1st Pic', 'Avg 2nd Pic', 'Avg Trans:' + str(misc.round_sig(np.mean(avgTransfers))), \n 'Avg Load:' + str(misc.round_sig(np.mean(avgPops))),'Atom-Generation: ' + str(misc.round_sig(np.mean(genAtomAvgs)))]\n\n for i, (ax, lim, image, cmap_) in enumerate(zip(axs.flatten(), lims, images, cmaps)):\n ims[i] = ax.imshow(image, vmin=lim[0], vmax=lim[1], origin='lower', cmap=cm.get_cmap(cmap_))\n for ax, lim, title, im in zip(axs.flatten(), lims, titles, ims):\n ax.set_yticklabels([])\n ax.set_xticklabels([])\n #ax.grid(False)\n ax.set_title(title, fontsize=12)\n imageTickedColorbar(fig, im, ax, lim)\n tt.clock('After-Image-Plots')\n f_img.suptitle('All Data')\n f_imgPlots.append(f_img)\n if plotImagingSignal:\n mainTwinx = mainPlot.twinx();\n mainTwinx.plot(key, imagingSignal, 'ro');\n #mainTwinx.grid(False)\n mainTwinx.set_ylabel('Imaging Signal (Counts)',color='r');\n mainTwinx.spines['right'].set_color('r')\n mainTwinx.yaxis.label.set_color('r')\n mainTwinx.tick_params(axis='y', colors='r')\n if plotIndvHists:\n if type(analysisOpts.initLocsIn[-1]) == int:\n shape = (analysisOpts.initLocsIn[-1], analysisOpts.initLocsIn[-2])\n else:\n raise ValueError(\"Can't currently plot indv hists if giving an explicit atom list instead of a grid.\")\n thresholdFigs = []\n if tOptions[0].indvVariationThresholds:\n print('Plotting individual variation threshold data...')\n binCenterList = ([th.binCenters for thresholds in initThresholds for th in thresholds] \n + [th.binCenters if th is not None else [] for thresholds_2 in transThresholds for th in thresholds_2])\n binCenterList = [item for sublist in binCenterList for item in sublist]\n binCenterList = [item for item in binCenterList if item] \n minx, maxx = min(binCenterList), max(binCenterList)\n for varInc in range(len(initThresholds[0])):\n thresholdFigs.append(plotThresholdHists([atomThresholds[varInc] for atomThresholds in initThresholds], \n colors, extra=avgTransfers, extraname=r\"$\\rightarrow$:\", \n thresholds_2=[atomThresholds[varInc] for atomThresholds in transThresholds], \n shape=shape, title= keyName + ': ' + str(key[varInc]), minx=minx,maxx=maxx))\n else:\n print('Plotting all threshold data...')\n thresholdFigs.append(plotThresholdHists([atomThresholds[0] for atomThresholds in initThresholds], \n colors, extra=avgTransfers, extraname=r\"$\\rightarrow$:\", \n thresholds_2=[atomThresholds[0] for atomThresholds in transThresholds], \n shape=shape, title='All Data'))\n tt.clock('After-Indv-Hists')\n for thresholdFig in thresholdFigs:\n display(thresholdFig)\n if timeit:\n tt.display()\n \n if (newAnnotation or not exp.checkAnnotation(fileNumber, force=False, quiet=True, useBase=useBase, expFile_version=expFile_version)) and not forceNoAnnotation :\n disp.display(fig)\n if fitModules[-1] is not None:\n print(\"Avg Fit R-Squared: \" + misc.round_sig_str(avgFit[\"R-Squared\"]))\n fitInfoString = \"\"\n for label, fitVal, err in zip(fitModules[-1].args(), avgFit['vals'], avgFit['errs']):\n fitInfoString += label+': '+misc.errString(fitVal, err) + \"
    \"\n fitInfoString += (fitModules[-1].getFitCharacterString() + ': ' \n + misc.errString(fitModules[-1].fitCharacter(avgFit['vals']), \n fitModules[-1].fitCharacterErr(avgFit['vals'], avgFit['errs'])))\n disp.display(disp.Markdown(fitInfoString))\n if showFitDetails:\n for f in getFitsDataFrame(fits, fitModules, avgFit):\n display(f)\n\n exp.annotate(fileNumber,expFile_version)\n configName = exp.getConfiguration(fileNumber,expFile_version=expFile_version, useBase=useBase)\n \n if not forceNoAnnotation:\n rawTitle, _, lev = exp.getAnnotation(fileNumber,expFile_version=expFile_version)\n expTitle = ''.join('#' for _ in range(lev)) + ' File ' + str(fileNumber) + \" (\" + configName +\"): \" + rawTitle\n else:\n expTitle = ''.join('#' for _ in range(3)) + ' File ' + str(fileNumber) + \" (\" + configName +\")\"\n \n if cleanOutput:\n disp.clear_output()\n disp.display(disp.Markdown(expTitle))\n with exp.ExpFile(fileNumber,expFile_version=expFile_version) as fid:\n fid.get_basic_info()\n \n if fitModules[-1] is not None and avgFit['errs'] is not None:\n print(\"Avg Fit R-Squared: \" + misc.round_sig_str(avgFit[\"R-Squared\"]))\n fitInfoString = \"\"\n for label, fitVal, err in zip(fitModules[-1].args(), avgFit['vals'], avgFit['errs']):\n fitInfoString += label+': '+misc.errString(fitVal, err) + \"
    \"\n fitInfoString += (fitModules[-1].getFitCharacterString() + ': ' \n + misc.errString(fitModules[-1].fitCharacter(avgFit['vals']), \n fitModules[-1].fitCharacterErr(avgFit['vals'], avgFit['errs'])))\n disp.display(disp.Markdown(fitInfoString))\n if fitModules[-1] is not None and showFitDetails:\n for f in getFitsDataFrame(fits, fitModules, avgFit):\n display(f)\n \n if outputThresholds:\n thresholdList = np.flip(np.reshape([threshold.th for threshold in initThresholds], (10,10)),1)\n with open('J:/Code-Files/T-File.txt','w') as f:\n for row in thresholdList:\n for thresh in row:\n f.write(str(thresh) + ' ')\n \n returnObj = {'Key':key, 'All_Transfer':transferData, 'All_Transfer_Errs':transferErrs, 'Initial_Populations':initPopulation, \n 'Transfer_Fits':fits, 'Average_Transfer_Fit':avgFit, 'Average_Atom_Generation':genAvgs, \n 'Average_Atom_Generation_Err':genErrs, 'Picture_1_Data':pic1Data, 'Fit_Character':fitCharacters, \n 'Average_Transfer_Pic':avgTransferPic, 'Transfer_Averaged_Over_Variations':transVarAvg, \n 'Transfer_Averaged_Over_Variations_Err':transVarErr, 'Average_Transfer':avgTransferData,\n 'Average_Transfer_Err':avgTransferErr, 'Initial_Atom_Images':initAtomImages, \n 'Transfer_Atom_Images':transAtomImages, 'Picture_2_Data':pic2Data, 'Initial_Thresholds':initThresholds,\n 'Transfer_Thresholds':transThresholds, 'Fit_Modules':fitModules, 'Average_Fit_Character':avgFitCharacter,\n 'InitAtoms':initAtoms, 'TferAtoms':tferAtoms, 'tferList':tferList, 'Main_Axis':mainPlot, 'Condition_Hit_List':condHitList}\n if showImagePlots:\n returnObj['Figures'] = [fig, *f_imgPlots]\n else:\n returnObj['Figures'] = [fig]\n \n return returnObj\n\ndef Loading(fileID, atomLocs, **TransferArgs):\n \"\"\"\n A small wrapper, partially for the extra defaults in this case partially for consistency with old function definitions.\n \"\"\"\n return Transfer(fileID, tao.getStandardLoadingOptions(atomLocs), atomLocs, **TransferArgs)\n\ndef Population(fileNum, atomLocations, whichPic, picsPerRep, plotLoadingRate=True, legendOption=None, showImagePlots=True,\n plotIndvHists=False, showFitDetails=False, showFitCharacterPlot=True, show=True, histMain=False,\n mainAlpha=0.2, avgColor='w', newAnnotation=False, thresholdOptions=to.ThresholdOptions(), clearOutput=True,\n dataCmap='gist_rainbow', countMain=False,\n **StandardArgs):\n \"\"\"\n Standard data analysis package for looking at population %s throughout an experiment.\n\n return key, loadingRateList, loadingRateErr\n\n This routine is designed for analyzing experiments with only one picture per cycle. Typically\n These are loading exeriments, for example. There's no survival calculation.\n \"\"\"\n atomLocs_orig = atomLocations\n avgColor='w'\n res = pa.standardPopulationAnalysis(fileNum, atomLocations, whichPic, picsPerRep, thresholdOptions=thresholdOptions, **StandardArgs)\n (locCounts, thresholds, avgPic, key, allPopsErr, allPops, avgPop, avgPopErr, fits,\n fitModules, keyName, atomData, rawData, atomLocations, avgFits, atomImages,\n totalAvg, totalErr, variationCountData, variationAtomData, varThresholds) = res\n colors, _ = misc.getColors(len(atomLocations) + 1, cmStr=dataCmap)\n \n if not show:\n return key, allPops, allPopsErr, locCounts, atomImages, thresholds, avgPop\n if legendOption is None and len(atomLocations) < 50:\n legendOption = True\n else:\n legendOption = False\n # get the colors for the plot.\n markers = ['o','^','<','>','v']\n f_main = figure(figsize=(20,7))\n # Setup grid\n grid1 = mpl.gridspec.GridSpec(12, 16)\n grid1.update(left=0.05, right=0.95, wspace=1.2, hspace=1000)\n gridLeft = mpl.gridspec.GridSpec(12, 16)\n gridLeft.update(left=0.001, right=0.95, hspace=1000)\n gridRight = mpl.gridspec.GridSpec(12, 16)\n gridRight.update(left=0.2, right=0.946, wspace=0, hspace=1000)\n # Main Plot\n typeName = \"L\"\n popPlot = subplot(grid1[0:3, 12:16])\n if countMain:\n countPlot = subplot(gridRight[:, :11])\n mainPlot = subplot(gridLeft[4:8, 15:16], sharey=countPlot)\n countHist = subplot(gridRight[:, 11:12])\n elif histMain:\n countPlot = subplot(gridRight[:, :1])\n countHist = subplot(grid1[:, 1:12])\n mainPlot = subplot(gridLeft[4:8, 15:16], sharey=countPlot)\n else:\n mainPlot = subplot(grid1[:, :12])\n countPlot = subplot(gridRight[:, 12:15])\n countHist = subplot(gridLeft[4:8, 15:16], sharey=countPlot) \n \n fitCharacters = []\n longLegend = len(allPops[0]) == 1\n\n if len(arr(key).shape) == 2:\n # 2d scan: no normal plot possible, so make colormap plot of avg\n key1, key2 = key[:,0], key[:,1]\n key1 = np.sort(key1)\n key2 = np.sort(key2)\n else:\n for i, (atomLoc, fit, module) in enumerate(zip(atomLocations, fits, fitModules)):\n leg = r\"[%d,%d] \" % (atomLoc[0], atomLoc[1])\n if longLegend:\n pass\n #leg += (typeName + \" % = \" + str(round_sig(allPops[i][0])) + \"$\\pm$ \"\n # + str(round_sig(allPopsErr[i][0])))\n unevenErrs = [[err[0] for err in allPopsErr[i]], [err[1] for err in allPopsErr[i]]]\n mainPlot.errorbar(key, allPops[i], yerr=unevenErrs, color=colors[i], ls='',\n capsize=6, elinewidth=3, label=leg, alpha=mainAlpha, marker=markers[i%len(markers)],markersize=5)\n if module is not None:\n if fit == [] or fit['vals'] is None:\n continue\n fitCharacters.append(module.fitCharacter(fit['vals']))\n mainPlot.plot(fit['x'], fit['nom'], color=colors[i], alpha = 0.5)\n if fitModules[-1] is not None:\n if avgFits['vals'] is None:\n print('Avg Fit Failed!')\n else:\n mainPlot.plot(avgFits['x'], avgFits['nom'], color=avgColor, alpha = 1,markersize=5)\n mainPlot.grid(True, color='#AAAAAA', which='Major')\n mainPlot.grid(True, color='#090909', which='Minor')\n mainPlot.set_yticks(np.arange(0,1,0.1))\n mainPlot.set_yticks(np.arange(0,1,0.05), minor=True)\n mainPlot.set_ylim({-0.02, 1.01})\n if not min(key) == max(key):\n mainPlot.set_xlim(left=min(key) - (max(key) - min(key)) / len(key), right=max(key)\n + (max(key) - min(key)) / len(key))\n if len(key) < 30:\n mainPlot.set_xticks(key)\n else:\n mainPlot.set_xticks(np.linspace(min(key),max(key),30))\n rotateTicks(mainPlot)\n titletxt = keyName + \" Atom \" + typeName + \" Scan\"\n if len(allPops[0]) == 1:\n titletxt = keyName + \" Atom \" + typeName + \" Point.\\n Avg \" + typeName + \"% = \" + misc.errString(totalAvg, totalErr) \n \n mainPlot.set_title(titletxt, fontsize=30 if not histMain else 12 )\n mainPlot.set_ylabel(\"S %\", fontsize=20 if not histMain else 9 )\n mainPlot.set_xlabel(keyName, fontsize=20 if not histMain else 9 )\n if legendOption == True:\n if histMain:\n cols = 4 if longLegend else 10\n countHist.legend(loc=\"upper center\", bbox_to_anchor=(0.5, -0.1), fancybox=True, ncol=cols, prop={'size': 12})\n else:\n cols = 4 if longLegend else 10\n mainPlot.legend(loc=\"upper center\", bbox_to_anchor=(0.5, -0.1), fancybox=True, ncol=cols, prop={'size': 12})\n # Population Plot\n for i, loc in enumerate(atomLocations):\n popPlot.plot(key, allPops[i], ls='', marker='o', color=colors[i], alpha=0.3)\n popPlot.axhline(np.mean(allPops[i]), color=colors[i], alpha=0.3)\n popPlot.set_ylim({0, 1})\n if not min(key) == max(key):\n popPlot.set_xlim(left=min(key) - (max(key) - min(key)) / len(key), right=max(key) \n + (max(key) - min(key)) / len(key))\n popPlot.set_xlabel(\"Key Values\")\n popPlot.set_ylabel(\"Population %\")\n popPlot.set_xticks(key)\n popPlot.set_yticks(np.arange(0,1,0.1), minor=True)\n popPlot.set_yticks(np.arange(0,1,0.2))\n popPlot.grid(True, color='#AAAAAA', which='Major')\n popPlot.grid(True, color='#090909', which='Minor')\n popPlot.set_title(\"Population: Avg$ = \" + str(misc.round_sig(np.mean(arr(allPops)))) + '$')\n for item in ([popPlot.title, popPlot.xaxis.label, popPlot.yaxis.label] +\n popPlot.get_xticklabels() + popPlot.get_yticklabels()):\n item.set_fontsize(10)\n # ### Count Series Plot\n for i, loc in enumerate(atomLocations):\n countPlot.plot(locCounts[i], color=colors[i], ls='', marker='.', markersize=1, alpha=0.3)\n countPlot.axhline(thresholds[i].th, color=colors[i], alpha=0.3)\n\n countPlot.set_xlabel(\"Picture #\")\n countPlot.set_ylabel(\"Camera Signal\")\n countPlot.set_title(\"Thresh.=\" + str(misc.round_sig(thresholds[i].th)), fontsize=10) #\", Fid.=\"\n # + str(round_sig(thresholdFid)), )\n ticksForVis = countPlot.xaxis.get_major_ticks()\n ticksForVis[-1].label1.set_visible(False)\n for item in ([countPlot.title, countPlot.xaxis.label, countPlot.yaxis.label] +\n countPlot.get_xticklabels() + countPlot.get_yticklabels()):\n item.set_fontsize(10)\n countPlot.set_xlim((0, len(locCounts[0])))\n tickVals = np.linspace(0, len(locCounts[0]), len(key) + 1)\n countPlot.set_xticks(tickVals[0:-1:2])\n # Count Histogram Plot\n for i, atomLoc in enumerate(atomLocations):\n if histMain:\n countHist.hist(locCounts[i], 50, color=colors[i], orientation='vertical', alpha=mainAlpha, histtype='stepfilled')\n countHist.axvline(thresholds[i].th, color=colors[i], alpha=0.3)\n else:\n countHist.hist(locCounts[i], 50, color=colors[i], orientation='horizontal', alpha=mainAlpha, histtype='stepfilled')\n countHist.axhline(thresholds[i].th, color=colors[i], alpha=0.3)\n for item in ([countHist.title, countHist.xaxis.label, countHist.yaxis.label] +\n countHist.get_xticklabels() + countHist.get_yticklabels()):\n item.set_fontsize(10 if not histMain else 20)\n rotateTicks(countHist)\n setp(countHist.get_yticklabels(), visible=False)\n # average image\n avgPlt = subplot(gridRight[8:12, 12:15])\n avgPlt.imshow(avgPic, origin='lower');\n avgPlt.set_xticks([]) \n avgPlt.set_yticks([])\n avgPlt.grid(False)\n for loc in atomLocations:\n circ = Circle((loc[1], loc[0]), 0.2, color='r')\n avgPlt.add_artist(circ)\n avgPopErr = [[err[0] for err in avgPopErr], [err[1] for err in avgPopErr]]\n mainPlot.errorbar(key, avgPop, yerr=avgPopErr, color=avgColor, ls='', marker='o', capsize=6, elinewidth=3, label='Avg', markersize=5)\n if fitModules is not [None] and showFitDetails:\n mainPlot.plot(avgFits['x'], avgFits['nom'], color=avgColor, ls=':')\n\n if fitModules is not [None] and showFitCharacterPlot and fits[0] != []:\n figure()\n print('fitCharacter',fitCharacters)\n fitCharacterPic, vmin, vmax = genAvgDiscrepancyImage(fitCharacters, avgPic.shape, atomLocations)\n imshow(fitCharacterPic, cmap=cm.get_cmap('seismic_r'), vmin=vmin, vmax=vmax, origin='lower')\n title('Fit-Character (white is average)')\n colorbar()\n if showImagePlots:\n ims = []\n lims = [[0,0] for _ in range(5)]\n f_im, axs = subplots(1,6, figsize=(20,5))\n \n ims.append(axs[0].imshow(avgPic, origin='lower'))\n axs[0].set_title('Avg 1st Pic')\n\n avgPops = []\n for l in allPops:\n avgPops.append(np.mean(l))\n avgPopPic, vmin, vmax = genAvgDiscrepancyImage(avgPops, avgPic.shape, atomLocations)\n ims.append(axs[1].imshow(avgPopPic, cmap=cm.get_cmap('seismic_r'), vmin=vmin, vmax=vmax, origin='lower'))\n axs[1].set_title('Avg Population')\n \n makeThresholdStatsImages(axs[2:], thresholds, atomLocations, avgPic.shape, ims, lims, f_im)\n\n avgPops = []\n for s in allPops:\n avgPops.append(np.mean(s))\n if plotIndvHists:\n shape = (atomLocs_orig[-1], atomLocs_orig[-2]) if type(atomLocs_orig[-1]) == int else (10,10)\n if thresholdOptions.indvVariationThresholds:\n for varInc in range(len(key)):\n #misc.transpose(varThresholds)[varInc]\n #print(len([atomTh[varInc] for atomTh in varThresholds]), len(avgPops), len(colors))\n #print([atomTh[varInc] for atomTh in varThresholds])\n plotThresholdHists(varThresholds[varInc], colors, extra=avgPops, extraname=r\"L:\", \n shape=shape, title= keyName + ': ' + str(key[varInc]))\n else:\n plotThresholdHists(thresholds, colors, extra=avgPops, extraname=\"L:\", shape=shape)\n \"\"\"\n thresholdFigs.append(plotThresholdHists([atomThresholds[0] for atomThresholds in initThresholds], \n colors, extra=avgTransfers, extraname=r\"$\\rightarrow$:\", \n thresholds_2=[atomThresholds[0] for atomThresholds in transThresholds], \n shape=shape, title='All Data'))\"\"\"\n\n \n\n \n disp.display(f_main)\n if newAnnotation or not exp.checkAnnotation(fileNum, force=False, quiet=True):\n exp.annotate(fileNum)\n if clearOutput:\n disp.clear_output()\n \n rawTitle, notes, lev = exp.getAnnotation(fileNum)\n expTitle = ''.join('#' for _ in range(lev)) + ' File ' + str(fileNum) + ': ' + rawTitle\n disp.display(disp.Markdown(expTitle))\n disp.display(disp.Markdown(notes))\n with exp.ExpFile(fileNum) as f:\n f.get_basic_info()\n \n if fitModules[-1] is not None:\n for label, fitVal, err in zip(fitModules[-1].args(), avgFits['vals'], avgFits['errs']):\n print( label,':', misc.errString(fitVal, err) )\n if showFitDetails:\n fits_df = getFitsDataFrame(fits, fitModules, avgFits, markersize=5)\n display(fits_df)\n return { 'Key': key, 'All_Populations': allPops, 'All_Populations_Error': allPopsErr, 'Pixel_Counts':locCounts, \n 'Atom_Images':atomImages, 'Thresholds':thresholds, 'Atom_Data':atomData, 'Raw_Data':rawData, \n 'Average_Population': avgPop, 'Average_Population_Error': avgPopErr }\n\ndef showPics(data, key, fitParams=None, indvColorBars=False, colorMax=-1, fancy=True, hFitParams=None, vFitParams=None):\n \"\"\"\n A little function for making a nice display of an array of pics and fits to the pics\n \"\"\"\n num = len(data)\n gridsize1, gridsize2 = (0, 0)\n if hFitParams is None:\n hFitParams = [None for _ in range(num)]\n if vFitParams is None:\n vFitParams = [None for _ in range(num)]\n for i in range(100):\n if i*(i-2) >= num:\n gridsize1 = i\n gridsize2 = i-2\n break\n if fancy:\n fig, axs = subplots( 2 if fitParams is not None else 1, num, figsize=(20,5))\n grid = axs.flatten()\n else:\n fig = figure(figsize=(20,20))\n grid = axesTool.AxesGrid( fig, 111, nrows_ncols=( 2 if fitParams is not None else 1, num), axes_pad=0.0, share_all=True,\n label_mode=\"L\", cbar_location=\"right\", cbar_mode=\"single\" )\n rowCount, picCount, count = 0,0,0\n maximum, minimum = sorted(data.flatten())[colorMax], min(data.flatten())\n # get picture fits & plots\n for picNum in range(num):\n pl = grid[count]\n if count >= len(data):\n count += 1\n picCount += 1\n continue\n pic = data[count]\n if indvColorBars:\n maximum, minimum = max(pic.flatten()), min(pic.flatten())\n y, x = [np.linspace(1, pic.shape[i], pic.shape[i]) for i in range(2)]\n x, y = np.meshgrid(x, y)\n if fancy: \n res =fancyImshow(fig, pl, pic, imageArgs={'extent':(x.min(), x.max(), y.min(), y.max()),\n 'vmin':minimum, 'vmax':maximum}, cb=False, ticklabels=False,\n hAvgArgs={'linewidth':0.5}, vAvgArgs={'linewidth':0.5}, \n hFitParams=hFitParams[count], vFitParams=vFitParams[count])\n pl = res[0]\n else:\n im1 = pl.imshow( pic, origin='bottom', extent=(x.min(), x.max(), y.min(), y.max()),\n vmin=minimum, vmax=maximum )\n pl.axis('off')\n pl.set_title(str(misc.round_sig(key[count], 4)), fontsize=8)\n if fitParams is not None:\n if (fitParams[count] != np.zeros(len(fitParams[count]))).all():\n try:\n ellipse = Ellipse(xy=(fitParams[count][1], fitParams[count][2]),\n width=2*fitParams[count][3], height=2*fitParams[count][4],\n angle=-fitParams[count][5]*180/np.pi, edgecolor='r', fc='None', lw=2, alpha=0.2)\n pl.add_patch(ellipse)\n except ValueError:\n pass\n pl2 = grid[count+num]\n pl2.grid(0)\n x, y = np.arange(0,len(pic[0])), np.arange(0,len(pic))\n X, Y = np.meshgrid(x,y)\n v_ = gaussian_2d.f_notheta((X,Y), *fitParams[count])\n vals = np.reshape(v_, pic.shape)\n if fancy: \n res=fancyImshow(fig, pl2, pic-vals, imageArgs={'extent':(x.min(), x.max(), y.min(), y.max())},\n cb=False, ticklabels=False, hAvgArgs={'linewidth':0.5}, vAvgArgs={'linewidth':0.5})\n pl2 = res[0]\n else:\n im2 = pl2.imshow(pic-vals, vmin=-2, vmax=2, origin='bottom',\n extent=(x.min(), x.max(), y.min(), y.max()))\n pl2.axis('off')\n count += 1\n picCount += 1\n return fig\n","sub_path":"Analysis_Python_Files/MatplotlibPlotters.py","file_name":"MatplotlibPlotters.py","file_ext":"py","file_size_in_byte":70278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"529500222","text":"import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = pybithumb.Bithumb(con_key, sec_key)\n\nkrw = bithumb.get_balance(\"BTC\")[2]\norderbook = pybithumb.get_orderbook(\"BTC\")\n\nasks = orderbook['asks']\nsell_price = asks[0]['price']\nunit = krw/sell_price\nprint(unit)","sub_path":"ch06/06_06.py","file_name":"06_06.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"53571475","text":"\"\"\"\r\n7-Card Hold 'Em\r\n\r\nAuthor: Jarett Nishijo\r\n\r\nA multi-player game on texas hold em\r\n\"\"\"\r\nimport random\r\n\r\nclass Deck:\r\n \r\n def __init__(self):\r\n \r\n self.rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10','J', 'Q', 'K']\r\n self.suit = ['H','D', 'S','C']\r\n self.dealt_cards = []\r\n\r\n def deal_card(self):\r\n rank_suit = (self.rank[random.randint(0, 12)], self.suit[random.randint(0, 3)])\r\n card = Card(rank_suit)\r\n while rank_suit in self.dealt_cards:\r\n rank_suit = (self.rank[random.randint(0, 12)], self.suit[random.randint(0, 3)])\r\n card = Card(rank_suit)\r\n self.dealt_cards.append(rank_suit)\r\n print(card)\r\n \r\n return card\r\n\r\nclass Card(Deck):\r\n\r\n def __init__(self, rank_suit):\r\n self.rank = rank_suit[0]\r\n self.suit = rank_suit[1]\r\n\r\n def __repr__(self):\r\n return repr((self.rank , self.suit))\r\n\r\n def __str__(self):\r\n return self.rank + self.suit\r\n \r\nclass Player:\r\n\r\n def __init__(self, name):\r\n self.name = name\r\n self.balance = 500\r\n self.hand = []\r\n self.hand_rank = {'H': False, 'P': False, 'TP': False, 'TK': False, 'S': False,\r\n 'FL': False, 'FH': False, 'FK': False, 'SF': False, 'RF': False}\r\n self.suit_org = {}\r\n self.rank_org = {}\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def __repr__(self):\r\n return 'Player('+self.name+')'\r\n\r\n def bet(self):\r\n while True:\r\n print('*************')\r\n print(self.name + \"'s\", 'balance is at:', self.balance)\r\n amount = input('Enter amount you would like to bet: ')\r\n try:\r\n amount = int(amount)\r\n if amount <= 0:\r\n print('*************')\r\n print('Amount must be greater than 0.')\r\n elif amount > self.balance:\r\n print('*************')\r\n print('Amount must be less than or equal to balance.')\r\n else:\r\n break\r\n except:\r\n print('*************')\r\n print('Amount must be an integer')\r\n continue\r\n amount = int(amount)\r\n self.balance -= amount\r\n return amount\r\n\r\n def call(self, bet):\r\n self.balance -= bet\r\n print(self.name, 'calls.')\r\n\r\n def organize_hand(self):\r\n for card in self.hand:\r\n rank = card.rank\r\n suit = card.suit\r\n if rank not in self.rank_org:\r\n self.rank_org[rank] = 1\r\n else:\r\n self.rank_org[rank] += 1\r\n \r\n if suit not in self.suit_org:\r\n self.suit_org[suit] = 1\r\n else:\r\n self.suit_org[suit] += 1\r\n print(self.rank_org)\r\n print(self.suit_org,self.name)\r\n\r\n def eval_hand(self):\r\n pair_count = 0\r\n for rank in self.rank_org:\r\n if self.rank_org[rank] == 2:\r\n self.hand_rank['P'] = True\r\n pair_count += 1\r\n \r\n if pair_count == 2:\r\n self.hand_rank['TP'] = True\r\n \r\n if self.rank_org[rank] == 3:\r\n self.hand_rank['TK'] = True\r\n\r\n if self.rank_org[rank] == 4:\r\n self.hand_rank['FK'] = True\r\n\r\n if self.hand_rank['TK'] == True and self.hand_rank['P'] == True:\r\n self.hand_rank['FH'] = True\r\n \r\n straight = self.is_straight()\r\n if straight:\r\n self.hand_rank['S'] = True\r\n\r\n for suit in self.suit_org:\r\n if self.suit_org[suit] >= 5:\r\n self.hand_rank['FL'] = True\r\n \r\n \r\n def get_hand(self):\r\n self.organize_hand()\r\n self.eval_hand()\r\n \r\n print(self.hand_rank, '\\n')\r\n\r\n def is_straight(self):\r\n \r\n straight_ranks = []\r\n \r\n for rank in self.rank_org.keys():\r\n if rank == 'A':\r\n straight_ranks.append(1)\r\n straight_ranks.append(14)\r\n elif rank == 'K':\r\n straight_ranks.append(13)\r\n elif rank == 'Q':\r\n straight_ranks.append(12)\r\n elif rank == 'J':\r\n straight_ranks.append(11)\r\n else:\r\n num = int(rank)\r\n straight_ranks.append(num)\r\n straight_ranks.sort()\r\n count = 0\r\n \r\n for rank in range(len(straight_ranks) - 1):\r\n current = straight_ranks[rank]\r\n next_r = straight_ranks[rank + 1]\r\n if next_r == current + 1:\r\n count += 1\r\n else:\r\n count = 0\r\n if count >= 5:\r\n return True\r\n return False\r\n \r\n\r\nclass Game:\r\n\r\n def __init__(self, players):\r\n self.deck = Deck()\r\n self.community = []\r\n self.players = players\r\n self.num_players = len(players)\r\n self.pot = 0\r\n self.turn_num = 0\r\n self.winner = None\r\n\r\n def deal_hand(self):\r\n for player in self.players:\r\n print('*************')\r\n print('Player:', str(player) + \"'s\",'hand is:')\r\n for card in range(2):\r\n current = self.deck.deal_card()\r\n player.hand.append(current)\r\n\r\n def deal_turn(self):\r\n print('*************')\r\n print('Turn card is:')\r\n current = self.deck.deal_card()\r\n self.community.append(current)\r\n print('Cards are now:')\r\n for card in self.community:\r\n print(card)\r\n for player in self.players:\r\n player.hand.append(current)\r\n\r\n def deal_river(self):\r\n print('*************')\r\n print('River card is:')\r\n current = self.deck.deal_card()\r\n self.community.append(current)\r\n print('Cards are now:')\r\n for card in self.community:\r\n print(card)\r\n for player in self.players:\r\n player.hand.append(current)\r\n player.get_hand()\r\n #print(player.hand, player.name)\r\n \r\n def deal_flop(self):\r\n \r\n print('The Flop is:')\r\n for i in range(3):\r\n current = self.deck.deal_card()\r\n self.community.append(current)\r\n for player in self.players:\r\n player.hand.append(current)\r\n print(player.hand, player.name)\r\n\r\n def to_act(self):\r\n \r\n if self.num_players == 0:\r\n self.winner = self.players[0]\r\n \r\n if self.winner is not None:\r\n print(self.winner, 'wins!')\r\n self.winner.balance += self.pot\r\n print(self.winner, 'won', self.pot)\r\n print(self.winner + 's', 'balance is now:', self.winner.balance)\r\n \r\n while self.turn_num < self.num_players:\r\n print('*************')\r\n print('Player:', str(self.players[self.turn_num]),'to act.')\r\n action = input('Type B to bet or C to check: ').upper()\r\n \r\n if action == 'B':\r\n bet = self.players[self.turn_num].bet()\r\n self.pot += bet\r\n print('*************')\r\n print(self.players[self.turn_num], 'bets.')\r\n print('Pot is now at:', self.pot)\r\n self.to_call(bet)\r\n \r\n elif action == 'C':\r\n print('*************')\r\n print(self.players[self.turn_num],'checks.')\r\n self.turn_num += 1\r\n \r\n self.turn_num = 0\r\n\r\n def to_call(self, new_bet):\r\n self.turn_num += 1\r\n for i in range(self.num_players - 1):\r\n if self.turn_num >= self.num_players:\r\n self.turn_num = 0\r\n print('*************')\r\n print('Player:', str(self.players[self.turn_num]),'to call.')\r\n print('Balance is:', self.players[self.turn_num].balance)\r\n while True:\r\n action = input('Type C to call, F to fold, R to re-raise: ').upper()\r\n if action == 'C':\r\n self.pot += new_bet\r\n self.players[self.turn_num].call(new_bet)\r\n print('*************')\r\n print('Pot is now at:', self.pot)\r\n break\r\n \r\n elif action == 'F':\r\n print('*************')\r\n print(str(self.players[self.turn_num]), \"folds.\")\r\n self.num_players -= 1\r\n self.players.remove(self.players[self.turn_num])\r\n self.turn_num -= 1\r\n break\r\n \r\n elif action == 'R':\r\n previous_bet = new_bet\r\n new_bet = self.players[self.turn_num].bet()\r\n self.pot += previous_bet\r\n print('*************')\r\n print('Pot is now at:', self.pot)\r\n self.to_call(new_bet, initial_better, previous_bet, j + 1)\r\n break\r\n self.turn_num += 1\r\n self.turn_num = self.num_players\r\n \r\n \r\n \r\ngame = Game([Player(\"Jarett\"), Player(\"Audrey\"), Player(\"Stefan\")])\r\ngame.deal_hand()\r\n#game.to_act()\r\ngame.deal_flop()\r\n#game.to_act()\r\ngame.deal_turn()\r\n#game.to_act()\r\ngame.deal_river()\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","sub_path":"Poker.py","file_name":"Poker.py","file_ext":"py","file_size_in_byte":9681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"639807650","text":"from __future__ import absolute_import\n\nimport tensorflow as tf\nimport logging\nimport os\n\nfrom ae import AE\nfrom load_data import load_data\n\n### ===== Set FLAGS ===== ###\nflags = tf.app.flags\nflags.DEFINE_string(\"model\", \"VAE_GAN\", \"Model to run [AE, VAE, VAE_GAN]\")\n\nflags.DEFINE_integer(\"epoch\", 100, \"Epoch to train [100]\")\nflags.DEFINE_float(\"learning_rate\", 0.0001, \"Learning rate [0.0001]\")\nflags.DEFINE_integer(\"batch_size\", 512, \"Batch size [512]\")\nflags.DEFINE_integer(\"batch_logging_step\", 100, \"Logging step for batch [100]\")\nflags.DEFINE_integer(\"epoch_logging_step\", 1, \"Logging step for epoch [1]\") # Need?\n\nflags.DEFINE_integer(\"input_dim\", 24000, \"Dimension of input [24000]\")\nflags.DEFINE_string(\"ae_h_dim_list\", \"[2048]\", \"List of AE dimensions [2048]\")\nflags.DEFINE_integer(\"z_dim\", 128, \"Dimension of z [128]\")\nflags.DEFINE_string(\"dis_h_dim_list\", \"[2048]\", \"List of Discriminator dimension [2048]\")\n\nflags.DEFINE_integer(\"gpu_id\", 0, \"GPU id [0]\")\nflags.DEFINE_string(\"data_dir\", \"data\", 'Directory name to load input data [data]')\nflags.DEFINE_string(\"checkpoint_dir\", \"checkpoint\", \"Directory name to save the checkpoints [checkpoint]\")\nflags.DEFINE_string(\"log_dir\", \"log\", \"Directory name to save the logs [log]\")\nflags.DEFINE_boolean(\"is_train\", False, \"True for training, False for testing [Fasle]\")\nflags.DEFINE_boolean(\"continue_train\", None,\n \"True to continue training from saved checkpoint. False for restarting. None for automatic [None]\")\nFLAGS = flags.FLAGS\n\n### ===== Set logger ===== ###\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\nsh = logging.StreamHandler()\nfh = logging.FileHandler(FLAGS.log_dir)\n\nfmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s')\nsh.setFormatter(fmt)\nfh.setFormatter(fmt)\n\nlogger.addHandler(sh)\nlogger.addHandler(fh)\n\n\ndef main(_):\n #print(FLAGS.__flags)\n file_name = 'm[' + FLAGS.model + ']_lr[' + str(FLAGS.learning_rate) + ']_b[' + str(FLAGS.batch_size) + \\\n ']_ae' + FLAGS.ae_h_dim_list + '_z[' + str(FLAGS.z_dim) + ']_dis' + FLAGS.dis_h_dim_list\n logger.info(file_name)\n\n with tf.device('/gpu:%d' % FLAGS.gpu_id):\n ### ===== Build model ===== ###\n if FLAGS.model == \"AE\":\n logger.info(\"Build AE model\")\n model = AE(logger, FLAGS.learning_rate, FLAGS.input_dim, FLAGS.z_dim, eval(FLAGS.ae_h_dim_list))\n\n elif FLAGS.model == \"VAE\":\n logger.info(\"Build VAE model\")\n\n elif FLAGS.model == \"VAE_GAN\":\n logger.info(\"Build VAE_GAN model\")\n\n\n ### ===== Train/Test =====###\n\n if FLAGS.is_train:\n #logger.info(\"Start training\")\n train_data = load_data(os.path.join(FLAGS.data_dir, 'train_data.npy'))\n val_data = load_data(os.path.join(FLAGS.data_dir, 'val_data.npy'))\n #print(train_data.shape)\n model.train(train_data, FLAGS.batch_size)\n else:\n logger.info(\"Start testing\")\n test_data = load_data(os.path.join(FLAGS.data_dir, 'test_data.npy'))\n\n\nif __name__ == '__main__':\n tf.app.run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"484416394","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root:\n return []\n dic = dict()\n ret = []\n queue = [[root, 1]]\n while len(queue) > 0:\n root, level = queue[0]\n del queue[0]\n if root.left:\n queue.append([root.left, level + 1])\n if root.right:\n queue.append([root.right, level + 1])\n if not dic.has_key(level):\n ret.append([root.val])\n dic[level] = 1\n else:\n ret[-1].append(root.val)\n return ret","sub_path":"lc102.py","file_name":"lc102.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"361958267","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 30 13:43:55 2020\n\n@author: loris\n\nFaça um Programa que leia 20 números inteiros e armazene-os num vetor. \nArmazene os números pares no vetor PAR e os números IMPARES no vetor impar. \nImprima os três vetores.\n\n\"\"\"\n\n\nvalores = []\npares = []\nimpares = []\n\nfor n in range(0,10):\n ent = int(input(\"Digite um numero: \"))\n valores.append(ent)\n\nfor n in valores:\n if n % 2 == 0:\n pares.append(n)\n else:\n impares.append(n)\n\nprint(\"VALORES: \")\nprint(valores)\nprint(\"PARES: \")\nprint(pares)\nprint(\"ÍMPARES: \")\nprint(impares)","sub_path":"4 - Listas/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"45836140","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 24 12:41:05 2020\r\n\r\n@author: quasi-researcher\r\n\"\"\"\r\n\r\nimport sys\r\n\r\ndef lsb_zeroes(num):\r\n if num == 0:\r\n return 32 # default for 32 bit integer\r\n p = 0\r\n while (num >> p) & 1 == 0:\r\n p += 1\r\n return p\r\n\r\nk=5 # number (power of two) of buckets to average the estimate\r\nnum_buckets = 2 ** k\r\nmax_zeroes = [0] * num_buckets\r\ntwo_r = [0] * num_buckets\r\nwith open(r'loglog.txt', 'r') as sf:\r\n n = sf.readline()\r\n n = int(n)\r\n i = 0\r\n small = True\r\n s = set()\r\n for i in range(n):\r\n req=sf.readline()\r\n if i < 1000:\r\n if req not in s:\r\n s.add(req)\r\n i+=1\r\n else:\r\n small=False\r\n \r\n h = hash(req)\r\n bucket = h & (num_buckets - 1) # create bucket ID\r\n bucket_hash = h >> k\r\n max_zeroes[bucket] = max(max_zeroes[bucket], lsb_zeroes(bucket_hash))\r\n two_r[bucket]=2 ** (-max_zeroes[bucket])\r\n if small:\r\n print(len(s))\r\n else:\r\n print(int(2 ** (float(sum(max_zeroes)) / num_buckets) * num_buckets * 0.79402))\r\n\r\n\r\n","sub_path":"LogLog.py","file_name":"LogLog.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"647948012","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\nimport os\r\nimport log as log\r\n\r\n\"Setup - Configurable parameters\"\r\ngoogledocs = \"Amedia PID WP8\"\r\nprefixtitelcolumn = \"Visiolink prefix\"\r\nurldocs = \"https://docs.google.com/spreadsheets/d/1WhbzQ2XvqOo_6R-twjdm7Z8FT1AGrq9QHe-7Ze3VwYk/edit#gid=494592811\"\r\ndashboardWindow = \"Windows Phone Dev Center\"\r\ntempfileName = \"temp.txt\"\r\ntempfileName2 = \"temp2.txt\"\r\nxapfolder = \"/Bin/ARM/Release\"\r\nmaxAmountKeywords = 5\r\nsleepTime = 60\r\n#Tab nr. til hvor google docs skal starte til næste run.\r\ndocsresetnum = 15\r\n#docsresetnum = 3\r\n\r\nInAppAlias = \"Enkelt kjøp\"\r\nInAppProductIdentifier = \"PurchaseSingleDay\"\r\nInAppTag = \"Amedia\"\r\n\r\n\"Directory from where this script is located\"\r\nrootdir = os.path.dirname(os.path.realpath(__file__))\r\nos.chdir(rootdir)\r\n\r\nglobal debugCounter\r\ndebugCounter = 13\r\n\r\nglobal startUpFlag\r\nstartUpFlag = True\r\n\r\nglobal endFlag\r\nendFlag = False\r\n\r\ndef startUserInput():\r\n global submittype\r\n submittype = log.printMessage(\"Choose submit type: 'b' for beta or 'l' for live\\n\", True)\r\n\r\n if submittype == 'b':\r\n c = log.printMessage(\"How many beta testers? (Type a number)\\n\", True)\r\n i = 1\r\n failureString = \"Write E-mails without non-ascii characthers like æ,ø,å\"\r\n log.printMessage(failureString.decode(\"utf-8\").encode(\"iso-8859-1\"))\r\n global participants\r\n participants = []\r\n while(i <= int(c)):\r\n parti = log.printMessage(str(i)+\": \", True)\r\n participants.append(parti)\r\n i += 1\r\n \r\n global xappssubmits\r\n xappssubmits = int(log.printMessage(\"Type how many apps you wish to upload. (Type a number)\\n\", True))\r\n \r\n log.printMessage(\"Starting autoupload script...\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n startUserInput()\r\n execfile('savescreenshotWP.py')\r\n sleep(5)\r\n execfile('autosubmitWP.py')\r\n sleep(5)\r\n execfile('uploadimages.py')\r\n sleep(5)\r\n\r\n\r\n","sub_path":"WindowsPhone/main_WP8.py","file_name":"main_WP8.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"640393014","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport sys, os, re\nfrom collections import defaultdict\nfrom io import StringIO\n\nchain_seq_record = defaultdict(list) # { (chain, seq) : [record1, record2, ...]}\nfor line in open(sys.argv[1], 'r'):\n if line.startswith('>'):\n chain = line[1:6]\n elif re.match(r'[A-Z]', line[0]):\n seq = line.strip()\n elif re.match(r'[0-9]', line[0]):\n chain_seq_record[(chain, seq)].append(line.strip())\n\ntempIO = StringIO()\nfor k, v in chain_seq_record.items():\n header = '>' + k[0]\n seq = k[1]\n if len(v) == 1:\n record = reduce(lambda x, y : str(bin(int(x, 2) | int(y, 2))), v)\n elif len(v) >= 2:\n record = reduce(lambda x, y : str(bin(int(x, 2) | int(y, 2))), v)[2:].zfill(len(v[0]))\n tempIO.write(str('\\n'.join([header, seq, record]) + '\\n').decode('utf-8'))\n\ntempIO.seek(0)\nwith open(sys.argv[1], 'w') as outfile:\n outfile.write(tempIO.read())\n\n","sub_path":"modify_BS.py","file_name":"modify_BS.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"434197166","text":"import pandas as pd\nimport settings\nfrom datetime import datetime, date\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\nhandler = logging.FileHandler(settings.log_name)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\n\ndef update_document(df, output_file, spreadsheet):\n #full_df = pd.read_excel(output_file, spreadsheet, parse_dates=True)\n full_df = pd.read_excel(output_file,\n spreadsheet,\n index_col=0,\n date_format='dd.mm.yyyy')\n #\n # Reformat index from pd.tslib.Timestamp to datetime.date()\n format_index = []\n for x in full_df.index:\n if isinstance(x, pd.tslib.Timestamp):\n format_index.append(x.to_datetime().date())\n elif isinstance(x, datetime):\n format_index.append(x.date())\n else:\n format_index.append(x)\n full_df.index = format_index\n #\n # Updating new values\n for ddate in df.index:\n if ddate in full_df.index:\n logger.info('\\tDate {ddate} allready in document skipping'.format(ddate=ddate))\n else:\n full_df.loc[ddate] = df.loc[ddate]\n logger.info('\\tDate {ddate} insert into document'.format(ddate=ddate))\n for column in settings.df_columns + ['Total']:\n logger.info('\\t\\t{fname}: {fvalue}'.format(fname=column, fvalue=df.loc[ddate, column]))\n #\n # Insert empty ddates\n new_indicies = []\n current_range = [x for x in full_df.index if isinstance(x, date) and x is not pd.NaT]\n for ddate in pd.date_range(current_range[0], current_range[-1]):\n ddate = ddate.to_datetime().date()\n if not ddate in full_df.index:\n logger.info('\\tDate {ddate} skipped. Add empty row'.format(ddate=ddate))\n new_indicies.append(ddate)\n #\n # Drop duplicates if exists\n full_df = full_df.reset_index().drop_duplicates(subset='index', take_last=True).set_index('index')\n #\n # Reindex with missed days\n full_df = full_df.reindex(new_indicies)\n writer = pd.ExcelWriter(output_file,\n engine='xlsxwriter',\n date_format='dd mmmm yyyy')\n full_df.to_excel(writer, spreadsheet)\n writer.save()\n logger.info('Excel document {document} successfully saved'.format(document=output_file))\n\n\ndef update_order_document(order, output_file, spreadsheet):\n df = pd.read_excel(\n output_file,\n spreadsheet\n )\n df = df.append(dict(order), ignore_index=True)\n #df = df.reset_index()\n df = df.drop_duplicates(subset='Case:', keep='last')\n #df = df.set_index('index')\n writer = pd.ExcelWriter(\n output_file,\n engine='xlsxwriter',\n date_format='dd mmmm yyyy'\n )\n df.to_excel(writer, spreadsheet, index=False)\n writer.save()\n logger.info(\n 'Excel document {document} successfully saved'.\n format(document=output_file)\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"post_australia/update_document.py","file_name":"update_document.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"410956184","text":"from ocelot.task.readcif import ReadCif\nimport numpy as np\nimport sys\n\n__author__ = 'Vinayak Bhat'\n\n\ndef make_gro(location,code_name):\n\n # read the cif file and select a clean structure\n rc = ReadCif.from_ciffile(location,\"\")\n rc.read()\n config = rc.results[\"configurations\"][0]\n pstructure = config.pstructure\n\n # get the molecules\n mols = config.molconformers\n\n # get number of atoms in unit cell and in a molecule\n num_atoms = len(pstructure.sites)\n mol_atoms = len(mols[0].pmgmol)\n\n # lattice parameters for periodic box\n flat_lattice = list(np.concatenate(list(pstructure.lattice.as_dict()[\"matrix\"])).flat)\n lattice_order = [0,4,8,1,2,3,5,6,7]\n flat_lattice = [flat_lattice[i] for i in lattice_order]\n\n # write the periodic and molecular gro files\n periodic_file = open(\"{}.gro\".format(code_name),\"w\")\n molecule_file = open(\"{}_mol.gro\".format(code_name), \"w\")\n\n # first two lines of the gro file\n atoms_counter = 1\n print(code_name,file=periodic_file)\n print(str(num_atoms), file=periodic_file)\n print(code_name,file=molecule_file)\n print(str(mol_atoms), file=molecule_file)\n\n # adding the atomic coordinates\n for mol_idx, mol in enumerate(mols):\n for site in mol.sites:\n element_name = site.specie.name\n coord_string = \"{}{}{}\".format(format(site.coords[0] /10,\"8.3f\"), format(site.coords[1]/10,\"8.3f\"), format(site.coords[2]/10,\"8.3f\"))\n res_name = str(mol_idx + 1) + code_name\n atom_number = str(atoms_counter)\n site_string = \"{0:>8s}{1:>5s}{2:>5s}{3}\".format(res_name, element_name, atom_number, coord_string)\n print(site_string,file=periodic_file)\n if mol_idx == 0:\n print(site_string, file=molecule_file)\n atoms_counter += 1\n\n # add the box dimensions\n lattice_string = \"\"\n for lattice in flat_lattice:\n lattice_string += format(lattice/10,'.5f') + \" \"\n print(lattice_string,file=periodic_file)\n print(\"5.0 5.0 5.0\", file=molecule_file)\n\n # close the files\n periodic_file.close()\n molecule_file.close()\n mols[0].pmgmol.to(fmt=\"xyz\",filename=\"{}_mol.xyz\".format(code_name))\n\nif __name__ == \"__main__\":\n location = sys.argv[1]\n code_name = sys.argv[2]\n make_gro(location,code_name)\n\n","sub_path":"cif2gro.py","file_name":"cif2gro.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"439868775","text":"from torch.utils.data import Dataset\nimport os\nimport glob\n\nclass VOC_Dataset(Dataset):\n class_names = ('aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat', 'chair',\n 'cow', 'diningtable', 'dog', 'horse',\n 'motorbike', 'person', 'pottedplant',\n 'sheep', 'sofa', 'train', 'tvmonitor')\n\n def __init__(self, root='/mnt/mydisk/hdisk/dataset/VOCdevkit', mode='TRAIN', year = 'VOC2007'):\n super(VOC_Dataset, self).__init__()\n\n root = os.path.join(root, mode, year)\n\n # VOC data image, annotation list 불러오\n self.img_list = sorted(glob.glob(os.path.join(root, 'JPEGImages/*.jpg')))\n self.anno_list = sorted(glob.glob(os.path.join(root, 'Annotations/*.xml')))\n self.classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow',\n 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train',\n 'tvmonitor']\n\n self.class_dict = {class_name: i for i, class_name in enumerate(self.class_names)}\n self.class_dict_inv = {i: class_name for i, class_name in enumerate(self.class_names)}\n\n print(len(self.anno_list))\n\n def __len__(self):\n return self.img_list\n\nif __name__ == '__main__':\n train_dataset = VOC_Dataset(root='/mnt/mydisk/hdisk/dataset/VOCdevkit', mode='TRAIN', year='VOC2007')","sub_path":"dataset/voc_dataset.py","file_name":"voc_dataset.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"464730047","text":"def persistence(n): \n if(n<10):\n print(0)\n count=0\n while(n>=10):\n strNum= str(n)\n endFor=len(strNum)\n numList=[]\n for i in range(0, endFor):\n numList.append(strNum[i:i+1])\n n=1\n for i in range(0, len(numList)):\n tempInt=int(numList[i])\n n*=tempInt\n count+=1\n return count\n","sub_path":"persistent-bugger.py","file_name":"persistent-bugger.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"583930619","text":"from github import Github\r\nimport unicodedata\r\nimport base64\r\nimport codecs\r\nimport csv\r\nimport xml.etree.ElementTree as et\r\n\r\n\r\ng3 = Github(\"claudioDsi\",\"github17\",per_page=100)\r\ng = Github(\"7dd09093da17523189a8686362f276756aed5fd5\", per_page=100)\r\n\r\ndef get_single_pom(groupdId, artifactId):\r\n out = open(\"repos_pom.txt\", \"a+\", encoding=\"utf-8\", errors=\"ignore\")\r\n out2 = open(\"repos_pom2.txt\", \"a+\", encoding=\"utf-8\", errors=\"ignore\")\r\n list_repo = g.search_repositories(query=\"language:java stars:>1000 \" + groupdId + \" \" + artifactId)\r\n flag = False\r\n for repo_name in list_repo:\r\n\r\n content = g.get_repo(repo_name.full_name).get_contents(path=\"\")\r\n groupid=False\r\n artifact=False\r\n for file in content:\r\n # print(file.name)\r\n if str(file.name) == \"pom.xml\":\r\n # out.write(str(file.decoded_content))\r\n s = file.decoded_content\r\n root = et.fromstring(s)\r\n print(s)\r\n for childe in root.findall(\"{http://maven.apache.org/POM/4.0.0}groupId\"):\r\n print(childe.text)\r\n if childe.text == groupdId:\r\n groupid = True\r\n for childe in root.findall(\"{http://maven.apache.org/POM/4.0.0}artifactId\"):\r\n print(childe.text)\r\n if childe.text == artifactId:\r\n artifact = True\r\n\r\n if artifact and groupid:\r\n out.write(str(repo_name.full_name))\r\n print(\"write file\")\r\n break\r\n\r\n if artifactId and not groupdId:\r\n out2.write(str(repo_name.full_name))\r\n print(\"write file\")\r\n break\r\n\r\ndef get_issue():\r\n out=open(\"repos_pom.txt\", \"a+\", encoding=\"utf-8\", errors=\"ignore\")\r\n\r\n\r\n list_repo=g3.search_repositories(query=\"language:java \")\r\n flag=False\r\n for repo_name in list_repo:\r\n content = g3.get_repo(repo_name.full_name).get_contents(path=\"\")\r\n for file in content:\r\n #print(file.name)\r\n if str(file.name) == \"pom.xml\":\r\n #out.write(str(file.decoded_content))\r\n s=file.decoded_content\r\n root=et.fromstring(s)\r\n\r\n\r\n for childe in root.findall(\"groupId\"):\r\n print(childe.text)\r\n\r\n\r\n # if str(childe.tag) == \"{http://maven.apache.org/POM/4.0.0}groupId\":\r\n # for elem in childe:\r\n # print(elem.tag)\r\n # if elem.tag == \"org.apache.commons\":\r\n # out.write(repo_name.full_name+\"\\n\")\r\n # print(\"write file\")\r\n # flag=True\r\n # else:\r\n # print(\"no\")\r\n if flag:\r\n break\r\n # stripped = lambda s: \"\".join(i for i in s if 31 < ord(i) < 127)\r\n # print(stripped(s))\r\n\r\ndef remove_control_characters(s):\r\n return \"\".join(ch for ch in s if unicodedata.category(ch)[0] != \"C\")\r\n\r\ndef clean_file(pom_file):\r\n begin=codecs.open(pom_file, \"r\", encoding=\"base-64\", errors=\"strict\")\r\n out=open(\"parsed_pom.txt\", \"w\", encoding=\"utf-8\", errors=\"ignore\")\r\n lines=begin.read()\r\n\r\n print(base64.b64decode(lines))\r\n\r\n\r\n\r\n\r\ndef parsing_csv():\r\n libname=\"\"\r\n with open('C:\\\\Users\\\\claudio\\\\Desktop\\\\result_def2.csv') as csv_file:\r\n csv_reader = csv.reader(csv_file, delimiter=';')\r\n line_count = 0\r\n for row in csv_reader:\r\n if line_count == 0:\r\n print(f'Column names are {\", \".join(row)}')\r\n line_count += 1\r\n else:\r\n #print(f'{row[1]} {row[2]}')\r\n libname=str(row[1])\r\n groupId=(str(row[2]).replace(\"/artifact/\",\"\").split(\"/\")[0])\r\n artifactId=(str(row[2]).replace(\"/artifact/\",\"\").split(\"/\")[1])\r\n\r\n print(artifactId)\r\n get_single_pom(groupId, artifactId)\r\n line_count += 1\r\n print(f'Processed {line_count} lines.')\r\n\r\n#get_single_pom(\"org.reflections\",\"reflections-maven\")\r\nparsing_csv()","sub_path":"MNB_code/mavenMapping.py","file_name":"mavenMapping.py","file_ext":"py","file_size_in_byte":4220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"567652889","text":"# coding=UTF-8\n# **********************************************************************\n# Copyright (c) 2013-2017 Cisco Systems, Inc. All rights reserved\n# written by zen warriors, do not modify!\n# **********************************************************************\n\n\nfrom cobra.mit.meta import ClassMeta\nfrom cobra.mit.meta import StatsClassMeta\nfrom cobra.mit.meta import CounterMeta\nfrom cobra.mit.meta import PropMeta\nfrom cobra.mit.meta import Category\nfrom cobra.mit.meta import SourceRelationMeta\nfrom cobra.mit.meta import NamedSourceRelationMeta\nfrom cobra.mit.meta import TargetRelationMeta\nfrom cobra.mit.meta import DeploymentPathMeta, DeploymentCategory\nfrom cobra.model.category import MoCategory, PropCategory, CounterCategory\nfrom cobra.mit.mo import Mo\n\n\n# ##################################################\nclass CPUHist(Mo):\n meta = StatsClassMeta(\"cobra.model.proc.CPUHist\", \"CPU utilization\")\n\n counter = CounterMeta(\"current\", CounterCategory.GAUGE, \"percentage\", \"CPU usage\")\n counter._propRefs[PropCategory.IMPLICIT_MIN] = \"currentMin\"\n counter._propRefs[PropCategory.IMPLICIT_MAX] = \"currentMax\"\n counter._propRefs[PropCategory.IMPLICIT_AVG] = \"currentAvg\"\n counter._propRefs[PropCategory.IMPLICIT_SUSPECT] = \"currentSpct\"\n counter._propRefs[PropCategory.IMPLICIT_THRESHOLDED] = \"currentThr\"\n counter._propRefs[PropCategory.IMPLICIT_TREND] = \"currentTr\"\n meta._counters.append(counter)\n\n meta.isAbstract = True\n meta.moClassName = \"procCPUHist\"\n\n\n meta.moClassName = \"procCPUHist\"\n meta.rnFormat = \"\"\n meta.category = MoCategory.STATS_HISTORY\n meta.label = \"historical CPU utilization stats\"\n meta.writeAccessMask = 0x1\n meta.readAccessMask = 0x1\n meta.isDomainable = False\n meta.isReadOnly = True\n meta.isConfigurable = False\n meta.isDeletable = False\n meta.isContextRoot = False\n\n meta.superClasses.add(\"cobra.model.stats.Item\")\n meta.superClasses.add(\"cobra.model.stats.Hist\")\n\n meta.concreteSubClasses.add(\"cobra.model.proc.CPUHist1d\")\n meta.concreteSubClasses.add(\"cobra.model.proc.CPUHist5min\")\n meta.concreteSubClasses.add(\"cobra.model.proc.CPUHist1year\")\n meta.concreteSubClasses.add(\"cobra.model.proc.CPUHist1qtr\")\n meta.concreteSubClasses.add(\"cobra.model.proc.CPUHist1h\")\n meta.concreteSubClasses.add(\"cobra.model.proc.CPUHist1mo\")\n meta.concreteSubClasses.add(\"cobra.model.proc.CPUHist1w\")\n meta.concreteSubClasses.add(\"cobra.model.proc.CPUHist15min\")\n\n meta.rnPrefixes = [\n ]\n\n prop = PropMeta(\"str\", \"childAction\", \"childAction\", 4, PropCategory.CHILD_ACTION)\n prop.label = \"None\"\n prop.isImplicit = True\n prop.isAdmin = True\n prop._addConstant(\"deleteAll\", \"deleteall\", 16384)\n prop._addConstant(\"deleteNonPresent\", \"deletenonpresent\", 8192)\n prop._addConstant(\"ignore\", \"ignore\", 4096)\n meta.props.add(\"childAction\", prop)\n\n prop = PropMeta(\"str\", \"cnt\", \"cnt\", 16212, PropCategory.REGULAR)\n prop.label = \"Number of Collections During this Interval\"\n prop.isImplicit = True\n prop.isAdmin = True\n meta.props.add(\"cnt\", prop)\n\n prop = PropMeta(\"str\", \"currentAvg\", \"currentAvg\", 10476, PropCategory.IMPLICIT_AVG)\n prop.label = \"CPU usage average value\"\n prop.isOper = True\n prop.isStats = True\n meta.props.add(\"currentAvg\", prop)\n\n prop = PropMeta(\"str\", \"currentMax\", \"currentMax\", 10475, PropCategory.IMPLICIT_MAX)\n prop.label = \"CPU usage maximum value\"\n prop.isOper = True\n prop.isStats = True\n meta.props.add(\"currentMax\", prop)\n\n prop = PropMeta(\"str\", \"currentMin\", \"currentMin\", 10474, PropCategory.IMPLICIT_MIN)\n prop.label = \"CPU usage minimum value\"\n prop.isOper = True\n prop.isStats = True\n meta.props.add(\"currentMin\", prop)\n\n prop = PropMeta(\"str\", \"currentSpct\", \"currentSpct\", 10477, PropCategory.IMPLICIT_SUSPECT)\n prop.label = \"CPU usage suspect count\"\n prop.isOper = True\n prop.isStats = True\n meta.props.add(\"currentSpct\", prop)\n\n prop = PropMeta(\"str\", \"currentThr\", \"currentThr\", 10478, PropCategory.IMPLICIT_THRESHOLDED)\n prop.label = \"CPU usage thresholded flags\"\n prop.isOper = True\n prop.isStats = True\n prop.defaultValue = 0\n prop.defaultValueStr = \"unspecified\"\n prop._addConstant(\"avgCrit\", \"avg-severity-critical\", 2199023255552)\n prop._addConstant(\"avgHigh\", \"avg-crossed-high-threshold\", 68719476736)\n prop._addConstant(\"avgLow\", \"avg-crossed-low-threshold\", 137438953472)\n prop._addConstant(\"avgMajor\", \"avg-severity-major\", 1099511627776)\n prop._addConstant(\"avgMinor\", \"avg-severity-minor\", 549755813888)\n prop._addConstant(\"avgRecovering\", \"avg-recovering\", 34359738368)\n prop._addConstant(\"avgWarn\", \"avg-severity-warning\", 274877906944)\n prop._addConstant(\"cumulativeCrit\", \"cumulative-severity-critical\", 8192)\n prop._addConstant(\"cumulativeHigh\", \"cumulative-crossed-high-threshold\", 256)\n prop._addConstant(\"cumulativeLow\", \"cumulative-crossed-low-threshold\", 512)\n prop._addConstant(\"cumulativeMajor\", \"cumulative-severity-major\", 4096)\n prop._addConstant(\"cumulativeMinor\", \"cumulative-severity-minor\", 2048)\n prop._addConstant(\"cumulativeRecovering\", \"cumulative-recovering\", 128)\n prop._addConstant(\"cumulativeWarn\", \"cumulative-severity-warning\", 1024)\n prop._addConstant(\"lastReadingCrit\", \"lastreading-severity-critical\", 64)\n prop._addConstant(\"lastReadingHigh\", \"lastreading-crossed-high-threshold\", 2)\n prop._addConstant(\"lastReadingLow\", \"lastreading-crossed-low-threshold\", 4)\n prop._addConstant(\"lastReadingMajor\", \"lastreading-severity-major\", 32)\n prop._addConstant(\"lastReadingMinor\", \"lastreading-severity-minor\", 16)\n prop._addConstant(\"lastReadingRecovering\", \"lastreading-recovering\", 1)\n prop._addConstant(\"lastReadingWarn\", \"lastreading-severity-warning\", 8)\n prop._addConstant(\"maxCrit\", \"max-severity-critical\", 17179869184)\n prop._addConstant(\"maxHigh\", \"max-crossed-high-threshold\", 536870912)\n prop._addConstant(\"maxLow\", \"max-crossed-low-threshold\", 1073741824)\n prop._addConstant(\"maxMajor\", \"max-severity-major\", 8589934592)\n prop._addConstant(\"maxMinor\", \"max-severity-minor\", 4294967296)\n prop._addConstant(\"maxRecovering\", \"max-recovering\", 268435456)\n prop._addConstant(\"maxWarn\", \"max-severity-warning\", 2147483648)\n prop._addConstant(\"minCrit\", \"min-severity-critical\", 134217728)\n prop._addConstant(\"minHigh\", \"min-crossed-high-threshold\", 4194304)\n prop._addConstant(\"minLow\", \"min-crossed-low-threshold\", 8388608)\n prop._addConstant(\"minMajor\", \"min-severity-major\", 67108864)\n prop._addConstant(\"minMinor\", \"min-severity-minor\", 33554432)\n prop._addConstant(\"minRecovering\", \"min-recovering\", 2097152)\n prop._addConstant(\"minWarn\", \"min-severity-warning\", 16777216)\n prop._addConstant(\"periodicCrit\", \"periodic-severity-critical\", 1048576)\n prop._addConstant(\"periodicHigh\", \"periodic-crossed-high-threshold\", 32768)\n prop._addConstant(\"periodicLow\", \"periodic-crossed-low-threshold\", 65536)\n prop._addConstant(\"periodicMajor\", \"periodic-severity-major\", 524288)\n prop._addConstant(\"periodicMinor\", \"periodic-severity-minor\", 262144)\n prop._addConstant(\"periodicRecovering\", \"periodic-recovering\", 16384)\n prop._addConstant(\"periodicWarn\", \"periodic-severity-warning\", 131072)\n prop._addConstant(\"rateCrit\", \"rate-severity-critical\", 36028797018963968)\n prop._addConstant(\"rateHigh\", \"rate-crossed-high-threshold\", 1125899906842624)\n prop._addConstant(\"rateLow\", \"rate-crossed-low-threshold\", 2251799813685248)\n prop._addConstant(\"rateMajor\", \"rate-severity-major\", 18014398509481984)\n prop._addConstant(\"rateMinor\", \"rate-severity-minor\", 9007199254740992)\n prop._addConstant(\"rateRecovering\", \"rate-recovering\", 562949953421312)\n prop._addConstant(\"rateWarn\", \"rate-severity-warning\", 4503599627370496)\n prop._addConstant(\"trendCrit\", \"trend-severity-critical\", 281474976710656)\n prop._addConstant(\"trendHigh\", \"trend-crossed-high-threshold\", 8796093022208)\n prop._addConstant(\"trendLow\", \"trend-crossed-low-threshold\", 17592186044416)\n prop._addConstant(\"trendMajor\", \"trend-severity-major\", 140737488355328)\n prop._addConstant(\"trendMinor\", \"trend-severity-minor\", 70368744177664)\n prop._addConstant(\"trendRecovering\", \"trend-recovering\", 4398046511104)\n prop._addConstant(\"trendWarn\", \"trend-severity-warning\", 35184372088832)\n prop._addConstant(\"unspecified\", None, 0)\n meta.props.add(\"currentThr\", prop)\n\n prop = PropMeta(\"str\", \"currentTr\", \"currentTr\", 10479, PropCategory.IMPLICIT_TREND)\n prop.label = \"CPU usage trend\"\n prop.isOper = True\n prop.isStats = True\n meta.props.add(\"currentTr\", prop)\n\n prop = PropMeta(\"str\", \"dn\", \"dn\", 1, PropCategory.DN)\n prop.label = \"None\"\n prop.isDn = True\n prop.isImplicit = True\n prop.isAdmin = True\n prop.isCreateOnly = True\n meta.props.add(\"dn\", prop)\n\n prop = PropMeta(\"str\", \"index\", \"index\", 115, PropCategory.REGULAR)\n prop.label = \"History Index\"\n prop.isImplicit = True\n prop.isAdmin = True\n meta.props.add(\"index\", prop)\n\n prop = PropMeta(\"str\", \"lastCollOffset\", \"lastCollOffset\", 111, PropCategory.REGULAR)\n prop.label = \"Collection Length\"\n prop.isImplicit = True\n prop.isAdmin = True\n meta.props.add(\"lastCollOffset\", prop)\n\n prop = PropMeta(\"str\", \"repIntvEnd\", \"repIntvEnd\", 110, PropCategory.REGULAR)\n prop.label = \"Reporting End Time\"\n prop.isImplicit = True\n prop.isAdmin = True\n meta.props.add(\"repIntvEnd\", prop)\n\n prop = PropMeta(\"str\", \"repIntvStart\", \"repIntvStart\", 109, PropCategory.REGULAR)\n prop.label = \"Reporting Start Time\"\n prop.isImplicit = True\n prop.isAdmin = True\n meta.props.add(\"repIntvStart\", prop)\n\n prop = PropMeta(\"str\", \"rn\", \"rn\", 2, PropCategory.RN)\n prop.label = \"None\"\n prop.isRn = True\n prop.isImplicit = True\n prop.isAdmin = True\n prop.isCreateOnly = True\n meta.props.add(\"rn\", prop)\n\n prop = PropMeta(\"str\", \"status\", \"status\", 3, PropCategory.STATUS)\n prop.label = \"None\"\n prop.isImplicit = True\n prop.isAdmin = True\n prop._addConstant(\"created\", \"created\", 2)\n prop._addConstant(\"deleted\", \"deleted\", 8)\n prop._addConstant(\"modified\", \"modified\", 4)\n meta.props.add(\"status\", prop)\n\n def __init__(self, parentMoOrDn, markDirty=True, **creationProps):\n namingVals = []\n Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps)\n\n\n\n# End of package file\n# ##################################################\n","sub_path":"data/python/243.py","file_name":"243.py","file_ext":"py","file_size_in_byte":10593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"621197676","text":"import pandas as pd\nimport json,os,requests\nfrom website_cleaning_w_multiprocessing import url_count, add_www, check_http, check_ending\n\n# free trial API keys\n#API_KEY_BRAD1 = '0b2a3b7f884f30ae87ee66297887042833c0f28d'\n#API_KEY_BRAD2 = 'd6e978f8190dc948cd963c37676eafef49bcf61d'\n#API_KEY_BRAD3 = '3f434b56d33d24ffb6276e03b6c2a2a164b6216c'\n#API_KEY_TOM = '90f4337f2645885f3c44d6e6200c926614bcd70b'\nclass Hunter:\n \"\"\"\n get email addresses for all contacts\n \"\"\"\n def __init__(self, domain, first_name, last_name):\n self.domain=domain\n self.first_name=first_name\n self.last_name=last_name\n self.url='https://api.hunter.io/v2/email-finder?domain={}&first_name={}&last_name={}&api_key={}'\n\n def email(self):\n info = pd.DataFrame(requests.get(self.url.format(self.domain,self.first_name,self.last_name,API_KEY_TOM)).json())\n return info\n\ndef parse_fname(first_name):\n space_split = str(first_name).split(' ')\n if(len(space_split)>1):\n return space_split[0]\n elif str(first_name).isalpha():\n return first_name\n else:\n if '.' in first_name:\n return str(first_name).split('.')[0]\n else:\n return first_name\n\ndef parse_lname(last_name):\n space_split = last_name.split(' ')\n if(len(space_split)>1):\n return space_split[1]\n elif last_name.isalpha():\n return last_name\n else:\n if '.' in last_name:\n return last_name.split('.')[0]\n else:\n return last_name\n\ndef extract_domain(url):\n dot_split = url.split('.')\n if len(dot_split)>2:\n return dot_split[1]+'.'+dot_split[2]\n else:\n print(url)\n return url\n return domain\n\ndef test_request(url):\n try:\n r = requests.get(url)\n if(r.ok):\n return True\n else:\n return False\n except Exception as e:\n return False\n pass\n\ndef get_indices(company_name,df):\n row_indices=df.index[df['Primary Business Name']==company_name].to_list()\n return row_indices\n\ndef get_query_info(row_index,df):\n # rename based on the added column\n website = df['corrected_site'].iloc[row_index]\n fname = parse_fname(df['Contact person first name'].iloc[row_index])\n lname = df['Contact person last name'].iloc[row_index]\n return website,fname,lname\n\ndef get_emails(sample,df):\n total_email_count = 0\n found_person_info = {}\n websites=[]\n firstnames=[]\n lastnames=[]\n companynames = []\n stop = 0\n for company_name in sample.values:\n company_email_count = 0\n indices = get_indices(company_name,df)\n i = 0\n while(company_email_count==0 and i < len(indices) and total_email_count < 100):\n website,fname,lname=get_query_info(indices[i],df)\n i+=1\n if test_request(website):\n if total_email_count == 0: \n h = Hunter(extract_domain(website),fname,lname)\n emails = h.email()\n if ('data' in emails.columns):\n if(~pd.isnull(emails['data'].loc['email'])):\n websites.append(website)\n firstnames.append(fname)\n lastnames.append(lname)\n companynames.append(company_name)\n company_email_count+=1\n total_email_count+=1\n else:\n h = Hunter(extract_domain(website),fname, lname)\n emails_df = h.email()\n if ('data' in emails_df.columns): \n if(~pd.isnull(emails_df['data'].loc['email'])):\n print(\"emails pre-concat: \")\n print(emails)\n emails=pd.concat([emails,emails_df])\n print(\"emails post-concat: \")\n print(emails)\n websites.append(website)\n firstnames.append(fname)\n lastnames.append(lname)\n companynames.append(company_name)\n company_email_count+=1\n total_email_count+=1\n elif 'id' in emails_df.columns:\n stop = 1\n else:\n company_email_count = 1\n #print('companynames: ')\n #print(companynames)\n #print('firstnames: ')\n #print(firstnames)\n #print('lastnames: ')\n #print(lastnames)\n #print(\"company_email_count: \")\n #print(company_email_count)\n print(\"total_email_count: \")\n print(total_email_count)\n print('index value: i=')\n print(i)\n if total_email_count == 100 | stop == 1:\n break\n found_person_info['websites']=websites\n found_person_info['first_name']=firstnames\n found_person_info['last_name']=lastnames\n found_person_info['company_name']=companynames\n return emails,pd.DataFrame(found_person_info)\n\n# this returns the output in a simple table, but\n# doesn't filter out NaN emails so that you can see \n# roughly how many requests did not yield results\n\n# this function is giving trouble because it does not\n# recognizing 'index' as a column in the df, but when\n# it is left as a pandas index, it throws an exception\n# because there are duplicate indices\ndef format_output(df):\n lname = df[df['index']=='last_name']['data']\n fname = df[df['index']=='first_name']['data']\n company = df[df['index']=='company']['data']\n email = df[df['index']=='email']['data']\n score = df[df['index']=='score']['data']\n position = df[df['index']=='position']['data']\n phone_number = df[df['index']=='phone_number']['data']\n lname.reset_index(drop=True,inplace=True)\n fname.reset_index(drop=True,inplace=True)\n company.reset_index(drop=True,inplace=True)\n emails.reset_index(drop=True,inplace=True)\n score.reset_index(drop=True,inplace=True)\n position.reset_index(drop=True,inplace=True)\n phone_number.reset_index(drop=True,inplace=True)\n compiled_df = pd.concat([company,fname,lname,emails,position,phone_number,score],axis=1)\n compiled_df.columns = ['company_name','first_name','last_name','email','position', 'phone_number','score']\n return compiled_df\n\nif __name__=='__main__':\n cleansed_db = pd.read_csv('~/ria/ria_db_w_website_mapping.csv')\n # first, filter out those companies which we already have emails for\n cleansed_db['email_count'] = cleansed_db.groupby('Primary Business Name')['Contact person email'].transform('count')\n cleansed_db = cleansed_db[cleansed_db['email_count']==0]\n # next, filter out all of those companies without working websites\n cleansed_db= cleansed_db[cleansed_db['exception']==1]\n # next, filter out all companies with AUM < 25 million\n cleansed_db = cleansed_db[cleansed_db['Total AUM']>25000000]\n # after the db is updated with the hunter output from previous run,\n # add a filter for those that have been run through the email finder\n # so they don't get run through multiple times\n # cleansed_db = cleansed_db[cleansed_db['Hunter']==1]\n \n # extract sample \n cleansed_db.reset_index(drop=True,inplace=True)\n sample = pd.Series(list(cleansed_db.groupby('Primary Business Name').groups.keys()),name='Primary Business Name').sample(500)\n sample.to_csv('sample_to_test4.csv',columns = ['index_in_db','Primary Business Name'])\n emails,individuals = get_emails(sample,cleansed_db)\n emails.to_csv('safety_net_emails4.csv')\n individuals.to_csv('safety_net_individuals4.csv')\n emails.reset_index()\n formatted_emails = format_output(emails)\n\n # need to make sure these files do not override previous ones\n # these will be unique when the column for hunter is added and filtered on\n formatted_emails.to_csv('Hunter_email_responses_sample'+str(sample.index[0])+'4.csv')\n individuals.to_csv('hunter_contacts_pulled'+str(sample.index[0])+'4.csv')\n","sub_path":"ria/Hunter.py","file_name":"Hunter.py","file_ext":"py","file_size_in_byte":8130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"650842543","text":"\n#%%\n\nfrom sqlalchemy import create_engine\nengine = create_engine('postgresql+psycopg2://postgres:system@localhost/test')\nprint('connected')\n#%%\n\n\nfrom sqlalchemy.ext.automap import automap_base\n\nBase = automap_base()\nBase.prepare(engine, reflect=True)\n\nUsers = Base.classes.users\n\n\n#%%\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.orm import relationship\n\nBase = declarative_base()\n\nclass Email(Base):\n __tablename__ = 'email'\n\n id = Column(Integer, primary_key=True)\n user_id = Column(Integer, ForeignKey(Users.id))\n email_address = Column(String, nullable=False)\n\nBase.metadata.create_all(engine)\n\n#%%\n\nimport pandas as pd\n\ndata = pd.read_csv('sqlalchemy_tutorial/email.csv', header=0, names=['id','email'])\n\n#%%\n\nfrom sqlalchemy.orm import sessionmaker\n\nSession = sessionmaker(bind=engine)\nsession = Session()\nsession.rollback()\nfor index, d in data.iterrows():\n session.add(Email(user_id=d['id'], email_address=d['email']))\n\nsession.commit()\n#%%\n\n","sub_path":"sqlalchemy_tutorial/fake_email_loader.py","file_name":"fake_email_loader.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"214336190","text":"from tkinter import *\n\ntop = Tk()\nbtn1 = Button()\nbtn1.pack()\nbtn1['text'] = 'start'\nbtn1['activeforeground'] = 'pink'\n\n\ndef enter(event):\n btn1[\"text\"] = \"click me!\"\n\n\nprint(1 == 0)\n\n\ndef leave(event):\n btn1[\"text\"] = \"start\"\n\n\ndef clicked(event):\n btn1[\"text\"] = \"I was clicked!\"\n\n\nbtn1.bind('', enter)\nbtn1.bind(\"\", leave)\nbtn1.bind('', clicked)\n\ntop.mainloop()\n","sub_path":"Project/GUI programing/A_Crude_Text_editor.py","file_name":"A_Crude_Text_editor.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"447175276","text":"from flask import Blueprint, request, jsonify\nfrom dashboard.models import User\nfrom dashboard import db\nfrom dashboard.auth.utils import token_required\nimport uuid\nfrom werkzeug.security import generate_password_hash\n\nuser = Blueprint('user', __name__)\n\n\n@user.route('/users', methods=['GET'])\n@token_required\ndef get_all_users(current_user):\n \"\"\"\n Get all users\n \"\"\"\n if not current_user.admin:\n return jsonify({'message': 'Only admin user can perform this function!'}), 403\n\n users = User.query.all()\n output = []\n\n for user in users:\n user_data = {}\n user_data['public_id'] = user.public_id\n user_data['username'] = user.username\n user_data['email'] = user.email\n user_data['admin'] = user.admin\n user_data['active'] = user.active\n user_data['api_user'] = user.api_user\n output.append(user_data)\n\n return jsonify({'users': output})\n\n\n@user.route('/users/', methods=['GET'])\n@token_required\ndef get_one_user(current_user, public_id):\n \"\"\"\n Get one user against user id\n \"\"\"\n if not current_user.admin:\n return jsonify({'message': 'Only admin user can perform this function!'}), 403\n\n user = User.query.filter_by(public_id=public_id).first()\n if not user:\n return jsonify({'message': 'No user found!'})\n user_data = {}\n user_data['public_id'] = user.public_id\n user_data['username'] = user.username\n user_data['email'] = user.email\n user_data['admin'] = user.admin\n user_data['active'] = user.active\n user_data['api_user'] = user.api_user\n\n return jsonify({'user': user_data})\n\n\n@user.route('/users', methods=['POST'])\n@token_required\ndef create_user(current_user):\n \"\"\"\n Create user\n \"\"\"\n data = request.get_json()\n hashed_password = generate_password_hash(data['password'], method='sha256')\n\n new_user = User(public_id=str(uuid.uuid4()),\n username=data['username'], email=data['email'], password=hashed_password,\n admin=False, active=True, api_user=data['api_user'])\n db.session.add(new_user)\n db.session.commit()\n\n return jsonify({'message': 'New user ({}) created!'.format(data['username'])}), 200\n\n\n@user.route('/users/', methods=['PUT'])\n@token_required\ndef update_user(current_user, public_id):\n \"\"\"\n update user\n \"\"\"\n if not current_user.admin:\n return jsonify({'message': 'Only admin user can perform this function!'}), 403\n\n user = User.query.filter_by(public_id=public_id).first()\n\n if not user:\n return jsonify({'message': 'No user found!'})\n\n data = request.get_json()\n user.admin = data['admin']\n user.active = data['active']\n user.api_user = data['api_user']\n db.session.commit()\n\n return jsonify({'message': 'The user ({}) has been updated!'.format(public_id)})\n\n\n@user.route('/users/', methods=['DELETE'])\n@token_required\ndef delete_user(current_user, public_id):\n \"\"\"\n Delete user\n \"\"\"\n if not current_user.admin:\n return jsonify({'message': 'Only admin user can perform this function!'}), 403\n\n user = User.query.filter_by(public_id=public_id).first()\n if not user:\n return jsonify({'message': 'No user found!'})\n db.session.delete(user)\n db.session.commit()\n\n return jsonify({'message': 'The user ({}) has been deleted!'.format(public_id)})\n","sub_path":"dashboard/user/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"426170851","text":"from django.conf.urls import url\r\n\r\nfrom users.views_autocomplete import \\\r\nusers_autocomplete, \\\r\nusers_shop_admins_autocomplete, \\\r\nmy_users_autocomplete, \\\r\nusers_store_admins_autocomplete, \\\r\nmy_users_analytics_autocomplete\r\n\r\nurlpatterns = [\r\n url(r'^all', users_autocomplete, name='users-autocomplete'),\r\n url(r'^my-users', my_users_autocomplete, name='my-users-autocomplete'),\r\n url(r'^users-analytics', my_users_analytics_autocomplete, name='my-users-analytics-autocomplete'),\r\n url(r'^shop-admins', users_shop_admins_autocomplete, name='users-shop-admins-autocomplete'),\r\n url(r'^store-admins', users_store_admins_autocomplete, name='users-store-admins-autocomplete'),\r\n]","sub_path":"users/urls_autocomplete.py","file_name":"urls_autocomplete.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"9430186","text":"\nfrom pathlib import Path, PureWindowsPath\nfrom numpy.lib.function_base import select\n\nfrom semantictagger import conllu\nfrom semantictagger import paradigms\nfrom semantictagger.conllu import CoNLL_U\nfrom semantictagger.dataset import Dataset\nfrom semantictagger.paradigms import Encoder, ParameterError , RELPOSVERSIONS\nfrom semantictagger.datatypes import Outformat\n\nfrom typing import Dict, Generator, Iterator , Tuple , Union\nimport os \nfrom pandas import DataFrame\nfrom tqdm import tqdm\nimport pdb \nimport enum\nimport numpy as np\nimport re\n\nimport pdb\nimport uuid\nimport matplotlib.pyplot as plt\n\nclass RoleTypes(enum.Enum):\n MISSED= 0 \n CORRECT = 1\n FALSE = 2\n\n\nclass ResultSet():\n def __init__(self):\n self.distance_dict = {}\n for i in range(15):\n self.distance_dict[i]= {\n \"Correct\":0 , \n \"Missed Role\":0,\n \"False Role\":0,\n }\n\n self.syntax_semantics_dict ={\n \"Correct\" :0 ,\n \"False\" : 0\n }\n\n self.correct_index = {}\n self.missed_role_index ={}\n self.false_role_index ={}\n self.target_tags_count = {}\n self.target_tags_counter = 0 \n\n self.search_for_confusions = [\"-1,ARG2|-1,ARG1\" ,\"-1,ARG1|-1,ARG2\",\"1,ARG1|1,ARG0\",\"-1,ARG3|-1,ARG2\",\"1,ARGM-MNR|1,ARGM-ADJ\",\"\"]\n\n\n def add_distance(self,\n dist,\n roletype:RoleTypes,\n ): \n\n if roletype == RoleTypes.CORRECT:\n key = \"Correct\" \n elif roletype == RoleTypes.FALSE:\n key = \"False Role\"\n elif roletype == RoleTypes.MISSED:\n key = \"Missed Role\"\n else :\n Exception()\n\n self.distance_dict[abs(dist)][key] += 1\n\n def add_confusion(self,pdist,prole,tdist,trole): \n self.add_distance(tdist,roletype=RoleTypes.FALSE)\n\n if f\"{pdist},{prole}|{tdist},{trole}\" in self.false_role_index:\n self.false_role_index[f\"{pdist},{prole}|{tdist},{trole}\"] += 1\n else :\n self.false_role_index[f\"{pdist},{prole}|{tdist},{trole}\"] = 1\n \n def add_correct_index(self,pdist,prole):\n self.add_distance(pdist,roletype=RoleTypes.CORRECT)\n\n if f\"{pdist},{prole}\" in self.correct_index:\n self.correct_index[f\"{pdist},{prole}\"] += 1\n else :\n self.correct_index[f\"{pdist},{prole}\"] = 1\n\n def add_missed_index(self,tdist,trole):\n self.add_distance(tdist,roletype=RoleTypes.MISSED)\n if f\"{tdist},{trole}\" in self.missed_role_index:\n self.missed_role_index[f\"{tdist},{trole}\"] += 1\n else :\n self.missed_role_index[f\"{tdist},{trole}\"] = 1\n\n def add_target_tag(self,tdist,trole):\n if f\"{tdist},{trole}\" in self.target_tags_count:\n self.target_tags_count[f\"{tdist},{trole}\"] += 1\n else :\n self.target_tags_count[f\"{tdist},{trole}\"] = 1\n \n self.target_tags_counter += 1\n\n def add_syntactic(self, distance , Tdistance , postag , Tpostag , deprel , Tdeprel):\n if distance == Tdistance and postag == Tpostag and deprel == Tdeprel:\n self.syntax_semantics_dict[\"Correct\"] +=1\n else :\n self.syntax_semantics_dict[\"False\"] +=1\n \n def get_distance_dict(self):\n self.distance_dict.pop(0)\n self.distance_dict.pop(12)\n self.distance_dict.pop(13)\n self.distance_dict.pop(14)\n return self.distance_dict\n \n def get_other_dicts(self,get_first=20):\n self.correct_index = sorted([(x[0],x[1],\"{:0.2f}\".format(x[1]/self.target_tags_count[x[0]])) for x in self.correct_index.items()],key = lambda x : x[2],reverse=True)[:get_first]\n self.false_role_index = sorted([(x[0].split(\"|\")[0],x[0].split(\"|\")[1],x[1]) for x in self.false_role_index.items()], key=lambda z:z[2], reverse=True)[:get_first]\n self.missed_role_index = sorted([(x[0],x[1],\"{:0.2f}\".format(x[1]/self.target_tags_count[x[0]])) for x in self.missed_role_index.items()], key= lambda x:x[1],reverse=True)[:get_first]\n \n return self.correct_index,self.false_role_index,self.missed_role_index\n\n\n\n\nclass EvaluationModule():\n\n def __init__(self, \n paradigm : Encoder , \n dataset : Dataset , \n pathroles : Union[Path,str]=None, \n path_frame_file : Union[Path,str]=None ,\n path_pos_file : Union[Path,str] =None,\n goldframes : bool = False,\n goldpos : bool = False,\n mockevaluation : bool = False , \n early_stopping : bool = False\n ):\n \n self.early_stopping = early_stopping\n self.postype : paradigms.POSTYPE = paradigm.postype \n self.paradigm : Encoder = paradigm\n self.dataset : Dataset = dataset\n self.mockevaluation = mockevaluation\n self.goldpos = goldpos\n self.goldframes = goldframes\n\n self.pathroles = pathroles\n self.path_frame_file = path_frame_file\n self.path_pos_file = path_pos_file\n self.goldframes = goldframes\n self.goldpos = goldpos\n\n if not self.mockevaluation :\n if pathroles is None or path_frame_file is None or path_pos_file is None:\n ParameterError(\"Initializing EvaluationModule without mockevaluation feature, requires path/to/rolefile path/to/frame/file and path/to/pos/file.\")\n\n self.rolesgen : Iterator = iter(self.__readresults__(pathroles , gold = False))\n self.predgen : Iterator = iter(self.__readresults__(path_frame_file, gold = goldframes))\n self.posgen : Iterator = iter(self.__readresults__(path_pos_file , gold = goldpos))\n\n \n self.entryiter : Iterator = iter(self.dataset)\n \n\n def reset_buffer(self):\n self.rolesgen : Iterator = iter(self.__readresults__(self.pathroles , gold = False))\n self.predgen : Iterator = iter(self.__readresults__(self.path_frame_file, gold = self.goldframes))\n self.posgen : Iterator = iter(self.__readresults__(self.path_pos_file , gold = self.goldpos))\n self.entryiter : Iterator = iter(self.dataset)\n\n\n def __readresults__(self , path , gold , getpair=False):\n \"\"\"\n Flair outputs two files , called dev.tsv and test.tsv respectively.\n These files can be read with this function and each time this function \n will yield one entry, which in theory should align with the corresponding dataset.\n \"\"\"\n entryid = 0\n entry = [\"\" for d in range(100)]\n pairentry = [\"\" for d in range(100)]\n counter = 0 \n earlystoppingcounter = 0\n\n \n if type(path) == str:\n path = Path(path)\n\n with path.open() as f:\n while True:\n line = f.readline().replace(\"\\n\" , \"\").replace(\"\\t\" , \" \")\n\n if line is None:\n break\n\n if line == \"\" : \n entryid += 1\n if getpair:\n yield (entry[:counter] , pairentry[:counter])\n else :\n yield entry[:counter]\n entry = [\"\" for d in range(100)] \n pairentry = [\"\" for d in range(100)]\n\n counter = 0\n earlystoppingcounter +=1\n if self.early_stopping != False:\n if self.early_stopping == earlystoppingcounter :\n return None\n else : \n \n elems = line.split(\" \")\n if len(elems) == 1: \n entry[counter] = \"\"\n elif len(elems) == 2:\n if gold :\n entry[counter] = elems[1]\n else :\n entry[counter] = \"\"\n elif len(elems) == 3:\n if getpair:\n pairentry[counter] = elems[1]\n entry[counter] = elems[2]\n counter += 1\n\n return None\n\n def single(self , verbose = False):\n \n try:\n target = next(self.entryiter)\n except StopIteration:\n return None\n \n \n words = target.get_words()\n\n\n if not self.mockevaluation:\n preds = next(self.predgen)\n pos = next(self.posgen)\n if preds is None:\n return None\n # preds = [\"V\" if x != \"\" and x!= \"_\" else \"_\" for x in preds]\n roles = next(self.rolesgen)\n if roles is None:\n return None \n predicted = self.paradigm.to_conllu(words , preds , roles , pos)\n\n else :\n roles = self.paradigm.encode(target)\n if self.postype == paradigms.POSTYPE.UPOS:\n pos = target.get_by_tag(\"upos\")\n else :\n pos = target.get_by_tag(\"xpos\")\n \n preds = target.get_vsa()\n # preds = [\"V\" if x != \"\" and x!= \"_\" else \"_\" for x in target.get_vsa()]\n predicted = self.paradigm.to_conllu(words , preds , roles , pos)\n\n \n if verbose:\n \n a = {\"words\":words , \"predicates\" : preds , \"roles\" : roles}\n a.update({f\"TARGET {i}\" : v for i , v in enumerate(target.get_span())})\n a.update({f\"PRED {i}\" : v for i , v in enumerate(predicted.reconstruct())})\n\n return DataFrame(a)\n \n\n return target , predicted , roles\n\n def createpropsfiles(self, saveloc , depth_constraint = False, debug = False):\n\n counter = -1\n\n outformats = [\n Outformat.CONLL05,\n Outformat.CONLL09\n ]\n \n with open(os.path.join(saveloc , \"predicted-props.tsv\") , \"x\") as fp:\n with open(os.path.join(saveloc ,\"target-props.tsv\") , \"x\") as ft:\n with open(os.path.join(saveloc , \"predicted-props-conll09.tsv\") , \"x\") as fp1:\n with open(os.path.join(saveloc ,\"target-props-conll09.tsv\") , \"x\") as ft1:\n total = len(self.dataset)\n if self.early_stopping != False:\n total = min(len(self.dataset),self.early_stopping)\n for i in tqdm(range(total)):\n s = self.single()\n \n if s is None :\n return \n \n target , predicted , roles = s[0] , s[1] , s[2]\n \n files = [(fp , ft),(fp1,ft1)]\n entries : Tuple[CoNLL_U]= (predicted , target)\n if depth_constraint:\n if target.depth != depth_constraint:\n continue\n\n counter += 1 \n for fpindex , fpval in enumerate(outformats):\n for k in range(2): \n if fpval == Outformat.CONLL05:\n if k == 0 :\n spans = self.paradigm.reconstruct(entries[k])\n else:\n spans = entries[k].get_span()\n # elif of[0] == Outformat.CoNLL09:\n else:\n if k == 0:\n files[fpindex][k].write(entries[k].to_conll_text(self.paradigm.frametype, entries[1]))\n else :\n files[fpindex][k].write(entries[k].to_conll_text(self.paradigm.frametype))\n continue\n\n vsa = entries[1].get_vsa()\n if fpval == Outformat.CONLL05:\n vsa = [\"V\" if a != \"_\" and a != \"\" else \"-\" for a in vsa]\n words = entries[1].get_words()\n \n if debug:\n files[fpindex][k].write(f\"{counter}\\n\")\n\n for i in range(len(vsa)):\n \n if debug:\n files[fpindex][k].write(f\"{words[i]}\\t\")\n files[fpindex][k].write(f\"{roles[i]}\\t\")\n\n files[fpindex][k].write(f\"{vsa[i]}\\t\")\n\n for j in range(len(spans)):\n files[fpindex][k].write(f\"{spans[j][i]}\\t\")\n files[fpindex][k].write(\"\\n\")\n files[fpindex][k].write(\"\\n\")\n\n def evaluate(self , path , depth_constraint=False , automated_testing=False):\n self.reset_buffer()\n self.createpropsfiles(path, depth_constraint=depth_constraint)\n conll09 = self.__evaluate_conll09(path,automated_testing)\n conll05 = self.__evaluate_conll05(path,automated_testing)\n \n\n return { \n \"CoNLL05\" : conll05\n }\n\n def create_conllu_files(self,path):\n with open(os.path.join(path , \"predicted.conllu\") , \"x\") as fp:\n with open(os.path.join(path ,\"target.conllu\") , \"x\") as ft:\n for entry in self.dataset:\n ft.write(str(entry))\n predicted = self.paradigm.to_conllu(entry.get_words(),entry.get_vsa(),self.paradigm.encode(entry),entry.get_pos(self.paradigm.postype))\n fp.write(predicted.__str__(entry))\n\n def __evaluate_conll09(self,path, automated_testing=False):\n if automated_testing:return\n # TODO add quiet -q.\n os.popen(f'perl ./evaluation/conll09/eval09.pl -g {path}/target-props-conll09.tsv -s {path}/predicted-props-conll09.tsv > {path}/conll09-results.txt')\n\n\n def __evaluate_conll05(self,path,automated_testing = False):\n \n sh_command = f'perl ./evaluation/conll05/srl-eval.pl ./{path}/target-props.tsv ./{path}/predicted-props.tsv'\n if not automated_testing:\n sh_command = f'perl ./evaluation/conll05/srl-eval.pl -latex -C ./{path}/target-props.tsv ./{path}/predicted-props.tsv > ./{path}/conll05-results.txt'\n\n with os.popen(sh_command) as output:\n while True:\n line = output.readline()\n print(line)\n if not line: break\n line = re.sub(\" +\" , \" \" , line)\n array = line.strip(\"\").strip(\"\\n\").split(\" \")\n if len(array) > 2 and array[1] == \"Overall\": \n results = { \n \"correct\" : np.float(array[2]), \n \"excess\" : np.float(array[3]),\n \"missed\" : np.float(array[4]),\n \"recall\" : np.float(array[5]),\n \"precision\" : np.float(array[6]),\n \"f1\" : np.float(array[7])\n }\n return results\n \n return None\n\n def mockevaluate(self):\n path = f\"mockevals/{str(uuid.uuid1())[:5]}\"\n print(f\"Mock evaluation path : {path}\")\n os.makedirs(f\"{path}\")\n self.evaluate(path)\n self.create_conllu_files(path)\n\n def reevaluate(self,path , depth_constraint = False , graph_for_depth=False):\n if graph_for_depth:\n precisions = []\n recalls = []\n for j in range(1,5):\n for i in [\"target-props-conll09.tsv\",\"predicted-props-conll09.tsv\",\"target-props.tsv\",\"predicted-props.tsv\",\"conll09-results.txt\",\"conll05-results.txt\"]:\n if os.path.isfile(os.path.join(path,i)):\n os.remove(os.path.join(path,i))\n result_dict = self.evaluate(path , depth_constraint=j,automated_testing=True)\n precisions.append(result_dict[\"CoNLL05\"][\"precision\"])\n recalls.append(result_dict[\"CoNLL05\"][\"recall\"])\n\n # print(results)\n plt.plot(['1','2','3','4'],precisions,recalls)\n plt.legend([\"Recall\",\"Precision\"])\n plt.title(\"P/R by depth\")\n plt.ylabel('Percentage')\n plt.xlabel('Depth')\n plt.savefig(os.path.join(path,\"by_depth.png\"))\n return\n \n \n for i in [\"target-props-conll09.tsv\",\"predicted-props-conll09.tsv\",\"target-props.tsv\",\"predicted-props.tsv\",\"conll09-results.txt\",\"conll05-results.txt\"]:\n if os.path.isfile(os.path.join(path,i)):\n os.remove(os.path.join(path,i))\n self.evaluate(path , depth_constraint)\n\n \n\n\n def role_prediction_by_distance(self , depth_constraint = False , latex = True):\n self.rolesgen = iter(self.__readresults__(self.pathroles , gold = False,getpair=True))\n self.entryiter : Iterator = iter(self.dataset)\n tagger_version = self.paradigm.version\n \n rset = ResultSet()\n\n\n \n\n\n while True:\n a , b = next(self.rolesgen)\n entry = next(self.entryiter)\n \n if entry is None:\n break\n \n # if entry.get_sentence().startswith(\"Let me join the choru\") or \"I 'm not fond of the Google - hates - privacy argument\" in entry.get_sentence(): \n # print(entry.get_sentence())\n # else :\n # continue\n\n if depth_constraint != False:\n if len(entry.get_srl_annotation()) != depth_constraint:\n continue\n\n\n srl = [*zip(*entry.get_srl_annotation())]\n vlocs = entry.get_verb_indices()\n postags = entry.get_pos(self.postype)\n \n if a is None:\n break\n \n for i in range(len(a)):\n t = a[i].split(\",\")\n s = b[i].split(\",\")\n if tagger_version == RELPOSVERSIONS.SRLEXTENDED:\n if len(s) == 5:\n distance , postag , deprel , preddistance , predrole = int(s[0]),s[1],s[2],int(s[3]),s[4]\n rset.add_target_tag(s[3],s[4])\n \n if len(t) != 5:\n rset.add_missed_index(preddistance,predrole)\n else :\n Tdistance , Tpostag , Tdeprel , Tpreddistance , Tpredrole = int(t[0]),t[1],t[2],int(t[3]),t[4]\n if preddistance == Tpreddistance and predrole == Tpredrole:\n if depth_constraint: assert(preddistance == depth_constraint)\n rset.add_correct_index(preddistance,predrole)\n elif preddistance == Tpreddistance and predrole != Tpredrole:\n rset.add_syntactic(preddistance,Tpreddistance,postag,Tpostag,deprel,Tdeprel)\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n else :\n layer = srl[i]\n if len([1 for k in layer if k != \"_\" and k !=\"V\"]) < 2 : \n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n continue\n if Tpredrole in layer:\n pointeddepth = 0 \n if i < vlocs[0] : pointeddepth = Tpreddistance-1 \n elif i == vlocs[0] : pointeddepth = Tpreddistance\n elif i > vlocs[-1] : pointeddepth = len(vlocs) - Tpreddistance\n elif i == vlocs[-1] : pointeddepth = len(vlocs) - Tpreddistance - 1\n else : \n tempind = 0 \n for verbindex in vlocs:\n if verbindex < i:\n tempind += 1\n elif verbindex == i:\n pointeddepth = tempind + (Tpreddistance if Tpreddistance > 0 else -Tpreddistance)\n break\n else:\n pointeddepth = tempind + (Tpreddistance - 1 if Tpreddistance > 0 else -Tpreddistance)\n break\n \n if pointeddepth < 0 or pointeddepth >= len(layer):\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n continue\n if layer[pointeddepth] == Tpredrole:\n if depth_constraint: assert(preddistance == depth_constraint)\n rset.add_correct_index(preddistance,predrole)\n else :\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n else :\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n continue\n\n elif tagger_version == RELPOSVERSIONS.SRLREPLACED:\n distance , postag , deprel = int(s[0]),s[1],s[2]\n if postag != \"FRAME\": continue\n if len(t) < 2:\n if postag == \"FRAME\":\n rset.add_target_tag(distance,deprel)\n rset.add_missed_index(distance,deprel)\n continue\n\n Tdistance , Tpostag , Tdeprel = int(t[0]),t[1],t[2]\n rset.add_target_tag(distance,deprel)\n \n if Tpostag != \"FRAME\": \n rset.add_missed_index(distance,deprel)\n else :\n preddistance = distance\n Tpreddistance = Tdistance\n predrole = deprel\n Tpredrole = Tdeprel\n \n if preddistance == Tpreddistance and predrole == Tpredrole:\n rset.add_correct_index(preddistance,predrole)\n elif preddistance == Tpreddistance and predrole != Tpredrole:\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n else :\n layer = srl[i]\n if len([1 for k in layer if k != \"_\" and k !=\"V\"]) < 2 : \n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n continue\n if Tpredrole in layer:\n pointeddepth = 0 \n if i < vlocs[0] : pointeddepth = Tpreddistance-1 \n elif i == vlocs[0] : pointeddepth = Tpreddistance\n elif i > vlocs[-1] : pointeddepth = len(vlocs) - Tpreddistance\n elif i == vlocs[-1] : pointeddepth = len(vlocs) - Tpreddistance - 1\n else : \n tempind = 0 \n for verbindex in vlocs:\n if verbindex < i:\n tempind += 1\n elif verbindex == i:\n pointeddepth = tempind + (Tpreddistance if Tpreddistance > 0 else -Tpreddistance)\n break\n else:\n pointeddepth = tempind + (Tpreddistance - 1 if Tpreddistance > 0 else -Tpreddistance)\n break\n \n if pointeddepth < 0 or pointeddepth >= len(layer):\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n continue\n if layer[pointeddepth] == Tpredrole:\n rset.add_correct_index(preddistance,predrole)\n else :\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n else :\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n\n elif tagger_version == RELPOSVERSIONS.DEPLESS or tagger_version == RELPOSVERSIONS.FLATTENED:\n if len(s) != 3 : continue\n preddistance , postag , predrole = int(s[0]),s[1],s[2]\n \n temparray= [preddistance]\n temparray2 = [postag]\n pointedverblocs = [0]\n for c in range(1):\n start = i-1 if temparray[c] < 0 else i+1\n end = -1 if temparray[c] < 0 else len(postags)\n seen = 0 \n vdistance = 0 \n for j in range(start , end , np.sign(temparray[c])):\n if j in vlocs:\n vdistance += 1\n if postags[j] == temparray2[c]:\n seen+=1\n if seen == np.abs(temparray[c]):\n pointedverblocs[c] = vdistance\n break\n preddistance = pointedverblocs[0] * np.sign(temparray[c])\n # yield preddistance , predrole , entry.get_sentence() , i \n # if preddistance > 1 :\n # print(DataFrame({\"Words\":entry.get_words() , \"Encoded\" :b ,\"POS\":postags , \"Verbs\":[\"V\" if x in vlocs else \"_\" for x in range(len(entry))], \"Ilgili\":[\"\" if x != i else f\"{preddistance}\" for x in range(len(entry))]}))\n # print(\"\\n\\n\")\n\n\n assert(preddistance != 0 )\n if depth_constraint :\n assert(preddistance <= depth_constraint )\n\n rset.add_target_tag(preddistance,predrole)\n\n if len(t) != 3 : \n rset.add_missed_index(preddistance,predrole)\n else :\n\n Tpreddistance , Tpostag , Tpredrole = int(t[0]),t[1],t[2]\n temparray= [Tpreddistance]\n temparray2 = [Tpostag]\n pointedverblocs = [0]\n for c in range(1):\n start = i-1 if temparray[c] < 0 else i+1\n end = -1 if temparray[c] < 0 else len(postags)\n seen = 0 \n vdistance = 0 \n for j in range(start , end , np.sign(temparray[c])):\n if j in vlocs: \n vdistance += 1\n if postags[j] == temparray2[c]:\n seen+=1 \n if seen == np.abs(temparray[c]):\n pointedverblocs[c] = vdistance\n break\n \n Tpreddistance = pointedverblocs[0] * np.sign(temparray[c])\n \n\n if preddistance == Tpreddistance and predrole == Tpredrole:\n rset.add_correct_index(preddistance,predrole)\n elif preddistance == Tpreddistance and predrole != Tpredrole:\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n\n else :\n layer = srl[i]\n try :\n if layer[Tpreddistance] == Tpredrole:\n if layer[pointeddepth] == Tpredrole:\n rset.add_correct_index(preddistance,predrole)\n else :\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole)\n except:\n rset.add_confusion(preddistance,predrole,Tpreddistance,Tpredrole) \n else:\n continue\n\n\n \n \n \n\n print(rset.target_tags_counter , \" viele Role Woerter insgesamt.\")\n \n\n print(DataFrame(rset.get_distance_dict()).to_latex())\n temparray = rset.get_other_dicts()\n print(DataFrame(temparray[0]).to_latex(caption=\"Correct roles.\"))\n print(DataFrame(temparray[1]).to_latex(caption=\"Missed roles.\"))\n print(DataFrame(temparray[2]).to_latex(caption=\"Confusion of roles.\"))\n\n # print(DataFrame(false_role_list).to_latex(caption=\"False labels.\"))\n print(DataFrame(sorted(rset.target_tags_count.items(),key=lambda x : x[1],reverse = True)[:20]).to_latex(caption=\"Distribution of semantic labels.\"))\n print(rset.syntax_semantics_dict)\n\n\n\n \n\n def inspect_learning_behavior(self,path,num_of_epoch :int , plot = True):\n \n syntax_correct_semantic_false = []\n syntax_correct_semantic_correct = []\n syntax_false_semantic_correct = []\n syntax_false_semantic_false = []\n\n for i in range(1,num_of_epoch+1):\n with open(f\"{path}/dev{i}.tsv\") as fp:\n typ1 = 0\n typ2 = 0 \n typ3 = 0\n typ4 = 0 \n\n while True:\n line = fp.readline()\n if len(line) == 0:\n syntax_correct_semantic_false.append(typ1)\n syntax_correct_semantic_correct.append(typ2)\n syntax_false_semantic_correct.append(typ3)\n syntax_false_semantic_false.append(typ4)\n break\n if line == \"\\n\":\n continue\n \n line = line.replace(\"\\n\",\"\")\n array = line.split(\" \")\n word , pred , target = array[0] , array[1] , array[2]\n if self.paradigm.version == RELPOSVERSIONS.FLATTENED:\n t1 = array[1].split(\",\")\n t2 = array[2].split(\",\")\n \n\n if t1[0] != t2[0] or t1[1] != t2[1]:\n if len(t1) == 3 and len(t2) == 3:\n if t1[2] == t2[2]:\n # print(t1 , t2 , \"syntax_false_semantic_correct\")\n typ3 += 1\n else :\n # print(t1 , t2 , \"syntax_false_semantic_false\")\n typ4 += 1\n elif len(t1) == 2 and len(t2) == 3 or len(t1) == 3 and len(t2) == 2:\n # print(t1 , t2 , \"syntax_false_semantic_false\")\n typ4 += 1\n else:\n # print(t1 , t2 , \"syntax_false_semantic_correct\")\n typ3 += 1\n else :\n if len(t1) == 3 and len(t2) == 3:\n if t1[2] == t2[2]:\n # print(t1 , t2 , \"syntax_correct_semantic_correct\")\n typ2 += 1\n else :\n # print(t1 , t2 , \"syntax_correct_semantic_false\")\n typ1 += 1\n elif len(t1) == 2 and len(t2) == 3 or len(t1) == 3 and len(t2) == 2:\n # print(t1 , t2 , \"syntax_correct_semantic_false\")\n typ1 += 1\n else:\n # print(t1 , t2 , \"syntax_correct_semantic_correct\")\n typ2 += 1\n\n\n\n\n\n # elif self.paradigm.version == RELPOSVERSIONS.SRLEXTENDED:\n # else:\n if plot:\n import matplotlib.pyplot as plt\n \n plt.subplot(121)\n plt.title('Semantic Error')\n plt.plot(syntax_correct_semantic_false)\n plt.ylabel(\"Occurence\")\n plt.xlabel(\"Epoch\")\n plt.subplot(122)\n plt.title('Syntactic Error')\n plt.plot(syntax_false_semantic_correct)\n plt.ylabel(\"Occurence\")\n plt.xlabel(\"Epoch\")\n # plt.subplot(223)\n # plt.title('Both Correct')\n # plt.plot(syntax_correct_semantic_correct)\n # plt.ylabel(\"Occurence\")\n # plt.xlabel(\"Epoch\")\n # plt.subplot(224)\n # plt.title('Both False')\n # plt.plot(syntax_false_semantic_false)\n # plt.ylabel(\"Occurence\")\n # plt.xlabel(\"Epoch\")\n plt.show()\n return syntax_correct_semantic_false , syntax_correct_semantic_correct , syntax_false_semantic_correct , syntax_false_semantic_false","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":34217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"257480307","text":"#!/usr/bin/env python3\n\"\"\" Project \"\"\"\n__author__ = 'Andrea Dainese '\n__copyright__ = 'Andrea Dainese '\n__license__ = 'https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode'\n__revision__ = '20170430'\n\nimport os, re, shutil, yaml\nfrom flask import abort, jsonify, make_response, request\nfrom scanner import config, logger\n\nclass Project():\n def __init__(self, id = None):\n self.id = self.parseProjectID(id)\n self.project_dir = '{}/{}'.format(config['data_dir'], id)\n if os.path.isdir(self.project_dir):\n # If project exists then load the YAML file\n self.exists = True\n try:\n with open('{}/project.yaml'.format(self.project_dir), 'r') as f_yaml:\n self.options = yaml.load(f_yaml)\n except Exception as err:\n self.options = {}\n else:\n self.exists = False\n self.options = {}\n\n def addProject(self, options):\n if self.exists:\n # Should use updateProject or patchProject\n logger.debug('project_id = \"{}\" already exists'.format(self.id))\n return False\n # Adding the Project directory\n try:\n os.makedirs(self.project_dir)\n self.exists = True\n except Exception as err:\n logger.error('failed to add directory \"{}\" (exception)'.format(self.project_dir), exc_info = True)\n return False\n # Adding the project.yaml file\n try:\n with open('{}/project.yaml'.format(self.project_dir), 'w') as f_yaml:\n yaml.dump(options, f_yaml, default_flow_style = False)\n self.options = options\n except Exception as err:\n self.options = {}\n return False\n return self.options\n\n def deleteProject(self):\n if self.exists:\n try:\n shutil.rmtree(self.project_dir)\n logger.debug('deleted project_id = \"{}\"'.format(self.id))\n return True\n except Exception as err:\n logger.error('failed to remove directory \"{}\" (exception)'.format(self.project_dir), exc_info = True)\n return False\n else:\n logger.debug('project_id = \"{}\" not found'.format(self.id))\n return False\n\n def parseProjectID(self, id):\n re_project_id = re.compile('^[0-9A-Za-z_]+$')\n if id and re_project_id.match(id):\n return id\n else:\n return False\n\n def printProject(self):\n if self.exists:\n return self.options\n else:\n logger.debug('project_id = \"{}\" not found'.format(self.id))\n return False\n","sub_path":"flask_apps/scanner/catalog/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"54866630","text":"import json\nimport itertools\nwith open('Data/NevenFuncties.json', 'r') as data_file:\n data = json.load(data_file)\n\nwith open('Data/Functies_1.json', 'r') as data_file:\n functies_1 = json.load(data_file)\n\nwith open('Data/Functies_2.json', 'r') as data_file:\n functies_2 = json.load(data_file)\n\nwith open('Data/Functies_3.json', 'r') as data_file:\n functies_3 = json.load(data_file)\n\nwith open('Data/Functies_4.json', 'r') as data_file:\n functies_4 = json.load(data_file)\n\nwith open('Data/Functies_5.json', 'r') as data_file:\n functies_5 = json.load(data_file)\n\n\n\n\n\"\"\"for person in data[\"value\"]:\n for jobs in functies_1[\"value\"], functies_2[\"value\"], functies_3[\"value\"], functies_4[\"value\"], functies_5[\"value\"]:\n for t in person:\n for x in jobs:\n if t[\"Id\"] == x[\"PersoonId\"]:\n t[\"Werk\"] = []\n t[\"Werk\"].append(x[\"Omschrijving\"])\"\"\"\n\n\nfor person in data[\"value\"]:\n person[\"Werk\"] = []\n for fs in functies_1[\"value\"]:\n if person[\"Id\"] == fs[\"PersoonId\"]:\n person[\"Werk\"].append(fs[\"Omschrijving\"])\n for ds in functies_2[\"value\"]:\n if person[\"Id\"] == ds[\"PersoonId\"]:\n person[\"Werk\"].append(ds[\"Omschrijving\"])\n for ms in functies_3[\"value\"]:\n if person[\"Id\"] == ms[\"PersoonId\"]:\n person[\"Werk\"].append(ms[\"Omschrijving\"])\n for ys in functies_4[\"value\"]:\n if person[\"Id\"] == ys[\"PersoonId\"]:\n person[\"Werk\"].append(ys[\"Omschrijving\"])\n for xs in functies_5[\"value\"]:\n if person[\"Id\"] == xs[\"PersoonId\"]:\n person[\"Werk\"].append(xs[\"Omschrijving\"])\n \n \n \n\n\n\nwith open('Data/NevenFuncties.json', 'w') as data_file:\n data = json.dump(data, data_file)\n","sub_path":"json/NevenFunctie Generator.py","file_name":"NevenFunctie Generator.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"652694389","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018-2021, earthobservations developers.\n# Distributed under the MIT License. See LICENSE for more info.\n\"\"\"\nWetterdienst Explorer UI Dash application.\n\"\"\"\nimport logging\nfrom typing import Optional\n\nimport dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport plotly.graph_objects as go\nimport requests\nfrom dash.dependencies import Input, Output, State\n\nfrom wetterdienst.exceptions import InvalidParameterCombination\nfrom wetterdienst.metadata.columns import Columns\nfrom wetterdienst.provider.dwd.observation import (\n DwdObservationDataset,\n DwdObservationPeriod,\n DwdObservationRequest,\n DwdObservationResolution,\n)\nfrom wetterdienst.ui.explorer.layout.main import get_app_layout\nfrom wetterdienst.ui.explorer.library import add_annotation_no_data, default_figure\nfrom wetterdienst.ui.explorer.util import frame_summary\nfrom wetterdienst.util.cli import setup_logging\n\nlog = logging.getLogger(__name__)\n\n# Create and configure Dash application object.\napp = dash.Dash(\n __name__,\n meta_tags=[{\"name\": \"viewport\", \"content\": \"width=device-width\"}],\n external_stylesheets=[dbc.themes.BOOTSTRAP, dbc.themes.SANDSTONE],\n)\napp.title = \"Wetterdienst Explorer\"\napp.layout = get_app_layout()\n\nempty_frame = pd.DataFrame().to_json(date_format=\"iso\", orient=\"split\")\n\n\n@app.callback(\n Output(\"modal-about\", \"is_open\"),\n [Input(\"open-about\", \"n_clicks\"), Input(\"close-about\", \"n_clicks\")],\n [State(\"modal-about\", \"is_open\")],\n)\ndef toggle_about(n1, n2, is_open):\n if n1 or n2:\n return not is_open\n return is_open\n\n\n@app.callback(\n Output(\"dataframe-stations\", \"children\"),\n [\n Input(\"select-parameter\", \"value\"),\n Input(\"select-resolution\", \"value\"),\n Input(\"select-period\", \"value\"),\n ],\n)\ndef fetch_stations(parameter: str, resolution: str, period: str):\n \"\"\"\n Fetch \"stations\" data.\n\n This will be used to populate the navigation chooser and to render the map.\n\n The data will be stored on a hidden within the browser DOM.\n \"\"\"\n log.info(\n f\"Requesting stations for \"\n f\"parameter={parameter}, \"\n f\"resolution={resolution}, \"\n f\"period={period}\"\n )\n try:\n stations = DwdObservationRequest(\n parameter=DwdObservationDataset(parameter),\n resolution=DwdObservationResolution(resolution),\n period=DwdObservationPeriod(period),\n ).all()\n except (requests.exceptions.ConnectionError, InvalidParameterCombination) as ex:\n log.warning(ex)\n # raise PreventUpdate\n log.error(\"Unable to connect to data source\")\n return empty_frame\n\n df = stations.df\n\n log.info(f\"Propagating stations data frame with {frame_summary(df)}\")\n\n return df.to_json(date_format=\"iso\", orient=\"split\")\n\n\n@app.callback(\n Output(\"dataframe-values\", \"children\"),\n [\n Input(\"select-parameter\", \"value\"),\n Input(\"select-resolution\", \"value\"),\n Input(\"select-period\", \"value\"),\n Input(\"select-station\", \"value\"),\n ],\n)\ndef fetch_values(parameter: str, resolution: str, period: str, station_id: int):\n \"\"\"\n Fetch \"values\" data.\n\n This will be used to populate the navigation chooser and to render the graph.\n\n The data will be stored on a hidden within the browser DOM.\n \"\"\"\n\n # Sanity checks.\n if station_id is None:\n log.warning(\"Querying without station_id is rejected\")\n return empty_frame\n\n log.info(\n f\"Requesting values for \"\n f\"station_id={station_id}, \"\n f\"parameter={parameter}, \"\n f\"resolution={resolution}, \"\n f\"period={period}\"\n )\n stations = DwdObservationRequest(\n parameter=DwdObservationDataset(parameter),\n resolution=DwdObservationResolution(resolution),\n period=DwdObservationPeriod(period),\n tidy=False,\n humanize=True,\n ).filter_by_station_id(station_id=(str(station_id),))\n\n try:\n df = stations.values.all().df\n except ValueError:\n log.exception(\"No data received\")\n return empty_frame\n\n df = df.dropna(axis=0)\n\n log.info(f\"Propagating values data frame with {frame_summary(df)}\")\n\n return df.to_json(date_format=\"iso\", orient=\"split\")\n\n\n@app.callback(\n Output(\"select-station\", \"options\"),\n [Input(\"dataframe-stations\", \"children\")],\n)\ndef render_navigation_stations(payload):\n \"\"\"\n Compute list of items from \"stations\" data for populating the \"stations\"\n chooser element.\n \"\"\"\n stations_data = pd.read_json(payload, orient=\"split\")\n if stations_data.empty:\n return []\n log.info(f\"Rendering stations dropdown from {frame_summary(stations_data)}\")\n return [\n {\"label\": name, \"value\": station_id}\n for name, station_id in sorted(\n zip(\n stations_data[Columns.NAME.value],\n stations_data[Columns.STATION_ID.value],\n )\n )\n ]\n\n\n@app.callback(\n Output(\"select-variable\", \"options\"),\n [Input(\"dataframe-values\", \"children\")],\n)\ndef render_navigation_variables(payload):\n \"\"\"\n Compute list of items from \"values\" data for populating the \"variables\"\n chooser element.\n \"\"\"\n climate_data = pd.read_json(payload, orient=\"split\")\n log.info(f\"Rendering variable dropdown from {frame_summary(climate_data)}\")\n\n # Build list of columns to be selectable.\n columns = []\n for column in climate_data.columns:\n\n # Skip some columns.\n if column in [\"station_id\", \"date\"]:\n continue\n\n columns.append({\"label\": column, \"value\": column})\n\n return columns\n\n\n@app.callback(\n Output(\"status-response-stations\", \"children\"),\n [\n Input(\"select-parameter\", \"value\"),\n Input(\"select-resolution\", \"value\"),\n Input(\"select-period\", \"value\"),\n Input(\"dataframe-stations\", \"children\"),\n ],\n)\ndef render_status_response_stations(\n parameter: str, resolution: str, period: str, payload: str\n):\n \"\"\"\n Report about the status of the query.\n \"\"\"\n\n title = [dcc.Markdown(\"#### Stations\")]\n\n empty_message = [\n dcc.Markdown(\n f\"\"\"\nNo data.\nMaybe the combination of \"{parameter}\", \"{resolution}\" and \"{period}\" is invalid.\n \"\"\"\n )\n ]\n\n try:\n stations_data = pd.read_json(payload, orient=\"split\")\n except ValueError:\n return title + empty_message\n\n if stations_data.empty:\n return title + empty_message\n\n return title + [\n html.Div(\n [\n html.Div(f\"Columns: {len(stations_data.columns)}\"),\n html.Div(f\"Records: {len(stations_data)}\"),\n ]\n )\n ]\n\n\n@app.callback(\n Output(\"status-response-values\", \"children\"),\n [\n Input(\"dataframe-values\", \"children\"),\n State(\"select-parameter\", \"value\"),\n State(\"select-resolution\", \"value\"),\n State(\"select-period\", \"value\"),\n State(\"select-station\", \"value\"),\n State(\"select-variable\", \"value\"),\n ],\n)\ndef render_status_response_values(\n payload: str,\n parameter: str,\n resolution: str,\n period: str,\n station: str,\n variable: str,\n):\n \"\"\"\n Report about the status of the query.\n \"\"\"\n values_data = pd.read_json(payload, orient=\"split\")\n\n messages = [dcc.Markdown(\"#### Values\")]\n\n if values_data.empty:\n\n # Main message.\n empty_message = [html.Span(\"No data. \")]\n\n candidates = [\"parameter\", \"resolution\", \"period\", \"station\", \"variable\"]\n missing = []\n for candidate in candidates:\n if locals().get(candidate) is None:\n missing.append(candidate)\n\n if missing:\n empty_message.append(\n html.Span(f\"Please select all of the missing options {missing}.\")\n )\n\n messages += [html.Div(empty_message), html.Br()]\n\n messages += [\n html.Div(f\"Columns: {len(values_data.columns)}\"),\n html.Div(f\"Records: {len(values_data)}\"),\n html.Br(),\n ]\n\n if \"date\" in values_data:\n messages += [\n html.Div(f\"Station: {station}\"),\n html.Div(f\"Begin date: {values_data.date.iloc[0]}\"),\n html.Div(f\"End date: {values_data.date.iloc[-1]}\"),\n ]\n\n return html.Div(messages)\n\n\n@app.callback(\n Output(\"map-stations\", \"figure\"),\n [Input(\"dataframe-stations\", \"children\")],\n)\ndef render_map(payload):\n \"\"\"\n Create a \"map\" Figure element from \"stations\" data.\n \"\"\"\n stations_data = pd.read_json(payload, orient=\"split\")\n\n layout_germany = dict(\n hovermode=\"closest\",\n mapbox=dict(\n bearing=0,\n center=go.layout.mapbox.Center(lat=51.5, lon=10),\n style=\"open-street-map\",\n pitch=0,\n zoom=4.5,\n ),\n margin=go.layout.Margin(\n l=0,\n r=0,\n b=0,\n t=0,\n ),\n )\n\n if stations_data.empty:\n fig = go.Figure(\n data=go.Scattermapbox(\n mode=\"markers\",\n ),\n layout=layout_germany,\n )\n add_annotation_no_data(fig)\n return fig\n\n log.info(f\"Rendering stations map from {frame_summary(stations_data)}\")\n fig = go.Figure(\n data=go.Scattermapbox(\n lat=stations_data[Columns.LATITUDE.value],\n lon=stations_data[Columns.LONGITUDE.value],\n mode=\"markers\",\n marker=go.scattermapbox.Marker(size=5),\n text=[\n f\"Name: {name}
    Id: {station_id}
    Height: {altitude}m \"\n for name, altitude, station_id in zip(\n stations_data[Columns.NAME.value],\n stations_data[Columns.HEIGHT.value],\n stations_data[Columns.STATION_ID.value],\n )\n ],\n ),\n layout=layout_germany,\n )\n\n return fig\n\n\n@app.callback(\n Output(\"graph-values\", \"figure\"),\n [Input(\"select-variable\", \"value\")],\n [Input(\"dataframe-values\", \"children\")],\n)\ndef render_graph(variable, payload):\n \"\"\"\n Create a \"graph\" Figure element from \"values\" data.\n \"\"\"\n\n try:\n climate_data = pd.read_json(payload, orient=\"split\")\n except ValueError:\n climate_data = pd.DataFrame()\n\n log.info(\n f\"Rendering graph for variable={variable} from {frame_summary(climate_data)}\"\n )\n\n fig = default_figure(climate_data, variable)\n\n fig.update_layout(\n margin=go.layout.Margin(\n l=0, # left margin\n r=0, # right margin\n b=0, # bottom margin\n t=0, # top margin\n )\n )\n\n return fig\n\n\ndef start_service(\n listen_address: Optional[str] = None, reload: Optional[bool] = False\n): # pragma: no cover\n \"\"\"\n This entrypoint will be used by `wetterdienst.cli`.\n \"\"\"\n\n setup_logging()\n\n if listen_address is None:\n listen_address = \"127.0.0.1:7891\"\n\n host, port = listen_address.split(\":\")\n port = int(port)\n app.server.run(host=host, port=port, debug=reload)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n This entrypoint will be used by `dash.testing`.\n \"\"\"\n app.run_server(debug=True)\n","sub_path":"wetterdienst/ui/explorer/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"520657221","text":"def text_edit(fieldname,value):\n waitForObject(fieldname)\n if value!='':\n if object.exists(fieldname):\n type(fieldname,value)\n test.log(\"The \"+value+\" has been entered successfully\")\n snooze(1.0)\n return(\"True\")\n else:\n test.log(\"The field \"+fieldname+\" is not identified\")\n return(\"False\") \n \ndef push_button(btn):\n waitForObject(btn)\n if object.exists(btn):\n clickButton(btn)\n test.log(\"The \"+btn+\" has been identified and clicked successfully\")\n snooze(1.0)\n return(\"True\")\n else:\n test.log(\"The field \"+btn+\" is not identified\")\n return(\"False\") \n\n\ndef click_link(mmubtn):\n waitForObject(mmubtn)\n if object.exists(mmubtn):\n clickLink(mmubtn)\n test.log(\"The \"+mmubtn+\" has been identified and clicked successfully\")\n snooze(1.0)\n return(\"True\")\n else:\n test.log(\"The field \"+mmubtn+\" is not identified\")\n return(\"False\")\n \n\ndef select_dropdown(fieldname,value):\n waitForObject(fieldname)\n if value!='':\n if object.exists(fieldname):\n selectOption(fieldname,value)\n test.log(\"The \"+value+\" has been selected successfully in the dropdown\")\n snooze(1.0)\n return(\"True\")\n else:\n test.log(\"The field \"+fieldname+\" is not identified\")\n return(\"False\") \n \ndef checkbox(fieldname,value):\n waitForObject(fieldname)\n if object.exists(fieldname):\n if value == \"Check\":\n clickButton(fieldname)\n test.log(\"The\" +fieldname+\" has been checked successfully\")\n snooze(1.0)\n return(\"True\")\n else:\n test.log(\"The\" +fieldname+\" has been unchecked as per the user request\")\n else:\n test.log(\"The field \"+fieldname+\" is not identified\")\n return(\"False\") \n \ndef CreateDict():\n dict = {}\n for row in testData.dataset('Y:\\suite_Demo_ELO\\shared\\ObjectRepository.tsv'):\n dict[testData.field(row,\"ObjectName\")] = testData.field(row,\"ObjectProperty\")\n return(dict)\n \n# def CreateDict():\n# START_ROW = 0\n# file_path = '/run/user/1000/gvfs/smb-share:server=3.204.38.30,share=elo-project/ObjectRepository.xls'\n# rb = xlrd.open_workbook(file_path)\n# r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file\n# #wr = copy(rb)\n# #wb = (rb) # a writable copy (I can't read values out of this, only write to it)\n# #w_sheet = wr.get_sheet(0) # the sheet to write to within the writable copy\n# dict = {}\n# for row_index in range(START_ROW, r_sheet.nrows):\n# dict [r_sheet.cell(row_index, Objectname).value] = r_sheet.cell(row_index, ObjectProperty).value\n# test.log(\"check rows\",r_sheet.cell(row_index, Objectname).value)\n# return(dict)","sub_path":"Squish/SquishDemo/suite_Demo_ELO/shared/scripts/CommonFunctions.py","file_name":"CommonFunctions.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"575132842","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nDIRECT_TEMPLATES = (('search',))\n\nAUTHOR = u'Yuchuan Gou'\nSITENAME = u\"tomgou.xyz\"\nSITEURL = 'http://blog.tomgou.xyz'\n\nPATH = 'content'\n\nTIMEZONE = 'Asia/Shanghai'\n\nDEFAULT_LANG = u'ch'\n\nTHEME = 'pelican-bootstrap3'\n#DISQUS_SITENAME = \"Tom's Blog\"\nDUOSHUO_SITENAME = \"blog.tomgou.xyz\"\n\nOUTPUT_PATH = './output'\n#需要把输出路径从默认的'output'改成根目录(your_id.github.com目录), 因为githubpage需要把index.html上传到repo的master分支的根目录才可以!\nDEFAULT_CATEGORY ='Blogs'\n\nGOOGLE_ANALYTICS = 'UA-74218843-1'#谷歌站点分析\n\n\n#DISPLAY_RECENT_POSTS_ON_SIDEBAR = True\n\n\nGITHUB_USER = \"plain1994\"\nGITHUB_REPO_COUNT = 3\n\nPLUGIN_PATHS = [\"plugins\"]\nPLUGINS = [\"tag_cloud\",\"sitemap\",\"tipue_search\"]\n\n\nSITEMAP = {\n 'format': 'xml',\n 'priorities': {\n 'articles': 0.5,\n 'indexes': 0.5,\n 'pages': 0.5\n },\n 'changefreqs': {\n 'articles': 'daily',\n 'indexes': 'daily',\n 'pages': 'daily'\n }\n}\n\n\nTAG_CLOUD_STEPS = 4\nTAG_CLOUD_MAX_ITEMS = 100\nTAG_CLOUD_SORTING = 'random'\nDISPLAY_TAGS_ON_SIDEBAR = True\nDISPLAY_TAGS_INLINE = True\n\n#BOOTSTRAP_FLUID = True\n#DISPLAY_CATEGORY_IN_BREADCRUMBS = True\nBOOTSTRAP_NAVBAR_INVERSE = True\nFAVICON = 'images/carrot.jpg'\n#AVATAR = 'images/gou.jpeg'\n#ABOUT_ME = 'A student at SJTU'\n\nBANNER = 'images/saul.jpg'\nBANNER_COMMENT = 'blog.tomgou.xyz'\n#BANNER_SUBTITLE = 'This is my subtitle'\n\n#ADDTHIS_PROFILE = 'plain1994'\n#add addthis in duoshuo comment\n#add revolvermaps in sidebar.html\n\n#DISPLAY_ARTICLE_INFO_ON_INDEX = True\n\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Blogroll\nLINKS = (('Pelican', 'http://getpelican.com/'),\n )\n\n# Social widget\nSOCIAL = (\n ('github', 'https://github.com/plain1994'),\n ('weibo', 'http://weibo.com/tomgou'),\n ('facebook', 'http://www.facebook.com/yuchuangou'),\n )\n\nDEFAULT_PAGINATION = 8\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"182545622","text":"'''In a previous exercise, we saw that the altitude along a hiking trail was roughly fit by a linear model, and we introduced the concept of differences between the model and the data as a measure of model goodness.\n\nIn this exercise, you'll work with the same measured data, and quantifying how well a model fits it by computing the sum of the square of the \"differences\", also called \"residuals\".'''\n#TASK\n# Load the x_data, y_data with the pre-defined load_data() function\n# Call the pre-defined model(), passing in x_dataand specific values a0, a1\n# Compute the residuals as y_data - y_model and then find rss by using np.square() and np.sum()\n# Print the resulting value of rss\n\n# Load the data\nx_data, y_data = load_data()\n\n# Model the data with specified values for parameters a0, a1\ny_model = model(____, a0=150, a1=25)\n\n# Compute the RSS value for this parameterization of the model\nrss = np.sum(np.square(____ - ____))\nprint(\"RSS = {}\".format(____))\n\n\n\n\n\n\n\n\n\n\n\n#SOLUTION\n# Load the data\nx_data, y_data = load_data()\n\n# Model the data with specified values for parameters a0, a1\ny_model = model(x_data, a0=150, a1=25)\n\n# Compute the RSS value for this parameterization of the model\nrss = np.sum(np.square(y_data - y_model))\nprint(\"RSS = {}\".format(rss))","sub_path":"DataCamp_Introduction_to_Linear_Modeling_in_Python/2.3.1.Residual_Sum_of_the_Squares.py","file_name":"2.3.1.Residual_Sum_of_the_Squares.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"367677904","text":"add_library('minim')\nfrom Wall import Wall\nfrom Player import Player\nfrom Goal import Goal\nfrom OuterWalls import OuterWalls\nfrom Button import Button\nfrom Score import Score\nfrom Blackout import Blackout\nfrom Background import Background\n\nwalls = []\ngoals = []\ndiff = 750\nouterWalls = None\nplayer = None\nkeycount = 0\nscore = None\nhighScore = 0\nfailed = False\nfailed1 = False\nrestartButton = None\nstartButton = None\ninsaneStartButton = None\ngameIsRunning = False\nisGameInsane = False\nblackout = None\nimgInsaneBackground = PImage\nimgNormalBackground = PImage\nnormalBlocks = PImage\ninsaneBlocks = PImage\nlightBulb = PImage\nsplashScreen = PImage\nnormalButton = PImage\ninsaneButton = PImage\nnormalRestartButton = PImage\ninsaneRestartButton = PImage\npu = PImage\npd = PImage\npl = PImage\npr = PImage\ndoc = PImage\nfont = PFont\nsong = None\nping = None\nthud = None\nsplat = None\nscream = None\nbg = None\nisDocumentationVisible = False\n\ndef setup():\n global diff, player, song, goals, pu, isDocumentationVisible, pd, pr, pl, doc, ping, thud, doc, scream, splat, insaneRestartButton, normalRestartButton, imgInsaneBackground, insaneButton, normalButton, font, splashScreen, lightBulb, imgNormalBackground, normalBlocks, insaneBlocks, walls, bg, score, failed, failed1, outerWalls, restartButton, slothStartButton, insaneStartButton, blackout, isGameInsane\n size(1500, 800)\n imgInsaneBackground = loadImage(\"gameinsanebackground2.png\")\n imgNormalBackground = loadImage(\"gamenormalbackground.png\")\n normalBlocks = loadImage(\"blocks.png\")\n insaneBlocks = loadImage(\"insaneblocks.png\")\n lightBulb = loadImage(\"lightbulb.png\")\n splashScreen = loadImage(\"splashscreen3.png\")\n normalButton = loadImage(\"normal.png\")\n insaneButton = loadImage(\"insane.png\")\n normalRestartButton = loadImage(\"normalrestart.png\")\n insaneRestartButton = loadImage(\"insanerestart.png\")\n font = loadFont(\"attackofthecucumbers-48.vlw\")\n pu = loadImage(\"playerup.png\")\n pd = loadImage(\"playerdown.png\")\n pl = loadImage(\"playerleft.png\")\n pr = loadImage(\"playerright.png\")\n doc = loadImage(\"documentation.png\")\n bg = Background(imgNormalBackground)\n player = Player(PVector(100, height / 2), 50, pr)\n outerWalls = OuterWalls()\n slothStartButton = Button(PVector(width / 2, height / 2.3), 300, 80, \"normal mode\", normalButton)\n restartButton = Button(PVector(width / 2, height / 1.7), 300, 80, \"restart\", normalRestartButton)\n insaneStartButton = Button(PVector(width / 2, height / 1.7), 300, 80, \"insane mode\", insaneButton)\n minim = Minim(this)\n score = Score(0)\n blackout = Blackout()\n \n song = minim.loadFile(\"music_box_loop.mp3\")\n ping = minim.loadFile(\"ping.mp3\")\n thud = minim.loadFile(\"thud.mp3\")\n splat = minim.loadFile(\"splat.mp3\")\n scream = minim.loadFile(\"scream.mp3\")\n song.play()\n song.loop()\n\n for i in range(3):\n walls.append(Wall(PVector(diff, random(height / 4, height - height / 4)), 40, 320, normalBlocks))\n diff += 500\n goals.append(Goal(PVector(random(width - width / 3, width + 500), random(50, height - 50)), lightBulb))\n\n textFont(font)\n\ndef draw():\n background(230)\n if gameIsRunning:\n game_loop()\n else:\n splash_screen()\n\ndef game_loop():\n global isGameInsane, failed, highScore, isDocumentationVisible \n bg.draw()\n bg.update()\n score.update()\n if isDocumentationVisible:\n draw_documentation()\n \n for wall in walls:\n wall.update(height / 6)\n wall.draw()\n\n outerWalls.update()\n outerWalls.draw()\n\n ifPlayerIntersectsGoal()\n\n for goal in goals:\n ifGoalIntersectsOuterWalls(outerWalls, goal)\n goal.update()\n if isGameInsane:\n goal.initialSpeed = random(11, 12)\n goal.draw()\n\n player.move()\n player.draw()\n \n fill(255, 254, 183)\n textSize(30)\n text(\"score: \" + str(score.s), width / 4, height - 30)\n\n failed1 = ifPlayerIntersectsOuterWalls(outerWalls)\n if ifPlayerIntersectsOuterWalls(outerWalls):\n scream.play()\n for wall in walls:\n if not isGameInsane:\n if ifPlayerIntersectsWall(wall):\n if sideOfWall(wall) == \"above\":\n player.direction = PVector(0, -1)\n elif sideOfWall(wall) == \"below\":\n player.direction = PVector(0, 1)\n elif sideOfWall(wall) == \"left\":\n player.direction = PVector(-1, 0)\n else:\n player.direction = PVector(1, 0)\n player.moveNum(5)\n thud.play()\n thud.rewind()\n\n else:\n failed = ifPlayerIntersectsWall(wall)\n if ifPlayerIntersectsWall(wall):\n splat.play()\n if failed or failed1:\n bg.stop()\n score.stop()\n player.stop()\n #outerWalls.stop()\n\n for goal in goals:\n goal.stop()\n\n for wall in walls:\n wall.stop()\n\n if highScore < score.s:\n highScore = score.s\n \n blackout.draw()\n blackout.update()\n\n with pushStyle():\n fill(255, 254, 183)\n textSize(90)\n textAlign(CENTER)\n\n text(\"oops, you lost!\", width / 2, height / 3.2)\n textSize(50)\n text(\"score: \" + str(score.s), width/2, height/2.5)\n text(\"highscore: \" + str(highScore), width / 2, height / 2.1)\n if isGameInsane:\n slothStartButton.pos = (PVector(width / 2, height / 1.4))\n slothStartButton.visible = True\n slothStartButton.draw()\n restartButton.t = \"restart\\ninsane mode\"\n restartButton.img = insaneRestartButton\n else:\n insaneStartButton.pos = (PVector(width / 2, height / 1.4))\n insaneStartButton.visible = True\n insaneStartButton.draw()\n restartButton.t = \"restart\\nnormal mode\"\n restartButton.img = normalRestartButton\n restartButton.visible = True\n restartButton.draw()\n \n if isDocumentationVisible:\n draw_documentation()\n\n\n\n\ndef splash_screen():\n global isDocumentationVisible\n image(splashScreen, 0, 0)\n slothStartButton.draw()\n insaneStartButton.draw()\n if isDocumentationVisible:\n draw_documentation()\n\n\ndef mousePressed():\n if not gameIsRunning:\n slothStartButton.press(PVector(mouseX, mouseY))\n insaneStartButton.press(PVector(mouseX, mouseY))\n else:\n restartButton.press(PVector(mouseX, mouseY))\n if isGameInsane:\n slothStartButton.press(PVector(mouseX, mouseY))\n else:\n insaneStartButton.press(PVector(mouseX, mouseY))\n\ndef mouseReleased():\n global isGameInsane, gameIsRunning\n if slothStartButton.isPressed:\n gameIsRunning = True\n isGameInsane = False\n slothStartButton.release()\n restart()\n score.start()\n if insaneStartButton.isPressed:\n gameIsRunning = True\n isGameInsane = True\n insaneStartButton.release()\n restart()\n score.start()\n\n\n if restartButton.isPressed and restartButton.visible:\n restart()\n restartButton.release()\n score.start()\n\n\n \ndef keyPressed():\n if key == CODED:\n if keyCode == LEFT:\n player.update(PVector(-1, 0))\n player.img = pl\n if keyCode == RIGHT:\n player.update(PVector(1, 0))\n player.img = pr\n if keyCode == UP:\n player.update(PVector(0, -1))\n player.img = pu\n if keyCode == DOWN:\n player.update(PVector(0, 1))\n player.img = pd\n \n \n\n if key == 'a':\n player.update(PVector(-1, 0))\n player.img = pl\n if key == 'd':\n player.update(PVector(1, 0))\n player.img = pr\n if key == 'w':\n player.update(PVector(0, -1))\n player.img = pu\n if key == 's':\n player.update(PVector(0, 1))\n player.img = pd\n if key == 'o':\n toggleDocumentation()\n\n\n\ndef restart():\n global score\n bg.reset()\n splat.rewind()\n scream.pause()\n scream.rewind()\n failed = False\n failed1 = False\n diff = 750\n player.img = pr\n blackout.reset()\n\n player.update(PVector(0, 0))\n player.start()\n player.pos = PVector(100, height / 2)\n for goal in goals:\n goal.pos.x = random(width - width / 3, width + 300)\n goal.start()\n\n for wall in walls:\n wall.pos = PVector(diff, random(height / 4, height - height / 4))\n wall.img = normalBlocks\n diff += 500\n wall.start()\n \n outerWalls.changeInSpeed = 0.0005\n outerWalls.start()\n score.start()\n bg.img = imgNormalBackground\n \n if isGameInsane:\n for goal in goals:\n goal.initialSpeed = random(11, 12)\n\n player.speed = 13\n\n for wall in walls:\n wall.pos.x += 500\n wall.initialSpeed = 10\n wall.img = insaneBlocks\n \n \n bg.img = imgInsaneBackground\n outerWalls.changeInSpeed = 0.0009\n \n\n slothStartButton.visible = False\n insaneStartButton.visible = False\n restartButton.visible = False\n\ndef ifPlayerIntersectsGoal():\n for goal in goals:\n if dist(player.pos.x, player.pos.y, goal.pos.x, goal.pos.y) < (player.r / 2) + (goal.r / 2):\n goal.caught()\n outerWalls.moveBack()\n ping.play()\n ping.rewind()\n\n\ndef ifPlayerIntersectsWall(wall):\n circleDistanceX = abs(player.pos.x - wall.pos.x)\n circleDistanceY = abs(player.pos.y - wall.pos.y)\n\n if circleDistanceX > (wall.w / 2 + player.r / 2 + 1):\n return False\n if circleDistanceY > (wall.h / 2 + player.r / 2 + 1):\n return False\n if circleDistanceX <= (wall.w / 2):\n return True\n if circleDistanceY <= (wall.h / 2):\n return True\n cornerDistance = sq(circleDistanceX - wall.w / 2) + \\\n sq(circleDistanceY - wall.h / 2)\n if cornerDistance <= sq(player.r / 2):\n return True\n\ndef sideOfWall(wall):\n if player.pos.y > wall.pos.y + wall.h / 2:\n return \"below\"\n elif player.pos.y < wall.pos.y - wall.h / 2:\n return \"above\"\n if player.pos.x > wall.pos.x:\n return \"right\"\n else:\n return \"left\"\n\ndef ifPlayerIntersectsOuterWalls(outerWalls):\n distanceTop = abs(player.pos.y - outerWalls.wallY / 2)\n distanceBottom = abs(player.pos.y - height + outerWalls.wallY / 2)\n if distanceTop <= player.r / 2 or distanceBottom <= player.r / 2 or player.pos.x - player.r / 2 < 0 or player.pos.x + player.r / 2 > width or player.pos.y < outerWalls.wallY/2 or player.pos.y > (height - outerWalls.wallY / 2):\n return True\n\ndef ifGoalIntersectsOuterWalls(outerWalls, goal):\n distanceTop = abs(goal.pos.y - outerWalls.wallY / 2)\n distanceBottom = abs(goal.pos.y - height + outerWalls.wallY / 2)\n if distanceTop <= goal.r / 2 or distanceBottom <= goal.r / 2 or goal.pos.y < outerWalls.wallY / 2 or goal.pos.y > (height - outerWalls.wallY / 2):\n goal.caught()\n \n \ndef toggleDocumentation():\n global isDocumentationVisible\n if isDocumentationVisible:\n isDocumentationVisible = False\n else:\n isDocumentationVisible = True\n \n \ndef draw_documentation():\n imageMode(CORNER)\n image(doc, 0, 0)","sub_path":"blackout/blackout.pyde","file_name":"blackout.pyde","file_ext":"pyde","file_size_in_byte":11575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"323503262","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 30 15:20:58 2018\n\n@author: Błażej\n\"\"\"\n\nimport theano\nimport os\nimport pandas as pd\nimport numpy as np\nimport itertools as iter\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.model_selection import cross_val_score\nimport timeit\nimport keras \nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.optimizers import SGD\nimport matplotlib\nfrom keras.utils import np_utils\nfrom keras.utils import to_categorical\nimport matplotlib.pyplot as plt\nimport threading\nimport multiprocessing\n\nos.chdir('C:/Users/Błażej/Desktop/python/repo/python-exercises/')\ndata=pd.read_csv('train.csv')\nhouse=pd.read_csv('house_prices.csv')\n\nclass InvalidWeightInitMethod(Exception):\n pass\nclass NoInputLayerPassed(Exception):\n pass\n\noutput = multiprocessing.Queue()\n\n\ndef multithreadedLearner(data,X,y,indexMin,indexMax,output):\n results=[0 for i in range(0,data.shape[0])]\n for i in range(indexMin,indexMax): \n model=Sequential()\n layersListLength=len(data.loc[i,'nunits'])\n if layersListLength>0:\n model.add(Dense(input_dim=X.shape[1],units=data.loc[1,'nunits'][0]))\n else:\n raise NoInputLayerPassed(\"there were no inout layers provided, please provide number of units per layer and try again\") \n for j in range(0,layersListLength-1):\n model.add(Dense(input_dim=j,units=(data.loc[i,'nunits'][j+1]))) \n model.add(Dense(input_dim=data.loc[i,'nunits'][-1],units=y.shape[1])) \n model.compile(loss='categorical_crossentropy',optimizer=data.loc[i,'optimizers'],metrics=['accuracy']) \n start_time = timeit.default_timer()\n fitted=model.fit(X,y,verbose=1,epochs=data.loc[i,'epochs'],validation_split=0.2) \n elapsed = timeit.default_timer() - start_time\n data.loc[i,'time']=elapsed\n results[i]=fitted.history['val_acc']\n data['results']=pd.Series(results)\n output.put(data)\n\n\n\n\nclass Simulator:\n\n def __init__(self):\n self.results=[[]]\n self.X=pd.DataFrame()\n self.y=pd.DataFrame()\n self.isRegression=False\n \n def dataPreparation(self,data,decision_variable,explanatory_variables,dummy_variables,isRegression=False):\n data=data[explanatory_variables+decision_variable+dummy_variables]\n data=data.fillna(0)\n data=pd.get_dummies(data,columns=dummy_variables)\n y=data[decision_variable]\n X=data.drop(decision_variable,axis=1)\n self.X=X\n if isRegression:\n self.y=y\n self.isRegression=isRegression\n else:\n self.y=pd.get_dummies(y)\n self.isRegression=isRegression\n\n @property\n def getResults(self):\n return self.accuracy\n \n\n \nclass PerceptronSimulator(Simulator):\n \n def __init__(self):\n super(PerceptronSimulator, self).__init__()\n self.niter=[60]\n self.eta0=[0.1,0.2,0.3,0.4] \n self.combinedParameters=pd.DataFrame()\n \n \n def combineParameters(self):\n combinations=list(iter.product(self.niter,self.eta0,self.classWeights,[0],[0]))\n self.results=pd.DataFrame.from_records(combinations,columns=['niter','eta0','weight0','time','result'])\n \n \n def performSimulation(self):\n self.combineParameters()\n for i in range(0,self.results.shape[0]): \n ppn=Perceptron(n_iter=self.results.loc[i,'niter'],eta0=self.results.loc[i,'eta0'])\n start_time = timeit.default_timer()\n score=cross_val_score(ppn, self.X, self.y,fit_params={'coef_init':self.results.loc[i,'weight0']},cv=5).mean()\n elapsed = timeit.default_timer() - start_time\n self.results.loc[i,'result']=score\n self.results.loc[i,'time']=elapsed\n \n def setParameters(self,niterList=[20,40,60],eta0List=[0.01,0.15,0.2],class_weightList=[[0,0,0,0],[3,1,4,1]]):\n self.niter=niterList\n self.eta0=eta0List\n listOfWeights=[] \n for i in class_weightList:\n listOfWeights.append(np.array([i,i[:]]))\n \n self.classWeights=class_weightList\n \n\n def sampleWeight(self,ntrials=1,method=\"gaussian\"):\n if(method==\"gaussian\"):\n self.classWeights=[np.random.normal(0, 1,self.X.shape[1]) for i in range(0,ntrials+1)]\n elif(method==\"uniform\"):\n \n self.classWeights=[np.random.uniform(-1, 1,self.X.shape[1]) for i in range(0,ntrials+1)]\n else:\n raise InvalidWeightInitMethod(\"unknown weight initialization method passed\")\n \n \nclass MultilayerNN(Simulator):\n def __init__(self):\n super(MultilayerNN, self).__init__()\n self.combinedParameters=pd.DataFrame()\n self.nUnits=[[]]\n self.optimizers=[] \n def dataPreparation(self,data,decision_variable,explanatory_variables,dummy_variables,isRegression):\n super(MultilayerNN,self).dataPreparation(data,decision_variable,explanatory_variables,dummy_variables,isRegression)\n self.X=self.X.values\n if isRegression: \n self.y=self.y.values\n else:\n self.y=to_categorical(self.y.values) \n\n def combineParameters(self):\n combinations=list(iter.product(self.nUnits,self.optimizers,self.epochs,self.activation,[0],[[0]],[0],[0]))\n self.results=pd.DataFrame.from_records(combinations,columns=['nunits','optimizers','epochs','activation','time','results','bestAcc','modelObject'])\n def performSimulation(self):\n self.combineParameters() \n results=[0 for i in range(0,self.results.shape[0])] \n for i in range(0,self.results.shape[0]): \n model=Sequential()\n layersListLength=len(self.results.loc[i,'nunits'])\n ##adding first hidden layer wih input dimensions equal to the number of variables\n if layersListLength>0:\n model.add(Dense(input_dim=self.X.shape[1],units=self.results.loc[i,'nunits'][0]))\n else:\n raise NoInputLayerPassed(\"there were no input layers provided, please provide number of units per layer and try again\") \n ##adding hidden layers \n if layersListLength>1: \n for j in range(1,layersListLength-1):\n model.add(Dense(input_dim=self.results.loc[i,'nunits'][j-1],units=(self.results.loc[i,'nunits'][j])))\n\n ##adding output layer\n if self.isRegression:\n model.add(Dense(input_dim=self.results.loc[i,'nunits'][-1],units=1,activation='linear')) \n else:\n model.add(Dense(input_dim=self.results.loc[i,'nunits'][-1],units=len(list(np.unique(self.y))),activation=self.results.loc[i,'activation'])) \n \n if self.isRegression:\n model.compile(loss='mean_squared_error',optimizer=self.results.loc[i,'optimizers'],metrics=['mse']) \n else:\n model.compile(loss='categorical_crossentropy',optimizer=self.results.loc[i,'optimizers'],metrics=['accuracy']) \n \n print(model.summary)\n start_time = timeit.default_timer()\n fitted=model.fit(self.X,self.y,verbose=1,epochs=self.results.loc[i,'epochs'],validation_split=0.2) \n elapsed = timeit.default_timer() - start_time\n self.results.loc[i,'time']=elapsed\n if self.isRegression:\n results[i]=fitted.history['val_mean_squared_error']\n self.results.loc[i,'bestAcc']=max(fitted.history['val_mean_squared_error'])\n else:\n results[i]=fitted.history['val_acc']\n self.results.loc[i,'bestAcc']=max(fitted.history['val_acc'])\n self.results.loc[i,'modelObject']=model\n self.results['results']=pd.Series(results)\n \n def plotResults(self,index=0,chartType='epochs',optimizer='sgd',activation='sigmoid',epochs=[15]):\n\n if chartType=='epochs':\n plt.plot([i+1 for i in range(0,len(self.results.loc[index,'results']))],self.results.loc[index,'results'])\n plt.xlabel('epoch number')\n plt.ylabel('validation test accuracy')\n plt.suptitle('accuracy vs epoch, optimizer:'+optimizer+' ,activation:'+activation+' ,epochs:'+str(epochs))\n plt.show()\n elif chartType=='layers':\n subset=self.results.query('optimizers==@optimizer & activation==@activation & epochs==@epochs')\n plt.plot([i+1 for i in range(0,len(subset['bestAcc']))],[i for i in subset['bestAcc']])\n plt.xlabel('number of hidden layers')\n plt.ylabel('best validation test accuracy')\n plt.suptitle('best accuracy vs number of hidden layers, optimizer:'+optimizer+' ,activation:'+activation+' ,epochs:'+str(epochs))\n plt.show()\n\n def obtainBestModel(self):\n index=self.results['maxAcc'].index(max(self.results['maxAcc']))\n return self.results.loc[index,'modelObject']\n\n def setParameters(self,nUnits=[[50],[150,400],[70,80,13],[5,15,40,120]],optimizers=['sgd','adagrad','adadelta'],activation=['sigmoid','tanh','softmax'],epochs=[15]): \n self.nUnits=nUnits\n self.optimizers=optimizers \n self.activation=activation\n self.epochs=epochs \n if self.isRegression:\n self.activation=['linear'] \n else: \n self.activation=activation \n \n\n#####house prices\ntarget=['SalePrice']\nexp=['YrSold','LotArea']\ndummy=['SaleCondition']\nmodel=MultilayerNN()\nmodel.dataPreparation(house,target,exp,dummy,True)\nmodel.setParameters()\nmodel.combineParameters()\nstart_time = timeit.default_timer()\nmodel.performSimulation()\nelapsed = timeit.default_timer() - start_time\nmodel.results[[\"nunits\",\"optimizers\",\"epochs\",\"activation\",\"bestAcc\",\"time\"]]\n\n''' \ntarget=['Survived']\nexp=['Age','Sex','Pclass']\ndummy=['Sex']\nmodel=MultilayerNN()\nmodel.dataPreparation(data,target,exp,dummy,True)\nmodel.setParameters()\nmodel.combineParameters()\nstart_time = timeit.default_timer()\nmodel.performSimulation()\nelapsed = timeit.default_timer() - start_time\nmodel.results[[\"nunits\",\"optimizers\",\"epochs\",\"activation\",\"bestAcc\",\"time\"]]\nmodel.plotResults(0,'layers',optimizer='sgd',activation='sigmoid',epochs=15)\n#model.results.query('optimizers==\"sgd\" & activation=\"sigmoid\" & epochs=5')\n'''","sub_path":"biai.py","file_name":"biai.py","file_ext":"py","file_size_in_byte":10520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"316739386","text":"import shutil\nimport sys\nimport tempfile\nimport io\nimport unittest\nfrom argparse import Namespace\nfrom os.path import join, split\nimport subprocess\nfrom typing import *\n\nimport pytest\n\nfrom crosshair.fnutil import NotFound\nfrom crosshair.test_util import simplefs\nfrom crosshair.util import add_to_pypath\nfrom crosshair.util import load_file\n\nfrom crosshair.main import *\n\n\n@pytest.fixture(autouse=True)\ndef rewind_modules():\n defined_modules = list(sys.modules.keys())\n yield None\n for name, module in list(sys.modules.items()):\n # Some standard library modules aren't happy with getting reloaded.\n if name.startswith(\"multiprocessing\"):\n continue\n if name not in defined_modules:\n del sys.modules[name]\n\n\ndef call_check(\n files: List[str], options: AnalysisOptionSet = AnalysisOptionSet()\n) -> Tuple[int, List[str], List[str]]:\n stdbuf: io.StringIO = io.StringIO()\n errbuf: io.StringIO = io.StringIO()\n retcode = check(Namespace(target=files), options, stdbuf, errbuf)\n stdlines = [l for l in stdbuf.getvalue().split(\"\\n\") if l]\n errlines = [l for l in errbuf.getvalue().split(\"\\n\") if l]\n return retcode, stdlines, errlines\n\n\ndef call_diffbehavior(fn1: str, fn2: str) -> Tuple[int, List[str]]:\n buf: io.StringIO = io.StringIO()\n errbuf: io.StringIO = io.StringIO()\n retcode = diffbehavior(Namespace(fn1=fn1, fn2=fn2), DEFAULT_OPTIONS, buf, errbuf)\n lines = [l for l in buf.getvalue().split(\"\\n\") + errbuf.getvalue().split(\"\\n\") if l]\n return retcode, lines\n\n\nSIMPLE_FOO = {\n \"foo.py\": \"\"\"\ndef foofn(x: int) -> int:\n ''' post: _ == x '''\n return x + 1\n\"\"\"\n}\n\nFOO_CLASS = {\n \"foo.py\": \"\"\"\nclass Fooey:\n def incr(self, x: int) -> int:\n ''' post: _ == x '''\n return x + 1\n\"\"\"\n}\nASSERT_BASED_FOO = {\n \"foo.py\": \"\"\"\ndef foofn(x: int) -> int:\n ''' :raises KeyError: when input is 999 '''\n assert x >= 100\n x = x + 1\n if x == 1000:\n raise KeyError\n assert x != 101\n return x\n\"\"\"\n}\n\nFOO_WITH_CONFIRMABLE_AND_PRE_UNSAT = {\n \"foo.py\": \"\"\"\ndef foo_confirmable(x: int) -> int:\n ''' post: _ > x '''\n return x + 1\ndef foo_pre_unsat(x: int) -> int:\n '''\n pre: x != x\n post: True\n '''\n return x\n\"\"\"\n}\n\nOUTER_INNER = {\n \"outer\": {\n \"__init__.py\": \"\",\n \"inner.py\": \"\"\"\ndef foofn(x: int) -> int:\n ''' post: _ == x '''\n return x\n\"\"\",\n }\n}\n\nCIRCULAR_WITH_GUARD = {\n \"first.py\": \"\"\"\nimport typing\nif typing.TYPE_CHECKING:\n from second import Second\nclass First():\n def __init__(self, f: \"Second\") -> None:\n ''' post: True '''\n\"\"\",\n \"second.py\": \"\"\"\nfrom first import First\nclass Second():\n pass\n\"\"\",\n}\n\n\nDIRECTIVES_TREE = {\n \"outerpkg\": {\n \"__init__.py\": \"# crosshair: off\",\n \"outermod.py\": textwrap.dedent(\n \"\"\"\\\n def fn1():\n assert True\n raise Exception\n \"\"\"\n ),\n \"innerpkg\": {\n \"__init__.py\": \"# crosshair: on\",\n \"innermod.py\": textwrap.dedent(\n \"\"\"\\\n # crosshair: off\n def fn2():\n # crosshair: on\n assert True\n raise Exception # this is the only function that's enabled\n def fn3():\n assert True\n raise Exception\n \"\"\"\n ),\n },\n }\n}\n\n\nclass MainTest(unittest.TestCase):\n # TODO convert all to pytest; \"rewind_modules\" fixture above will handle teardown\n\n def setUp(self):\n self.root = Path(tempfile.mkdtemp())\n self.defined_modules = list(sys.modules.keys())\n\n def tearDown(self):\n shutil.rmtree(self.root)\n defined_modules = self.defined_modules\n for name, module in list(sys.modules.items()):\n # Some standard library modules aren't happy with getting reloaded.\n if name.startswith(\"multiprocessing\"):\n continue\n if name not in defined_modules:\n del sys.modules[name]\n\n def test_load_file(self):\n simplefs(self.root, SIMPLE_FOO)\n module = load_file(join(self.root, \"foo.py\"))\n self.assertNotEqual(module, None)\n self.assertEqual(module.foofn(5), 6)\n\n def test_check_by_filename(self):\n simplefs(self.root, SIMPLE_FOO)\n retcode, lines, _ = call_check([str(self.root / \"foo.py\")])\n self.assertEqual(retcode, 1)\n self.assertEqual(len(lines), 1)\n self.assertIn(\"foo.py:3: error: false when calling foofn\", lines[0])\n\n def test_check_by_class(self):\n simplefs(self.root, FOO_CLASS)\n with add_to_pypath(self.root):\n retcode, lines, _ = call_check([\"foo.Fooey\"])\n self.assertEqual(retcode, 1)\n self.assertEqual(len(lines), 1)\n self.assertIn(\"foo.py:4: error: false when calling incr\", lines[0])\n\n def test_check_failure_via_main(self):\n simplefs(self.root, SIMPLE_FOO)\n try:\n sys.stdout = io.StringIO()\n self.assertEqual(1, unwalled_main([\"check\", str(self.root / \"foo.py\")]))\n finally:\n sys.stdout = sys.__stdout__\n\n def test_check_ok_via_main(self):\n # contract is assert-based, but we do not analyze that type.\n simplefs(self.root, ASSERT_BASED_FOO)\n try:\n sys.stdout = io.StringIO()\n exitcode = unwalled_main(\n [\n \"check\",\n str(self.root / \"foo.py\"),\n \"--analysis_kind=PEP316,icontract\",\n ]\n )\n self.assertEqual(exitcode, 0)\n finally:\n sys.stdout = sys.__stdout__\n\n def test_no_args_prints_usage(self):\n try:\n sys.stderr = io.StringIO()\n exitcode = unwalled_main([])\n finally:\n out = sys.stderr.getvalue()\n sys.stderr = sys.__stderr__\n self.assertEqual(exitcode, 2)\n self.assertRegex(out, r\"^usage\")\n\n def DISABLE_TODO_test_assert_mode_e2e(self):\n simplefs(self.root, ASSERT_BASED_FOO)\n try:\n sys.stdout = io.StringIO()\n exitcode = unwalled_main(\n [\"check\", self.root / \"foo.py\", \"--analysis_kind=asserts\"]\n )\n finally:\n out = sys.stdout.getvalue()\n sys.stdout = sys.__stdout__\n self.assertEqual(exitcode, 1)\n self.assertRegex(\n out, r\"foo.py\\:8\\: error\\: AssertionError\\: when calling foofn\\(x \\= 100\\)\"\n )\n self.assertEqual(len([l for l in out.split(\"\\n\") if l]), 1)\n\n def test_directives(self):\n simplefs(self.root, DIRECTIVES_TREE)\n ret, out, err = call_check(\n [str(self.root)], AnalysisOptionSet(analysis_kind=[AnalysisKind.asserts])\n )\n self.assertEqual(err, [])\n self.assertEqual(ret, 1)\n self.assertRegex(out[0], r\"innermod.py:5: error: Exception: for any input\")\n self.assertEqual(len(out), 1)\n\n def test_directives_on_check_with_linenumbers(self):\n simplefs(self.root, DIRECTIVES_TREE)\n ret, out, err = call_check(\n [str(self.root / \"outerpkg\" / \"innerpkg\" / \"innermod.py\") + \":5\"],\n AnalysisOptionSet(analysis_kind=[AnalysisKind.asserts]),\n )\n self.assertEqual(err, [])\n self.assertEqual(ret, 1)\n self.assertRegex(out[0], r\"innermod.py:5: error: Exception: for any input\")\n self.assertEqual(len(out), 1)\n\n def test_report_confirmation(self):\n simplefs(self.root, FOO_WITH_CONFIRMABLE_AND_PRE_UNSAT)\n retcode, lines, _ = call_check([str(self.root / \"foo.py\")])\n self.assertEqual(retcode, 0)\n self.assertEqual(lines, [])\n # Now, turn on confirmations with the `--report_all` option:\n retcode, lines, _ = call_check(\n [str(self.root / \"foo.py\")], options=AnalysisOptionSet(report_all=True)\n )\n self.assertEqual(retcode, 0)\n self.assertEqual(len(lines), 2)\n output_text = \"\\n\".join(lines)\n self.assertIn(\"foo.py:3: info: Confirmed over all paths.\", output_text)\n self.assertIn(\"foo.py:7: info: Unable to meet precondition.\", output_text)\n\n def test_check_nonexistent_filename(self):\n simplefs(self.root, SIMPLE_FOO)\n retcode, _, errlines = call_check([str(self.root / \"notexisting.py\")])\n self.assertEqual(retcode, 2)\n self.assertEqual(len(errlines), 1)\n self.assertIn(\"File not found\", errlines[0])\n self.assertIn(\"notexisting.py\", errlines[0])\n\n def test_check_by_module(self):\n simplefs(self.root, SIMPLE_FOO)\n with add_to_pypath(self.root):\n retcode, lines, _ = call_check([\"foo\"])\n self.assertEqual(retcode, 1)\n self.assertEqual(len(lines), 1)\n self.assertIn(\"foo.py:3: error: false when calling foofn\", lines[0])\n\n def test_check_nonexistent_module(self):\n simplefs(self.root, SIMPLE_FOO)\n retcode, _, errlines = call_check([\"notexisting\"])\n self.assertEqual(retcode, 2)\n self.assertEqual(\n \"crosshair.fnutil.NotFound: Module 'notexisting' was not found\",\n errlines[-1],\n )\n\n def test_check_by_package(self):\n simplefs(self.root, OUTER_INNER)\n with add_to_pypath(self.root):\n retcode, lines, _ = call_check([\"outer.inner.foofn\"])\n self.assertEqual(retcode, 0)\n self.assertEqual(len(lines), 0)\n\n def test_check_nonexistent_member(self):\n simplefs(self.root, OUTER_INNER)\n with add_to_pypath(self.root):\n self.assertRaises(NotFound, lambda: call_check([\"outer.inner.nonexistent\"]))\n\n def test_check_circular_with_guard(self):\n simplefs(self.root, CIRCULAR_WITH_GUARD)\n with add_to_pypath(self.root):\n retcode, lines, _ = call_check([str(self.root / \"first.py\")])\n self.assertEqual(retcode, 0)\n\n def test_watch(self):\n # Just to make sure nothing explodes\n simplefs(self.root, SIMPLE_FOO)\n retcode = watch(\n Namespace(directory=[str(self.root)]),\n AnalysisOptionSet(),\n max_watch_iterations=2,\n )\n self.assertEqual(retcode, 0)\n\n def test_diff_behavior_same(self):\n simplefs(self.root, SIMPLE_FOO)\n with add_to_pypath(self.root):\n retcode, lines = call_diffbehavior(\"foo.foofn\", str(self.root / \"foo.py:2\"))\n self.assertEqual(\n lines,\n [\n \"No differences found. (attempted 2 iterations)\",\n \"All paths exhausted, functions are likely the same!\",\n ],\n )\n self.assertEqual(retcode, 0)\n\n def test_diff_behavior_different(self):\n simplefs(\n self.root,\n {\n \"foo.py\": \"\"\"\ndef add(x: int, y: int) -> int:\n return x + y\ndef faultyadd(x: int, y: int) -> int:\n return 42 if (x, y) == (10, 10) else x + y\n\"\"\"\n },\n )\n with add_to_pypath(self.root):\n retcode, lines = call_diffbehavior(\"foo.add\", \"foo.faultyadd\")\n self.assertEqual(retcode, 1)\n self.assertEqual(\n lines,\n [\n \"Given: (x=10, y=10),\",\n \" foo.add : returns 20\",\n \" foo.faultyadd : returns 42\",\n ],\n )\n\n def test_diff_behavior_error(self):\n retcode, lines = call_diffbehavior(\"foo.unknown\", \"foo.unknown\")\n self.assertEqual(retcode, 2)\n self.assertRegex(lines[0], \".*NotFound\")\n\n def test_diff_behavior_targeting_error(self):\n simplefs(self.root, SIMPLE_FOO)\n with add_to_pypath(self.root):\n retcode, lines = call_diffbehavior(\"foo.foofn\", \"foo\")\n self.assertEqual(retcode, 2)\n self.assertEqual(lines, ['\"foo\" does not target a function.'])\n\n def test_diff_behavior_via_main(self):\n simplefs(self.root, SIMPLE_FOO)\n sys.stdout = io.StringIO()\n try:\n with add_to_pypath(self.root):\n self.assertEqual(\n 0, unwalled_main([\"diffbehavior\", \"foo.foofn\", \"foo.foofn\"])\n )\n finally:\n out = sys.stdout.getvalue()\n sys.stdout = sys.__stdout__\n self.assertRegex(out, \"No differences found\")\n\n\ndef test_cover(tmp_path: Path, capsys: pytest.CaptureFixture[str]):\n simplefs(tmp_path, SIMPLE_FOO)\n with add_to_pypath(str(tmp_path)):\n assert unwalled_main([\"cover\", \"foo.foofn\"]) == 0\n assert capsys.readouterr().out == \"foofn(0)\\n\"\n\n\ndef test_main_as_subprocess(tmp_path: Path):\n # This helps check things like addaudithook() which we don't want to run inside\n # the testing process.\n simplefs(tmp_path, SIMPLE_FOO)\n completion = subprocess.run(\n [\"python\", \"-m\", \"crosshair\", \"check\", str(tmp_path)],\n capture_output=True,\n text=True,\n )\n assert completion.returncode == 1\n assert \"foo.py:3: error: false when calling foofn\" in completion.stdout\n assert completion.stderr == \"\"\n\n\ndef test_mypycrosshair_command():\n example_file = join(\n split(__file__)[0], \"examples\", \"icontract\", \"bugs_detected\", \"wrong_sign.py\"\n )\n completion = subprocess.run(\n [\n f\"python\",\n f\"-c\",\n f\"import crosshair.main;\"\n + f\"crosshair.main.mypy_and_check(['{example_file}'])\",\n ],\n capture_output=True,\n text=True,\n )\n assert completion.stderr.strip() == \"\"\n assert completion.returncode == 1\n\n\ndef test_describe_message():\n msg = AnalysisMessage(MessageType.PRE_UNSAT, \"unsat\", \"filename\", 1, 1, \"traceback\")\n opts = DEFAULT_OPTIONS.overlay(report_all=True, report_verbose=True)\n assert describe_message(msg, opts).split(\"\\n\") == [\n \"traceback\",\n \"\\x1b[91mI am having trouble finding any inputs that meet your preconditions.\\x1b[0m\",\n \"filename:1:\",\n \"\",\n \"unsat\",\n \"\",\n ]\n\n\nif __name__ == \"__main__\":\n if (\"-v\" in sys.argv) or (\"--verbose\" in sys.argv):\n set_debug(True)\n unittest.main()\n","sub_path":"crosshair/main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":14229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"569827965","text":"#! /usr/bin/python3\nimport re\nfile_path=\"/home/xdnsadmin/success.txt\"\nresult_path=\"/home/xdnsadmin/good_domains.txt\"\ndef is_domain( domain):\n domain_regex = re.compile(r'(?:[A-Z0-9_](?:[A-Z0-9-_]{0,247}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,}(? dict\n\n Parses the .cef file indicated by filename and returns a dictionary of the contents. \"\"\"\n with open(filename, 'r') as _file:\n output = parse(_file)\n return output\n\ndef parse(_file):\n \"\"\" usage: parse(cef_file) => dict\n\n Parses a .cef file and returns a dictionary of the contents. \"\"\"\n output = dict()\n indentation = 0\n category_levels = []\n last_section_type = ''\n while True:\n try:\n section_type, new_indentation = _determine_section_type(_file)\n except EOFError:\n if not all(output.values()):\n raise FieldError(\"Unable to find fields for entry '{}'\".format(entry_name))\n return output\n if last_section_type == \"entry\" and section_type != \"fields\":\n raise FieldError(\"Unable to find fields for entry '{}'\".format(entry_name))\n\n if section_type == \"category\":\n category_name = _parse_category(_file)\n if not new_indentation:\n output[category_name] = category = dict()\n category_levels = [category]\n elif new_indentation > indentation:\n indentation = new_indentation\n category_levels.append(category)\n category[category_name] = category = dict()\n elif new_indentation == indentation:\n category_levels[-2][category_name] = category = dict()\n else:\n assert new_indentation < indentation\n del category_levels[-1]\n elif section_type == \"entry\":\n if new_indentation < indentation:\n indentation = new_indentation\n del category_levels[-1]\n category = category_levels[-1]\n entry_name = _parse_entry(_file)\n else:\n fields = _parse_fields(_file, indentation)\n assert fields\n category[entry_name] = fields\n last_section_type = section_type\n\ndef _determine_section_type(_file):\n position = _file.tell()\n output = ''\n indentation = 0\n while True:\n line = _file.readline()\n if not line:\n raise EOFError()\n indentation = _determine_indentation(line)\n line = line.strip()\n _indicator = set(line)\n if _indicator == set('='):\n output = \"category\"\n elif _indicator == set('-'):\n output = \"entry\"\n elif ':' in line:\n output = \"fields\"\n else:\n continue\n if output:\n _file.seek(position)\n return output, indentation\n\ndef _determine_indentation(line):\n indent_character = line[0]\n if indent_character not in (' ', '\\n'):\n return 0\n else:\n for indentation, character in enumerate(line):\n if character != indent_character:\n return indentation\n\ndef _parse_category(_file):\n category = ''\n while True:\n line = _file.readline()\n if not line:\n raise EOFError()\n line = line.strip()\n if not line:\n continue\n if not category:\n if set(line) == set('='):\n raise CategoryError(\"Unable to find category name before indicator line\")\n else:\n category = line\n else:\n return category\n\ndef _parse_entry(_file):\n entry = ''\n while True:\n line = _file.readline()\n if not line:\n raise EOFError()\n line = line.strip()\n if not line:\n continue\n if not entry:\n if set(line) == set('-'):\n raise EntryError(\"Entry name not found before indicator line\")\n else:\n entry = line\n else:\n return entry\n\ndef _parse_fields(_file, indentation):\n output = dict()\n while True:\n position = _file.tell()\n line = _file.readline()\n if not line:\n return output\n\n if not line.strip():\n continue\n\n line_indentation = _determine_indentation(line)\n if line_indentation < indentation:\n _file.seek(position)\n return output\n if line_indentation > indentation:\n indentation = line_indentation\n\n line = line.strip()\n if ':' not in line:\n _file.seek(position)\n return output\n field, value = line.split(':', 1)\n field = field.replace('-', '', 1).strip()\n value = value.strip()\n if not value:\n entry_name = _parse_entry(_file)\n fields = _parse_fields(_file, indentation)\n value = {entry_name: fields}\n output[field] = value\n\n\n#class CEF_File(object):\n#\n# def __init__(self, filename):\n# self.filename = filename\n# self.info = parse_filename(filename)\n#\n# def _get_categories(self):\n# return self.info.keys()\n# categories = property(_get_categories)\n","sub_path":"cefparser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"119969485","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('image/pic_0012.jpg', cv2.IMREAD_GRAYSCALE)\n\nlower_reso = cv2.pyrDown(img)\nheight_reso = cv2.pyrUp(img)\n\ncv2.imshow('img', img)\ncv2.imshow('lower_reso', lower_reso)\ncv2.imshow('height_reso', height_reso)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"Learn_OpenCV_in_Python/opencv_28_图像金字塔.py","file_name":"opencv_28_图像金字塔.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"484112685","text":"from flask import Flask,request\nfrom flask.wrappers import Request\nfrom Database import database \nfrom Department import department\nfrom Doctor import doctor\nfrom Patient import patient\nfrom Hospital import hospital\n\napp=Flask(__name__)\n\n@app.route('/add_new_account',methods=['POST']) #{\"hospital_name\": \"hospital1\"}\ndef add_new_account():\n req=request.get_json()\n hospital_name=req[\"hospital_name\"]\n hospital_obj=hospital.hospital(hospital_name)\n res=database.database.database_existance_check_and_create_database(hospital_obj)\n return res\n\n\n\n@app.route('/add_department',methods=['POST']) #{\"department_name\": \"department1\"}\ndef add_department():\n req=request.get_json()\n department_name_to_add=req[\"department_name\"]\n res=department.department.add_department(department_name_to_add)\n return res\n\n@app.route('/remove_department',methods=['POST']) #{\"department_id\": \"department_id_2\"} \ndef remove_department():\n req=request.get_json()\n department_id_to_remove=req[\"department_id\"]\n res=department.department.remove_department(department_id_to_remove)\n return res\n\n@app.route('/edit_department',methods=['POST']) #{\"value_indicator\":{\"department_id\": \"department_id_1\"},\"values_to_update\":{\"department_name\": \"department_2.1\"}}\ndef edit_department():\n req=request.get_json()\n value_indicator_to_edit=req[\"value_indicator\"]\n values_to_update=req[\"values_to_update\"]\n res=department.department.edit_department(value_indicator_to_edit,values_to_update)\n return res\n\n@app.route('/search_department_id',methods=['POST']) #{\"department_id\":\"department_id_2\"}\ndef search_department_id():\n req=request.get_json()\n department_id_to_search=req[\"department_id\"]\n res=department.department.search_department_id(department_id_to_search)\n return res\n\n@app.route('/search_department_name',methods=['POST']) #{\"department_name\": \"department_1\"}\ndef search_department_name():\n req=request.get_json()\n department_name_to_search=req[\"department_name\"]\n res=department.department.search_department_name(department_name_to_search)\n return res\n\n\n@app.route('/search_all_departments',methods=['POST'])\ndef search_all_departments():\n res=department.department.search_all_department()\n return res\n \n\n\n #doctor\n\n@app.route('/add_doctor',methods=['POST']) #{\"department_name\":\"department1\",\"doctor_name\":\"doctor1\"}\ndef add_doctor():\n req=request.get_json()\n doctor_name_to_add=req[\"doctor_name\"]\n department_name_to_add=req[\"department_name\"]\n res=doctor.doctor.add_doctor(doctor_name_to_add,department_name_to_add)\n return res\n\n@app.route('/remove_doctor',methods=['POST']) #{\"doctor_id\": \"doctor_id_1\"}\ndef remove_doctor():\n req=request.get_json()\n doctor_id_to_remove=req[\"doctor_id\"]\n res=doctor.doctor.remove_doctor(doctor_id_to_remove)\n return res\n\n@app.route('/edit_doctor',methods=['POST']) #{\"value_indicator\":{\"doctor_id\": \"doctor_id_1\"},\"values_to_update\":{\"doctor_name\": \"doctor_name_edited\",deprtment_id:\"department_id_edited\"}}\ndef edit_doctor():\n req=request.get_json()\n value_indicator_to_edit=req[\"value_indicator\"]\n values_to_update=req[\"values_to_update\"]\n res=doctor.doctor.edit_doctor(value_indicator_to_edit,values_to_update)\n return res\n\n@app.route('/search_doctor_id',methods=['POST']) #{\"doctor_id\": \"doctor_id_1\"}\ndef search_doctor_id():\n req=request.get_json()\n doctor_id_to_search=req[\"doctor_id\"]\n res=doctor.doctor.search_doctor_id(doctor_id_to_search)\n return res \n\n\n@app.route('/search_doctor_name',methods=['POST']) #{\"doctor_name\": \"doctor_1\"}\ndef search_doctor_name():\n req=request.get_json()\n doctor_name_to_search=req[\"doctor_name\"]\n res=doctor.doctor.search_doctor(doctor_name_to_search)\n return res\n \n\n@app.route('/search_all_doctors',methods=['POST'])\ndef search_all_doctors():\n res=doctor.doctor.search_all_doctor()\n return res\n\n@app.route('/search_all_doctors_department_id',methods=['POST'])\ndef search_all_doctors_department_id():\n req=request.get_json()\n department_id=req[\"department_id\"]\n res=doctor.doctor.search_all_doctors_department_id(department_id)\n return res\n\n@app.route('/search_all_doctors_department_name',methods=['POST'])\ndef search_all_doctors_department_name():\n req=request.get_json()\n department_name=req[\"department_name\"]\n res=doctor.doctor.search_all_doctors_department_name(department_name)\n return res\n\n#patient\n\n@app.route('/add_patient',methods=['POST']) #{\"patient_name\":\"aneesh\",\"patient_age\":21,\"patient_gender\":\"male\",\"doctor_name\":\"doctor_1\",\"department_name\":\"department_1\"}\ndef add_patient():\n req=request.get_json()\n patient_name_to_add=req[\"patient_name\"]\n doctor_name_to_add=req[\"doctor_name\"]\n department_name_to_add=req[\"department_name\"]\n patient_age_to_add=req[\"patient_age\"]\n patient_gender_to_add=req[\"patient_gender\"]\n res=patient.patient.add_patient(patient_name_to_add,patient_age_to_add,patient_gender_to_add,doctor_name_to_add,department_name_to_add)\n return res\n\n@app.route('/remove_patient',methods=['POST']) #{\"patient_id\":\"patient_id_1\"}\ndef remove_patient():\n req=request.get_json()\n patient_id_to_add=req[\"patient_id\"]\n res=patient.patient.remove_patient(patient_id_to_add)\n return res\n\n@app.route('/edit_patient',methods=['POST']) #{\"value_indicator\":{\"patient_id\": \"patient_id_1\"},\"values_to_update\":{\"patient_name\":\"aneesh_edited\",\"patient_age\":21,\"patient_gender\":\"male\",\"doctor_name\":\"doctor_1\",\"department_name\":\"department_1\"}}\ndef edit_patient():\n req=request.get_json()\n value_indicator_to_edit=req[\"value_indicator\"]\n values_to_update=req[\"values_to_update\"]\n res=patient.patient.edit_patient(value_indicator_to_edit,values_to_update)\n return res\n\n@app.route('/search_patient_id',methods=['POST']) #{\"patient_id\":\"patient_id_1\"}\ndef search_patient_id():\n req=request.get_json()\n patient_id_to_search=req[\"patient_id\"]\n res=patient.patient.search_patient_id(patient_id_to_search)\n return res\n\n@app.route('/search_patient_name',methods=['POST']) #{\"patient_name\": \"aneesh_edited\"}\ndef search_patient_name():\n req=request.get_json()\n patient_name_to_search=req[\"patient_name\"]\n res=patient.patient.search_patient_name(patient_name_to_search)\n return res\n\n\n@app.route('/search_all_patients',methods=['POST']) #{\"patient_id\":\"patient_id_1\"}\ndef search_all_patients():\n res=patient.patient.search_all_patients()\n return res\n\n\n@app.route('/search_patient_department_name',methods=['POST']) #{\"department_name\": \"department_1\"}\ndef search_patient_department_name():\n req=request.get_json()\n department_name_to_search=req[\"department_name\"]\n res=patient.patient.search_patient_department_name(department_name_to_search)\n return res\n\n@app.route('/search_patient_doctor_name',methods=['POST']) #{\"doctor_name\": \"doctor_1\"}\ndef search_patient_doctor_name():\n req=request.get_json()\n doctor_name_to_search=req[\"doctor_name\"]\n res=patient.patient.search_patient_doctor_name(doctor_name_to_search)\n return res\n\n@app.route('/search_patient_department_name_doctor_name',methods=['POST']) #{\"doctor_name\": \"doctor_1\",\"department_name\": \"department_1\"}\ndef search_patient_department_name_doctor_name():\n req=request.get_json()\n department_name_to_search=req[\"department_name\"]\n doctor_name_to_search=req[\"doctor_name\"]\n res=patient.patient.search_patient_department_name_doctor_name(department_name_to_search,doctor_name_to_search)\n return res\n\n\n \n\n\nif __name__==\"__main__\":\n app.run(debug=True)","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":7594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"552655705","text":"#!/usr/bin/env python\n## This module is the base module for running the cockpit software; invoke\n# Python on it to start the program. It initializes everything and creates\n# the GUI.\n\nimport os\nimport sys\nimport threading\nimport traceback\nimport wx\n\nimport Pyro4\nimport distutils.version\nif (distutils.version.LooseVersion(Pyro4.__version__) >=\n distutils.version.LooseVersion('4.22')):\n Pyro4.config.SERIALIZERS_ACCEPTED.discard('serpent')\n Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle')\n Pyro4.config.SERIALIZER = 'pickle'\n Pyro4.config.REQUIRE_EXPOSE = False\n\n# We need these first to ensure that we can log failures during startup.\nimport depot\ndepot.loadConfig()\nimport util.files\nimport util.logger\nutil.files.initialize()\nutil.files.ensureDirectoriesExist()\nutil.logger.makeLogger()\n\nfrom config import config\n\nCOCKPIT_PATH = os.path.dirname(os.path.abspath(__file__))\n\nclass CockpitApp(wx.App):\n def OnInit(self):\n try:\n # Allow subsequent actions to abort startup by publishing\n # a \"program startup failure\" event.\n import events\n events.subscribe('program startup failure', self.onStartupFail)\n events.subscribe('program exit', self.onExit)\n\n # If I don't import util here, then if initialization fails\n # due to one of the other imports, Python complains about\n # local variable 'util' being used before its assignment,\n # because of the \"import util.user\" line further down combined\n # with the fact that we want to use util.logger to log the\n # initialization failure. So instead we have a useless\n # import to ensure we can access the already-loaded util.logger.\n import util\n import depot\n\n numDevices = len(config.sections()) + 1 # + 1 is for dummy devs.\n numNonDevices = 15\n status = wx.ProgressDialog(parent = None,\n title = \"Initializing OMX Cockpit\",\n message = \"Importing modules...\",\n ## Fix maximum: + 1 is for dummy devices\n maximum = numDevices + numNonDevices)\n status.Show()\n\n import gui.camera.window\n import gui.loggingWindow\n # Do this early so we can see output while initializing.\n gui.loggingWindow.makeWindow(None)\n import gui.macroStage.macroStageWindow\n import gui.mainWindow\n import gui.mosaic.window\n import gui.shellWindow\n import gui.statusLightsWindow\n import interfaces\n import util.user\n import util.userConfig\n\n updateNum=1\n status.Update(updateNum, \"Initializing config...\")\n updateNum+=1\n util.userConfig.initialize()\n\n status.Update(updateNum, \"Initializing devices...\")\n updateNum+=1\n for i, device in enumerate(depot.initialize(config)):\n status.Update(updateNum, \"Initializing devices...\\n%s\" % device)\n updateNum+=1\n #depot.initialize(config)\n status.Update(updateNum, \"Initializing device interfaces...\")\n updateNum+=1\n interfaces.initialize()\n\n status.Update(updateNum, \"Initializing user interface...\")\n updateNum+=1\n\n frame = gui.mainWindow.makeWindow()\n status.Update(updateNum, \" ... camera window\")\n updateNum+=1\n self.SetTopWindow(frame)\n gui.camera.window.makeWindow(frame)\n status.Update(updateNum, \" ... mosaic window\")\n updateNum+=1\n gui.mosaic.window.makeWindow(frame)\n status.Update(updateNum, \" ... macrostage window\")\n updateNum+=1\n gui.macroStage.macroStageWindow.makeWindow(frame)\n status.Update(updateNum, \" ... shell window\")\n updateNum+=1\n gui.shellWindow.makeWindow(frame)\n status.Update(updateNum, \" ... statuslights window\")\n updateNum+=1\n gui.statusLightsWindow.makeWindow(frame)\n\n # At this point, we have all the main windows are displayed.\n self.primaryWindows = [w for w in wx.GetTopLevelWindows()]\n # Now create secondary windows. These are single instance\n # windows that won't appear in the primary window marshalling\n # list.\n status.Update(updateNum, \" ... secondary windows\")\n updateNum+=1\n #start touchscreen only if enableds.\n #if(util.userConfig.getValue('touchScreen',\n # isGlobal = True, default= 0) is 1):\n import gui.touchscreen.touchscreen\n gui.touchscreen.touchscreen.makeWindow(frame)\n import gui.valueLogger\n gui.valueLogger.makeWindow(frame)\n from util import intensity\n intensity.makeWindow(frame)\n # All secondary windows created.\n self.secondaryWindows = [w for w in wx.GetTopLevelWindows() if w not in self.primaryWindows]\n\n for w in self.secondaryWindows:\n #bind close event to just hide for these windows\n w.Bind(wx.EVT_CLOSE, lambda event, w=w: w.Hide())\n # get saved state of secondary windows.\n title=w.GetTitle()\n windowstate=util.userConfig.getValue('windowState'+title,\n isGlobal = False,\n default= 0)\n #if they were hidden then return them to hidden\n if (windowstate is 0):\n # Hide the window until it is called up.\n w.Hide()\n\n # Now that the UI exists, we don't need this any more.\n # Sometimes, status doesn't make it into the list, so test.\n if status in self.primaryWindows:\n self.primaryWindows.remove(status)\n status.Destroy()\n\n util.user.login(frame)\n util.logger.log.debug(\"Login complete as %s\", util.user.getUsername())\n\n #now loop over secondary windows open and closeing as needed.\n for w in self.secondaryWindows:\n # get saved state of secondary windows.\n title=w.GetTitle()\n windowstate=util.userConfig.getValue('windowState'+title,\n isGlobal = False,\n default= 0)\n #if they were hidden then return them to hidden\n if (windowstate is 0):\n # Hide the window until it is called up.\n w.Hide()\n\n\n depot.makeInitialPublications()\n interfaces.makeInitialPublications()\n events.publish('cockpit initialization complete')\n self.Bind(wx.EVT_ACTIVATE_APP, self.onActivateApp)\n return True\n except Exception as e:\n wx.MessageDialog(None,\n \"An error occurred during initialization:\\n\\n\" +\n (\"%s\\n\\n\" % e) +\n \"A full code traceback follows:\\n\\n\" +\n traceback.format_exc() +\n \"\\nThere may be more details in the logs.\").ShowModal()\n util.logger.log.error(\"Initialization failed: %s\" % e)\n util.logger.log.error(traceback.format_exc())\n return False\n\n def onActivateApp(self, event):\n if not event.Active:\n return\n top = wx.GetApp().GetTopWindow()\n windows = top.GetChildren()\n for w in windows:\n if w.IsShown(): w.Raise()\n top.Raise()\n\n ## Startup failed; log the failure information and exit.\n def onStartupFail(self, *args):\n util.logger.log.error(\"Startup failed: %s\" % args)\n sys.exit()\n\n\n # Do anything we need to do to shut down cleanly. At this point UI\n # objects still exist, but they won't by the time we're done.\n def onExit(self):\n import util.user\n util.user.logout(shouldLoginAgain = False)\n # Manually clear out any parent-less windows that still exist. This\n # can catch some windows that are spawned by WX and then abandoned,\n # typically because of bugs in the program. If we don't do this, then\n # sometimes the program will continue running, invisibly, and must\n # be killed via Task Manager.\n for window in wx.GetTopLevelWindows():\n util.logger.log.error(\"Destroying %s\" % window)\n window.Destroy()\n\n # Call any deviec onExit code to, for example, close shutters and\n # switch of lasers.\n for dev in depot.getAllDevices():\n try:\n dev.onExit()\n except:\n pass\n\n\n\nif __name__ == '__main__':\n CockpitApp(redirect = False).MainLoop()\n # HACK: manually exit the program. If we don't do this, then there's a small\n # possibility that non-daemonic threads (i.e. ones that don't exit when the\n # main thread exits) will hang around uselessly, forcing the program to be\n # manually shut down via Task Manager or equivalent. Why do we have non-daemonic\n # threads? That's tricky to track down. Daemon status is inherited from the\n # parent thread, and must be manually set otherwise. Since it's easy to get\n # wrong, we'll just leave this here to catch any failures to set daemon\n # status.\n badThreads = []\n for thread in threading.enumerate():\n if not thread.daemon:\n badThreads.append(thread)\n if badThreads:\n util.logger.log.error(\"Still have non-daemon threads %s\" % map(str, badThreads))\n for thread in badThreads:\n util.logger.log.error(str(thread.__dict__))\n os._exit(0)\n\n","sub_path":"cockpit.pyw","file_name":"cockpit.pyw","file_ext":"pyw","file_size_in_byte":9900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"18582454","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2015 Serv. Tecnol. Avanz. ()\n# Pedro M. Baeza \n#\n# 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 published\n# by the Free Software Foundation, either version 3 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 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#\n##############################################################################\n\n\ndef migrate(cr, version):\n if not version:\n return\n # Ensure an unique sequence value\n cr.execute(\"\"\"\n UPDATE account_periodical_invoicing_agreement_line\n SET sequence = id\n \"\"\")\n","sub_path":"account_periodical_invoicing/migrations/8.0.1.1.0/post-migration.py","file_name":"post-migration.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"309470616","text":"# Create your views here.\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.template.loader import get_template\nfrom django.template import Context\nfrom django.shortcuts import render_to_response\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.template import RequestContext\nfrom django.utils.safestring import mark_safe\nfrom string import Template\nfrom django import template\nfrom django.utils.safestring import SafeUnicode\nfrom django.contrib.auth.decorators import permission_required\nfrom raceresults.failedloginblocker.exceptions import LoginBlockedError\nfrom django.forms import forms, ModelForm, Select\nfrom django.forms.formsets import formset_factory\nfrom django.forms.models import model_to_dict, modelformset_factory\nfrom django.forms.fields import DateField, TypedChoiceField\nfrom django.forms.extras.widgets import SelectDateWidget\nfrom django.contrib.admin.widgets import FilteredSelectMultiple\n\n#import time, datetime\n#from datetime import datetime, timedelta\nimport datetime as dt\nimport logging\nimport re\n\n#import models and search functions\nfrom raceresults.main.models import *\nfrom raceresults.main.newDatabase import *\nfrom raceresults.main.dbSearchFunctions import *\n\n#import excel import functions\nfrom raceresults.main.import_util import *\nfrom raceresults.main.importRiders import *\nfrom raceresults.main.processImportedObjects import *\n\nfrom raceresults.main.permissions import checkPermissions, errorPage, getPermissions, flattenPermissions\n\nfrom raceresults.main.mergeData import *\n\n# ----------- defines ------------\nDisplayFullResults = 0\n\ndef riderView(request, rider, full = False):\n\tcontext={}\n\t\n\tclubs = getClubs()\n\triderObject, flag = getRider(rider)\n\tif flag: raise Http404()\n\t\n\tclub = riderObject.club\n\n\tif request.user.is_authenticated():\n\t\tuser = request.user\n\t\tcontext['user'] = user\n\t\tif user.id == rider:\n\t\t\tcontext['hasPermissions'] = True\n\t\telse:\n\t\t\tpermissions, hasPermission, superUser = getPermissions(user)\n\t\t\tif hasPermission and (superUser or checkPermissions(permissions, club = club, superUser = True, manager = True, membership = True)):\n\t\t\t\tcontext['hasPermissions'] = True\n\n\tseasons, flag = getClubSeasons(club)\n\tif not flag:\n\t\tcontext['seasons'] = seasons\n\t\n\tcontext['athlete'] = riderObject\n\tcontext['club'] = club\n\tcontext['clubs'] = clubs\n\tcontext['comingRaces'] = getComingClubRaces(club)\n\tif (full):\n\t\tcontext['results'] = getFullRiderResults(riderObject)\n\t\tcontext['DisplayFullResults'] = True\n\telse:\n\t\tcontext['results'] = getRiderResults(riderObject)\n\t\n\tcontext['gradeHistory'] = getRiderGradeHistory(riderObject)\n\tcontext['clubHistory'] = getRiderClubHistory(riderObject)\n\tcontext['teamHistory'] = getRiderGradeHistory(riderObject)\n\tcontext['currentGrades'] = getRiderGrades(riderObject)\n\tcontext['squad'] = getRiderSquadHistory(riderObject)\n\t\n\treturn render_to_response('rider/rider.html', context, context_instance=RequestContext(request))\n\t\ndef fullRiderView(request, rider):\n\treturn riderView(request, rider, True)\t\n\t\n\t\ndef ridersView(request):\n\tcontext={}\n\tif request.user.is_authenticated():\n\t\tuser = request.user\n\t\tcontext['user'] = user\n\n\t# search need to be fixed\n\tif request.method == 'POST':\n\t\tclubs = getClubs()\n\t\tflag = False\n\t\tcontext['clubs'] = clubs\n\t\tif 'club' in request.POST and request.POST['club']:\n\t\t\tclub = request.POST['club']\t\n\t\t\tif club > 0:\n\t\t\t\ttry:\n\t\t\t\t\tclubObject = Club.objects.get(id=club)\n\t\t\t\t\tquery = Athlete.objects.filter(club=clubObject)\n\t\t\t\t\tcontext['club'] = clubObject\n\t\t\t\t\tflag = True\n\t\t\t\texcept Club.DoesNotExist:\n\t\t\t\t\tflag = False\n\t\t\t\t\tcontext['club'] = None\n\t\t\t\texcept Club.MultipleObjectsReturned:\n\t\t\t\t\tflag = False\n\t\t\t\t\tcontext['club'] = None\n\n\t\tif 'first_name' in request.POST and request.POST['first_name']:\n\t\t\tfirst_name = request.POST['first_name']\n\t\t\tcontext['first_name'] = first_name\n\t\t\tquery = Athlete.objects.filter(first_name__istartswith=first_name)\n\t\t\tflag = True\n\n\t\tif 'last_name' in request.POST and request.POST['last_name']:\t\n\t\t\tlast_name = request.POST['last_name']\n\t\t\tcontext['last_name'] = last_name\n\t\t\tif (flag):\n\t\t\t\tq2 = query.filter(last_name__istartswith=last_name)\n\t\t\t\tquery = q2\n\t\t\telse:\n\t\t\t\tquery = Athlete.objects.filter(last_name__istartswith=last_name)\n\t\t\t\tflag = True\n\t\t\n\t\tif 'number' in request.POST and request.POST['number']:\n\t\t\tnumber = request.POST['number']\n\t\t\tcontext['number'] = number\n\t\t\tif (flag):\n\t\t\t\tq2 = query.filter(athleteNumber__istartswith=number)\n\t\t\t\tquery = q2\n\t\t\telse:\n\t\t\t\tquery = Athlete.objects.filter(athleteNumber__istartswith=number)\n\t\t\t\tflag = True\n\n\t\tif flag:\n\t\t\tcontext['riders'] = query.order_by('last_name')\n\t\telse:\n\t\t\ttry:\n\t\t\t\tcontext['riders'] = Athlete.objects.order_by('last_name').all()\n\t\t\texcept:\n\t\t\t\tcontext['riders'] = []\n\telse:\n\t\tHttp404()\t\n\treturn render_to_response('rider/riders.html',context, context_instance=RequestContext(request))\n\n# edit functions\n\nFEMALE = 0\nMALE = 1\nSEX_CHOICES = (\n (FEMALE, 'Female'),\n (MALE, 'Male'),\n)\n\nPICTURE_LONGEST_SIDE = 500\n\nclass AthleteForm(ModelForm):\n\tsex = TypedChoiceField(widget = Select(), \n\t choices=SEX_CHOICES,initial=1, required = True,)\n\tclass Meta:\n\t\tmodel = Athlete\n\t\texclude = ('username','locationString','password','is_staff','is_active','is_superuser','grade','subGrade','trackGrade',\n\t\t\t\t\t'criteriumGrade','hasPermission', 'groups','user_permissions', 'last_login', 'date_joined')\n\t\twidgets = {'age' : SelectDateWidget(years=range(dt.datetime.now().year-10, dt.datetime.now().year-90, -1))}\n\t\t\nclass SelfForm(ModelForm):\n\tsex = TypedChoiceField(widget = Select(), \n\t choices=SEX_CHOICES,initial=1, required = True,)\n\tclass Meta:\n\t\tmodel = Athlete\n\t\texclude = ('username','locationString','password','is_staff','is_active','is_superuser','grade','subGrade','trackGrade',\n\t\t\t\t\t'criteriumGrade','hasPermission', 'groups','user_permissions', 'last_login', 'date_joined', 'isDirector','isActive', )\n\t\twidgets = {'age' : SelectDateWidget(years=range(dt.datetime.now().year-10, dt.datetime.now().year-90, -1))}\n\n\ndef newAthlete(request):\n\tcontext={}\n\tuser = request.user\n\tcontext['user'] = user\n\tcontext['clubs'] = getClubs()\n\n\tpermissions, hasPermission, superUser = getPermissions(user)\n\tif hasPermission and (superUser or checkPermissions(permissions, superUser = True, manager = True, membership = True)):\n\t\ttry:\n\t\t\tclub = user.athlete.club\n\t\texcept:\n\t\t\tclub = None\n\n\t\tseasons, flag = getClubSeasons(club)\n\t\tif not flag:\n\t\t\tcontext['seasons'] = seasons\n\n\t\tif request.method == 'POST': # If the form has been submitted...\n\t\t\tform = AthleteForm(request.POST) # A form bound to the POST data\n\t\t\tif form.is_valid() and form.cleaned_data['first_name'] != '' and form.cleaned_data['last_name'] != '':\n\t\t\t\tif superUser or checkPermissions(permissions, club = form.cleaned_data['club'], manager=True, membership=True):\n\t\t\t\t\tathleteObject = form.save(commit=False)\n\t\t\t\t\tuniqueName,error = generateUniqueUsername(form.cleaned_data['first_name'],form.cleaned_data['last_name'])\n\t\t\t\t\tathleteObject.username = uniqueName\n\t\t\t\t\tathleteObject.locationString = athleteObject.location.locationString\n\t\t\t\t\timage = request.FILES.get('image', None)\n\t\t\t\t\tif not image == None:\n\t\t\t\t\t\thandleUploadedImage(image = image, rider = athleteObject)\n\t\t\t\t\t\n\t\t\t\t\tathleteObject.save()\n\t\t\t\t\treturn HttpResponseRedirect('/rider/' + str(athleteObject.id) + '/') # Redirect after POST\n\t\t\t\telse:\n\t\t\t\t\treturn errorPage(request, context, [form.cleaned_data['club'].uniqueName + ' : Manager or Membership'])\n\t\t\telse:\n\t\t\t\tcontext['form']\t= form\t\t\t\n\t\t\t\treturn render_to_response('rider/athlete.html', context, context_instance=RequestContext(request))\n\t\telse:\n\t\t\tform = AthleteForm() # An unbound form\n\n\t\tcontext['form']\t= form\t\n\n\t\treturn render_to_response('rider/edit/athlete.html', context, context_instance=RequestContext(request))\n\telse:\n\t\tcontext['permissions'] = permissions\n\t\treturn errorPage(request, context, ['Manager or Race or Director'])\n\ndef editAthlete(request, athlete):\n\tcontext={}\n\tuser = request.user\n\tcontext['user'] = user\n\tcontext['clubs'] = getClubs()\n\tpermissions, hasPermission, superUser = getPermissions(user)\n\tif hasPermission and (superUser or checkPermissions(permissions, superUser = True, manager = True, membership = True)):\n\t\ttry:\n\t\t\tclub = user.athlete.club\n\t\texcept:\n\t\t\tclub = None\n\n\t\tseasons, flag = getClubSeasons(club)\n\t\tif not flag:\n\t\t\tcontext['seasons'] = seasons\n\t\t\n\t\tif request.method == 'POST': # If the form has been submitted...\n\t\t\tathleteObj, flag = getRider(athlete)\n\t\t\tif not flag and (superUser or \n\t\t\t\tcheckPermissions(permissions, club = athleteObj.club, manager=True, membership=True)): \t\t\t\t\n\t\t\t\tform = AthleteForm(request.POST, instance=athleteObj)\n\t\t\t\tif form.is_valid() and form.cleaned_data['first_name'] != '' and form.cleaned_data['last_name'] != '':\n\t\t\t\t\tif (superUser or checkPermissions(permissions, club = form.cleaned_data['club'], manager=True, membership=True)):\n\t\t\t\t\t\timage = form.cleaned_data['picture']\n\t\t\t\t\t\tpicture = request.FILES.get('picture',None)\n\t\t\t\t\t\tif picture:\n\t\t\t\t\t\t\thandleUploadedImage(image = picture, rider = athleteObj)\n\t\t\t\t\t\tif athleteObj.club != form.cleaned_data['club']:\n\t\t\t\t\t\t\tnote = 'Changed club from: ' + athleteObj.club.uniqueName + ' to ' + form.cleaned_data['club'].uniqueName + ' by ' + user.username\n\t\t\t\t\t\t\tclubHistory = AthleteClubHistory.objects.create(athlete = athleteObj,\n\t\t\t\t\t\t\t\tnote = '', date = datetime.now(), current = True)\n\t\t\t\t\t\t\tclubHistory.save()\n\t\t\t\t\t\tathleteObject = form.save(commit=False)\n\t\t\t\t\t\tathleteObject.locationString = athleteObject.location.locationString\n\t\t\t\t\t\tathleteObject.save()\n\t\t\t\t\t\treturn HttpResponseRedirect('/rider/' + str(athleteObject.id) + '/') # Redirect after POST\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn errorPage(request, context, [form.cleaned_data['club'] + ' : Manager or Membership'])\n\t\t\t\tcontext['form']\t= form\t\n\t\t\t\tcontext['athlete'] = athleteObj\t\t\n\t\t\t\treturn render_to_response('rider/edit/athlete.html', context, context_instance=RequestContext(request))\n\t\t\telse:\n\t\t\t\traise Http404()\n\t\telse:\n\t\t\tathleteObject, flag = getRider(athlete)\n\t\t\tif not flag:\n\t\t\t\tform = AthleteForm(instance=athleteObject)\n\t\t\t\tcontext['athlete'] = athleteObject\n\t\t\telse:\n\t\t\t\traise Http404()\n\n\t\t\tcontext['form']\t= form\t\n\t\t\treturn render_to_response('rider/edit/athlete.html', context, context_instance=RequestContext(request))\n\t\n\tcontext['permissions'] = permissions\n\treturn errorPage(request, context, ['Manager or Membership'])\t\n\ndef editSelf(request):\n\tcontext={}\n\tuser = request.user\n\tcontext['user'] = user\n\tcontext['clubs'] = getClubs()\n\tif user.is_authenticated() and not user.is_superuser:\n\t\tathlete = user.athlete\n\t\tclub = user.athlete.club\n\t\tseasons, flag = getClubSeasons(club)\n\t\tif not flag:\n\t\t\tcontext['seasons'] = seasons\n\n\t\tif request.method == 'POST': # If the form has been submitted...\n\t\t\tform = AthleteForm(request.POST, instance=athlete)\n\t\t\tif form.is_valid():\n\t\t\t\timage = form.cleaned_data['picture']\n\t\t\t\tpicture = request.FILES.get('picture',None)\n\t\t\t\tif picture:\n\t\t\t\t\thandleUploadedImage(image = picture, rider = athlete)\n\t\t\t\tif athlete.club != form.cleaned_data['club']:\n\t\t\t\t\tnote = 'Changed club from: ' + athlete.club.uniqueName + ' to ' + form.cleaned_data['club'].uniqueName + ' by ' + user.username\n\t\t\t\t\tclubHistory = AthleteClubHistory.objects.create(athlete = athlete,\n\t\t\t\t\t\tnote = '', date = datetime.now(), current = True)\n\t\t\t\t\tclubHistory.save()\n\n\t\t\t\tathleteObject = form.save(commit=False)\n\t\t\t\tathleteObject.locationString = athleteObject.location.locationString\n\t\t\t\tathleteObject.save()\n\t\t\t\treturn HttpResponseRedirect('/rider/' + str(athlete.id) + '/') # Redirect after POST\n\t\t\telse:\n\t\t\t\tcontext['athlete'] = athlete\n\t\t\t\tcontext['form']\t= form\t\n\t\t\t\treturn render_to_response('edit/self.html', context, context_instance=RequestContext(request))\t\t\t\t\n\t\telse:\n\t\t\tform = SelfForm(instance=athlete)\n\t\t\tcontext['athlete'] = athlete\n\t\t\tcontext['form']\t= form\t\n\t\t\treturn render_to_response('rider/edit/self.html', context, context_instance=RequestContext(request))\n\n\traise Http404()\n\ndef editRiders(request, club, last_name=None):\n\tcontext = {}\n\tuser = request.user\n\tcontext['user'] = user\n\n\tclubObject, error = getClubId(club)\n\tif error: raise Http404()\n\tcontext['club'] = clubObject\n\tcontext['clubs'] = getClubs()\n\n\tpermissions, hasPermission, superUser = getPermissions(user)\n\tif hasPermission and (superUser or \n\t\tcheckPermissions(permissions, club = clubObject, superUser = True, manager = True, membership = True)):\n\t\tcontext['permissions'] = permissions.get(clubObject.uniqueName, None)\n\t\tif last_name:\n\t\t\tif last_name == 'All':\n\t\t\t\tcontext['riders'] = getAllClubRiders(club)\n\t\t\telse:\n\t\t\t\tcontext['riders'] = getAllClubRiders(club,last_name)\n\telse:\n\t\tcontext['permissions'] = permissions\n\t\treturn errorPage(request, context, [clubObject.uniqueName + ' : Manager or Membership'])\n\n\treturn render_to_response(\"rider/edit/riders.html\", context, context_instance=RequestContext(request))\n","sub_path":"raceresults/main/riderViews.py","file_name":"riderViews.py","file_ext":"py","file_size_in_byte":12963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"538128838","text":"# RFM Analysis - Online Retail 2010-2011\r\n\r\n\r\n# Import libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport datetime as dt\r\n\r\n# to display all columns and rows:\r\npd.set_option(\"display.max_columns\", None)\r\npd.set_option(\"display.max_rows\", None)\r\n\r\n# how many digits will be shown after the comma:\r\npd.set_option(\"display.float_format\", lambda x: \"%.2f\" % x)\r\n\r\n\r\n\r\n# General overview #\r\n\r\n# Data for 2010 - 2011\r\ndf_2010_2011 = pd.read_excel(\"data/online_retail_II.xlsx\", sheet_name = \"Year 2010-2011\")\r\n\r\n# Let's back up dataset.\r\ndf = df_2010_2011.copy()\r\n\r\n# First 5 lines.\r\ndf.head()\r\n\r\n# Last 5 lines.\r\ndf.tail()\r\n\r\n# Shape of the dataset\r\ndf.shape\r\n\r\n# General information\r\ndf.info()\r\n\r\n# Are there any missing values in the dataset?\r\ndf.isnull().values.any()\r\n\r\n# How many missing values are in which variable?\r\ndf.isnull().sum()\r\n\r\n# How many unique products are in the data set?\r\ndf[\"Description\"].nunique()\r\n\r\n# Products and order quantities\r\ndf[\"Description\"].value_counts().head()\r\n\r\n# Let's find the most ordered products\r\ndf.groupby(\"Description\").agg({\"Quantity\":\"sum\"}).sort_values(\"Quantity\", ascending=False).head()\r\n\r\n# For RFM Analysis, let's find the total spending for each customer by multiplying the quantity and price variables.\r\ndf[\"TotalPrice\"] = df[\"Quantity\"] * df[\"Price\"]\r\n\r\ndf.head()\r\n\r\n# Let's find the canceled orders and then delete those orders from the data set.\r\ndf[df[\"Invoice\"].str.contains(\"C\", na = False)].head()\r\n\r\n# Let's delete canceled products with the help of Tilda\r\ndf = df[~df[\"Invoice\"].str.contains(\"C\", na = False)]\r\n\r\n# Look at the total price for each invoice\r\ndf.groupby(\"Invoice\").agg({\"TotalPrice\":\"sum\"}).head()\r\n\r\n# Country order amount\r\ndf[\"Country\"].value_counts()\r\n\r\n# Total price for each country\r\ndf.groupby(\"Country\").agg({\"TotalPrice\":\"sum\"}).head()\r\n\r\n# Now let's sort the countries by total price\r\ndf.groupby(\"Country\").agg({\"TotalPrice\":\"sum\"}).sort_values(\"TotalPrice\", ascending = False).head()\r\n\r\n\r\n# Let's try to find the most returned product.\r\n\r\n# First, let's restore the initial state of the dataset.\r\ndf1 = df_2010_2011\r\n\r\ndf1.head()\r\n\r\ndf1[df1[\"Invoice\"].str.contains(\"C\", na = False)].head()\r\n\r\n# Keep cancelled orders elsewhere\r\ndf_c = df1[df1[\"Invoice\"].str.contains(\"C\", na = False)]\r\n\r\ndf_c.head()\r\n\r\n# 5 most returned products\r\ndf_c[\"Description\"].value_counts().head()\r\n\r\n\r\n# Missing value analysis\r\ndf.isnull().sum()\r\n\r\n# Let's delete the missing values\r\ndf.dropna(inplace=True)\r\n\r\n# Look at the missing values again\r\ndf.isnull().sum()\r\n\r\n# Dataset after deleting missing data\r\ndf.shape\r\n\r\n\r\n# Describe\r\ndf.describe([0.01,0.05,0.10,0.25,0.50,0.75,0.90,0.95, 0.99]).T\r\n\r\n# Querying outlier for dataset\r\nfor feature in [\"Quantity\",\"Price\",\"TotalPrice\"]:\r\n\r\n Q1 = df[feature].quantile(0.01)\r\n Q3 = df[feature].quantile(0.99)\r\n IQR = Q3-Q1\r\n upper = Q3 + 1.5*IQR\r\n lower = Q1 - 1.5*IQR\r\n\r\n if df[(df[feature] > upper) | (df[feature] < lower)].any(axis=None):\r\n print(feature,\"yes\")\r\n print(df[(df[feature] > upper) | (df[feature] < lower)].shape[0])\r\n else:\r\n print(feature, \"no\")\r\n\r\n\r\n\r\n# RFM ANALYSIS #\r\n\r\n\"\"\"\r\nIt consists of the initials of Recency, Frequency, Monetary.\r\n\r\nIt is a technique that helps determine marketing and sales strategies based on customers' buying habits.\r\n\r\n* Recency: Time since the customer's last purchase\r\n\r\n - In other words, it is the time elapsed since the last contact of the customer.\r\n\r\n - Today's date - Last purchase\r\n\r\n - For example, if we are doing this analysis today, today's date - the last product purchase date.\r\n\r\n - For example, this could be 20 or 100. We know that the customer with Recency = 20 is hotter. \r\n He has been in contact with us recently.\r\n\r\n* Frequency: Total number of purchases.\r\n\r\n* Monetary: The total expenditure made by the customer.\r\n\"\"\"\r\n\r\n\r\n# RECENCY\r\n\r\ndf.head()\r\n\r\ndf.info()\r\n\r\n# first invoice date\r\ndf[\"InvoiceDate\"].min()\r\n\r\n# last invoice date\r\ndf[\"InvoiceDate\"].max()\r\n\r\n# We will consider the last transaction date as today's date.\r\ntoday_date = dt.datetime(2011, 12, 9)\r\n\r\ntoday_date\r\n\r\n# Last invoice date for each customer\r\ndf.groupby(\"Customer ID\").agg({\"InvoiceDate\":\"max\"}).head()\r\n\r\n# intager\r\ndf[\"Customer ID\"] = df[\"Customer ID\"].astype(int)\r\n\r\ndf.groupby(\"Customer ID\").agg({\"InvoiceDate\":\"max\"}).head()\r\n\r\n# Time passed since the customer's last transaction?\r\ntemp_df = (today_date - (df.groupby(\"Customer ID\")).agg({\"InvoiceDate\":\"max\"}))\r\n\r\ntemp_df.head()\r\n\r\n# Rename\r\ntemp_df.rename(columns = {\"InvoiceDate\": \"Recency\"}, inplace = True)\r\n\r\ntemp_df.head()\r\n\r\n# let's just pick the days\r\n# ex:\r\ntemp_df.iloc[0,0].days\r\n\r\n# for all rows\r\nrecency_df = temp_df[\"Recency\"].apply(lambda x: x.days)\r\n\r\nrecency_df.head()\r\n\r\n\r\n# FREQUENCY\r\n\r\ndf.head()\r\n\r\n# Number of invoices for each customer\r\n\r\ndf.groupby([\"Customer ID\", \"Invoice\"]).agg({\"Invoice\":\"nunique\"}).head(50)\r\n\r\n# We can calculate \"Fequency\" by simply finding number of unique values for each customer.\r\nfreq_df = df.groupby(\"Customer ID\").agg({\"InvoiceDate\":\"nunique\"})\r\n\r\nfreq_df.head()\r\n\r\n# Rename\r\nfreq_df.rename(columns = {\"InvoiceDate\":\"Frequency\"}, inplace=True)\r\n\r\nfreq_df.head(10)\r\n\r\n\r\n# MONETARY\r\n\r\ndf.head()\r\n\r\n# Let's calculate the total spend for each customer\r\nmonetary_df = df.groupby(\"Customer ID\").agg({\"TotalPrice\":\"sum\"})\r\n\r\nmonetary_df.head()\r\n\r\n# Rename\r\nmonetary_df.rename(columns = {\"TotalPrice\":\"Monetary\"}, inplace = True)\r\n\r\nmonetary_df.head()\r\n\r\n\r\n# Look at the shapes of the recency, frequency, monetary dataframe\r\nprint(recency_df.shape, freq_df.shape, monetary_df.shape)\r\n\r\n# Let's Concatenate the above data frames.\r\nrfm = pd.concat([recency_df, freq_df, monetary_df], axis = 1)\r\n\r\nrfm.head()\r\n\r\n\r\n# Recency Score\r\n\r\n# We gave the smallest value the highest score. Because smaller value is better for innovation.\r\n# It means that the customer has been shopping recently.\r\nrfm[\"RecencyScore\"] = pd.qcut(rfm[\"Recency\"], 5, labels = [5, 4 , 3, 2, 1])\r\n\r\nrfm.head()\r\n\r\n\r\n# Frequency Score\r\n\r\n# The higher the value for Frequency, the better.\r\n# That's why we give the highest score to the highest value.\r\nrfm[\"FrequencyScore\"] = pd.qcut(rfm[\"Frequency\"].rank(method = \"first\"), 5, labels = [1,2,3,4,5])\r\n\r\nrfm.head()\r\n\r\n\r\n# Monetary Score\r\n\r\nrfm[\"MonetaryScore\"] = pd.qcut(rfm[\"Monetary\"].rank(method = \"first\"), 5, labels = [1,2,3,4,5])\r\n\r\nrfm.head()\r\n\r\n\r\n# Calculating RFM Score --> R + F + M = RFM --> 3 + 1 + 4 = 314\r\n(rfm['RecencyScore'].astype(str) +\r\n rfm['FrequencyScore'].astype(str) +\r\n rfm['MonetaryScore'].astype(str)).head()\r\n\r\n# Let's add the RFM score to the rfm data frame\r\nrfm['RFM_SCORE'] = (rfm['RecencyScore'].astype(str) +\r\n rfm['FrequencyScore'].astype(str) +\r\n rfm['MonetaryScore'].astype(str))\r\n\r\nrfm.head()\r\n\r\n# Describe\r\nrfm.describe().T\r\n\r\n# Customers with a value of 555 (champions)\r\nrfm[rfm[\"RFM_SCORE\"]==\"555\"].head()\r\n\r\n# Customers with a value of 111 (hibernating)\r\nrfm[rfm[\"RFM_SCORE\"]==\"111\"].head()\r\n\r\n\r\n# RFM Mapping\r\n\r\nseg_map = {\r\n r'[1-2][1-2]':'Hibernating',\r\n r'[1-2][3-4]':'At Risk',\r\n r'[1-2]5':'Can\\'t Loose',\r\n r'3[1-2]':'About to Sleep',\r\n r'33':'Need Attention',\r\n r'[3-4][4-5]':'Loyal Customers',\r\n r'41':'Promising',\r\n r'51':'New Customers',\r\n r'[4-5][2-3]':'Potential Loyalists',\r\n r'5[4-5]':'Champions'\r\n}\r\n\r\n# For segmenting we will use Recency and Frequency scores\r\n\r\nrfm['Segment'] = rfm['RecencyScore'].astype(str) + rfm['FrequencyScore'].astype(str)\r\n\r\nrfm.head()\r\n\r\n# Let's replace 'segment' names with the seg_map names.\r\n\r\nrfm['Segment'] = rfm['Segment'].replace(seg_map, regex=True)\r\n\r\nrfm.head()\r\n\r\n# Summary\r\nrfm[[\"Segment\",\"Recency\",\"Frequency\", \"Monetary\"]].groupby(\"Segment\").agg([\"mean\",\"median\",\"count\"])\r\n\r\n# Number of customers\r\nrfm.shape[0]\r\n\r\n\r\n# Let's access the ID numbers of the customers in the loyal customers class.\r\n\r\nrfm[rfm[\"Segment\"] == \"Loyal Customers\"].index\r\n\r\nloyal_df = pd.DataFrame()\r\n\r\nloyal_df[\"LoyalCustomersID\"] = rfm[rfm[\"Segment\"] == \"Loyal Customers\"].index\r\n\r\nloyal_df.head()\r\n\r\n\r\n# Save dataframe in a .csv file.\r\n\r\nloyal_df.to_csv(\"RFM_Loyal_Customers_ID_2010-2011.csv\", index=False)\r\n\r\n\r\n# References\r\n\r\n\"\"\"\r\nhttps://www.datacamp.com/community/tutorials/introduction-customer-segmentation-python\r\n\r\nhttps://medium.com/@sbkaracan/rfm-analizi-ile-m%C3%BC%C5%9Fteri-segmentasyonu-proje-416e57efd0cf\r\n\r\nhttps://www.wikiwand.com/en/RFM_(market_research)\r\n\r\nhttps://www.veribilimiokulu.com/blog/rfm-analizi-ile-musteri-segmentasyonu/\r\n\"\"\"\r\n","sub_path":"RFM_Retail_2010-2011.py","file_name":"RFM_Retail_2010-2011.py","file_ext":"py","file_size_in_byte":8584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"432761809","text":"# Given a rectangular matrix containing only digits, calculate the number of different 2 × 2 squares in it.\n\n# + Example\n\n# - For\n# > matrix = [[1, 2, 1],\n# [2, 2, 2],\n# [2, 2, 2],\n# [1, 2, 3],\n# [2, 2, 1]]\n# the output should be\n# differentSquares(matrix) = 6.\n\n# + Input/Output\n\n# - [execution time limit] 4 seconds (py3)\n# - [input] array.array.integer matrix\n# Guaranteed constraints:\n# 1 ≤ matrix.length ≤ 100,\n# 1 ≤ matrix[i].length ≤ 100,\n# 0 ≤ matrix[i][j] ≤ 9.\n# - [output] integer\n# The number of different 2 × 2 squares in matrix.\n\n# + Solutions\n\n# - 13/13\n\n\ndef differentSquares(m):\n s = set()\n\n for y in range(len(m) - 1):\n for x in range(len(m[0]) - 1):\n s.add(m[y][x] + m[y][x+1] * 10 +\n m[y+1][x] * 100 + m[y+1][x+1] * 1000)\n\n return len(s)\n\n\nprint(differentSquares([\n [1, 2, 1],\n [2, 2, 2],\n [2, 2, 2],\n [1, 2, 3],\n [2, 2, 1]\n]))\n# > 6\n","sub_path":"code-fights/arcade/intro/12-land-of-logic/55-different-squares.py","file_name":"55-different-squares.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"521169437","text":"import logging\n\nfrom odoo import models,api,fields, _\nfrom datetime import datetime\nfrom odoo.exceptions import ValidationError\n\nclass taskPacchettoOre(models.Model):\n _name = 'task.pacchetto.ore'\n\n task_id = fields.Many2one('project.task')\n requested_hours = fields.Float()\n type = fields.Selection([\n ('developing', 'Sviluppo'),\n ('training', 'Formazione/consulenza')\n ])\n\nclass taskOreInherit(models.Model):\n\n _inherit = 'project.task'\n ore_lines = fields.One2many('task.pacchetto.ore', 'task_id')\n\n @api.onchange('ore_lines')\n def _onchange_ore_task(self):\n\n task = self.env['project.task'].browse(self.id)\n ore_task_formazione = 0\n ore_task_sviluppo = 0\n for ore in task.ore_lines:\n if ore.type == 'training':\n ore_task_formazione += ore.requested_hours\n if ore.type == 'developing':\n ore_task_sviluppo += ore.requested_hours\n\n ore_task_formazione_modifiche = 0\n ore_task_sviluppo_modifiche = 0\n for ore in self.ore_lines:\n if ore.type == 'training':\n ore_task_formazione_modifiche += ore.requested_hours\n if ore.type == 'developing':\n ore_task_sviluppo_modifiche += ore.requested_hours\n\n if self.partner_id.ore_sviluppo_disponibili + ore_task_sviluppo - ore_task_sviluppo_modifiche < 0:\n raise ValidationError(_('Non ci sono più ore di sviluppo disponibili per assegnare il task'))\n\n if self.partner_id.ore_formazione_consulenza_disponibili + ore_task_formazione - ore_task_formazione_modifiche < 0:\n raise ValidationError(_('Non ci sono più ore di formazione/consulenza disponibili per assegnare il task'))\n\n @api.onchange('partner_id')\n def _onchange_partner_id(self):\n\n\n ore_task_formazione_modifiche = 0\n ore_task_sviluppo_modifiche = 0\n for ore in self.ore_lines:\n if ore.type == 'training':\n ore_task_formazione_modifiche += ore.requested_hours\n if ore.type == 'developing':\n ore_task_sviluppo_modifiche += ore.requested_hours\n\n if self.partner_id.ore_sviluppo_disponibili - ore_task_sviluppo_modifiche < 0:\n raise ValidationError(_('Non ci sono più ore di sviluppo disponibili per assegnare il task'))\n\n if self.partner_id.ore_formazione_consulenza_disponibili - ore_task_formazione_modifiche < 0:\n raise ValidationError(_('Non ci sono più ore di formazione/consulenza disponibili per assegnare il task'))\n\n \"\"\"\n Va ad assegnare la riga di lavoro di una task \n al primo pacchetto ore disponibile(pacchetto con data di creazione più vecchia e che ha ancora ore disponibili).\n Le ore disponibili del pacchetto vengono scalate in base all somma delle ore di lavoro assegnate al quel pacchetto\n \"\"\"\n def write(self, vals):\n super(taskOreInherit, self).write(vals)\n\n if not self.partner_id.parent_id:\n cliente = self.partner_id\n else:\n cliente = self.partner_id.parent_id\n for type in ['developing', 'training']:\n new_lines = []\n ore_nuovo_pacchetto = 0\n data_pacchetto = False\n for line in self.timesheet_ids:\n if not line.pacchetto_ore_id and line.type == type:\n\n\n pacchetto_valido = self.env['pacchetti.ore'].search([('type', '=', line.type), ('ore_residue', '>', 0),\n ('partner_id', '=', cliente.id)], order='create_date asc', limit=1)\n if pacchetto_valido:\n\n if pacchetto_valido.ore_residue - line.unit_amount >= 0:\n\n # se con il pacchetto trovato riesco coprire tutte le ore della riga le assegno al pacchetto.\n pacchetto_valido.write({'ore_lines': [(4, line.id)]})\n line.pacchetto_ore_id = pacchetto_valido.id\n else:\n # Le ore del pacchetto non bastano quindi faccio uno split.\n # Alla riga corrente assegnamo le ore disponibili del pacchetto\n differenza_ore = line.unit_amount - pacchetto_valido.ore_residue\n\n if not data_pacchetto:\n # modifico la riga inserendo le ore residue del pacchetto\n line.unit_amount = pacchetto_valido.ore_residue\n pacchetto_valido.write({'ore_lines': [(4, line.id)]})\n line.pacchetto_ore_id = pacchetto_valido.id\n\n # cerco altri pacchetti disponibili e assegno le ore rimaste a questi creando nuove righe\n while pacchetto_valido and differenza_ore > 0:\n pacchetto_valido = self.env['pacchetti.ore'].search(\n [('type', '=', line.type), ('ore_residue', '>', 0),\n ('partner_id', '=', cliente.id)], order='create_date asc', limit=1)\n if pacchetto_valido:\n vals_nuova_riga = {\n 'date': line.date,\n 'employee_id': line.employee_id.id,\n 'name': line.name,\n 'type': line.type,\n 'pacchetto_ore_id': pacchetto_valido.id,\n 'unit_amount': 0,\n 'account_id': line.account_id.id\n }\n if pacchetto_valido.ore_residue > differenza_ore :\n vals_nuova_riga['unit_amount'] = differenza_ore\n differenza_ore = 0\n else:\n vals_nuova_riga['unit_amount'] = pacchetto_valido.ore_residue\n differenza_ore -= pacchetto_valido.ore_residue\n\n nuova_riga = self.env['account.analytic.line'].create(vals_nuova_riga)\n pacchetto_valido.write({'ore_lines': [(4, nuova_riga.id)]})\n super(taskOreInherit, self).write({'timesheet_ids': [(4, nuova_riga.id)]})\n\n # se ci sono ancora ore rimaste da assegnare ad un pacchetto ma non ce ne sono più disponibili,\n # si crea un nuovo pacchetto\n if differenza_ore > 0:\n ore_nuovo_pacchetto += differenza_ore\n data_pacchetto = {\n 'name': 'pacchetto aggiuntivo ' + datetime.today().date().strftime(\"%d/%m/%Y\"),\n 'type': pacchetto_valido.type,\n 'hours': 0,\n 'partner_id': cliente.id\n }\n new_lines.append({\n 'date': line.date,\n 'employee_id': line.employee_id.id,\n 'name': line.name,\n 'type': line.type,\n 'pacchetto_ore_id': 0,\n 'unit_amount': differenza_ore,\n 'account_id': line.account_id.id\n })\n else:\n ore_nuovo_pacchetto += line.unit_amount\n if not data_pacchetto:\n data_pacchetto = {\n 'name': self.partner_id.name + ' pacchetto aggiuntivo ' + datetime.today().date().strftime(\n \"%d/%m/%Y\"),\n 'type': type,\n 'hours': 0,\n 'partner_id': cliente.id\n }\n\n if data_pacchetto:\n # devo creare un nuovo pacchetto e le relative righe\n data_pacchetto['hours'] = ore_nuovo_pacchetto\n nuovo_pacchetto = self.env['pacchetti.ore'].create(data_pacchetto)\n for line in new_lines:\n line['pacchetto_ore_id'] = nuovo_pacchetto.id\n id = self.env['account.analytic.line'].create(line).id\n nuovo_pacchetto.write({'ore_lines': [(4, id)]})\n super(taskOreInherit, self).write({'timesheet_ids': [(4, id)]})\n for line in self.timesheet_ids:\n if not line.pacchetto_ore_id and line.type == type:\n line.pacchetto_ore_id = nuovo_pacchetto.id\n nuovo_pacchetto.write({'ore_lines': [(4, line.id)]})\n\n cliente.check_soglia_ore()\n\n","sub_path":"addoons_pacchetto_ore/models/addoons_task_ore.py","file_name":"addoons_task_ore.py","file_ext":"py","file_size_in_byte":9147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"625471379","text":"import pickle\n\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtWidgets import (QApplication, QWidget, QCompleter, QMessageBox,\n QDesktopWidget, QSplashScreen, QProgressBar)\n\nfrom ui_dict_form import UiDictForm\n\n\nclass DictWindow(QWidget, UiDictForm):\n def __init__(self, dict_file, parent=None):\n QWidget.__init__(self, parent)\n self.setup_ui(self)\n self.setLayout(self.gridLayout)\n self.center()\n with open(dict_file, 'rb') as f:\n self.dict = pickle.load(f)\n self.completer = QCompleter()\n self.model = QtCore.QStringListModel()\n self.model.setStringList(sorted(self.dict.keys()))\n self.input_russian_word.setCompleter(self.completer)\n self.completer.setModel(self.model)\n self.input_russian_word.setFixedHeight(40)\n self.input_russian_word.setFont(QtGui.QFont(\"Helvetica\", 13, QtGui.QFont.Light, False))\n self.input_russian_word.setPlaceholderText(\"Начните вводить\")\n self.output_translate.setFont(QtGui.QFont(\"Helvetica\", 14, QtGui.QFont.Normal, False))\n self.input_russian_word.returnPressed.connect(self.handle_enter)\n\n def closeEvent(self, event):\n reply = QMessageBox.question(self, 'Подтверждение выхода', 'Вы действительно хотите выйти?',\n QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n def keyPressEvent(self, key_event):\n if key_event.key() == QtCore.Qt.Key_Enter:\n self.handle_enter()\n\n @QtCore.pyqtSlot(name='handle_enter')\n def handle_enter(self):\n self.output_translate.setText('')\n keyword = self.input_russian_word.text()\n if keyword == '':\n self.output_translate.setText(\"Совпадений не найдено\")\n elif keyword in self.dict:\n all_translate = ''\n for translate in self.dict[keyword]:\n all_translate += translate + \"\\n\\n\"\n self.output_translate.setText(all_translate)\n else:\n self.output_translate.setText(\"Совпадений не найдено\")\n\n def center(self):\n rectangle = self.frameGeometry()\n center_point = QDesktopWidget().availableGeometry().center()\n rectangle.moveCenter(center_point)\n self.move(rectangle.topLeft())\n\n\nif __name__ == '__main__':\n import sys\n import time\n\n app = QApplication(sys.argv)\n\n splash_pix = QtGui.QPixmap('marvel.jpg')\n splash = QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint)\n splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)\n splash.setEnabled(False)\n progressBar = QProgressBar(splash)\n progressBar.setMaximum(10)\n progressBar.setGeometry(0, splash_pix.height() - 50, splash_pix.width(), 20)\n splash.show()\n\n for i in range(1, 11):\n progressBar.setValue(i)\n t = time.time()\n while time.time() < t + 0.025:\n app.processEvents()\n time.sleep(1)\n\n window = DictWindow('esk_rus_dict.dict')\n window.show()\n splash.finish(window)\n sys.exit(app.exec_())\n","sub_path":"dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"351993140","text":"from django.utils.translation import ugettext_lazy as _\nfrom cms.toolbar_pool import toolbar_pool\nfrom cms.toolbar_base import CMSToolbar\nfrom cms.utils.urlutils import admin_reverse\nfrom .models import Concept, InterestPage\n\n\nclass FocusToolbar(CMSToolbar):\n supported_apps = (\n 'apps.focus',\n )\n\n watch_models = [Concept, InterestPage]\n\n def populate(self):\n user = getattr(self.request, 'user', None)\n try:\n view_name = self.request.resolver_match.view_name\n except AttributeError:\n view_name = None\n\n if not user or not view_name:\n return\n\n change_concept_perm = user.has_perm(\n 'focus.change_concept')\n add_concept_perm = user.has_perm('focus.add_concept')\n change_ip_perm = user.has_perm(\n 'focus.change_interestpage')\n add_ip_perm = user.has_perm('focus.add_interestpage')\n\n menu = self.toolbar.get_or_create_menu('focus-app', _('Concepts'))\n\n if change_concept_perm:\n menu.add_sideframe_item(\n name=_('Concept list'),\n url=admin_reverse('focus_concept_changelist'),\n )\n\n if add_concept_perm:\n menu.add_modal_item(\n name=_('Add new concept'),\n url=admin_reverse('focus_concept_add'),\n )\n\n if change_ip_perm:\n menu.add_sideframe_item(\n name=_('Interest page list'),\n url=admin_reverse('focus_interestpage_changelist'),\n )\n\n if add_ip_perm:\n menu.add_modal_item(\n name=_('Add new interest page'),\n url=admin_reverse('focus_interestpage_add'),\n )\n\n if self.is_current_app and self.toolbar.obj:\n obj = self.toolbar.obj\n if isinstance(obj, Concept) and change_concept_perm:\n url = admin_reverse('focus_concept_change', args=[obj.pk])\n menu.add_modal_item(\n name=_('Edit this concept'),\n url = url,\n active = True,\n )\n if isinstance(obj, InterestPage) and change_ip_perm:\n url = admin_reverse('focus_interestpage_change', args=[obj.pk])\n menu.add_modal_item(\n name=_('Edit this interest page'),\n url = url,\n active = True,\n )\n\n\ntoolbar_pool.register(FocusToolbar) # register the toolbar\n","sub_path":"apps/focus/cms_toolbars.py","file_name":"cms_toolbars.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"40401097","text":"import sys\r\nimport os\r\nimport random as rnd\r\n\r\n# a 16-bit field that has the value 1010101010101010, indicating that this is an ACK packet.\r\nACKmagicno = '1010101010101010'\r\n# Read the information from the CMD\r\n\r\n# if(len(sys.argv)!=3):\r\n# print(\"Wrong Input\")\r\n#print(len(sys.argv))\r\n\r\nprob = float(sys.argv[3])\r\nfile = sys.argv[2]\r\nport = int(sys.argv[1])\r\nbuff_size = 2048\r\nseqno = 0\r\nl_flag = -1\r\n\r\nimport socket\r\n\r\n# https://wiki.python.org/moin/UdpCommunication\r\ncl_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\ncl_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\ncl_socket.bind(('', port))\r\n\r\n\r\ndef checksum(message, l):\r\n # l is len of message\r\n\r\n # if l is not even , padding an additional zero\r\n if (l % 2 != 0):\r\n message += \"0\".encode('utf-8')\r\n\r\n x = message[0] + ((message[1]) << 8)\r\n y = (x & 0xffff) + (x >> 16)\r\n\r\n for i in range(2, len(message), 2):\r\n x = message[i] + ((message[i + 1]) << 8)\r\n y = ((x + y) & 0xffff) + ((x + y) >> 16)\r\n return ~y & 0xffff\r\n\r\n\r\ndef sequence_generator():\r\n global seqno\r\n if seqno == int((2 ** 32) - 1):\r\n seqno = 0\r\n else:\r\n seqno += 1\r\n\r\n\r\ndef prob_gen():\r\n #rnd.seed(5)\r\n by = rnd.random()\r\n #print(by)\r\n return by\r\n\r\n\r\ndef l_flag_checker(val):\r\n a = str(val)\r\n #print(val)\r\n #print(str(val))\r\n #print(a[2])\r\n #print(a[3])\r\n\r\n if int(a[2]) == 1 and int(a[3])==1:\r\n #print(\"dsfds\")\r\n return 0\r\n\r\n return -1\r\n\r\n\r\nfname = file + '.txt'\r\nf = open(fname, 'w')\r\ns_checker =10\r\n#print(l_flag)\r\nctr_check =0\r\n\r\nwhile l_flag == -1:\r\n #print(\"entered the loop\")\r\n data_recvd, add = cl_socket.recvfrom(buff_size)\r\n # get the sequence number from the data_recd\r\n seq_recvd = int(data_recvd[0:32], 2)\r\n checksum_recvd = int(data_recvd[32:48], 2)\r\n payload_recvd = data_recvd[64:]\r\n\r\n # calculate checksum in server side of the payload_recvd\r\n checker = checksum(payload_recvd, len(payload_recvd))\r\n if seq_recvd == seqno-1:\r\n ctr_check = ctr_check+1\r\n else:\r\n ctr_check =0\r\n\r\n if ctr_check ==s_checker:\r\n seqno = seqno-1\r\n ctr_check =0\r\n\r\n # random number\r\n r_got = prob_gen()\r\n\r\n if r_got <= prob or seq_recvd != seqno:\r\n print('Timeout, sequence number = ', seqno)\r\n\r\n else:\r\n if seq_recvd == seqno and checksum_recvd == checker:\r\n #print('hello')\r\n l_flag = l_flag_checker(data_recvd[48:64])\r\n #print(int(data_recvd[48:64], 2))\r\n f.write(payload_recvd.decode('utf-8'))\r\n send_ack = '{:032b}'.format(int(seqno))\r\n data = send_ack.encode('utf-8') + ACKmagicno.encode('utf-8')\r\n sequence_generator()\r\n cl_socket.sendto(data, add)\r\n\r\nf.close()\r\nprint('Done')\r\ncl_socket.close()\r\n","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"9347114","text":"# -*- coding: utf-8 -*-\n\n\n# 暗号文\n# 与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.英小文字ならば(219 - 文字コード)の文字に置換その他の文字はそのまま出力この関数を用い,英語のメッセージを暗号化・復号化せよ.\n\n\ndef cipher(string):\n sentence = \"\"\n for char in string:\n if char.islower():\n sentence = sentence + chr(219 - ord(char))\n else:\n sentence = sentence + char\n return sentence\n\nif __name__ == \"__main__\":\n s = \"I am a NLPer\"\n print (s)\n print ('\\nEncode')\n print (cipher(s))\n print ('\\nDecode')\n print (cipher(cipher(s)))\n\n\n#\n#\n# def cipher(string):\n# result = ''\n# for char in string:\n# if char.islower():\n# result += chr(219 - ord(char))\n# else:\n# result += char\n# return result\n#\n# if __name__ == '__main__':\n# s = 'Test Stringa'\n# print s\n# print '\\nEncode'\n# print cipher(s)\n# print '\\nDecode'\n# print cipher(cipher(s))\n","sub_path":"yui/chapter01/knock08.py","file_name":"knock08.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"593635960","text":"# Nth Fibonacci\n# The Fibonacci sequence is defined as follows: the first number of the sequence\n# is 0, the second number is 1, and the nth number is the sum of the (n - 1)th\n# and (n - 2)th numbers. Write a function that takes in an integer n and returns\n# the nth Fibonacci number.\n\n# Important note: the Fibonacci sequence is often defined with its first two\n# numbers as F0 = 0 and F1 = 1. For the purpose of this question, the first\n# Fibonacci number is F0; therefore, getNthFib(1) is equal to F0, getNthFib(2)\n# is equal to F1, etc..\n\n# Sample Input #1\n# n = 2\n# Sample Output #1\n# 1 // 0, 1\n# Sample Input #2\n# n = 6\n# Sample Output #2\n# 5 // 0, 1, 1, 2, 3, 5\n\n# Initial solution - O(2^n) time, O(n) space\ndef get_nth_fib(n):\n if n == 1:\n return 0\n elif n == 2:\n return 1\n else:\n return getNthFib(n - 1) + getNthFib(n - 2)\n\n# Improved solution - O(n) time, O(1) space\ndef get_nth_fib(n):\n if n == 1:\n return 0\n if n == 2:\n return 1\n minus_two = 0\n minus_one = 1\n curr = 1\n for num in range(n - 3):\n new_curr = curr + minus_one\n minus_two = minus_one\n minus_one = curr\n curr = new_curr\n return curr\n","sub_path":"easy/get_nth_fibonacci.py","file_name":"get_nth_fibonacci.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"415144987","text":"\"\"\"\n\n\"\"\"\n\nimport pytest\nfrom orcidvalidator.orcid_misc import orcid_id_to_list\nfrom orcidvalidator.orcid_misc import calculate_orcid_id_checksum\nfrom orcidvalidator.orcid_misc import check_orcid_id_checksum\n\ninput_orcid_ids = ['0000-0002-6006-647X',\n '0000-0003-2123-4255',\n '0000-0003-1805-603X',\n '0000-0002-6021-3564',\n '0000-0001-7359-2711']\ninput_bad_orcid_ids = ['0000-0102-6006-647X',\n '0000-0003-1805-6039',\n '0000-0003-2123-3255']\nexpected_assertions = [True, True, True, True, True, False, False, False]\nexpected_orcid_checksums = ['X', '5', 'X', '4', '1']\nexpected_orcid_list = [\"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"2\", \"6\", \"0\", \"0\", \"6\", \"6\", \"4\", \"7\", \"X\"]\n\n\ndef test_orcid_id_to_list():\n assert orcid_id_to_list(input_orcid_ids[0]) == expected_orcid_list\n\n\n@pytest.mark.parametrize('input_orcid,expected_checksum', zip(input_orcid_ids, expected_orcid_checksums))\ndef test_calculate_orcid_id_checksum(input_orcid, expected_checksum):\n orcid_as_list = [x for x in input_orcid if x in \"01234567890X\"]\n checksum = calculate_orcid_id_checksum(orcid_as_list)\n assert checksum == expected_checksum\n\n\n@pytest.mark.parametrize('input_orcid,expected_assertion', zip(input_orcid_ids+input_bad_orcid_ids, expected_assertions))\ndef test_check_orcid_id_checksum(input_orcid, expected_assertion):\n assert check_orcid_id_checksum(input_orcid) == expected_assertion\n","sub_path":"test/test_orcid_misc.py","file_name":"test_orcid_misc.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"74359212","text":"#!/usr/bin/env python3\n\n# %%\nimport base64\nimport os\nimport tempfile\n\nimport bs4\nimport numpy as np\nimport requests\nimport torch\nimport torch.nn as nn\nfrom PIL import Image\nfrom torchvision import models\n\n\nTARGET_CLASS_NAME = 'frog'\nMODEL_DIR = os.environ.get('MODEL_DIR', '/tmp/pwnies_please/challenge/models/')\nMAX_SQUARED_DIFFERENCE = 1.0 # TODO: this needs tuning\nimagenet_class_index = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\nsess = requests.Session()\n\n# TODO: \n# WRITE PYTHON REQUESTS TO SUBMIT MULTIPLE ADVERSARIAL IMAGES\n# \n# make a session\n# get image sess.get('the_url')\n# adversarial-ify the image\n# sess.post(adversarial_image)\n# print last response to see that the number has incremented\n\ndef get_model(model_name=\"pwny_cifar_eps_0.pth\"):\n # Loads the model onto the cpu\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n model = models.resnet18()\n num_ftrs = model.fc.in_features\n model.fc = nn.Linear(num_ftrs, len(imagenet_class_index))\n model.load_state_dict(torch.load(os.path.join(\n MODEL_DIR, model_name), map_location=device))\n model.eval()\n return model\n\n\ndef bytes_to_image(img_data):\n with tempfile.NamedTemporaryFile(suffix='.png') as tmp:\n tmp.write(img_data)\n tmp.flush()\n return Image.open(tmp.name)\n\n\ndef get_image_to_attack(url='http://54.184.185.227:5000'):\n req = requests.get(url)\n req.raise_for_status()\n text = req.text\n soup = bs4.BeautifulSoup(text, 'html.parser')\n img_tag = soup.find('img')\n img_string = img_tag['src']\n img_string[:100]\n FOUND = 'data:image/png;base64,'\n assert img_string.startswith(FOUND), img_string[:100]\n\n img_data = base64.b64decode(img_string[len(FOUND):])\n return bytes_to_image(img_data)\n\n\ndef image_to_tensor(img):\n # convert to numpy array\n tensor = np.array(img).astype(np.float32) / 255.0\n tensor = tensor.transpose(2, 0, 1)\n tensor = tensor[None, :, :, :] # add batch dimension\n tensor = torch.tensor(tensor, requires_grad=True)\n assert tensor.shape == (1, 3, 32, 32), tensor.shape\n return tensor\n\n\ndef image_diff(A, B):\n return ((A - B) ** 2).sum()\n\n\ndef attack_image_tensor(atak_image, model):\n orig_image = atak_image.detach().clone()\n target = torch.tensor([imagenet_class_index.index(TARGET_CLASS_NAME)])\n optimizer = torch.optim.Adam([atak_image], lr=0.001)\n criterion = nn.CrossEntropyLoss()\n\n for i in range(100):\n optimizer.zero_grad()\n output = model(atak_image)\n loss = criterion(output, target)\n if i % 10 == 0:\n diff = image_diff(atak_image, orig_image)\n print(i, 'loss', loss.item(), 'diff', diff.item())\n loss.backward()\n optimizer.step()\n\n return atak_image\n\n\ndef tensor_to_img(tensor):\n tensor = tensor.detach().squeeze().numpy()\n tensor = tensor.transpose(1, 2, 0)\n tensor = (tensor * 255).astype(np.uint8)\n return Image.fromarray(tensor)\n\n\ndef save_image(img, save_file='/tmp/atak.png'):\n if os.path.exists(save_file):\n os.remove(save_file)\n img.save(save_file)\n\n\n# %%\nmodel = get_model()\natak_tensor = image_to_tensor(get_image_to_attack())\natak_tensor = attack_image_tensor(atak_tensor, model)\nsave_image(tensor_to_img(atak_tensor))\n\n","sub_path":"misc/pwnies_please/atak2.py","file_name":"atak2.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"216541490","text":"import sys\n\n\nalpha = ['A', 'C', 'G', 'T']\nloa = len(alpha)\n\n\nclass Node:\n\n def __init__(self, key, leaf=False):\n self.id = key\n self.label = ''\n self.leaf = leaf\n self.edges = {}\n\n def is_leaf(self):\n return self.leaf\n\n def get_label(self):\n return self.label\n\n def add_label(self, label):\n self.label += label\n\n def children(self):\n return [v for v in self.edges if v < self.id]\n\n def add_edge(self, v, w):\n self.edges[v] = w\n\n def get_weight(self, v):\n return self.edges[v]\n\n def change_weight(self, v, w):\n self.edges[v] = w\n\n def add_weight(self, v, dw):\n self.edges[v] += dw\n\n def remove_edge(self, v):\n self.edges.pop(v)\n\n def output_edges(self):\n return self.edges.items()\n\n\ndef ripe_node(t, tag):\n for v in range(len(tag)):\n if tag[v] == 1:\n continue\n node = t[v]\n if all([tag[child] for child in node.children()]):\n return v\n return 0\n\n\ndef small_parsimony(t, character):\n tag = [0] * len(t)\n s = [[0] * 4 for _ in range(len(t))]\n for v in t:\n if t[v].is_leaf():\n tag[v] = 1\n for i in range(loa):\n ch = alpha[i]\n if character[v] != ch:\n s[v][i] = 10**10\n\n while ripe_node(t, tag):\n v = ripe_node(t, tag)\n tag[v] = 1\n daughter, son = t[v].children()\n for i in range(loa):\n ch = alpha[i]\n min_daughter = min([s[daughter][j] + (alpha[j] != ch) for j in range(loa)])\n min_son = min([s[son][j] + (alpha[j] != ch) for j in range(loa)])\n s[v][i] = min_daughter + min_son\n return s\n\n\ndef parsimony(t, n):\n # length of dna string\n k = len(t[0].get_label())\n score = 0\n # looping through characters of dna strings\n for j in range(k):\n # calculating scores\n character = [t[i].get_label()[j] for i in range(n)]\n s = small_parsimony(t, character)\n min_score = min(s[-1])\n score += min_score\n # assigning label to root\n ch = alpha[s[-1].index(min_score)]\n root = len(s) - 1\n t[root].add_label(ch)\n # backtracking through internal nodes\n stack = [(root, ch)]\n visited = [i < n for i in range(len(t))]\n while stack:\n u, u_ch = stack.pop()\n children = t[u].children()\n for v in children:\n transition = [s[v][j] + (alpha[j] != u_ch) for j in range(loa)]\n index = transition.index(min(transition))\n v_ch = alpha[index]\n dw = int(u_ch != v_ch)\n t[u].add_weight(v, dw)\n t[v].add_weight(u, dw)\n # in case if not visited or not leaf\n if not visited[v]:\n visited[v] = 1\n stack.append((v, v_ch))\n t[v].add_label(v_ch)\n return score, t\n\n\ndef main():\n n = int(sys.stdin.readline())\n tree = {key: Node(key, leaf=True) for key in range(n)}\n c = 0\n # tree parsing\n for line in sys.stdin:\n u, v = line.strip().split('->')\n u = int(u)\n if v.isalpha():\n if u not in tree:\n internal_node = Node(u)\n tree[u] = internal_node\n tree[c].add_label(v)\n tree[u].add_edge(c, 0)\n tree[c].add_edge(u, 0)\n c += 1\n else:\n v = int(v)\n if u not in tree:\n u_node = Node(u)\n tree[u] = u_node\n if v not in tree:\n v_node = Node(v)\n tree[v] = v_node\n tree[u].add_edge(v, 0)\n tree[v].add_edge(u, 0)\n # computation\n score, tree = parsimony(tree, n)\n print(score)\n for u in tree:\n u_node = tree[u]\n u_label = u_node.get_label()\n for v, w in u_node.output_edges():\n v_node = tree[v]\n v_label = v_node.get_label()\n print(u_label + '->' + v_label + ':' + str(w))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Chapter7/BA7F.py","file_name":"BA7F.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"587020679","text":"\"\"\"\nleetcode 224 -- Basic Calculator\npassed all test cases with 568 ms, beat 20.10% python submissions\n\nNote the way how we treat \"(\", which complicates the algorithm\n\"\"\"\n\nclass Solution(object):\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\" \n numStack = []\n opStack = []\n index = 0\n if s[0] == \"-\":\n numStack.append(0)\n while index < len(s):\n if s[index] == \" \":\n index += 1 \n elif s[index].isdigit():\n length = 0 \n while index+length < len(s) and s[index+length].isdigit():\n length += 1\n numStack.append(int(s[index: index+length]))\n index += length\n else:\n self.collapse(s[index], numStack, opStack)\n index+=1\n \n self.collapse(None ,numStack, opStack)\n return numStack[-1]\n \n \n def collapse(self, op, numStack, opStack):\n if op == \"(\":\n opStack.append(op)\n \n else:\n while len(opStack)>0 and opStack[-1] != \"(\":\n second = numStack.pop()\n first = numStack.pop()\n cur_op = opStack.pop()\n res = self.applyOp(first, second, cur_op)\n numStack.append(res)\n if len(opStack)>0 and op == \")\" and opStack[-1] == \"(\":\n opStack.pop()\n else:\n opStack.append(op)\n \n \n def applyOp(self, first, second, op):\n if op ==\"+\":\n return first + second\n else:\n return first- second\n \n","sub_path":"python/basic_calculator.py","file_name":"basic_calculator.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"563268507","text":"from django import template\nimport random\n\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef random_color():\n r = lambda: random.randint(0,255)\n color_data = '%02X%02X%02X' % (r(),r(),r())\n return color_data","sub_path":"code/mapview/templatetags/random_color.py","file_name":"random_color.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"77883823","text":"from zope.component.hooks import getSite\nfrom zope.component import adapts\nfrom zope.interface import implements\nfrom Products.Archetypes.public import BooleanWidget\nfrom Products.Archetypes.public import BooleanField\nfrom Products.CMFCore.utils import getToolByName\n\nfrom archetypes.schemaextender.interfaces import ISchemaExtender\nfrom archetypes.schemaextender.field import ExtensionField\n\nfrom minaraad.projects.interfaces import IAttachment\n\nfrom Products.minaraad import MinaraadMessageFactory as _\n\n\nclass PublishedField(ExtensionField, BooleanField):\n \"\"\"\n \"\"\"\n\n\nclass FileAttachmentExtender(object):\n adapts(IAttachment)\n implements(ISchemaExtender)\n\n fields = [\n PublishedField(\n \"published\",\n widget=BooleanWidget(\n label=_(\n u'label_attachment_published',\n default=u'Is published'),\n description=_(\n u'labelattachment_published_desc',\n default=(u'Check this box if you want this attachment to '\n u'be publicly available'))\n )\n ),\n ]\n\n def __init__(self, context):\n self.context = context\n\n def getFields(self):\n \"\"\"Get the fields.\n\n Our extra field should only be available when we are using the\n file_attachment_workflow, so that would be something like this:\n\n wft = getToolByName(self.context, 'portal_workflow')\n if 'file_attachment_workflow' in [\n wf.id for wf in wft.getWorkflowsFor(self.context)]:\n return self.fields\n return []\n\n But that does not work when we are being created in the portal\n factory (self.context.isTemporary()). So we fall back to\n a simple check to see if we are in the digibib.\n\n \"\"\"\n portal = getSite()\n if hasattr(portal, 'absolute_url'):\n portal_url = portal.absolute_url\n else:\n # 'portal' can be an instance of\n # Products.Five.metaclass.ValidationView during kss\n # validation... So try something else then.\n portal_url = getToolByName(self.context, 'portal_url')\n digibib_url = portal_url() + '/digibib'\n if self.context.absolute_url().startswith(digibib_url):\n return self.fields\n return []\n","sub_path":"src/Products.minaraad/Products/minaraad/schema_extensions/fileAttachment.py","file_name":"fileAttachment.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"539820389","text":"\"\"\"Physical operators specific to graphical data sources.\"\"\"\n\nfrom copy import deepcopy\nimport logging\nimport rdflib as _rdflib\nfrom pyparsing import Word, CaselessKeyword, alphanums, OneOrMore, Literal, SkipTo\nfrom deriva.core import ermrest_model as _em\nfrom .base import PhysicalOperator\n\nlogger = logging.getLogger(__name__)\n\n__all__ = ['Shred']\n\n\nclass Shred (PhysicalOperator):\n \"\"\"Shred operator for graphical data sources.\"\"\"\n\n #: a cache of the introspected schemas keyed on (repr(graph), expression, introspect)\n _schema_cache = {}\n\n def __init__(self, graph, expression, **kwargs):\n \"\"\"Creates a shred operator.\n\n Use keyword argument `introspect` with value `deep` to force a \"deep\" introspection of the query to determine\n the names and types of variables returned from the query expression. By default, the operator only performs a\n shallow introspection by parsing the expression but not executing the query. Note that if 'deep' introspection\n is selected, the graph will be read and parsed, if given as a filename.\n\n :param graph: a filename of an RDF jsonld graph or a parsed rdflib.Graph instance\n :param expression: text of a SPARQL expression\n :param kwargs: keyword arguments\n \"\"\"\n assert graph, \"Invalid value for 'graph'\"\n assert expression, \"Invalid value for 'expression'\"\n super(Shred, self).__init__()\n self._graph = graph\n self._expression = expression\n introspect = kwargs.get('introspect', 'shallow')\n cache_key = (repr(graph), expression, introspect)\n if cache_key in Shred._schema_cache:\n self._description = deepcopy(Shred._schema_cache[cache_key])\n else:\n if introspect == 'shallow':\n self._description = self._shallow_introspection(graph, expression)\n elif introspect == 'deep':\n self._description = self._deep_introspection(self._parsed_graph, expression)\n else:\n raise ValueError(\"unrecognized value for 'introspect' property: ${val}\".format(val=introspect))\n # lastly, cache the schema\n Shred._schema_cache[cache_key] = self._description\n\n @property\n def _parsed_graph(self):\n # if graph is a string, assume its a filename, else assume its a rdflib.Graph object\n if isinstance(self._graph, type('str')) or isinstance(self._graph, type('unicode')):\n graph = _rdflib.Graph()\n graph.parse(self._graph)\n self._graph = graph\n elif not isinstance(self._graph, _rdflib.Graph):\n raise ValueError('graph object is not a rdflib.Graph instances')\n return self._graph\n\n def __iter__(self):\n # query the parsed graph and yield results\n results = self._parsed_graph.query(self._expression)\n for row in results:\n yield {str(var): str(row[var]) for var in results.vars}\n\n @classmethod\n def _deep_introspection(cls, graph, expression):\n \"\"\"Queries the graph to generate a description of the projected variables.\n\n :param graph: rdflib.Graph instance\n :param expression: SPARQL query string\n :return: table definition\n \"\"\"\n assert isinstance(graph, _rdflib.Graph)\n results = graph.query(expression)\n col_defs = [\n _em.Column.define(\n str(var), Shred._rdflib_to_ermrest_type(var)\n ) for var in results.vars\n ]\n return _em.Table.define(repr(graph), column_defs=col_defs, provide_system=False)\n\n @classmethod\n def _rdflib_to_ermrest_type(cls, var):\n \"\"\"Translate from RDFLib variable types to ERMrest types.\"\"\"\n if var.isdecimal():\n return _em.builtin_types.float8\n elif var.isnumeric():\n return _em.builtin_types.int8\n else:\n return _em.builtin_types.text\n\n @classmethod\n def _get_parser(cls):\n \"\"\"Returns parser for introspecting column names from a SPARQL query string.\"\"\"\n # Note, this parser is not intended to validate a SPARQL query string. It's purpose is only to extract\n # the list of projected variables from a given SELECT expression.\n if not hasattr(cls, '_parser'):\n # keywords\n select, distinct, where, as_ = map(CaselessKeyword, \"select distinct where as\".split())\n # identifier\n identifier = Word('?', alphanums + '_')\n identifier.setParseAction(lambda tokens: tokens[0][1:]) # strip the leading '?'\n # alias\n lpar = Literal('(').suppress()\n rpar = Literal(')').suppress()\n alias = \\\n identifier + as_ + identifier | \\\n lpar + SkipTo(as_) + as_ + identifier + rpar # skips b/c we don't want to implement the full grammar\n alias.setParseAction(lambda tokens: tokens[2]) # get just the alias name\n # simple select statement parser, ignores everthing after the where clause\n _parser = select + distinct * (0, 1) + OneOrMore(alias| identifier)(\"projection\") + where\n _parser.setParseAction(lambda tokens: tokens['projection'])\n setattr(cls, '_parser', _parser)\n return getattr(cls, '_parser', None)\n\n @classmethod\n def _shallow_introspection(cls, graph, expression):\n \"\"\"Parses the expression and returns a table definition based on the projected variables.\n\n :param graph: text of filename or rdflib.Graph instance\n :param expression: SPARQL query string\n :return: table definition\n \"\"\"\n parser = cls._get_parser()\n # results = parser.parseString(expression)\n # vars_ = results['projection']\n vars_ = parser.parseString(expression)\n logger.debug('Parsed vars from SPARQL expression: %s', str(vars_))\n\n col_defs = [\n _em.Column.define(\n var, _em.builtin_types.text\n ) for var in vars_\n ]\n return _em.Table.define(repr(graph), column_defs=col_defs, provide_system=False)\n","sub_path":"deriva/chisel/operators/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"290600766","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nfrom PyQt4 import QtCore, QtGui\n\nclass BaseWin(QtGui.QMainWindow):\n\n\tdef centered(self):\n\t\trect = QtGui.QApplication.desktop().screenGeometry()\n\t\t###\n\t\tiXpos = rect.width()/2 - self.width()/2;\n\t\tiYpos = rect.height()/2 - self.height()/2;\n\t\t###\n\t\tself.move(iXpos,iYpos)\n\n\tdef keyPressEvent(self, event):\n\t\tif (event.key() == QtCore.Qt.Key_Escape):\n\t\t\tself.close()\n","sub_path":"forms/basewin.py","file_name":"basewin.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"202544634","text":"#!/usr/bin/env python\n\"\"\"\n================================================================================\n:mod:`availability` -- Availability table directive\n================================================================================\n\n.. module:: availability\n :synopsis: Availability table directive\n\n.. inheritance-diagram:: pymontecarlo.sphinxext.availability\n\n\"\"\"\n\n# Script information for the file.\n__author__ = \"Philippe T. Pinard\"\n__email__ = \"philippe.pinard@gmail.com\"\n__version__ = \"0.1\"\n__copyright__ = \"Copyright (c) 2013 Philippe T. Pinard\"\n__license__ = \"GPL v3\"\n\n# Standard library modules.\nfrom operator import attrgetter\n\n# Third party modules.\nfrom docutils.parsers.rst.directives.tables import Table\nfrom docutils import nodes\nfrom sphinx import addnodes\n\n# Local modules.\nfrom pymontecarlo.settings import get_settings\nfrom pymontecarlo.util.human import camelcase_to_words\n\n# Globals and constants variables.\n\nclass AvailabilityTableDirective(Table):\n\n required_arguments = 1\n has_content = False\n option_spec = {'only': str}\n\n def run(self):\n # Extract choices\n settings = get_settings()\n programs = sorted(settings.get_available_programs(), key=attrgetter('name'))\n attr = self.arguments[0]\n\n choices = {}\n for program in programs:\n converter = program.converter_class\n\n for clasz in getattr(converter, attr, []):\n modulepath = clasz.__module__ + '.' + clasz.__name__\n choices.setdefault(modulepath, set()).add(program)\n\n if 'only' in self.options:\n if self.options['only'] not in choices:\n raise ValueError(\"Unknown module in only flag\")\n\n # Create table\n table_node = self._build_table(programs, choices)\n table_node['classes'] += self.options.get('class', [])\n\n self.add_name(table_node)\n return [table_node]\n\n def _build_table(self, programs, choices):\n env = self.state.document.settings.env\n isonly = 'only' in self.options\n\n def create_reference(modulepath):\n # From sphinx.roles.XRefRole\n classes = ['xref', 'ref']\n\n modulename = modulepath.rsplit('.', 1)[-1]\n title = ' '.join(camelcase_to_words(modulename).split()[:-1])\n target = modulename.lower()\n rawtext = ':ref:`%s <%s>`' % (title, target)\n\n refnode = \\\n addnodes.pending_xref(rawtext, reftype='ref', refdomain='std',\n refexplicit=True,\n reftarget=target,\n refdoc=env.docname)\n refnode += nodes.literal(rawtext, title, classes=classes)\n\n return refnode\n\n # table\n table = nodes.table()\n\n ncol = len(programs)\n if not isonly: ncol += 1\n tgroup = nodes.tgroup(cols=ncol)\n table += tgroup\n\n colwidths = self.get_column_widths(ncol)\n if not isonly: colwidths[0] *= 2\n tgroup.extend(nodes.colspec(colwidth=colwidth) for colwidth in colwidths)\n\n # header\n thead = nodes.thead()\n tgroup += thead\n rownode = nodes.row()\n thead += rownode\n hs = [''] if not isonly else []\n hs += programs\n rownode.extend(nodes.entry(h, nodes.paragraph(text=h)) for h in hs)\n\n # body\n tbody = nodes.tbody()\n tgroup += tbody\n\n for modulepath in sorted(choices):\n available_programs = choices[modulepath]\n\n if isonly and modulepath != self.options['only']:\n continue\n\n rownode = nodes.row()\n tbody += rownode\n\n # Reference to class\n if not isonly:\n refnode = nodes.paragraph()\n refnode += create_reference(modulepath)\n rownode.append(nodes.entry('', refnode))\n\n # Exist for program\n for program in programs:\n text = 'x' if program in available_programs else ''\n rownode.append(nodes.entry(text, nodes.paragraph(text=text)))\n\n\n return table\n\ndef setup(app):\n app.add_directive('availability', AvailabilityTableDirective)\n","sub_path":"pymontecarlo/util/dist/sphinxext/availability.py","file_name":"availability.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"176883040","text":"from django.shortcuts import render, redirect\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.views.generic import ListView, DetailView\n\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth import login\n\nimport uuid\nimport boto3\nfrom .models import Jersey, Player, Sponsor, Photo, Photo_sponsor, Photo_player\n\nfrom .forms import ChampionshipForm\n\nS3_BASE_URL = 'https://s3-us-west-1.amazonaws.com/'\nBUCKET = 'jerseycollector-gt-2'\nnew_S3_url = 'https://jerseycollector-gt.s3.amazonaws.com/'\n\n# Create your views here.\ndef signup(request):\n error_message = ''\n\n if request.method == 'POST':\n #handle the signup of a new user\n form = UserCreationForm(request.POST)\n \n if form.is_valid():\n user = form.save()\n \n login(request, user)\n \n return redirect('index')\n else:\n error_message = 'Invalid Sign Up - Try Again'\n\n form = UserCreationForm()\n context = {'form': form, 'error': error_message}\n return render(request, 'registration/signup.html', context)\n\n\n\ndef home(request):\n return render(request, 'index.html')\n\ndef about(request):\n return render(request, 'about.html')\n\n@login_required\ndef jerseys_detail(request, jersey_id):\n jersey = Jersey.objects.get(id=jersey_id)\n player_jersey_doesnt_have = Player.objects.exclude(id__in = jersey.players.all().values_list('id'))\n sponsor_jersey_doesnt_have = Sponsor.objects.exclude(id__in = jersey.sponsors.all().values_list('id'))\n championship_form = ChampionshipForm()\n\n return render(request, 'jerseys/detail.html', {\n 'jersey': jersey,\n 'players': player_jersey_doesnt_have,\n 'sponsors': sponsor_jersey_doesnt_have,\n 'championship_form': championship_form\n })\n\n@login_required\ndef add_championship(request, jersey_id):\n form = ChampionshipForm(request.POST)\n\n if form.is_valid():\n new_championship = form.save(commit=False)\n new_championship.jersey_id = jersey_id\n new_championship.save()\n return redirect('detail', jersey_id=jersey_id) \n\n@login_required\ndef assoc_player(request, jersey_id, player_id):\n Jersey.objects.get(id=jersey_id).players.add(player_id)\n return redirect('detail', jersey_id=jersey_id)\n\n@login_required\ndef disassoc_player(request, jersey_id, player_id):\n Jersey.objects.get(id=jersey_id).players.remove(player_id)\n return redirect('detail', jersey_id=jersey_id)\n\n@login_required\ndef assoc_sponsor(request, jersey_id, sponsor_id):\n Jersey.objects.get(id=jersey_id).sponsors.add(sponsor_id)\n return redirect('detail', jersey_id=jersey_id)\n\n@login_required\ndef disassoc_sponsor(request, jersey_id, sponsor_id):\n Jersey.objects.get(id=jersey_id).sponsors.remove(sponsor_id)\n return redirect('detail', jersey_id=jersey_id)\n\n@login_required\ndef jerseys_index(request):\n context = {'jerseys': Jersey.objects.filter(user=request.user)}\n return render(request, 'jerseys/index.html', context)\n\n@login_required\ndef add_photo(request, jersey_id):\n photo_file = request.FILES.get('photo-file', None)\n if photo_file:\n\n # s3 = boto3.session.Session(profile_name='project1').client('s3')\n s3 = boto3.client('s3')\n\n key = uuid.uuid4().hex[:6] + photo_file.name[photo_file.name.rfind('.'):]\n\n try:\n s3.upload_fileobj(photo_file, BUCKET, key)\n\n url = f\"{S3_BASE_URL}{BUCKET}/{key}\"\n\n photo = Photo(url=url, jersey_id=jersey_id)\n photo.save()\n except Exception as e:\n print(e)\n print('An error occurred uploading file to S3')\n return redirect('detail', jersey_id=jersey_id)\n\n@login_required\ndef add_player_photo(request, player_id):\n photo_file = request.FILES.get('photo-file', None)\n if photo_file:\n\n # s3 = boto3.session.Session(profile_name='project1').client('s3')\n s3 = boto3.client('s3')\n\n key = uuid.uuid4().hex[:6] + photo_file.name[photo_file.name.rfind('.'):]\n\n try:\n s3.upload_fileobj(photo_file, BUCKET, key)\n\n url = f\"{S3_BASE_URL}{BUCKET}/{key}\"\n\n photo = Photo_player(url=url, player_id=player_id)\n photo.save()\n except Exception as e:\n print(e)\n print('An error occurred uploading file to S3')\n return redirect('players_index')\n\n@login_required\ndef add_sponsor_photo(request, sponsor_id):\n photo_file = request.FILES.get('photo-file', None)\n if photo_file:\n\n # s3 = boto3.session.Session(profile_name='project1').client('s3')\n s3 = boto3.client('s3')\n\n key = uuid.uuid4().hex[:6] + photo_file.name[photo_file.name.rfind('.'):]\n\n try:\n s3.upload_fileobj(photo_file, BUCKET, key)\n\n url = f\"{S3_BASE_URL}{BUCKET}/{key}\"\n\n photo = Photo_sponsor(url=url, sponsor_id=sponsor_id)\n photo.save()\n except Exception as e:\n print(e)\n print('An error occurred uploading file to S3')\n return redirect('sponsors_detail', sponsor_id=sponsor_id)\n\nclass JerseyCreate(LoginRequiredMixin, CreateView):\n model = Jersey\n fields = ['team_name', 'jersey_type', 'country', 'year_added', 'jersey_colors', 'jersey_description']\n\n def form_valid(self, form):\n form.instance.user = self.request.user\n return super().form_valid(form)\n\nclass JerseyUpdate(LoginRequiredMixin, UpdateView):\n model = Jersey\n fields = '__all__'\n\nclass JerseyDelete(LoginRequiredMixin, DeleteView):\n model = Jersey\n success_url = '/jerseys/'\n\nclass PlayerList(LoginRequiredMixin, ListView):\n model = Player\n\nclass PlayerDetail(LoginRequiredMixin, DetailView):\n model = Player\n\nclass PlayerCreate(LoginRequiredMixin, CreateView):\n model = Player\n fields = '__all__'\n success_url = '/players/'\n\nclass PlayerUpdate(LoginRequiredMixin, UpdateView):\n model = Player\n fields = '__all__'\n success_url = '/players/'\n\nclass PlayerDelete(LoginRequiredMixin, DeleteView):\n model = Player\n success_url = '/players/'\n\nclass SponsorList(LoginRequiredMixin, ListView):\n model = Sponsor\n\nclass SponsorDetail(LoginRequiredMixin, DetailView):\n model = Sponsor\n\nclass SponsorCreate(LoginRequiredMixin, CreateView):\n model = Sponsor\n fields = '__all__'\n success_url = '/sponsors/'\n\nclass SponsorUpdate(LoginRequiredMixin, UpdateView):\n model = Sponsor\n fields = '__all__'\n success_url = '/sponsors/'\n\nclass SponsorDelete(LoginRequiredMixin, DeleteView):\n model = Sponsor\n success_url = '/sponsors/'","sub_path":"main_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"323730095","text":"# Створити консольний додаток, що моделює таку гру. На ігровому полі захований скарб.\n# Розмір ігрового поля задається користувачем. Місце розташування кладу визначається випадковим чином.\n# На початку гри гравець розташовується в лівому нижньому кутку поля.\n# На кожному етапі можна переміщатися на одну позицію по горизонталі або по вертикалі.\n# Гравцеві після кожного кроку надається підказка – відстань до скарбу.\n\nimport random\n\n# sets size of a matrix\nn = 7 # verticals - number of inner lists\nm = 7 # horizontals - number of elements in each inner list\n\n\n# initializes a matrix\nl = []\nfor i in range(n):\n l.append([0 for el in range(m)])\n\n\nx_tr = random.randint(0, n - 1)\ny_tr = random.randint(0, n - 1)\nl[x_tr][y_tr] = 1\n\n\nx_pl = n - 1\ny_pl = 0\nl[x_pl][y_pl] = 2\n\n\n# prints a matrix\nprint()\nfor i in range(n):\n for j in range(m):\n print(l[i][j], end='\\t')\n print()\nprint()\n\ndist_x = abs(x_tr - x_pl)\ndist_y = abs(y_tr - y_pl)\n\ndist = (dist_x ** 2 + dist_y ** 2) ** 0.5\n\nprint(dist_x)\nprint(dist_y)\nprint(dist)\n\nrepeat = True\n\n\nx_old = n - 1\ny_old = 0\n\nwhile dist > 0:\n repeat = True\n while repeat:\n direct = input(\"Please enter a direction: u for up, d for down, l for left, r for right: \").lower()\n if direct == 'u':\n if x_pl > 0:\n x_old = x_pl\n x_pl -= 1\n repeat = False\n if direct == 'd':\n if x_pl < n - 1:\n x_old = x_pl\n x_pl += 1\n repeat = False\n if direct == 'l':\n if y_pl > 0:\n y_old = y_pl\n y_pl -= 1\n repeat = False\n if direct == 'r':\n if y_pl < n - 1:\n y_old = y_pl\n y_pl += 1\n repeat = False\n if repeat:\n print(\"INCORRECT DIRECTION. TRY AGAIN\")\n print(x_old, y_old)\n l[x_old][y_old] = 0\n l[x_pl][y_pl] = 2\n\n # prints a matrix\n print()\n for i in range(n):\n for j in range(m):\n print(l[i][j], end='\\t')\n print()\n print()\n\n dist_x = abs(x_tr - x_pl)\n dist_y = abs(y_tr - y_pl)\n\n dist = (dist_x ** 2 + dist_y ** 2) ** 0.5\n\n print(dist_x)\n print(dist_y)\n print(dist)\n\n\n\n","sub_path":"lessons_with_tutor/miscellaneous/с11_treasure.py","file_name":"с11_treasure.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"449185181","text":"\ndef doit():\n print (\"DIDIT\")\n\nfrom tkinter import *\n\nroot=Tk()\nroot.geometry(\"500x300\")\nroot.title(\"Mine\")\n\nmain=Frame(root)\nmain.grid()\n\nspc1=Label(main)\nspc1.grid()\n\nspc2=Label(main,text=\" \")\nspc2.grid(row=1,column=0)\n\nbut1=Button(main,width=15,text=\"Hey\",command=doit)\nbut1.grid(row=1,column=1)\n\nroot.mainloop()\n\n","sub_path":"Python Pgms/New folder/Python/nextBut.p.py","file_name":"nextBut.p.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"19526731","text":"import re\nimport numpy as np\nimport gzip\nimport pickle\n\ndef get_vocab(data_list=None, dataset=\"\", n=1):\n\n ngram2id = dict()\n for data in data_list: # file path\n #if dataset == \"AG\": # kind of dataset\n f = open(data, encoding=\"utf-8\")\n ngram2id[\"padding\"] = 0\n id = 1 # padding 0 있음\n for line in f:\n words = line_to_words(line, dataset, n)\n for word in words:\n if word not in ngram2id:\n ngram2id[word] = id\n id += 1\n f.close()\n print(\"{} gram embeddings : {}\".format(n ,len(ngram2id.keys())))\n return ngram2id\n\ndef line_to_words(line=None, dataset=\"\", n=1):\n clean_line= clean_str(line)\n clean_line = clean_line.split(\" \")\n #if dataset ==\"AG\":\n words = clean_line[2:]\n if n > 1:\n ngrams = [\" \".join(words[i:i+n]) for i in range(len(words)-(n-1))]\n words += ngrams\n return words\n\ndef clean_str(string):\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\']\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" ( \", string)\n string = re.sub(r\"\\)\", \" ) \", string)\n string = re.sub(r\"\\?\", \" ? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n\ndef load_data(dataset, train_path, dev_path=\"\", test_path='' , n=1):\n f_names = [train_path]\n if not test_path ==\"\": f_names.append(test_path)\n if not dev_path ==\"\": f_names.append(dev_path)\n\n ngram2id = get_vocab(data_list=f_names, dataset=dataset, n=n)\n\n train = []\n train_label = []\n\n dev = []\n dev_label = []\n\n test=[]\n test_label=[]\n\n files=[]\n data= []\n data_label = []\n\n f_train = open(train_path, 'r')\n files.append(f_train)\n data.append(train)\n data_label.append(train_label)\n\n if not test_path==\"\":\n f_test = open(test_path, 'r')\n files.append(f_test)\n data.append(test)\n data_label.append(test_label)\n\n if not dev_path==\"\":\n f_dev = open(dev_path, \"r\")\n files.append(f_dev)\n data.append(dev)\n data_abel.append(dev_label)\n\n for d, l, f in zip(data, data_label, files):\n\n for line in f:\n ngrams = line_to_words(line, dataset)\n if dataset in [\"AG\", \"Sogou\", \"Yelp_P\", \"Yelp_F\", 'Yah_A', \"Amz_F\", \"Amz_P\"]:\n y = int(line.strip().split(\",\")[0][1])-1\n elif dataset==\"DBP\":\n y = int(line.strip().split(\",\")[0]) - 1\n\n sent = [ngram2id[word] for word in ngrams]\n d.append(sent)\n l.append(y)\n f_train.close()\n if not test_path == \"\":\n f_test.close()\n if not dev_path == \"\":\n f_dev.close()\n\n # data adjust\n train, train_label, dev, dev_label, test, test_label = adjust_data(train, train_label, dev, dev_label, test, test_label)\n return ngram2id, np.array(train, dtype=object), np.array(train_label, dtype=object),np.array(dev, dtype=object), np.array(dev_label, dtype=object), np.array(test, dtype=object), np.array(test_label, dtype=object)\n\ndef adjust_data(train, train_label, test, test_label, dev, dev_label):\n limit = len(train)//10\n if (len(test)==0 & len(dev)==0):\n test = train[:limit]\n test_label = train_label[:limit]\n\n dev = train[limit:limit*2]\n dev_label = train_label[limit:limit*2]\n\n elif (len(test)==0 & len(dev)!=0):\n test = train[:limit]\n test_label = train_label[:limit]\n elif (len(test)!=0 & len(dev)==0):\n dev = train[:limit]\n dev_label = train_label[:limit]\n\n else:\n pass\n return train, train_label, dev, dev_label, test, test_label\n\n\n# with open(\"/hdd1/user15/workspace/FastText/data/raw/dbpedia_csv/train.csv\", \"r\") as f:\n# line = f.readline()\n#\n# int(line.strip().split(\",\")[0])-1\n# int(line.strip().split(\",\")[0])-1","sub_path":"src/prepro.py","file_name":"prepro.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"102490866","text":"from bottle import route, run, template\nfrom GeoNames import *\n\nurl_template = 'https://api.forecast.io/forecast/{api}/{lat},{lon}'\napikey = 'dd7278d70bf285fe1a9d0cd33cc59ccb'\nlatitude = 47.53\nlongitude = 19.05\nusername = \"ostap\"\n\n\n@route('/')\n@route('/hello/')\n@route('/hello//')\ndef greet(name='Stranger', width=300):\n\treturn template('Hello {{name}}, how are you?', name=name, width=width)\n\n\n@route('/sq/')\ndef sq(number):\n\tnumber = float(number) #convert from str to number\n\treturn str(number**2) #and convert back to \n\t\n\n@route('/palindrom/')\ndef is_palinfrom(word):\n\tresult = word == word[::-1]\n\treturn str(result)\n\n\n@route('temp//')\ndef temperature_lat_lon(lat,lon):\n\tlat = float(lat)\n\tlon = float(lon)\n\turl = url_template.format(api=apikey, lat=latitude, lon=longitude)\n\tparams_dict = {\n\t\t'units':'si'\n\t}\n\n\tr = r.requests.get(url, params=params_dict)\n\tif not r.ok:\n\t\treturn 'error'\n\n\tdata = r.json()\n\ttemp = data['currently']['temperature']\n\treturn temp\n\n@route('temp/')\ndef temperature_city(cityName):\n\n\tlat,lon = getCityByName(cityName)\n\n\tlat = float(lat)\n\tlon = float(lon)\n\n\turl = url_template.format(api=apikey,lat=lat, lon=lon)\n\n\tparams_dict = {'units':'si'}\n\n\tr = requests.get(url, params=params_dict)\n\n\tif not r.ok:\n\t\treturn 'error'\n\n\tdata = r.json()\n\ttemp = data['currently']['temperature']\n\treturn str(temp)\n\n# def getCityLanLonByName (name):\n\n# \tglobal username\n\n# \turl_template_geoNames = 'http://api.geonames.org/searchJSON?name_equals={name}&username={username}'\n\n# \turl_geoNames = url_template_geoNames.format(name=name, username=username)\n\n# \tr = requests.get(url_geoNames)\n\n# \tif not r.ok:\n# \t\treturn 'error'\n\n# \tdata = r.json()\n\n# \tlat = data['geonames'][0]['lat']\n# \tlon = data['geonames'][0]['lng']\n\t\n# \treturn lat,lon\n\n\n# do the same with city names\n# check maphub.net\n# geocoding/ reverse geocoding\n# do geocoding using \n\nrun(host='localhost', port=8080, debug=True)\t","sub_path":"Python/Pylvax/Bottle/Hello_bottle.py","file_name":"Hello_bottle.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"442401890","text":"# 给定M×N矩阵,每一行、每一列都按升序排列,请编写代码找出某元素。\r\n\r\n# 示例:\r\n\r\n# 现有矩阵 matrix 如下:\r\n\r\n# [\r\n# [1, 4, 7, 11, 15],\r\n# [2, 5, 8, 12, 19],\r\n# [3, 6, 9, 16, 22],\r\n# [10, 13, 14, 17, 24],\r\n# [18, 21, 23, 26, 30]\r\n# ]\r\n# 给定 target = 5,返回 true。\r\n\r\n# 给定 target = 20,返回 false。\r\n\r\n# 通过次数413提交次数836\r\n\r\n# 来源:力扣(LeetCode)\r\n# 链接:https://leetcode-cn.com/problems/sorted-matrix-search-lcci\r\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\r\n\r\nclass Solution:\r\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\r\n # 方法1 (O(r+c)): 从左下角或者右上角开始查找\r\n # 1. 若左下角开始:如果当前元素小于t:c+=1, 大于t:r-=1\r\n # 2. 若右上角开始:如果当前元素小于t:r+=1, 大于t:c-=1\r\n if not matrix:\r\n return False\r\n rows, cols = len(matrix), len(matrix[0])\r\n # 1.1 左下角开始\r\n r, c = rows - 1, 0\r\n while r >= 0 and c < cols:\r\n if matrix[r][c] < target:\r\n c += 1\r\n elif matrix[r][c] == target:\r\n return True\r\n else:\r\n r -= 1\r\n return False\r\n # 1.2 右上角开始\r\n # r, c = 0, cols - 1\r\n # while r < rows and c >= 0:\r\n # if matrix[r][c] < target:\r\n # r += 1\r\n # elif matrix[r][c] == target:\r\n # return True\r\n # else:\r\n # c -= 1\r\n # return False\r\n # 方法2 (O(rlogc)): 对于每一行二分查找, 可以提前结束, 忽\r\n","sub_path":"Medium/面试题 10.09. 排序矩阵查找.py","file_name":"面试题 10.09. 排序矩阵查找.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"156868076","text":"import tensorflow as tf\r\nfrom keras.layers import *\r\nimport math\r\n\r\n\r\n# source model\r\nclass Sketch2Image(tf.keras.Model):\r\n def __init__(self):\r\n super(Sketch2Image, self).__init__()\r\n self.encoder = tf.keras.Sequential([\r\n downsample(16, 4, strides=2, apply_batch_normalization=False),\r\n downsample(16, 4, strides=1, padding='same', apply_batch_normalization=False),\r\n downsample(32, 4, strides=2),\r\n downsample(32, 4, strides=1, padding='same'),\r\n downsample(64, 4, strides=2, apply_batch_normalization=False),\r\n downsample(64, 4, strides=1, padding='same', apply_batch_normalization=False),\r\n downsample(128, 4, strides=2),\r\n downsample(128, 4, strides=1, padding='same'),\r\n downsample(256, 4, strides=2),\r\n downsample(256, 4, strides=1, padding='same')\r\n ])\r\n\r\n self.encoder_out = downsample(512, 4, strides=2)\r\n\r\n self.decoder = tf.keras.Sequential([\r\n upsample(512, 4, strides=2, apply_dropout=True),\r\n upsample(256, 4, strides=2, apply_dropout=True),\r\n upsample(256, 4, strides=1, padding='same', apply_dropout=True),\r\n upsample(128, 4, strides=2, apply_dropout=True),\r\n upsample(128, 4, strides=1, padding='same', apply_dropout=True),\r\n upsample(64, 4, strides=2),\r\n upsample(64, 4, strides=1, padding='same'),\r\n upsample(32, 4, strides=2),\r\n upsample(32, 4, strides=1, padding='same'),\r\n upsample(16, 4, strides=2),\r\n upsample(16, 4, strides=1, padding='same')\r\n ])\r\n\r\n self.c1 = Conv2DTranspose(8, (2, 2), strides=(1, 1), padding='valid')\r\n self.c2 = Conv2DTranspose(3, (2, 2), strides=(1, 1), padding='valid')\r\n\r\n def call(self, x):\r\n x = self.encoder(x)\r\n encoder_out = self.encoder_out(x)\r\n x = self.decoder(encoder_out)\r\n x = self.c1(x)\r\n x = self.c2(x)\r\n return x\r\n\r\n\r\ndef downsample(filters, size, strides, padding='valid', apply_batch_normalization=True):\r\n downsample = tf.keras.models.Sequential()\r\n downsample.add(Conv2D(filters=filters, kernel_size = size, strides=strides,\r\n use_bias=False, kernel_initializer='he_normal', padding=padding))\r\n if apply_batch_normalization:\r\n downsample.add(BatchNormalization())\r\n downsample.add(LeakyReLU())\r\n return downsample\r\n\r\n\r\ndef upsample(filters, size, strides, padding='valid', apply_dropout=False):\r\n upsample = tf.keras.models.Sequential()\r\n upsample.add(Conv2DTranspose(filters=filters, kernel_size=size, strides=strides,\r\n use_bias=False, kernel_initializer='he_normal', padding=padding))\r\n if apply_dropout:\r\n upsample.add(Dropout(0.1))\r\n upsample.add(LeakyReLU())\r\n return upsample\r\n\r\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"616721886","text":"#!/usr/bin/env python\nimport os\n\nfrom app import create_app, db\nfrom flask.ext.script import Shell, Manager\n\n# configuration file path\nconfig_path = os.path.dirname(os.path.abspath(__file__)) + '/ui.cfg'\n\napp = create_app(config_path)\nmanager = Manager(app)\n\ndef make_shell_context():\n return dict(app=app, db=db)\n\n# python manage.py shell\nmanager.add_command('shell', Shell(make_context=make_shell_context))\n\nif __name__ == '__main__':\n manager.run()","sub_path":"ui/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"181277951","text":"def LinearSearch(LIST, ELEMENT_TO_SEARCH):\r\n POINTER = 0;\r\n while POINTER < len(LIST) and LIST[POINTER] != ELEMENT_TO_SEARCH:\r\n if POINTER >= len(LIST):\r\n print(\"Not found!\");\r\n return;\r\n else:\r\n POINTER += 1;\r\n \r\n print(\"Item found at \" + str(POINTER));\r\n\r\nprint(\"LINEAR SEARCH\");\r\nLinearSearch([0, 3, 78, 1, 9, 67, 6859], 67);\r\n","sub_path":"searches/Linear Search.py","file_name":"Linear Search.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"372484220","text":"import os\n\npliki = os.listdir('servers')\n\ndef reader(plik):\n sumaUser = 0.0\n sumaNice = 0.0\n sumaSystem = 0.0\n sumaIOwait = 0.0\n sumaSteal = 0.0\n tabela = []\n tabela2 = []\n\n linijka = open('servers/'+plik).readlines()\n \n for linia in linijka:\n tabela.append(linia)\n \n i = 3\n\n while i < len(tabela):\n for char in tabela[i]:\n if char != ' ':\n tabela2.append(char)\n user = tabela2[13] + tabela2[14] + tabela2[15] + tabela2[16]\n nice = tabela2[17] + tabela2[18] + tabela2[19] + tabela2[20]\n system = tabela2[21] + tabela2[22] + tabela2[23] + tabela2[24]\n iowait = tabela2[25] + tabela2[26] + tabela2[27] + tabela2[28]\n steal = tabela2[29] + tabela2[30] + tabela2[31] + tabela2[32]\n \n sumaNice += float(nice)\n sumaUser += float(user)\n sumaSystem += float(system)\n sumaIOwait += float(iowait)\n sumaSteal += float(steal)\n i += 1\n print ('User=%s Nice=%s System=%s IOwait=%s Steal=%s'%(sumaUser,sumaNice,sumaSystem,sumaIOwait,sumaSteal))\n\n \n\nfor plik in pliki:\n reader(plik)\n \n","sub_path":"python/sar/skrypt.py","file_name":"skrypt.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"294505080","text":"import requests\nimport json\nimport tablib\n\nprint(\"请输入直播明细连接\")\nurl_ming = input()\n# ur2 = \"https://apimwcs.mogujie.com/h5/mwp.livelist.adcRoomItemInfo/1/?data=%7B%22pageNum%22%3A1%2C%22pageSize%22%3A10%2C%22itemName%22%3A%22%22%2C%22itemUrl%22%3A%22%22%2C%22roomId%22%3A%221dy12m%22%7D&mw-appkey=100028&mw-ttid=NMMain%40mgj_pc_1.0&mw-t=1587018686468&mw-uuid=8c183fb2-7051-486e-be77-3eacbdf2c1d5&mw-h5-os=unknown&mw-sign=eba4c2b0f62006d6da4b80fa69a996dc&callback=mwpCb2&_=1587018686470\"\nur2 = url_ming\n\n# 字典,key是固定的\nh = {\n 'Host': 'apimwcs.mogujie.com',\n 'Connection': 'keep-alive',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',\n 'Sec-Fetch-Dest': 'script',\n 'Accept': '*/*',\n 'Sec-Fetch-Site': 'same-site',\n 'Sec-Fetch-Mode': 'no-cors',\n 'Referer': 'https://pc.mogujie.com/assistant/index.html?ptp=31.HS8WT.0.0.S9YEIvxZ',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Cookie': '__mgjuuid=8c183fb2-7051-486e-be77-3eacbdf2c1d5; _mwp_h5_token_enc=8be096ee6cf137a63667b2271e0d6aef; _mwp_h5_token=a688099ffd23af8d8861aada0a451c26_1586507735361; FRMS_FINGERPRINTN=HTvZZvVLQ7GkFuoBgKjjxw; __mogujie=HbEX41eorQIZs308rUvjU33EUtHdBTgqmVtAavjLXYhsQyBajTTJrJry7XsqzJol5A0XRs0jsgg4aaGyHgANKA%3D%3D; __ud_=1eoe7vc; __must_from=10000000_; _ga=GA1.2.250068851.1587009101; _gid=GA1.2.1963589664.1587009101'\n}\n\n# 设置代理\nproxies = {\n \"http\": \"118.112.195.152\",\n # \"http\": \"118.212.107.105\",\n # \"http\": \"183.166.96.2\",\n # \"http\": \"182.87.45.2\",\n # \"http\": \"60.13.42.140\",\n # \"http\": \"182.34.36.194\",\n # \"http\": \"182.138.238.150\",\n # \"http\": \"182.46.110.222\",\n # \"http\": \"27.43.191.84\",\n # \"http\": \"183.230.179.164\",\n # \"http\": \"60.205.132.71\",\n # \"http\": \"171.35.167.173\",\n # \"http\": \"58.253.154.8\",\n}\nrequests.packages.urllib3.disable_warnings()\n\n# 下部分数据表格\nresponse1 = requests.get(ur2, headers=h, proxies=proxies, verify=False)\ntext1 = response1.text\n# 得到数据\nprint(text1)\n# 去除没用字符\nprint('请输入删除的字符')\nde = input()\n\ninput()\nioa1 = str(text1).strip(\"'%s'\" % de).strip(')')\nprint(ioa1)\njsonobj1 = json.loads(ioa1, strict=False) # 将响应内容转换为Json对象\ntoCntPercent1 = jsonobj1['data']['list'] # 从Json对象获取想要的内容\nprint(toCntPercent1)\n\n# 商品列表数据导入\n# 将json中的key作为header, 也可以自定义header(列名)——商品列表\nheader1 = tuple([i for i in toCntPercent1[0].keys()])\n\ndata1 = []\n# 循环里面的字典,将value作为数据写入进去\nfor row1 in toCntPercent1:\n body = []\n for v in row1.values():\n body.append(v)\n data1.append(tuple(body))\n\ndata1 = tablib.Dataset(*data1, headers=header1)\nprint(data1)\n\nprint(\"请输入保存的文件名\")\nwen = input()\nopen('%s.xls' % wen, 'wb').write(data1.xls)\n","sub_path":"scrapy/shopping.py","file_name":"shopping.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"565980677","text":"\n\nclass Telemetry:\n def __init__(self):\n self.longitude = None\n self.latitude = None\n self.altitude = None\n self.azimuth = None\n\n def update_telemetry(self):\n self.latitude = 51.085234\n self.longitude = 19.869299\n self.altitude = 20\n self.azimuth = 0\n\n def update_telemetry_manually(self, longitude, latitude, altitude, azimuth):\n self.longitude = longitude\n self.latitude = latitude\n self.altitude = altitude\n self.azimuth = azimuth","sub_path":"telemetry/telemetry.py","file_name":"telemetry.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"368129781","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport math\nimport ssdata\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport threading\nfrom time import time\n\n\n###############################################################################\n# Define framework classes #\n###############################################################################\n\n\nclass account:\n def __init__(self, start_date, end_date, capital_base, freq, benchmark,\n universe, tax=0.001, commission=0.00025, slippage=0.01):\n \"\"\"\n start_date: the start date of back test\n end_date: the end date of back test\n capital_base: initial fund to perform back test\n freq: back test frequencies, measured in days, eg. 1 for daily and 7\n for weekly\n tax: tax rate\n commission: commission rate\n slippage: slippage\n \"\"\"\n self.start_date = start_date\n self.end_date = end_date\n self.capital_base = capital_base\n self.freq = freq\n self.benchmark = benchmark\n self.universe = universe\n self.tax = tax\n self.commission = commission\n self.slippage = slippage\n\n # 存储股票数据的字典,key是股票代码,value是一个以时间为索引的dataframe\n self.ini_dic = None\n # 存储基准证券数据的dataframe\n self.benchmark_data = None\n # 从起始日期到终止日期之间的交易日列表\n self.trade_days = None\n # 根据交易日列表和设定的交易频率得出的下单日\n self.order_days = None\n # 每个交易日的总资产,用来计算收益率\n self.today_capital = None\n # 存储收益情况的dataframe,索引是日期,列有策略收益率、基准收益率、最大回撤、\n # 最大回撤区间\n self.ret = None\n # 历史最大回撤\n self.history_max = None\n # 历史最大回撤区间起始日\n self.drawdown_start = None\n # 历史最大回撤区间终止日\n self.drawdown_end = None\n # 存储每个交易日总资产的列表\n self.capital = None\n # 现金\n self.cash = None\n\n def setup(self):\n \"\"\"\n 用来初始化账户,得到ini_dic, benchmark_data, trade_days 和 order_days等。\n \"\"\"\n # 初始化这些变量\n self.ini_dic = {}\n self.ret = pd.DataFrame()\n self.benchmark_data = pd.DataFrame()\n self.history_max = 0\n self.capital = []\n self.cash = self.capital_base\n\n # 用多线程的方式,通过ssdata包获取股票数据,存入ini_dic,这个函数的参数为想开启的线程数\n # 注:新三板股票都是月度数据\n self.concurrently_get_stock_data(15)\n\n # 把获取不到数据的股票从universe中去掉\n self.universe = list(self.ini_dic.keys())\n\n # 获取benchmark的数据\n try:\n data = ssdata.get_data(secid=self.benchmark,\n start_date=self.start_date,\n end_date=self.end_date,\n field='open').sort_index().dropna()\n self.benchmark_data = self.benchmark_data.append(data)\n except Exception:\n print(\"Benchmark \", self.benchmark, \" data unavailable.\")\n\n # 交易日列表\n self.trade_days = self.benchmark_data.index\n # 调用下面的get_order_days函数算出下单日列表\n self.order_days = self.get_order_days()\n\n def get_order_days(self):\n \"\"\"\n Return the list of order days based on frequency.\n \"\"\"\n tdays = list(self.trade_days)\n odays = []\n # 遍历tdays,如果能够整除freq,则说明在下单日,将其存入odays\n for i in range(len(tdays)):\n if i % self.freq == 0:\n odays.append(tdays[i])\n return odays\n\n def div_list(self, ls, n):\n \"\"\"\n Divide the list 'ls' into n pieces.\n \"\"\"\n j = math.ceil(len(ls)/n)\n return [ls[i:i+j] for i in range(0, len(ls), j)]\n\n def get_stock_data(self, stocklist):\n \"\"\"\n Get data of the stocks in 'stocklist'.\n \"\"\"\n for stock in stocklist:\n try:\n self.ini_dic[stock] = ssdata.get_data(\n secid=stock,\n start_date=self.start_date,\n end_date=self.end_date,\n field='open,yoyop').dropna().sort_index()\n print(\"Succeed: \", stock, stocklist.index(stock)+1, '/',\n len(stocklist))\n except Exception:\n print(stock, \"data unavailable.\", self.universe.index(\n stock)+1, '/', len(self.universe))\n\n def concurrently_get_stock_data(self, n):\n \"\"\"\n Using multi-threading to increase data downloading speed.\n \"\"\"\n start = time()\n univ = self.div_list(self.universe, n)\n for i in range(n):\n print('The current number of threads is: %s' %\n threading.active_count())\n thread_alive = threading.Thread(\n target=self.get_stock_data, args=(univ[i],))\n thread_alive.start()\n thread_alive.join()\n end = time()\n print(\"Time cost to download stock data: %s s\" % (end-start))\n\n\n###############################################################################\n# Define framework functions #\n###############################################################################\n\n\ndef order_to(target):\n \"\"\"\n 下单到多少股。\n \"\"\"\n global h_amount\n trade_days = account.trade_days\n order_days = account.order_days\n tax = account.tax\n commission = account.commission\n ini_dic = account.ini_dic\n today_capital = account.today_capital\n slippage = account.slippage\n\n # 如果date在下单日,就需要进行调仓\n if date in order_days:\n # print(date.strftime('%Y-%m-%d'), list(target.index))\n # t_amount是目标仓位数据的dataframe\n t_amount = pd.DataFrame({'tamount': [0]}, index=list(target.index))\n\n # Sell stocks in holding but not in target\n for stock in list(h_amount.index):\n if stock not in list(target.index):\n try:\n stock_data = ini_dic[stock].loc[date.strftime(\"%Y-%m-%d\")]\n price = stock_data['open']\n account.cash += h_amount.loc[stock, 'hamount'] *\\\n (price-slippage) * (1-tax-commission)\n print('order: ', stock, 'amount ',\n int(0-h_amount.loc[stock, 'hamount']))\n h_amount.loc[stock, 'hamount'] = -1\n except Exception:\n h_amount.loc[stock, 'hamount'] = -1\n h_amount = h_amount[h_amount['hamount'] != -1]\n # print(\"cash: \", account.cash)\n\n # Deal with stocks in target\n for stock in list(target.index):\n stock_data = ini_dic[stock].loc[date.strftime(\n \"%Y-%m-%d\")].fillna(0)\n price = stock_data['open']\n # price = stock_data.loc[date.strftime('%Y-%m-%d'), 'open']\n\n # Buy stocks in target but not in holding\n if stock not in list(h_amount.index):\n h_amount = h_amount.append(pd.DataFrame({'hamount': [0],\n 'price': [0],\n 'value': [0],\n 'percent': [0]},\n index=[stock]))\n # print(target)\n t_amount.loc[stock, 'tamount'] = math.floor(target[stock]/100)*100\n\n # If hoding > target, sell\n if h_amount.loc[stock, 'hamount'] - t_amount.loc[stock, 'tamount']\\\n > 0:\n account.cash += (h_amount.loc[stock, 'hamount'] -\n t_amount.loc[stock, 'tamount'])\\\n * (price-slippage) * (1-tax-commission)\n\n # If hoding < target, buy\n if h_amount.loc[stock, 'hamount'] - t_amount.loc[stock, 'tamount']\\\n < 0:\n # Attention: buy hand by hand in case cash becomes negative\n for number in range(int(t_amount.loc[stock, 'tamount']/100),\n 0, -1):\n if account.cash - (number*100 -\n h_amount.loc[stock, 'hamount']) *\\\n (price+slippage) * (1+commission) < 0:\n continue\n else:\n account.cash -= (number*100 -\n h_amount.loc[stock, 'hamount']) *\\\n (price+slippage) * (1+commission)\n t_amount.loc[stock, 'tamount'] = number * 100\n break\n\n if h_amount.loc[stock, 'hamount'] - t_amount.loc[stock, 'tamount']\\\n != 0:\n print('order: ', stock, 'amount ',\n int(t_amount.loc[stock, 'tamount'] -\n h_amount.loc[stock, 'hamount']))\n\n h_amount.loc[stock, 'hamount'] = t_amount.loc[stock, 'tamount']\n h_amount.loc[stock, 'price'] = price\n h_amount.loc[stock, 'value'] = h_amount.loc[stock, 'price'] *\\\n h_amount.loc[stock, 'hamount']\n\n h_amount['percent'] = h_amount['value'] / sum(h_amount['value'])\n\n # # Output holding details\n # h_amount.to_csv('position_details.csv')\n\n account.capital.append(today_capital)\n try:\n drawdown = (max(account.capital[:-1])-account.capital[-1]) /\\\n max(account.capital[:-1])\n except Exception:\n drawdown = 0\n\n if drawdown > account.history_max:\n account.drawdown_start =\\\n trade_days[account.capital.index(max(account.capital[:-1]))]\n account.drawdown_end =\\\n trade_days[account.capital.index(account.capital[-1])]\n account.history_max = drawdown\n\n account.ret = account.ret.append(pd.DataFrame(\n {'rev': (account.capital[-1]-account.capital[0])/account.capital[0],\n 'max_drawdown': account.history_max,\n 'benchmark':\n (account.benchmark_data.loc[date.strftime('%Y-%m-%d'), 'open'] -\n account.benchmark_data.loc[trade_days[0].strftime('%Y-%m-%d'),\n 'open']) /\n account.benchmark_data.loc[trade_days[0].strftime('%Y-%m-%d'),\n 'open']},\n index=[date]))\n\n\ndef order_pct_to(pct_target):\n \"\"\"\n 下单到多少百分比。\n \"\"\"\n ini_dic = account.ini_dic\n today_capital = account.today_capital\n # target是存储目标股数的Series\n target = pd.Series()\n\n # 将pct_target中的仓位百分比数据转化为target中的股数\n for stock in list(pct_target.index):\n stock_data = ini_dic[stock].loc[date.strftime(\"%Y-%m-%d\")]\n price = stock_data['open']\n # price = stock_data.loc[date.strftime('%Y-%m-%d'), 'open']\n # print(\"today_capital: \", today_capital)\n target[stock] = (pct_target[stock]*today_capital) / price\n\n print(\"pct_target: \", pct_target)\n print(\"target: \", target)\n # 调用order_to函数\n order_to(target)\n\n\ndef result_display(account):\n \"\"\"\n Display results, including the return curve and a table showing returns\n drawdown and drawdown intervals.\n \"\"\"\n # account.ret.to_csv('return_details.csv')\n # strategy annual return\n Ra = (1+(account.ret.iloc[-1].rev)) **\\\n (12/len(list(account.trade_days))) - 1\n results = pd.DataFrame({'benchmark return':\n '%.2f%%' % (account.ret.iloc[-1].benchmark * 100),\n 'Strategy return':\n '%.2f%%' % (account.ret.iloc[-1].rev * 100),\n 'Strategy annual return':\n '%.2f%%' % (Ra*100),\n 'Max drawdown':\n '%.2f%%' % (account.ret.iloc[-1].max_drawdown*100),\n 'Max drawdown interval':\n str(account.drawdown_start.strftime('%Y-%m-%d')\n + ' to '\n + account.drawdown_end.strftime('%Y-%m-%d'))\n },\n index=[''])\n results.reindex(['benchmark return',\n 'Strategy return',\n 'Strategy annual return',\n 'Max drawdown'\n 'Max drawdown interval'\n ], axis=1)\n print(results.transpose())\n\n # plot the results\n account.ret['rev'].plot(color='royalblue', label='strategy return')\n account.ret['benchmark'].plot(color='black', label='benchmark return')\n x = np.array(list(account.ret.index))\n plt.fill_between(x, max(max(account.ret.rev), max(account.ret.benchmark)),\n min(min(account.ret.rev), min(account.ret.benchmark)),\n where=((x <= account.drawdown_end) &\n (x >= account.drawdown_start)),\n facecolor='lightsteelblue',\n alpha=0.4)\n plt.legend()\n plt.show()\n\n\n###############################################################################\n# Parameters and functions set up manually #\n###############################################################################\n\n\ndef initialize(account):\n \"\"\"\n This is a function that runs only once, before the backtest begins.\n \"\"\"\n pass\n\n\nglobal volume_each_month\nvolume_each_month = list()\n\n\ndef stock_filter(account):\n \"\"\"\n 根据yoyop进行选股的函数。选yoyop前n的股票。\n \"\"\"\n global selected\n # 将date这一交易日的股票数据取出存到一个新的dataframe中\n all_stock_df = pd.DataFrame()\n mktmaker_information = pd.read_csv(\n 'market_maker_information.csv', index_col=\"secid\")\n amount_information = pd.read_csv(\n 'amount_information.csv', index_col=\"secid\")\n # 遍历ini_dic中所有的股票\n for stock in list(account.ini_dic.keys()):\n # 将date这一天的数据存入all_stock_df中,去掉无数据的\n if mktmaker_information.loc[stock, date.strftime('%Y-%m-%d')] == 1 and\\\n amount_information.loc[stock, date.strftime('%Y-%m-%d')] >= 1000000:\n try:\n all_stock_df = all_stock_df.append(\n account.ini_dic[stock].loc[date.strftime('%Y-%m-%d')])\n except Exception:\n pass\n\n # 按yoyop降序排序\n all_stock_df = all_stock_df.sort_values('yoyop', ascending=False)\n # 取前n支股票\n selected_stock_df = all_stock_df[:5]\n # 增加交易额\n selected_stock_df['amount'] = None\n selected_stock_df = selected_stock_df.set_index('secid')\n for stock in selected_stock_df.index:\n selected_stock_df['amount'][stock] = amount_information.loc[\n stock, date. strftime('%Y-%m-%d')]\n # 取交易额之和的十分之一作为该月的策略容量\n volume_each_month.append(sum(selected_stock_df['amount']) / 10)\n # 将选取的股票代码存入buylist\n buylist = selected_stock_df.index\n # 输出选股情况\n print(date.strftime('%Y-%m-%d'), \"selected stocks: \", list(buylist))\n # # 向selected中填入该月的选股情况\n # selected = selected.append(pd.DataFrame(\n # {\"selected stocks\": str(buylist)}, index=[date.strftime('%Y-%m-%d')]))\n return buylist\n\n\ndef handle_data(account):\n \"\"\"\n This is a function that runs every backtest frequency.\n \"\"\"\n # selected_stocks为上述选股函数选出的函数\n selected_stocks = stock_filter(account)\n # print(selected_stocks)\n # positions为声明的一个存储目票仓位情况的Series\n positions = pd.Series()\n # 这里采用平均配仓的方式\n for stock in selected_stocks:\n positions[stock] = 1/len(selected_stocks)\n # 将仓位传入下单函数进行下单\n order_pct_to(positions)\n\n\nprint(\"Hello world!\")\nstart_date = '2015-07-01'\nend_date = '2018-06-01'\ncapital_base = 1000000\nfreq = 1\nbenchmark = ['430002.OC']\nuniverse = list(pd.read_csv(\"All stocks.csv\")['secid'])\n\n###############################################################################\n# Backtest begins #\n###############################################################################\n\n\naccount = account(start_date=start_date, end_date=end_date,\n capital_base=capital_base, freq=freq,\n benchmark=benchmark, universe=universe)\naccount.setup()\ninitialize(account)\n\nh_amount = pd.DataFrame({'hamount': [0],\n 'price': [0],\n 'value': [0],\n 'percent': [0]}, index=account.universe)\nselected = pd.DataFrame()\n\nfor date in list(account.trade_days):\n account.today_capital = 0\n for stock in list(h_amount.index):\n try:\n stock_data = account.ini_dic[stock].loc[date.strftime(\n \"%Y-%m-%d\")].fillna(0)\n price = stock_data['open']\n account.today_capital += price * h_amount.loc[stock, 'hamount']\n except Exception:\n pass\n account.today_capital += account.cash\n\n print(\"cash: \", account.cash)\n print(\"today_capital: \", account.today_capital)\n handle_data(account)\n\n# selected.to_csv(str(\"selected_stocks_information5.csv\"))\nresult_display(account)\n\n# 输出策略容量结果\nvolume_final = min(volume_each_month)\nvolumes = list([min(volume_each_month[:12]), min(\n volume_each_month[12:24]), min(volume_each_month[24:])])\nprint(\"Market volume(3 years): \", volume_final)\nprint(\"Market volume(2015.7 - 2016.6: \", volumes[0])\nprint(\"Market volume(2016.7 - 2017.6: \", volumes[1])\nprint(\"Market volume(2017.7 - 2018.6: \", volumes[2])\n","sub_path":"NTB_backtest_engine.py","file_name":"NTB_backtest_engine.py","file_ext":"py","file_size_in_byte":18287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"170172416","text":"import requests\nimport unittest\nheaders = {\n \"Accept\": \"image/webp,image/apng,image/*,*/*;q=0.8\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36\",\n \"Accept-Encoding\":\"gzip, deflate, br\",\n \"Accept-Language\":\"zh-CN,zh;q=0.9\",\n \"Cookie\":\"JSESSIONID=3232B0D76632CE175FCC84720DA11C5A\"\n}\nparams = {\"userName\":\"admin\",\"pwd\":\"123456\",\"captcha\":\"cclp\"}\nloginUrl='http://192.168.40.1:18080/user/login'\n#r = requests.post(loginUrl,json=params,headers=headers)\nr = requests.post(loginUrl,json=params,headers=headers)\nprint(r.status_code)\nprint(r.encoding)\nprint(r.text)\nif(r.text.__contains__(\"admin\")):\n print(\"登录成功\")\nelse:\n print(\"登录失败\")","sub_path":"Python_Study/com01_cainiao/sample3/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"382906252","text":"import numpy as np\nfrom numpy.lib.stride_tricks import as_strided\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport scipy.stats\nfrom scipy.special import gammaln\n\nfrom itertools import permutations\n\nimport os\n\nimport time\n\nimport sys\n\nimport tqdm\n\nfrom smdl import SMDL\nfrom model import Norm1D\n\nfrom mybocpd import BOCD, constant_hazard, StudentT\n\nfrom functools import partial\n\nfrom volatility_detector import VolatilityDetector\n\n#outdir = '../output/experiment3_final_fixed'\n#outdir = '../output/experiment3_final_fixed_gradual'\n#outdir = '../output/experiment3_final_fixed_abrupt'\n#outdir = '../output/experiment3_final_abrupt'\n#outdir = '../output/experiment3_final_abrupt_20190930'\n#outdir = '../output/experiment3_final_abrupt_20191001'\n#outdir = '../output/experiment3_final_abrupt_20191002'\noutdir = '../output/experiment3_final_abrupt_20191002_v2'\nif not os.path.exists(outdir):\n os.makedirs(outdir)\n\n\n\"\"\"\ndef generate_data_experiment3(length1=500, length2=600, n_repeat=50,\n y_max=1.0, y_max2=0.9, sigma=0.1, seed=123):\n np.random.seed(seed)\n\n X_list = []\n\n # SEGMENT1\n for i in range(n_repeat):\n X1 = sigma * np.random.randn(length1)\n X_list.append(X1)\n\n X2 = y_max + sigma * np.random.randn(length1)\n X_list.append(X2)\n\n # SEGMENT2\n X3 = sigma * np.random.randn(length2)\n X_list.append(X3)\n X4 = y_max2 + sigma * np.random.randn(length2)\n X_list.append(X4)\n X5 = sigma * np.random.randn(length2)\n X_list.append(X5)\n X6 = y_max2 + sigma * np.random.randn(length2)\n X_list.append(X6)\n\n X = np.hstack(X_list)\n X = X.reshape(-1, 1)\n return X\n\"\"\"\n\ndef generate_data_experiment3(length1=500, length2=600, n_repeat=50,\n y_max=1.0, y_max2=0.9, sigma=0.1, seed=123):\n np.random.seed(seed)\n\n X_list = []\n real_changepoints = []\n total_length = 0\n\n # SEGMENT1\n for i in range(n_repeat):\n X1 = sigma * np.random.randn(length1)\n X_list.append(X1)\n total_length += len(X1)\n real_changepoints.append(total_length)\n\n X2 = y_max + sigma * np.random.randn(length1)\n total_length += len(X2)\n X_list.append(X2)\n real_changepoints.append(total_length)\n\n # SEGMENT2\n X3 = sigma * np.random.randn(length2)\n total_length += len(X3)\n X_list.append(X3)\n real_changepoints.append(total_length)\n metapoint = total_length\n \n X4 = y_max2 + sigma * np.random.randn(length2*3)\n total_length += len(X3)\n X_list.append(X4)\n real_changepoints.append(total_length)\n #X5 = sigma * np.random.randn(length2)\n #X_list.append(X5)\n #X6 = y_max2 + sigma * np.random.randn(length2)\n #X_list.append(X6)\n\n X = np.hstack(X_list)\n X = X.reshape(-1, 1)\n return X, real_changepoints, metapoint\n\n\n\ndef generate_data_experiment3_gradual(length1=500, length2=1000, n_repeat=50, \n y_max=1.0, y_max2=0.9, sigma=0.1, seed=123):\n np.random.seed(seed)\n \n X_list = []\n real_changepoints = []\n \n total_length = 0 \n \n # SEGMENT1\n for i in range(n_repeat):\n len1_frac = np.random.randint(-int(0.1*length1), int(0.1*length1))\n X1 = sigma * np.random.randn(length1 + len1_frac)\n X_list.append(X1)\n total_length += len(X1)\n real_changepoints.append(total_length)\n \n len2_frac = np.random.randint(-int(0.1*length1), int(0.1*length1))\n X2 = y_max * np.arange(1, length1 + len2_frac + 1)/ (length1 + len2_frac) + sigma * np.random.randn(length1 + len2_frac)\n X_list.append(X2)\n total_length += len(X2)\n real_changepoints.append(total_length)\n \n len3_frac = np.random.randint(-int(0.1*length1), int(0.1*length1))\n X3 = y_max + sigma * np.random.randn(length1 + len3_frac)\n X_list.append(X3)\n total_length += len(X3)\n real_changepoints.append(total_length)\n \n len4_frac = np.random.randint(-int(0.1*length1), int(0.1*length1))\n X4 = y_max - y_max * np.arange(1, length1 + len4_frac + 1)/(length1 + len4_frac) + sigma * np.random.randn(length1 + len4_frac)\n X_list.append(X4)\n total_length += len(X4)\n real_changepoints.append(total_length)\n \n metapoint = len(X_list)\n\n # SEGMENT2\n len5_frac = np.random.randint(-int(0.1*length2), int(0.1*length2))\n X5 = sigma * np.random.randn(length2 + len5_frac)\n X_list.append(X5)\n total_length += len(X5)\n real_changepoints.append(total_length)\n \n len6_frac = np.random.randint(-int(0.1*length2), int(0.1*length2))\n X6 = y_max2 + sigma * np.random.randn(length2 + len6_frac)\n X_list.append(X6)\n total_length += len(X6)\n real_changepoints.append(total_length)\n \n len7_frac = np.random.randint(-int(0.1*length2), int(0.1*length2))\n X7 = sigma * np.random.randn(length2 + len7_frac)\n X_list.append(X7)\n total_length += len(X7)\n real_changepoints.append(total_length)\n \n len8_frac = np.random.randint(-int(0.1*length2), int(0.1*length2))\n X8 = y_max2 + sigma * np.random.randn(length2 + len8_frac)\n X_list.append(X8)\n total_length += len(X8)\n real_changepoints.append(total_length)\n\n X = np.hstack(X_list)\n X = X.reshape(-1, 1)\n \n return X, real_changepoints, metapoint\n\n\ndef detect_change_points_mdl(mdl_stats):\n mdl_stats = np.array(mdl_stats)\n idxes_stats_positive = np.where(mdl_stats > 0)[0]\n\n idxes_end = np.where(\n np.diff(idxes_stats_positive) > 1\n )[0]\n end = idxes_stats_positive[idxes_end]\n\n idxes_start = idxes_end + 1\n if 0 not in idxes_start:\n idxes_start = np.hstack((0, idxes_start))\n\n start = idxes_stats_positive[idxes_start]\n\n if idxes_stats_positive[idxes_start[1] - 1] not in end:\n end = np.hstack((idxes_stats_positive[idxes_start[1] - 1], end))\n if idxes_stats_positive[-1] not in end:\n end = np.hstack((end, idxes_stats_positive[-1]))\n\n change_points = []\n for s, e in zip(start, end):\n cp = s + np.argmax(mdl_stats[s:e + 1])\n change_points.append(cp)\n\n change_points = np.array(change_points)\n return change_points\n\n\ndef detect_change_points_start(scores):\n scores = np.array(scores)\n idxes_stats_positive = np.where(scores > 0)[0]\n\n idxes_end = np.where(\n np.diff(idxes_stats_positive) > 1\n )[0]\n end = idxes_stats_positive[idxes_end]\n\n idxes_start = idxes_end + 1\n if 0 not in idxes_start:\n idxes_start = np.hstack((0, idxes_start))\n\n start = idxes_stats_positive[idxes_start]\n\n if idxes_stats_positive[idxes_start[1] - 1] not in end:\n end = np.hstack((idxes_stats_positive[idxes_start[1] - 1], end))\n if idxes_stats_positive[-1] not in end:\n end = np.hstack((end, idxes_stats_positive[-1]))\n\n change_points = np.array(start)\n return change_points\n\n\ndef calc_auc(fars, benefits):\n fars = np.array(fars)\n benefits = np.array(benefits)\n # sort by ascending order\n # idx_ordered = np.argsort(fars)\n idx_ordered = np.lexsort((fars, benefits))\n fars_ordered = fars[idx_ordered]\n benefits_ordered = benefits[idx_ordered]\n # if abs(fars_ordered[0]) > 1e-6:\n # if fars_ordered[0] != 0.0:\n if np.abs(fars_ordered[0]) > 1e-6:\n # fars_ordered = np.hstack((0, 0, fars_ordered))\n fars_ordered = np.hstack((0, 0, fars_ordered))\n # benefits_ordered = np.hstack((0, benefits_ordered[0], benefits_ordered))\n # fars_ordered = np.hstack((0, fars_ordered[0], fars_ordered))\n # benefits_ordered = np.hstack((0, 0, benefits_ordered))\n benefits_ordered = np.hstack((0, benefits_ordered[0], benefits_ordered))\n # fars_ordered = np.hstack((0, fars_ordered))\n # benefits_ordered = np.hstack((0, benefits_ordered))\n elif benefits_ordered[0] != 0.0:\n fars_ordered = np.hstack((0, fars_ordered))\n benefits_ordered = np.hstack((0, benefits_ordered))\n\n # calculate AUC\n # auc = np.abs(np.sum(np.diff(fars_ordered/np.max(fars_ordered)) *\n # np.abs(benefits_ordered[:-1])/np.max(np.abs(benefits_ordered[:-1])))\n # )\n if np.all(benefits_ordered == 0):\n auc = 0.0\n else:\n auc = np.trapz(benefits_ordered,\n fars_ordered / np.max(fars_ordered))\n return auc\n\n\ndef calc_benefit_far_state(change_points, stats, metapoint, length, n_repeat, limit=5):\n benefits = []\n fars = []\n\n thresholds = np.sort(stats[~np.isnan(stats)]) - 1e-3\n thresholds = np.linspace(thresholds[0], thresholds[-1], 100)\n\n for thr in thresholds:\n idxes_over_thr = np.where(stats >= thr)[0]\n within_tol_interval = np.logical_and(\n 0 <= (change_points[idxes_over_thr] - metapoint),\n (change_points[idxes_over_thr] - metapoint) <= limit * length)\n # benefit\n benefit = 0.0\n if np.any(within_tol_interval):\n benefit = 1 - (change_points[idxes_over_thr][within_tol_interval][0] - metapoint) / (limit * length)\n\n # false positive rate\n n_fp = np.sum(\n np.logical_and(\n np.logical_or(\n change_points <= metapoint,\n change_points >= metapoint + limit * length\n ),\n np.logical_and(\n stats >= thr,\n ~np.isnan(stats)\n )\n )\n )\n\n benefits.append(benefit)\n fars.append(n_fp)\n\n fars = np.array(fars)\n benefits = np.array(benefits)\n\n return benefits, fars\n\n\nfrom scipy.special import gammaln\n\n\ndef calc_metachange_stats_v2(X, change_points, h=100, mu_max=2.0, sigma_min=0.005):\n metachange_stats = []\n\n # for t in range(h, len(X)-h):\n for i, cp in enumerate(change_points):\n mean1 = np.mean(X[(cp - h):cp, :].ravel())\n std1 = np.std(X[(cp - h):cp, :].ravel())\n # mean2 = np.mean(X[cp:(cp+h+1), :].ravel())\n # std2 = np.std(X[cp:(cp+h+1), :].ravel())\n mean2 = np.mean(X[(cp + 1):(cp + h + 1), :].ravel())\n std2 = np.std(X[(cp + 1):(cp + h + 1), :].ravel())\n\n if i == 0:\n mean1_prev, std1_prev = mean1, std1\n mean2_prev, std2_prev = mean2, std2\n continue\n\n metachange_up = np.mean(\n -scipy.stats.norm(mean1 + (mean2_prev - mean1_prev), std1 + (std2_prev - std1_prev)).logpdf(\n X[(cp+1):(cp+h+1), :].ravel()))\n metachange_down = np.mean(\n -scipy.stats.norm(mean1 - (mean2_prev - mean1_prev), std1 - (std2_prev - std1_prev)).logpdf(\n X[(cp+1):(cp+h+1), :].ravel()))\n\n metachange = np.nanmin([metachange_up, metachange_down]) - 0.5 * np.log((16 * np.abs(mu_max))/ (np.pi * sigma_min**2)) \\\n +np.log(2.0) + 1.0 - gammaln(0.5)\n\n metachange_stats.append(metachange)\n # print(metachange)\n\n mean1_prev, std1_prev = mean1, std1\n mean2_prev, std2_prev = mean2, std2\n\n return np.array(metachange_stats)\n # return np.abs(np.diff(metachange_stats))\n\n### Change detection\ndef gridsearch_bocpd(\n X, \n length1, length2, \n real_changepoints,\n LAMBDA,\n THRESHOLD, \n ALPHA=0.1,\n BETA=1.,\n KAPPA=1.,\n MU=0.,\n DELAY=15,\n n_repeat=10,\n ymax=1.0,\n delay=100,\n delay_cp=30, \n n_trial=10, \n seed=0\n):\n aucs = []\n T = len(X)\n\n scores = []\n # BOCPD\n bocd = BOCD(partial(constant_hazard, LAMBDA),\n StudentT(ALPHA, BETA, KAPPA, MU), X)\n change_points = []\n scores = []\n for x in X[:DELAY, 0]:\n bocd.update(x)\n for x in tqdm.tqdm(X[DELAY:, 0]):\n bocd.update(x)\n if bocd.growth_probs[DELAY] >= THRESHOLD:\n change_points.append(bocd.t - DELAY + 1)\n score = np.sum(bocd.growth_probs[:bocd.t - DELAY] * 1.0 / (1.0 + np.arange(1, bocd.t - DELAY + 1)))\n scores.append(score)\n\n change_points = np.array(change_points)\n scores = np.array(scores)\n\n # AUCs for change points\n\n thresholds = np.sort(scores[~np.isnan(scores)]) - 1e-3\n thresholds = np.linspace(thresholds[0], thresholds[-1], 100)\n\n \"\"\"\n fars, benefits = [], []\n for thr in thresholds:\n idxes_over_thr = np.where(scores >= thr)[0]\n n_fp = len(idxes_over_thr)\n\n benefit_thr = []\n n_fp_thr = []\n for r_cp in real_changepoints:\n benefit = 0.0\n ok = np.logical_and(idxes_over_thr - r_cp >= 0,\n idxes_over_thr - r_cp <= delay)\n if any(ok):\n benefit = 1 - (idxes_over_thr[ok][0] - r_cp) / delay\n\n n_fp = np.sum(\n np.logical_or(\n idxes_over_thr < r_cp,\n idxes_over_thr >= r_cp + delay\n )\n )\n \n benefit_thr.append(benefit)\n n_fp_thr.append(n_fp)\n\n benefits.append(benefit_thr)\n fars.append(n_fp_thr)\n \n benefits = np.array(benefits).T\n fars = np.array(fars).T\n\n aucs_i = []\n for j in range(fars.shape[0]):\n benefit = benefits[j, :]\n far = fars[j, :]\n auc = calc_auc(far, benefit)\n aucs_i.append(auc)\n\n aucs.append(np.mean(aucs_i))\n\n return np.array(aucs), change_points\n \"\"\"\n \n fars, benefits = [], []\n for thr in thresholds:\n idxes_over_thr = np.where(scores >= thr)[0]\n n_fp = len(idxes_over_thr)\n\n benefit = 0.0\n count = 0\n for r_cp in real_changepoints:\n ok = np.logical_and(idxes_over_thr - r_cp >= 0,\n idxes_over_thr - r_cp <= delay)\n if any(ok):\n benefit += 1 - (idxes_over_thr[ok][0] - r_cp)/delay\n count += 1\n #if count >= 1:\n # benefit /= count\n \n fars.append(n_fp)\n benefits.append(benefit)\n \n auc = calc_auc(np.array(fars), np.array(benefits)/np.max(benefits))\n \n tp = 0\n for cp in real_changepoints:\n ok = np.abs(change_points - cp) <= delay_cp\n if np.any(ok):\n tp += 1\n \n m = len(change_points)\n l = len(real_changepoints)\n fp = m - tp\n fn = l - tp\n \n precision = tp/(tp+fp)\n recall = tp/(tp+fn)\n \n diff = change_points - 2*n_repeat*length1 - length2\n idxes = np.where(diff >= 0)[0]\n d = diff[idxes[0]]\n \n #return auc, change_points\n return auc, change_points, precision, recall, d\n\n \"\"\"\n for i in tqdm.tqdm(range(n_trial)):\n # generate data\n #X = generate_data_experiment3(length1, length2, n_repeat=n_repeat,\n # y_max=ymax,\n # seed=seed)\n T = len(X)\n # SMDL\n # smdl = SMDL(w, T, Norm1D, 0.05)\n # mdl_stats = [np.nan] * w + \\\n # [smdl.calc_change_score(X[(i-w):(i+w), :].ravel(),\n # mu_max=2.0, sigma_min=0.005) \\\n # for i in range(w, T-w)] + \\\n # [np.nan] * w\n # mdl_stats = np.array(mdl_stats)\n\n # detect change points\n # change_points = detect_change_points_mdl(mdl_stats - epsilon)\n\n scores = []\n # BOCPD\n bocd = BOCD(partial(constant_hazard, LAMBDA),\n StudentT(ALPHA, BETA, KAPPA, MU), X)\n change_points = []\n scores = []\n for x in X[:DELAY, 0]:\n bocd.update(x)\n for x in tqdm.tqdm(X[DELAY:, 0]):\n bocd.update(x)\n if bocd.growth_probs[DELAY] >= THRESHOLD:\n change_points.append(bocd.t - DELAY + 1)\n score = np.sum(bocd.growth_probs[:bocd.t - DELAY] * 1.0 / (1.0 + np.arange(1, bocd.t - DELAY + 1)))\n scores.append(score)\n\n change_points = np.array(change_points)\n scores = np.array(scores)\n\n # AUCs for change points\n\n thresholds = np.sort(scores[~np.isnan(scores)]) - 1e-3\n thresholds = np.linspace(thresholds[0], thresholds[-1], 100)\n\n fars, benefits = [], []\n for thr in thresholds:\n idxes_over_thr = np.where(scores >= thr)[0]\n n_fp = len(idxes_over_thr)\n\n benefit_thr = []\n n_fp_thr = []\n for r_cp in real_changepoints:\n benefit = 0.0\n ok = np.logical_and(idxes_over_thr - r_cp >= 0,\n idxes_over_thr - r_cp <= delay)\n if any(ok):\n benefit = 1 - (idxes_over_thr[ok][0] - r_cp) / delay\n\n n_fp = np.sum(\n np.logical_or(\n idxes_over_thr < r_cp,\n idxes_over_thr >= r_cp + delay\n )\n )\n \n benefit_thr.append(benefit)\n n_fp_thr.append(n_fp)\n \n benefits.append(benefit_thr)\n fars.append(n_fp_thr)\n \n benefits = np.array(benefits).T\n fars = np.array(fars).T\n\n aucs_i = []\n for j in range(fars.shape[0]):\n benefit = benefits[j, :]\n far = fars[j, :]\n auc = calc_auc(far, benefit)\n aucs_i.append(auc)\n\n aucs.append(np.mean(aucs_i))\n\n return np.array(aucs), change_points\n \"\"\"\n\n \"\"\"\n fars, benefits = [], []\n for thr in thresholds:\n idxes_over_thr = np.where(scores >= thr)[0]\n n_fp = len(idxes_over_thr)\n\n benefit = 0.0\n count = 0\n for r_cp in real_changepoints:\n ok = np.logical_and(idxes_over_thr - r_cp >= 0,\n idxes_over_thr - r_cp <= delay)\n if any(ok):\n benefit += 1 - (idxes_over_thr[ok][0] - r_cp) / delay\n count += 1\n if count >= 1:\n benefit /= count\n\n fars.append(n_fp)\n benefits.append(benefit)\n\n auc = calc_auc(np.array(fars), np.array(benefits))\n\n return auc, change_points, X\n \"\"\"\n\n\n### Metachange detection along time\ndef calc_metachange_time_md(X, change_points, r=0.05):\n change_points_diff = np.diff(change_points)\n\n lambdas_hat = np.array(\n [(1 - (1 - r) ** (i + 1)) / \\\n (r * np.sum((1 - r) ** np.arange(i, -1, -1) * change_points_diff[:i + 1])) \\\n for i in range(len(change_points_diff))]\n )\n codelen = -np.log(lambdas_hat[:-1]) + lambdas_hat[:-1] * change_points_diff[1:]\n #change_rate_codelen = np.diff(codelen) / codelen[:-1]\n\n return codelen\n\n\ndef calc_metachange_time_vd(X, change_points, seed=0):\n change_points_diff = np.diff(change_points)\n\n vdetector = VolatilityDetector(seed=seed)\n relvol = np.array([vdetector.detect(cpd) for cpd in change_points_diff])\n\n return relvol\n\n\ndef calc_benefit_far_mcat(change_rate_codelen, change_points,\n metapoint, \n length1, length2, n_repeat,\n limit=5, r=0.2, B=32, R=32, seed=0):\n ## MCAT\n benefits_md_i, fars_md_i = [], []\n thr_list = np.sort(np.abs(change_rate_codelen[B + R - 3:]))\n thr_list = np.linspace(thr_list[0], thr_list[-1], 100)\n\n #metapoint = 2*n_repeat*length1 + length2\n\n for thr in thr_list:\n # metachange detector\n idxes_over_thr_after_cp_within = np.where(\n np.logical_and(\n np.logical_and(\n #change_points[B + R:] >= 2 * length1 * n_repeat + length2, # + blockSize,\n #change_points[B + R:] < 2 * length1 * n_repeat + length2 + limit * length2\n change_points[B + R:] >= metapoint, # + blockSize,\n change_points[B + R:] < metapoint + limit * length2\n ),\n np.abs(change_rate_codelen[B + R - 3:]) > thr\n ))[0]\n if len(idxes_over_thr_after_cp_within) == 0:\n benefit = 0.0\n else:\n #benefit = 1 - (change_points[B + R + idxes_over_thr_after_cp_within[0]] - 2 * length1 * n_repeat - length2) / (\n benefit = 1 - (change_points[B + R + idxes_over_thr_after_cp_within[0]] - metapoint) / (\n limit * length2)\n\n # false positive rate\n n_fp = np.sum(\n np.logical_and(\n np.logical_or(\n #change_points[B + R:] >= 2 * length1 * n_repeat + length2 + limit * length2,\n #change_points[B + R:] < 2 * length1 * n_repeat + length2\n change_points[B + R:] >= metapoint + limit * length2,\n change_points[B + R:] < metapoint\n ),\n np.logical_and(\n np.abs(change_rate_codelen[B + R - 3:]) > thr,\n ~np.isnan(change_rate_codelen[B + R - 3:])\n )\n )\n )\n\n benefits_md_i.append(benefit)\n fars_md_i.append(n_fp)\n\n return benefits_md_i, fars_md_i\n\n\ndef calc_benefit_far_vd(change_points, change_points_diff,\n metapoint,\n length1, length2, n_repeat, limit=5,\n B=32, R=32, \n blockSize=32, seed=0):\n cps = change_points[1:]\n\n #metapoint = 2*n_repeat*length1 + length2\n\n ## volatility detector\n vdetector = VolatilityDetector(seed=seed, b=B, r=R)\n relvol = np.array([vdetector.detect(cpd) for cpd in change_points_diff])\n\n benefits_vd_i, fars_vd_i = [], []\n bnd_list = np.sort(np.abs(relvol[~np.isnan(relvol)] - 1.0)) - 1e-3\n #bnd_list = np.linspace(bnd_list[0], bnd_list[-1], 100)\n for bnd in bnd_list:\n is_metachange = np.logical_or(relvol > 1.0 + bnd, relvol < 1.0 - bnd)\n\n idxes_over_thr = np.where(\n np.logical_and(\n np.logical_or(relvol > 1.0 + bnd, relvol < 1.0 - bnd),\n ~np.isnan(relvol)\n )\n )[0]\n cps_over_thr = cps[idxes_over_thr]\n within_tol_interval = np.logical_and(\n #cps_over_thr - 2 * n_repeat * length1 - length2 >= blockSize,\n #cps_over_thr - 2 * n_repeat * length1 - length2 < limit * length2)\n cps_over_thr - metapoint >= 0,\n cps_over_thr - metapoint < limit * length2)\n\n # benefit\n benefit = 0.0\n if np.any(within_tol_interval):\n #dist_from_cp = np.abs(cps_over_thr[within_tol_interval] - 2 * n_repeat * length1 - length2)\n dist_from_cp = np.abs(cps_over_thr[within_tol_interval] - metapoint)\n benefit = 1 - (dist_from_cp[0] / (limit * length2))\n\n benefits_vd_i.append(benefit)\n\n # false alarm\n n_fp = np.sum(\n np.logical_and(\n np.logical_and(\n np.logical_or(relvol > 1.0 + bnd, relvol < 1.0 - bnd),\n ~np.isnan(relvol)\n ),\n np.logical_or(\n #cps < 2 * n_repeat * length1 + length2,\n #cps >= 2 * n_repeat * length1 + length2 + limit * length2\n cps < metapoint,\n cps >= metapoint + limit * length2\n )\n )\n )\n fars_vd_i.append(n_fp)\n\n return benefits_vd_i, fars_vd_i, relvol\n\n\ndef gridsearch_mct(\n length1, length2,\n change_points_diff,\n change_points,\n metapoint, \n r=0.2,\n B=32, R=32,\n n_repeat=10,\n limit=1,\n n_trial=20, \n seed=0\n):\n lambdas_hat = np.array(\n [(1 - (1 - r) ** (i + 1)) / \\\n (r * np.sum((1 - r) ** np.arange(i, -1, -1) * change_points_diff[:i + 1])) \\\n for i in range(len(change_points_diff))]\n )\n codelen = -np.log(lambdas_hat[:-1]) + lambdas_hat[:-1] * change_points_diff[1:]\n change_rate_codelen = np.diff(codelen) / codelen[:-1]\n\n benefits_md, fars_md = calc_benefit_far_mcat(\n change_rate_codelen, change_points,\n metapoint, \n length1, length2, n_repeat,\n limit=limit, r=r, B=B, R=R, seed=seed)\n auc_md = calc_auc(np.array(fars_md), np.array(benefits_md))\n\n #print('## volatility detector')\n benefits_vd, fars_vd, relvol = calc_benefit_far_vd(\n change_points, change_points_diff,\n metapoint, \n length1, length2, n_repeat, limit=limit, \n B=B, R=R, seed=seed\n )\n auc_vd = calc_auc(np.array(fars_vd), np.array(benefits_vd))\n\n return auc_md, auc_vd, codelen, relvol\n\n\n### Metachange detection along state\ndef gridsearch_mcs(\n X, \n length1, length2, \n change_points,\n metapoint,\n h=50,\n n_repeat=10,\n limit=1\n):\n # AUC for metachange\n mcas = calc_metachange_stats_v2(X, change_points, h=h)\n #metapoint = 2*n_repeat*length1 + length2\n benefits_mcas_i, fars_mcas_i = calc_benefit_far_state(\n change_points[1:], mcas,\n metapoint, length2,\n n_repeat, limit=limit)\n auc_mcas = calc_auc(np.array(fars_mcas_i),\n np.array(benefits_mcas_i))\n\n #print('## SMDL-MC')\n T = len(X)\n #smdl = SMDL(h, T, Norm1D, 0.05)\n smdl = SMDL(Norm1D, 0.05)\n mdl_stats = [np.nan] * h + \\\n [smdl.calc_change_score(X[(i-h):(i+h), :].ravel(), h, \n mu_max=2.0, sigma_min=0.005) \\\n for i in range(h, T-h)] + \\\n [np.nan] * h\n mdl_stats = np.array(mdl_stats)\n\n mdl_stats_rate = np.abs(np.diff(mdl_stats[change_points])/\n mdl_stats[change_points][:-1])\n benefits_smdlmc, fars_smdlmc = calc_benefit_far_state(\n change_points[1:], mdl_stats_rate,\n metapoint, length2,\n n_repeat, limit=limit)\n\n auc_smdlmc = calc_auc(np.array(fars_smdlmc),\n np.array(benefits_smdlmc))\n\n return auc_mcas, auc_smdlmc, mcas\n\n\n\nresults = []\n\nn_repeat = 50\nn_trial = 20\nlimit = 1\n\nr_list = np.array([0.05, 0.1, 0.2, 0.3, 0.4, 0.5])\n#h_list = np.array([50, 100, 150])\nR_list = np.array([16, 24, 32, 40])\nlambda_list = np.array([1e-3, 1e-2, 1e-1, 1.0, 5.0, 10.0])\n\n#for (length1, length2) in permutations([400, 450, 500, 600], 2):\n#for (length1, length2) in permutations([400, 500, 600], 2):\nfor (length1, length2) in permutations([400, 450, 500], 2):\n#for (length1, length2) in permutations([500, 1000, 1500, 2000], 2):\n #real_changepoints = np.linspace(length1, 2*n_repeat*length1 + 3*length2, length2)\n #real_changepoints = np.hstack((np.arange(length1, 2*n_repeat*length1 + length1, \n # length1),\n # np.arange(2*n_repeat*length1 + length2, \n # 2*n_repeat*length1 + 4*length2, length2)))\n #h = 100\n h_list = np.array([int(0.1*length1), int(0.2*length1)])\n seed = 0\n for i in tqdm.tqdm(range(n_trial)):\n #X, real_changepoints, metapoint = generate_data_experiment3_gradual(length1, length2, n_repeat=n_repeat, seed=i)\n #X, real_changepoints, metapoint = generate_data_experiment3(length1, length2, n_repeat=n_repeat, seed=i)\n #X, real_changepoints, metapoint = generate_data_experiment3(length1, length2, n_repeat=n_repeat, y_max=0.5, y_max2=0.4, seed=i)\n X, real_changepoints, metapoint = generate_data_experiment3(length1, length2, n_repeat=n_repeat, y_max=0.5, y_max2=0.45, seed=i)\n for LAMBDA in [100, 300, 600]:\n for THRESHOLD in [0.1, 0.3]:\n auc_cp, change_points, precision, recall, delay = gridsearch_bocpd(\n X, \n length1, length2,\n real_changepoints,\n LAMBDA=LAMBDA, THRESHOLD=THRESHOLD,\n n_repeat=n_repeat,\n n_trial=5,\n seed=seed)\n \n print(change_points)\n\n change_points_diff = np.diff(change_points)\n\n print('# Metachange detection along time')\n seed_t = 0\n for r in r_list:\n for R in R_list:\n try:\n auc_mct, auc_vd, codelen, relvol = gridsearch_mct(\n length1, length2,\n change_points_diff,\n change_points,\n metapoint, \n r=r,\n B=R, R=R,\n n_repeat=n_repeat,\n limit=limit, \n seed=seed_t\n )\n except:\n auc_mct = np.nan\n auc_vd = np.nan\n codelen = np.nan\n relvol = np.nan\n\n seed_t += 1\n\n print('# Metachange detection along state')\n for h in h_list:\n try:\n auc_mcas, auc_smdlmc, mcas = gridsearch_mcs(\n X, \n length1, length2, \n change_points,\n metapoint, \n h=h, \n n_repeat=n_repeat\n )\n except:\n auc_mcas = np.nan\n auc_smdlmc = np.nan\n mcas = np.nan\n \n print('# Metachange detection along time and state')\n for lam in lambda_list:\n codelen_integrated = codelen + lam * mcas[1:]\n benefits_integrated, fars_integrated = \\\n calc_benefit_far_state(change_points[2:], codelen_integrated,\n #metapoint=2*n_repeat*length1+length2,\n metapoint=metapoint,\n length=length2, n_repeat=n_repeat, limit=limit)\n auc_integrated = calc_auc(fars_integrated, benefits_integrated)\n\n result = pd.DataFrame({\n 'length1': length1,\n 'length2': length2,\n 'LAMBDA': LAMBDA,\n 'THRESHOLD': THRESHOLD,\n 'r': r,\n 'R': R,\n 'h': h, \n 'lam': lam,\n 'AUC_CP': auc_cp,\n 'PRECISION_CP': precision,\n 'RECALL_CP': recall,\n 'DELAY': delay, \n 'AUC_MCAT': auc_mct,\n 'AUC_VD': auc_vd,\n 'AUC_MCAS': auc_mcas,\n 'AUC_SMDLMC': auc_smdlmc,\n 'AUC_INTEGRATED': [auc_integrated]},\n columns=['length1', 'length2',\n 'LAMBDA', 'THRESHOLD', 'r', 'R', 'h', 'lam',\n 'AUC_CP', \n 'PRECISION_CP', 'RECALL_CP', 'DELAY', \n 'AUC_MCAT', 'AUC_VD',\n 'AUC_MCAS', 'AUC_SMDLMC',\n 'AUC_INTEGRATED'])\n results.append(result)\n print(\n 'length1:', length1,\n 'length2:', length2,\n 'LAMBDA:', LAMBDA,\n 'THRESHOLD:', THRESHOLD, \n 'r:', r,\n 'R:', R, \n 'lam:', lam,\n 'AUC_CP:', auc_cp,\n 'PRECISION_CP:', precision, \n 'RECALL_CP:', recall, \n 'DELAY:', delay, \n 'AUC_MCAT:', auc_mct,\n 'AUC_VD:', auc_vd,\n 'AUC_MCAS:', auc_mcas,\n 'AUC_SMDLMC:', auc_smdlmc,\n 'AUC_INTEGRATED:', auc_integrated\n )\n results_df = pd.concat(results)\n results_df.to_csv(os.path.join(outdir, 'bocpd_auc_mixed.csv'), index=None)\n\n seed += 1\n\n","sub_path":"src/experiment3/experiment3_bocpd.py","file_name":"experiment3_bocpd.py","file_ext":"py","file_size_in_byte":33187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"651562093","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n# pylint: disable=invalid-name\n\n\"\"\"\nHamiltonian models module.\n\"\"\"\n\nfrom typing import Union, List, Optional\nimport numpy as np\n\nfrom qiskit.quantum_info.operators import Operator\nfrom qiskit_dynamics.dispatch import Array\nfrom qiskit_dynamics.signals import Signal, SignalList\nfrom qiskit_dynamics.type_utils import to_array\nfrom .generator_models import GeneratorModel\n\n\nclass HamiltonianModel(GeneratorModel):\n r\"\"\"A model of a Hamiltonian.\n\n This class represents a Hamiltonian as a time-dependent decomposition the form:\n\n .. math::\n\n H(t) = \\sum_{i=0}^{k-1} s_i(t) H_i,\n\n where :math:`H_i` are Hermitian operators, and the :math:`s_i(t)` are\n time-dependent functions represented by :class:`Signal` objects.\n\n This class inherits\n\n Currently the functionality of this class is as a subclass of\n :class:`GeneratorModel`, with the following modifications:\n\n - The operators in the linear decomposition are verified to be\n Hermitian.\n - Frames are dealt with assuming the structure of the Schrodinger\n equation. I.e. Evaluating the Hamiltonian :math:`H(t)` in a\n frame :math:`F = -iH`, evaluates the expression\n :math:`e^{-tF}H(t)e^{tF} - H`. This is in contrast to\n the base class :class:`OperatorModel`, which would ordinarily\n evaluate :math:`e^{-tF}H(t)e^{tF} - F`.\n \"\"\"\n\n def __init__(\n self,\n operators: List[Operator],\n signals: Optional[Union[SignalList, List[Signal]]] = None,\n frame: Optional[Union[Operator, Array]] = None,\n cutoff_freq: Optional[float] = None,\n validate: bool = True,\n ):\n \"\"\"Initialize, ensuring that the operators are Hermitian.\n\n Args:\n operators: list of Operator objects.\n signals: Specifiable as either a SignalList, a list of\n Signal objects, or as the inputs to signal_mapping.\n OperatorModel can be instantiated without specifying\n signals, but it can not perform any actions without them.\n frame: Rotating frame operator. If specified with a 1d\n array, it is interpreted as the diagonal of a\n diagonal matrix.\n cutoff_freq: Frequency cutoff when evaluating the model.\n validate: If True check input operators are Hermitian.\n\n Raises:\n Exception: if operators are not Hermitian\n \"\"\"\n # verify operators are Hermitian, and if so instantiate\n operators = to_array(operators)\n\n if validate:\n adj = np.transpose(np.conjugate(operators), (0, 2, 1))\n if np.linalg.norm(adj - operators) > 1e-10:\n raise Exception(\"\"\"HamiltonianModel only accepts Hermitian operators.\"\"\")\n\n super().__init__(operators=operators, signals=signals, frame=frame, cutoff_freq=cutoff_freq)\n\n def evaluate(self, time: float, in_frame_basis: bool = False) -> Array:\n \"\"\"Evaluate the Hamiltonian at a given time.\n\n Note: This function from :class:`OperatorModel` needs to be overridden,\n due to frames for Hamiltonians being relative to the Schrodinger\n equation, rather than the Hamiltonian itself.\n See the class doc string for details.\n\n Args:\n time: Time to evaluate the model\n in_frame_basis: Whether to evaluate in the basis in which the frame\n operator is diagonal\n\n Returns:\n Array: the evaluated model\n\n Raises:\n Exception: if signals are not present\n \"\"\"\n\n if self.signals is None:\n raise Exception(\n \"\"\"OperatorModel cannot be evaluated without\n signals.\"\"\"\n )\n\n sig_vals = self.signals.complex_value(time)\n\n op_combo = self._evaluate_in_frame_basis_with_cutoffs(sig_vals)\n\n op_to_add_in_fb = None\n if self.frame.frame_operator is not None:\n op_to_add_in_fb = -1j * np.diag(self.frame.frame_diag)\n\n return self.frame._conjugate_and_add(\n time,\n op_combo,\n op_to_add_in_fb=op_to_add_in_fb,\n operator_in_frame_basis=True,\n return_in_frame_basis=in_frame_basis,\n )\n\n def __call__(self, t: float, y: Optional[Array] = None, in_frame_basis: Optional[bool] = False):\n \"\"\"Evaluate generator RHS functions. Needs to be overriden from base class\n to include :math:`-i`. I.e. if ``y is None``, returns :math:`-iH(t)`,\n and otherwise returns :math:`-iH(t)y`.\n\n Args:\n t: Time.\n y: Optional state.\n in_frame_basis: Whether or not to evaluate in the frame basis.\n\n Returns:\n Array: Either the evaluated model or the RHS for the given y\n \"\"\"\n\n if y is None:\n return -1j * self.evaluate(t, in_frame_basis=in_frame_basis)\n\n return -1j * self.lmult(t, y, in_frame_basis=in_frame_basis)\n","sub_path":"qiskit_dynamics/models/hamiltonian_models.py","file_name":"hamiltonian_models.py","file_ext":"py","file_size_in_byte":5520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"474058090","text":"import struct\r\nfrom extra_functions import *\r\n\r\nSWAPPED_VALUE = 0xD4C3B2A1\r\nIDENTICAL_VALUE = 0xA1B2C3D4\r\n\r\nSIZE_OF_GLOBAL_HEADER = 24\r\nSIZE_OF_PACKET_HEADER = 16\r\nSIZE_OF_ETHERNET_HEADER = 14\r\n\r\n\r\nclass IP_Header:\r\n src_ip = None # \r\n dst_ip = None # \r\n ip_header_len = None # \r\n total_len = None # \r\n\r\n def __init__(self):\r\n self.src_ip = None\r\n self.dst_ip = None\r\n self.ip_header_len = 0\r\n self.total_len = 0\r\n\r\n def get_info(self, binary, endian):\r\n # determine length of IPV4 header\r\n self.get_header_len(binary[0:1])\r\n\r\n # We could get IP V# here, but we are gonna skip it\r\n # Get relevant data listed in tut4.pdf\r\n\r\n # Parse out ip4 header\r\n ip4_header, binary = getNextBytes(binary, self.ip_header_len)\r\n\r\n # Total Length\r\n self.get_total_len(ip4_header[2:4])\r\n\r\n # src and dst ip\r\n self.get_IP(ip4_header[12:16], ip4_header[16:])\r\n # print(self)\r\n\r\n return binary\r\n\r\n def ip_set(self, src_ip, dst_ip):\r\n self.src_ip = src_ip\r\n self.dst_ip = dst_ip\r\n\r\n def header_len_set(self, length):\r\n self.ip_header_len = length\r\n\r\n def total_len_set(self, length):\r\n self.total_len = length\r\n\r\n def get_IP(self, buffer1, buffer2):\r\n src_addr = struct.unpack(\"BBBB\", buffer1)\r\n dst_addr = struct.unpack(\"BBBB\", buffer2)\r\n s_ip = (\r\n str(src_addr[0])\r\n + \".\"\r\n + str(src_addr[1])\r\n + \".\"\r\n + str(src_addr[2])\r\n + \".\"\r\n + str(src_addr[3])\r\n )\r\n d_ip = (\r\n str(dst_addr[0])\r\n + \".\"\r\n + str(dst_addr[1])\r\n + \".\"\r\n + str(dst_addr[2])\r\n + \".\"\r\n + str(dst_addr[3])\r\n )\r\n self.ip_set(s_ip, d_ip)\r\n\r\n def get_header_len(self, value):\r\n result = struct.unpack(\"B\", value)[0]\r\n length = (result & 15) * 4\r\n self.header_len_set(length)\r\n\r\n def get_total_len(self, buffer):\r\n num1 = ((buffer[0] & 240) >> 4) * 16 * 16 * 16\r\n num2 = (buffer[0] & 15) * 16 * 16\r\n num3 = ((buffer[1] & 240) >> 4) * 16\r\n num4 = buffer[1] & 15\r\n length = num1 + num2 + num3 + num4\r\n self.total_len_set(length)\r\n\r\n def __str__(self):\r\n return str(self.__class__) + \": \" + str(self.__dict__)\r\n\r\n\r\nclass TCP_Header:\r\n src_port = 0\r\n dst_port = 0\r\n seq_num = 0\r\n ack_num = 0\r\n data_offset = 0\r\n flags = {}\r\n window_size = 0\r\n checksum = 0\r\n ugp = 0\r\n\r\n def __init__(self):\r\n self.src_port = 0\r\n self.dst_port = 0\r\n self.seq_num = 0\r\n self.ack_num = 0\r\n self.data_offset = 0\r\n self.flags = {}\r\n self.window_size = 0\r\n self.checksum = 0\r\n self.ugp = 0\r\n\r\n def src_port_set(self, src):\r\n self.src_port = src\r\n\r\n def dst_port_set(self, dst):\r\n self.dst_port = dst\r\n\r\n def seq_num_set(self, seq):\r\n self.seq_num = seq\r\n\r\n def ack_num_set(self, ack):\r\n self.ack_num = ack\r\n\r\n def data_offset_set(self, data_offset):\r\n self.data_offset = data_offset\r\n\r\n def flags_set(self, ack, rst, syn, fin):\r\n self.flags[\"ACK\"] = ack\r\n self.flags[\"RST\"] = rst\r\n self.flags[\"SYN\"] = syn\r\n self.flags[\"FIN\"] = fin\r\n\r\n def win_size_set(self, size):\r\n self.window_size = size\r\n\r\n def get_src_port(self, buffer):\r\n num1 = ((buffer[0] & 240) >> 4) * 16 * 16 * 16\r\n num2 = (buffer[0] & 15) * 16 * 16\r\n num3 = ((buffer[1] & 240) >> 4) * 16\r\n num4 = buffer[1] & 15\r\n port = num1 + num2 + num3 + num4\r\n self.src_port_set(port)\r\n # print(self.src_port)\r\n return None\r\n\r\n def get_dst_port(self, buffer):\r\n num1 = ((buffer[0] & 240) >> 4) * 16 * 16 * 16\r\n num2 = (buffer[0] & 15) * 16 * 16\r\n num3 = ((buffer[1] & 240) >> 4) * 16\r\n num4 = buffer[1] & 15\r\n port = num1 + num2 + num3 + num4\r\n self.dst_port_set(port)\r\n # print(self.dst_port)\r\n return None\r\n\r\n def get_seq_num(self, buffer):\r\n seq = struct.unpack(\">I\", buffer)[0]\r\n self.seq_num_set(seq)\r\n # print(seq)\r\n return None\r\n\r\n def get_ack_num(self, buffer):\r\n ack = struct.unpack(\">I\", buffer)[0]\r\n self.ack_num_set(ack)\r\n return None\r\n\r\n def get_flags(self, buffer):\r\n value = struct.unpack(\"B\", buffer)[0]\r\n fin = value & 1\r\n syn = (value & 2) >> 1\r\n rst = (value & 4) >> 2\r\n ack = (value & 16) >> 4\r\n self.flags_set(ack, rst, syn, fin)\r\n return None\r\n\r\n def get_window_size(self, buffer1, buffer2):\r\n buffer = buffer2 + buffer1\r\n size = struct.unpack(\"H\", buffer)[0]\r\n self.win_size_set(size)\r\n return None\r\n\r\n def get_data_offset(self, buffer):\r\n value = struct.unpack(\"B\", buffer)[0]\r\n length = ((value & 240) >> 4) * 4\r\n self.data_offset_set(length)\r\n # print(self.data_offset)\r\n return None\r\n\r\n def relative_seq_num(self, orig_num):\r\n if self.seq_num >= orig_num:\r\n relative_seq = self.seq_num - orig_num\r\n self.seq_num_set(relative_seq)\r\n # print(self.seq_num)\r\n\r\n def relative_ack_num(self, orig_num):\r\n if self.ack_num >= orig_num:\r\n relative_ack = self.ack_num - orig_num + 1\r\n self.ack_num_set(relative_ack)\r\n\r\n def get_info(self, binary):\r\n # src_port\r\n self.get_src_port(binary[0:2])\r\n\r\n # dst_port\r\n self.get_dst_port(binary[2:4])\r\n\r\n # seq_num\r\n self.get_seq_num(binary[4:8])\r\n\r\n # ack_num\r\n self.get_ack_num(binary[8:12])\r\n\r\n # data_offset\r\n self.get_data_offset(binary[12:13])\r\n\r\n # flags\r\n self.get_flags(binary[13:14])\r\n\r\n # window_size\r\n self.get_window_size(binary[14:15], binary[15:16])\r\n\r\n # check sum\r\n # LOL SKIP ME WITH THAT\r\n\r\n # urgent\r\n # LOL SKIP ME WITH THAT\r\n\r\n # print(self)\r\n\r\n return binary\r\n\r\n def __str__(self):\r\n return str(self.__class__) + \": \" + str(self.__dict__)\r\n\r\n\r\nclass packet:\r\n\r\n # pcap_hd_info = None\r\n IP_header = None\r\n TCP_header = None\r\n timestamp = 0\r\n packet_No = 0\r\n RTT_value = 0\r\n RTT_flag = False\r\n buffer = None\r\n orig_time = 0\r\n incl_len = 0\r\n orig_len = 0\r\n\r\n def __init__(self):\r\n self.IP_header = IP_Header()\r\n self.TCP_header = TCP_Header()\r\n # self.pcap_hd_info = pcap_ph_info()\r\n self.timestamp = 0\r\n self.packet_No = 0\r\n self.RTT_value = 0.0\r\n self.RTT_flag = False\r\n self.buffer = None\r\n self.orig_time = packet.orig_time\r\n self.incl_len = 0\r\n # self.orig_len = 0\r\n\r\n def get_bytes(self):\r\n # self.incl_len - (SIZE_OF_ETHERNET_HEADER + IP.ip_header_len + TCP.data_offset)\r\n header_size = self.IP_header.ip_header_len + self.TCP_header.data_offset\r\n len_with_no_buffer = self.IP_header.total_len\r\n return len_with_no_buffer - header_size\r\n\r\n def get_info(self, header_binary, endian):\r\n ts_sec = header_binary[0:4]\r\n ts_usec = header_binary[4:8]\r\n incl_len = struct.unpack(endian + \"I\", header_binary[8:12])[0]\r\n # orig_len = struct.unpack(endian + \"I\", header_binary[12:])[0]\r\n self.timestamp_set(ts_sec, ts_usec, self.orig_time)\r\n self.packet_No_set()\r\n self.incl_len = incl_len\r\n return incl_len\r\n\r\n def packet_data(self, binary, endian):\r\n # ethernet header\r\n # ethernet_header, binary = getNextBytes(binary, SIZE_OF_ETHERNET_HEADER)\r\n binary = binary[SIZE_OF_ETHERNET_HEADER:]\r\n\r\n binary = self.IP_header.get_info(binary, endian)\r\n # binary is remaining packet data minus the\r\n\r\n binary = self.TCP_header.get_info(binary)\r\n\r\n # ip_4 header\r\n\r\n def timestamp_set(self, buffer1, buffer2, orig_time):\r\n seconds = struct.unpack(\"I\", buffer1)[0]\r\n microseconds = struct.unpack(\"\"\r\n elif self.magic_number == IDENTICAL_VALUE:\r\n self.endian = \"<\"\r\n else:\r\n print(\"ERROR: magic number is not swapped or identical\")\r\n\r\n # Version major\r\n self.version_major = struct.unpack(self.endian + \"H\", binary[4:6])[0]\r\n\r\n # Version minor\r\n self.version_minor = struct.unpack(self.endian + \"H\", binary[6:8])[0]\r\n\r\n # Thiszone\r\n self.thiszone = struct.unpack(self.endian + \"i\", binary[8:12])[0]\r\n\r\n # Sigfigs\r\n self.sigfigs = struct.unpack(self.endian + \"I\", binary[12:16])[0]\r\n\r\n # Snaplen\r\n self.snaplen = struct.unpack(self.endian + \"I\", binary[16:20])[0]\r\n\r\n # Network\r\n self.network = struct.unpack(self.endian + \"I\", binary[20:])[0]\r\n\r\n\r\nclass Connection_detail:\r\n\r\n source_address = None # str\r\n destination_address = None # str\r\n source_port = 0 # int\r\n destination_port = 0 # int\r\n status = []\r\n # (Only if the connection is complete provide the following information)\r\n start_time = 0 # int\r\n end_time = 0 # int\r\n duration = 0 # int\r\n packets_src_to_dest = 0 # int\r\n packets_dest_to_src = 0 # int\r\n packets_total = 0 # int\r\n bytes_src_to_dest = 0 # int\r\n bytes_dest_to_src = 0 # int\r\n bytes_total = 0 # int\r\n\r\n complete = None # bool\r\n received = None # list\r\n sent = None # list\r\n window_list = None # list\r\n\r\n connection_num = 0 # int\r\n\r\n def __init__(self):\r\n self.source_address = None # done\r\n self.destination_address = None # done\r\n self.source_port = 0 # done\r\n self.destination_port = 0 # int # done\r\n self.status = [0, 0, 0] # Sx, Fx, Rx\r\n # (Only if the connection is complete provide the following information)\r\n self.start_time = 0 # int # done\r\n self.end_time = 0 # int\r\n self.duration = 0 # int\r\n self.packets_src_to_dest = 0 # int\r\n self.packets_dest_to_src = 0 # int\r\n self.packets_total = 0 # int\r\n self.bytes_src_to_dest = 0 # int\r\n self.bytes_dest_to_src = 0 # int\r\n self.bytes_total = 0 # int\r\n\r\n self.complete = False\r\n self.received = []\r\n self.sent = []\r\n self.window_list = []\r\n\r\n Connection_detail.connection_num += 1\r\n self.connection_num = Connection_detail.connection_num\r\n\r\n def __str__(self):\r\n return str(self.__class__) + \": \" + str(self.__dict__)\r\n\r\n def print_partb(self):\r\n # this will print out via format of part b\r\n \"\"\"Connection 47:\r\n source address: 192.168.1.164\r\n destination address: 132.170.108.140\r\n source port: 1246\r\n destination port: 80\r\n status: S2F1\r\n start time: 266.578746 seconds\r\n end time: 282.552667 seconds\r\n duration: 15.973921 seconds\r\n number of packets sent from source to destination: 20\r\n number of packets sent from destination to source: 29\r\n total number of packets: 49\r\n number of data bytes sent from source to destination: 1150\r\n number of data bytes sent from destination to source: 34469\r\n total number of data bytes: 35619\r\n END\r\n \"\"\"\r\n indent = \" \"\r\n print(\"Connection {}:\".format(self.connection_num))\r\n print(indent + \"source address: {}\".format(self.source_address))\r\n print(indent + \"destination address: {}\".format(self.destination_address))\r\n print(indent + \"source port: {}\".format(self.source_port))\r\n print(indent + \"destination port: {}\".format(self.destination_port))\r\n\r\n if self.status[2] != 0:\r\n print(indent + \"status: S{}F{}/R\".format(self.status[0], self.status[1]))\r\n else:\r\n print(indent + \"status: S{}F{}\".format(self.status[0], self.status[1]))\r\n\r\n if self.complete:\r\n print(indent + \"start time: {} seconds\".format(self.start_time))\r\n print(indent + \"end time: {} seconds\".format(self.end_time))\r\n print(indent + \"duration: {} seconds\".format(self.duration))\r\n print(\r\n indent\r\n + \"number of packets sent from source to destination: {} packets\".format(\r\n self.packets_src_to_dest\r\n )\r\n )\r\n print(\r\n indent\r\n + \"number of packets sent from destination to source: {} packets\".format(\r\n self.packets_dest_to_src\r\n )\r\n )\r\n print(\r\n indent\r\n + \"total number of packets: {} packets\".format(self.packets_total)\r\n )\r\n print(\r\n indent\r\n + \"number of data bytes sent from source to destination: {} bytes\".format(\r\n self.bytes_src_to_dest\r\n )\r\n )\r\n print(\r\n indent\r\n + \"number of data bytes sent from destination to source: {} bytes\".format(\r\n self.bytes_dest_to_src\r\n )\r\n )\r\n print(\r\n indent + \"total number of data bytes: {} bytes\".format(self.bytes_total)\r\n )\r\n print(\"END\")\r\n\r\n def get_info(self, connection_list):\r\n # given a list of packets in a connection get all the data needed\r\n\r\n # Get connection data that is dependant on the first packet\r\n\r\n # Get first packet\r\n first_packet = connection_list[0]\r\n # print(len(connection_list))\r\n # Get sub objects\r\n first_packet_ip4 = first_packet.IP_header\r\n first_packet_tcp = first_packet.TCP_header\r\n\r\n # source_address\r\n self.source_address = first_packet_ip4.src_ip\r\n\r\n # destination_port\r\n self.destination_address = first_packet_ip4.dst_ip\r\n\r\n # ports\r\n self.source_port = first_packet_tcp.src_port\r\n self.destination_port = first_packet_tcp.dst_port\r\n\r\n # Init variabes for looping in connections\r\n final_packet = None\r\n\r\n # iterate through packets in the connection\r\n for packet in connection_list:\r\n\r\n tcp_header = packet.TCP_header\r\n\r\n # STATUS STUFF\r\n flags = tcp_header.flags\r\n\r\n # check for status\r\n if flags[\"SYN\"] == 1:\r\n if self.status[0] == 0:\r\n # find first s1f0 flag set for time\r\n # start time\r\n self.start_time = round(packet.timestamp, 6)\r\n self.status[0] += 1\r\n\r\n # count s if flag set\r\n\r\n if flags[\"RST\"] == 1:\r\n # set r to true if reset is come across\r\n self.status[2] = 1\r\n\r\n if flags[\"FIN\"] == 1:\r\n # count f and store last f packet\r\n final_packet = packet\r\n self.status[1] += 1\r\n # set complete or not depending on f flag\r\n self.complete = True\r\n\r\n # PACKET STUFF\r\n\r\n # find src and dst of the packet\r\n src = packet.IP_header.src_ip\r\n dst = packet.IP_header.dst_ip\r\n # check to see packet going src to dest or vice versa\r\n if (self.source_address == src) and (self.destination_address == dst):\r\n # sent packet\r\n # get bytes for packet and add to correct list\r\n self.bytes_src_to_dest += packet.get_bytes()\r\n # append packet to coresponding list\r\n self.sent.append(packet)\r\n elif (self.source_address == dst) and (self.destination_address == src):\r\n # received packet\r\n # get bytes for packet and add to correct list\r\n self.bytes_dest_to_src += packet.get_bytes()\r\n # append packet to coresponding list\r\n self.received.append(packet)\r\n\r\n # Now we add packet window to list for window sizes\r\n self.window_list.append(packet.TCP_header.window_size)\r\n\r\n # count src / dst packet count accordingly\r\n self.packets_dest_to_src = len(self.received)\r\n self.packets_src_to_dest = len(self.sent)\r\n\r\n # if complete\r\n if self.complete:\r\n\r\n # Get end time from last packet with f\r\n self.end_time = final_packet.timestamp\r\n # set duration\r\n self.duration = round(self.end_time - self.start_time, 6)\r\n\r\n # count packet total\r\n self.packets_total = len(connection_list)\r\n # add bytes total\r\n self.bytes_total = self.bytes_dest_to_src + self.bytes_src_to_dest\r\n","sub_path":"Assignments/A2/basic_structures.py","file_name":"basic_structures.py","file_ext":"py","file_size_in_byte":18649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"529674226","text":"#coding=utf-8\n\nfrom admin import admin, AdminCtrl\n\nclass Admin_MailsCtrl(AdminCtrl):\n @admin\n def get(self):\n pager = {}\n pager['qnty'] = min(int(self.input('qnty', 10)), 50)\n pager['page'] = max(int(self.input('page', 1)), 1)\n pager['list'] = 0;\n\n cur = self.dbase('mails').cursor()\n cur.execute('select * from mails order by mail_id desc limit ? offset ?', (pager['qnty'], (pager['page']-1)*pager['qnty'], ))\n mails = cur.fetchall()\n cur.close()\n\n if mails:\n pager['list'] = len(mails)\n\n self.render('admin/mails.html', pager = pager, mails = mails)\n\nclass Admin_MailAccessCtrl(AdminCtrl):\n @admin\n def post(self):\n try:\n mail_id = self.input('mail_id')\n\n con = self.dbase('mails')\n cur = con.cursor()\n cur.execute('update mails set mail_stat=1, mail_utms=? where mail_id = ?', (self.stime(), mail_id,))\n con.commit()\n cur.close()\n if cur.rowcount:\n self.flash(1)\n return\n except:\n pass\n self.flash(0)\n\nclass Admin_MailDeleteCtrl(AdminCtrl):\n @admin\n def post(self):\n try:\n user = self.current_user\n\n mail_id = self.input('mail_id')\n mail_utms = self.input('mail_utms')\n\n con = self.dbase('mails')\n cur = con.cursor()\n cur.execute('delete from mails where mail_id = ? and mail_utms = ?', (mail_id, mail_utms ,))\n con.commit()\n cur.close()\n if cur.rowcount:\n self.model('alogs').add(self.dbase('alogs'), '删除留言:' + str(mail_id), user_ip = self.request.remote_ip, user_id = user['user_id'], user_name = user['user_name'])\n self.flash(1)\n return\n except:\n pass\n self.flash(0)\n","sub_path":"www.luokr.com/app/ctrls/admin/mails.py","file_name":"mails.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"217174855","text":"# 判断101-200之间有多少个素数,并输出所有素数。\n# 程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),\n# 如果能被整除,则表明此数不是素数,反之是素数。\nlist = []\nfor i in range(101,200):#遍历101-200\n bool = True #定义一个布尔类型的变量,方便判断\n for j in range(2,i): #遍历2到这个数,用这个数循环%小于自己的所有正整数\n if i%j==0:#判断能不能被整除,如果整除了,bool值变成false,则该数不是质数\n bool = False\n if(bool):#判断bool的值,如果是true 则该数为质数,加入到list中,如果是false,则不是质数,跳过添加直接进行下次循环\n list.append(i)\n# 按题目要求打印结果\nprint(list)\nprint(\"101-200之间的素数个数为:\",len(list))","sub_path":"day05/demo2.py","file_name":"demo2.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"280199190","text":"import math as m\r\nimport numpy as np\r\nimport copy, macros, helpers\r\nfrom objs import leg_data, body_data\r\nfrom time import time\r\n\r\n\r\n# IK functions\r\n\r\ndef fix_angles_2(theta):\r\n while(theta > 180):\r\n theta += -360\r\n while(theta < -180):\r\n theta += 360\r\n return(theta)\r\n\r\n# Leg IK\r\n# leg_ik(leg: leg_data object, claw: desired claw location in cylindrical coordinates in leg frame)\r\n# returns [h, e, k] list\r\n# If inputs are invalid, returns a list of length 4\r\ndef leg_ik(leg, claw, times={}):\r\n \r\n # Timing value\r\n tv_leg_ik = time()\r\n\r\n # Constants\r\n hyp = ((claw[1] - leg.trolen)**2 + claw[2]**2)**.5\r\n\r\n try:\r\n # Inverse Kinematics\r\n h = claw[0] - leg.gamma\r\n e = helpers.rtod(m.asin((claw[1] - leg.trolen)/hyp) + m.acos((leg.tiblen**2 - leg.femlen**2 - hyp**2)/(-2 * leg.femlen * hyp)) - (m.pi/2)) - 90\r\n k = helpers.rtod(m.pi - m.acos((hyp**2 - leg.tiblen**2 - leg.femlen**2)/(-2 * leg.tiblen * leg.femlen))) - 180\r\n\r\n times = helpers.dict_timer(\"Ik.leg_ik\", times, time()-tv_leg_ik)\r\n\r\n return np.array([fix_angles_2(h), fix_angles_2(e), fix_angles_2(k)])\r\n\r\n except:\r\n\r\n times = helpers.dict_timer(\"Ik.leg_ik\", times, time()-tv_leg_ik)\r\n\r\n print(\"Invalid parameters. Leg ik failed.\")\r\n return np.array([0, 1, 2, 3])\r\n\r\n\r\n# Body IK\r\n# body_ik(legs: list of leg_data objects, claws: list of desired claw locations in floor plane,\r\n# pitch: desired pitch of robot, roll: desired roll of robot)\r\n# returns newclaws: list of desired claw positions in cylindrical coordinates in leg frame of rotated robot\r\ndef body_ik(body, claws, pitch, roll, height, zs, times={}):\r\n\r\n # Timing value\r\n tv_body_ik = time()\r\n \r\n # copy claws to prevent error propagation and add z coordinate\r\n# hclaws = copy.copy(claws)\r\n\r\n # create rotation matrix\r\n pc, ps, rc, rs = m.cos(helpers.dtor(pitch)), m.sin(helpers.dtor(pitch)), m.cos(helpers.dtor(roll)), m.sin(helpers.dtor(roll))\r\n pitchm = np.matrix([[pc, 0, -ps], [0, 1, 0], [ps, 0, pc]])\r\n rollm = np.matrix([[1, 0, 0], [0, rc, -rs], [0, rs, rc]])\r\n rot = pitchm * rollm\r\n\r\n # put leg offsets through rotation and subtract difference\r\n newclaws = []\r\n for i in range(len(body.legs)):\r\n claws[i] = np.append(claws[i], -1 * height)\r\n vec = rot * body.legs[i].off[np.newaxis].T \r\n newclaws.append(helpers.tocyl(claws[i] - np.squeeze(np.asarray(vec))))\r\n\r\n # incorporate leg lifts\r\n for i in range(len(zs)):\r\n if (zs[i] > 0):\r\n newclaws[i][2] = -1*(height-zs[i])\r\n\r\n times = helpers.dict_timer(\"Ik.body_ik\", times, time()-tv_body_ik) \r\n\r\n return newclaws\r\n \r\n \r\n\r\n# Other\r\n\r\n# make_standard_bot()\r\n# creates a bot with equidistant claws at distance RAD from hip with macros.NUMLEGS legs (and sides)\r\ndef make_standard_bot(side=macros.SIDE, trolen=macros.TROLEN, femlen=macros.FEMLEN, tiblen=macros.TIBLEN, zdist=macros.ZDIST):\r\n\r\n # Timing value\r\n tv_msb = time()\r\n\r\n claws = []\r\n legs = []\r\n poly_rad = side/(2 * m.sin(m.pi/macros.NUMLEGS)) # polygon radius\r\n for i in range(macros.NUMLEGS):\r\n # calculate unit multipliers\r\n x_unit = m.cos(helpers.dtor(macros.GAMMAS[i]))\r\n y_unit = m.sin(helpers.dtor(macros.GAMMAS[i]))\r\n\r\n # append appropriate data to claws and legs\r\n claws.append([(x_unit * (poly_rad + macros.DEFAULT_RADIUS)), (y_unit * (poly_rad + macros.DEFAULT_RADIUS))])\r\n legs.append(leg_data(i, x_unit * poly_rad, y_unit * poly_rad, macros.GAMMAS[i], trolen, femlen, tiblen))\r\n if (i == 0):\r\n legs[i].state.signs = np.array([1, 1])\r\n elif (i == 1):\r\n legs[i].state.signs = np.array([-1, 1])\r\n elif (i == 2):\r\n legs[i].state.signs = np.array([-1, -1])\r\n else:\r\n legs[i].state.signs = np.array([1, -1])\r\n\r\n # create a body with the legs\r\n body = body_data(legs, side, zdist, trolen, femlen, tiblen)\r\n\r\n # Timing print\r\n print(\"Make_standard_bot time: \", (time() - tv_msb))\r\n\r\n return(claws, body)\r\n\r\n# extract_angles(body: body_data object, claws: list of claw positions, pitch: desired pitch in degrees, roll: desired roll in degrees)\r\n# returns list of angles [h1, e1, k1, h2, e2, k2, h3, e3, k3, h4, e4, k4]\r\ndef extract_angles(body, claws, pitch=macros.DEFAULT_PITCH, roll=macros.DEFAULT_ROLL, height=macros.DEFAULT_HEIGHT, zs=[0,0,0,0], times={}):\r\n\r\n # Timing value\r\n tv_ea = time()\r\n\r\n # Returns np.array\r\n# newclaws = body_ik(body, claws, pitch, roll, height, zs, times)\r\n# ret_angles = np.array([])\r\n# for i in range(len(body.legs)):\r\n# ret_angles = np.append(ret_angles, (leg_ik(body.legs[i], newclaws[i], times)))\r\n\r\n # Returns list\r\n newclaws = body_ik(body, claws, pitch, roll, height, zs, times)\r\n ret_angles = []\r\n for i in range(len(body.legs)):\r\n toadd = leg_ik(body.legs[i], newclaws[i], times)\r\n for j in toadd:\r\n ret_angles.append(j)\r\n\r\n\r\n times = helpers.dict_timer(\"Ik.extract_angles\", times, time()-tv_ea)\r\n\r\n return ret_angles\r\n\r\n## body_ik_error_handler(body: body_data object, claws: list of claws in floor frame, \r\n## pitch: desired pitch, roll: desired roll, height: \r\n#def body_ik_error_handler(body, claws, pitch, roll, height, zs):\r\n# # variable for height\r\n# bigrad = 0\r\n#\r\n# # check each claw location\r\n# for i in range(len(claws)):\r\n# xoff, yoff = body.legs[i].off[0], body.legs[i].off[1]\r\n#\r\n# # convert claw to radial coordinates\r\n# claws[i] = helpers.torad(np.array([claws[i][0]-xoff, claws[i][1]-yoff]))\r\n#\r\n# # bound radius \r\n# claws[i][1] = helpers.bound(claws[i][1], 0, body.legs[i].trolen+body.legs[i].femlen+body.legs[i].tiblen)\r\n#\r\n# # update bigrad\r\n# bigrad = max(bigrad, claws[i][1])\r\n#\r\n# # bound theta\r\n# claws[i][0] = helpers.degreesmod(claws[i][0])\r\n# claws[i][0] = helpers.bound(claws[i][0], body.legs[i].gamma-body.hip_wiggle, body.legs[i].gamma+body.hip_wiggle)\r\n#\r\n# # return to cartesian coordinates and add leg offset back in\r\n# claws[i] = helpers.fromrad(claws[i])\r\n# claws[i][0] = claws[i][0] + xoff\r\n# claws[i][1] = claws[i][1] + yoff\r\n#\r\n# trlen, flen, tilen = body.trolen, body.femlen, body.tiblen\r\n#\r\n# # bound height\r\n# maxheight, minheight = m.sqrt(((flen+tilen)**2) - (bigrad-trlen)**2), body.zdist\r\n# height = helpers.bound(height, minheight, maxheight)\r\n#\r\n# # bound pitch\r\n# pitch = helpers.bound(pitch, macros.PITCH_BOUND, macros.PITCH_BOUND*-1)\r\n# # check if height affects possible pitch and rebound accordingly\r\n# heightzone = m.sin(abs(pitch)) * (body.side/2)\r\n# if (height > maxheight-heightzone or height-heightzone < minheight):\r\n# pitchsign = pitch/abs(pitch)\r\n# pitch = pitchsign*m.asin(heightzone/(body.side/2))\r\n#\r\n# # bound roll\r\n# roll = helpers.bound(roll, macros.ROLL_BOUND, macros.ROLL_BOUND*-1)\r\n# # check if height and pitch affect possible pitch and rebound accordingly\r\n# heightzone = heightzone - (m.sin(abs(pitch)) * (body.side/2))\r\n# if (height > maxheight-heightzone or height-heightzone < minheight):\r\n# rollsign = roll/abs(roll)\r\n# roll = rollsign*m.asin(heightzone/(body.side/2))\r\n#\r\n# # bound zs\r\n# for z in zs:\r\n# helpers.bound(z, macros.MIN_Z, macros.MAX_Z)\r\n#\r\n# return(claws, pitch, roll, height, zs)\r\n","sub_path":"2018-19_New/server/ik.py","file_name":"ik.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"526946843","text":"from typing import List\n\ndef removeDuplicates(nums: List[int]) -> int:\n if len(nums) <= 0:\n return 0\n\n curr = nums[0]\n cnt = 1\n\n for i in range(1, len(nums)):\n if curr != nums[i]:\n curr = nums[i]\n nums[cnt] = curr # 길이만 구하면 없어도 되지만, 배열 수정을 하라고 했으므로 필요함\n cnt+= 1\n\n return cnt\n\nprint(removeDuplicates([1,1,2]))","sub_path":"LeetCode/finished/LeetCode26_RemoveDuplicatesFromSortedArray.py","file_name":"LeetCode26_RemoveDuplicatesFromSortedArray.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"563596864","text":"import redis\nfrom random import choice\nfrom error import PoolEmptyError\nfrom setting import *\n\n\n\n\nclass RedisClient(object):\n def __init__(self,host=REDIS_HOST,port=REDIS_PORT,password=REDIS_PASSWORD):\n '''\n 初始化\n :param host: Redis 地址\n :param post: Redis 端口\n :param password: Redis密码\n '''\n self.db = redis.StrictRedis(host=host,port=port,password=password,decode_responses=True)\n print(self.db)\n print('连接成功')\n\n def add(self,proxy,score=INITIAL_SCORE):\n '''\n 添加代理,设置分数为最高\n :param proxy: 代理\n :param score: 分数\n :return: 添加结果\n '''\n #db.zscore返回成员key的分数,若成员元素不是有序集key的成员,或key不存在,返回nil。nil属于假\n if not self.db.zscore(REDIS_KEY1,proxy):\n print('in redis')\n print(proxy)\n print(type(proxy))\n #db.zadd将一个或多个成员元素及其分数值加入到有序集当中\n return self.db.zadd(REDIS_KEY1,{proxy:score})\n else:\n print('更新成功')\n return self.db.zadd(REDIS_KEY1,{proxy:score})\n\n def random(self):\n '''\n 随机获取有效代理,首先尝试获取最高分代理,如果最高分不存在,则按照排名获取,否则异常\n :return: 随机代理\n '''\n result = self.db.zrangebyscore(REDIS_KEY1,MAX_SCORE,MAX_SCORE)\n if len(result):\n return choice(result)\n else:\n #0-100内递减排序\n result = self.db.zrevrange(REDIS_KEY1,0,100)\n if len(result):\n return choice(result)\n else:\n raise PoolEmptyError()\n\n def decrease(self,proxy):\n '''\n 代理值减一分,分数小于最小值,则代理删除\n :param proxy: 代理\n :return: 修改后的代理分数\n '''\n score = self.db.zscore(REDIS_KEY1,proxy)\n if score and score > MIN_SCORE:\n print('代理',proxy,'当前分数',score,'减1')\n #参数:key,score,value\n return self.db.zincrby(REDIS_KEY1,-1,proxy)\n else:\n print('代理',proxy,'当前分数',score,'移除')\n return self.db.zrem(REDIS_KEY1,proxy)\n\n def exists(self,proxy):\n '''\n 判断是否存在\n :param proxy:代理\n :return: 是否存在\n '''\n return not self.db.zscore(REDIS_KEY1,proxy) == None\n\n def max(self,proxy):\n '''\n 将代理设置为MAX_SCORE\n :param proxy: 代理\n :return: 设置结果\n '''\n print('代理',proxy,'可用,设置为',MAX_SCORE)\n return self.db.zadd(REDIS_KEY1,MAX_SCORE,proxy)\n\n def count(self):\n '''\n 获取数量\n :return:数量\n '''\n return self.db.zcard(REDIS_KEY1)\n\n def all(self):\n '''\n 获取所有代理\n :return: 全部代理列表\n '''\n return self.db.zrangebyscore(REDIS_KEY1,MIN_SCORE,MAX_SCORE)\n\n def batch(self,start,stop):\n '''\n 批量湖区\n :param start:\n :param stop:\n :return: 代理列表\n '''\n return self.db.zrevrange(REDIS_KEY1,start,stop-1)\n\n\n\n\n\n\n\n","sub_path":"daili_pour/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"515384907","text":"# coding=utf-8\nimport tensorflow as tf\nfrom tensorflow.data import TextLineDataset\nimport numpy as np\nfrom data import preprocess\nimport os\n\n\nclass RNNConfig(object):\n \"\"\"\n # TODO: 在此修改RNN以及训练的参数\n \"\"\"\n def __init__(self, train_mode='CHAR-RANDOM'):\n self.train_mode = train_mode # 训练模式,'CHAR-RANDOM'为字符级,样本分割为字符并使用自训练词嵌入\n # 'WORD-NON-STATIC'为词级, 使用word2vec预训练词向量并能够继续在训练中优化\n\n self.class_num = 1258 # 输出类别的数目\n self.embedding_dim = 128 # 词向量维度,'CHAR'模式适用,\n # 'WORD-NON-STATIC'模式默认为preprocess.py中定义的vec_dim\n\n self.layer_num = 4\n self.unit_num = 128 # LSTM神经元数目\n\n self.dense_unit_num = 512 # 全连接层神经元\n\n self.vocab_size = preprocess.VOCAB_SIZE # 词汇表大小\n\n self.dropout_keep_prob = 0.5 # dropout保留比例\n self.learning_rate = 1e-3 # 学习率\n\n self.train_batch_size = 128 # 每批训练大小\n self.valid_batch_size = 5000 # 每批验证大小\n self.test_batch_size = 5000 # 每批测试大小\n self.valid_per_batch = 1000 # 每多少批进行一次验证\n self.epoch_num = 20 # 总迭代轮次\n\n\nclass TextRNN(object):\n def __init__(self, config):\n self.class_num = config.class_num\n self.layer_num = config.layer_num\n self.unit_num = config.unit_num\n self.vocab_size = config.vocab_size\n\n self.dense_unit_num = config.dense_unit_num\n self.train_batch_size = config.train_batch_size\n self.valid_batch_size = config.valid_batch_size\n self.test_batch_size = config.test_batch_size\n\n if config.train_mode == 'CHAR-RANDOM':\n # 文本长度\n self.text_length = preprocess.MAX_CHAR_TEXT_LENGTH\n # 词嵌入维度\n self.embedding_dim = config.embedding_dim\n\n elif config.train_mode == 'WORD-NON-STATIC':\n self.text_length = preprocess.MAX_WORD_TEXT_LENGTH\n self.embedding_dim = preprocess.vec_dim\n\n self.train_mode = config.train_mode\n\n self.input_x = None\n self.input_y = None\n self.labels = None\n self.dropout_keep_prob = None\n self.training = None\n self.embedding_inputs = None\n self.embedding_inputs_expanded = None\n self.loss = None\n self.accuracy = None\n self.prediction = None\n self.vocab = None\n self.vecs_dict = {}\n self.embedding_W = None\n self.dataset = None\n\n def setRNN(self):\n # 输入层\n self.input_x = tf.placeholder(tf.int32, [None, self.text_length], name=\"input_x\")\n\n self.labels = tf.placeholder(tf.int32, [None], name=\"input_y\")\n # 把数字标签转为one hot形式\n self.input_y = tf.one_hot(self.labels, self.class_num)\n self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\n\n # 训练时batch_normalization的Training参数应为True,\n # 验证或测试时应为False\n self.training = tf.placeholder(tf.bool, name='training')\n\n # 词嵌入层\n with tf.device('/cpu:0'), tf.name_scope('embedding'):\n if self.train_mode == 'CHAR-RANDOM':\n # 随机初始化的词向量\n W = tf.Variable(tf.random_uniform([self.vocab_size, self.embedding_dim], -1.0, 1.0))\n elif self.train_mode == 'WORD-NON-STATIC':\n # 用之前读入的预训练词向量\n W = tf.Variable(self.embedding_W)\n self.embedding_inputs = tf.nn.embedding_lookup(W, self.input_x)\n\n with tf.name_scope(\"batch_norm\"):\n self.embedding_inputs = tf.layers.batch_normalization(self.embedding_inputs, training=self.training)\n\n def basic_lstm_cell():\n bcell = tf.nn.rnn_cell.LSTMCell(self.unit_num)\n return tf.nn.rnn_cell.DropoutWrapper(bcell, output_keep_prob=self.dropout_keep_prob)\n\n with tf.name_scope(\"RNN\"):\n # 多层RNN网络,每层有units_num个神经元\n # =======================================================================================\n cells = [basic_lstm_cell() for _ in range(self.layer_num)]\n cell = tf.nn.rnn_cell.MultiRNNCell(cells)\n # output的形状为[batch_size, text_length, units_num]\n output, _ = tf.nn.dynamic_rnn(cell, inputs=self.embedding_inputs, dtype=tf.float32)\n rnn_output = output[:, -1, :] # 取最后一个时序作为输出结果\n # =========================================================================================\n\n with tf.name_scope(\"dense\"):\n # 全连接层\n # ======================================================================================\n h_full = tf.layers.dense(inputs=rnn_output,\n units=self.dense_unit_num,\n use_bias=True,\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.1),\n bias_initializer=tf.constant_initializer(0.1)\n )\n h_full = tf.layers.dropout(h_full, rate=self.dropout_keep_prob)\n h_full = tf.nn.relu(h_full)\n # ==========================================================================================\n\n # Output layer\n with tf.name_scope('output'):\n score = tf.layers.dense(\n h_full,\n units=self.class_num,\n activation=None,\n use_bias=True,\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.1),\n bias_initializer=tf.constant_initializer(0.1)\n )\n self.score = tf.multiply(score, 1, name='score')\n self.prediction = tf.argmax(score, 1, name='prediction')\n\n # Loss function\n with tf.name_scope('loss'):\n losses = tf.nn.softmax_cross_entropy_with_logits_v2(logits=score, labels=self.input_y)\n self.loss = tf.reduce_mean(losses)\n\n # Calculate accuracy\n with tf.name_scope('accuracy'):\n correct_predictions = tf.equal(self.prediction, tf.argmax(self.input_y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))\n\n def convert_input(self, lines):\n \"\"\"\n 将训练集数据转换为id或词向量表示\n \"\"\"\n batch_x = []\n batch_y = []\n title = \"\"\n # 1.id\n for line in lines:\n line_ = line.decode(\"gbk\").strip().split(',')\n title = ''.join(line_[0:-1]) # 逗号前段为标题\n label = ''.join(line_[-1]) # 最后一项为标签\n batch_x.append(preprocess.to_id(title, self.vocab, self.train_mode))\n batch_y.append(label)\n\n batch_x = np.stack(batch_x)\n return batch_x, batch_y\n\n def convert_test_input(self, titles):\n \"\"\"\n 将测试集tsv数据转为id或词向量表示\n :param titles:\n :return:\n \"\"\"\n batch_x = []\n # 1.id\n for title in titles:\n valid_title = title.decode('gb18030').strip('\\t')\n batch_x.append(preprocess.to_id(valid_title, self.vocab, self.train_mode))\n\n batch_x = np.stack(batch_x)\n return batch_x\n\n def prepare_data(self):\n # Data preparation.\n # =======================================================\n if self.train_mode == 'CHAR-RANDOM':\n # 1.字符级\n # 读取词汇表\n self.vocab = preprocess.read_vocab(os.path.join('data',preprocess.CHAR_VOCAB_PATH))\n\n elif self.train_mode == 'WORD-NON-STATIC' or self.train_mode == 'MULTI':\n # 把预训练词向量的值读到变量中\n self.vocab = preprocess.read_vocab(os.path.join('data', preprocess.WORD_VOCAB_PATH))\n self.vecs_dict = preprocess.load_vecs(os.path.join('data', preprocess.SGNS_WORD_PATH))\n self.embedding_W = np.ndarray(shape=[self.vocab_size, self.embedding_dim], dtype=np.float32)\n for word in self.vocab:\n # 第n行对应id为n的词的词向量\n if word not in self.vecs_dict:\n preprocess.add_word(word, self.vecs_dict)\n self.embedding_W[self.vocab[word]] = self.vecs_dict[word]\n\n self.dataset = TextLineDataset(os.path.join('data', preprocess.TRAIN_WITH_ID_PATH))\n\n return\n # =============================================================\n # Date preparation ends.\n\n def shuffle_datset(self):\n # 打乱数据集\n # ==========================================================\n print('Shuffling dataset...')\n self.dataset = self.dataset.shuffle(preprocess.TOTAL_TRAIN_SIZE)\n\n # 分割数据集\n # 取前VALID_SIZE个样本给验证集\n valid_dataset = self.dataset.take(preprocess.VALID_SIZE).batch(self.valid_batch_size)\n # 剩下的给训练集\n train_dataset = self.dataset.skip(preprocess.VALID_SIZE).batch(self.train_batch_size)\n\n # Create a reinitializable iterator\n train_iterator = train_dataset.make_initializable_iterator()\n valid_iterator = valid_dataset.make_initializable_iterator()\n\n train_init_op = train_iterator.initializer\n valid_init_op = valid_iterator.initializer\n\n # 要获取元素,先sess.run(train_init_op)初始化迭代器\n # 再sess.run(next_train_element)\n next_train_element = train_iterator.get_next()\n next_valid_element = valid_iterator.get_next()\n\n return train_init_op, valid_init_op, next_train_element, next_valid_element\n # ==============================================================\n\n def prepare_test_data(self):\n # 读取词汇表\n if self.train_mode == 'CHAR-RANDOM':\n # 1.字符级\n self.vocab = preprocess.read_vocab(os.path.join('data',preprocess.CHAR_VOCAB_PATH))\n\n elif self.train_mode == 'WORD-NON-STATIC':\n self.vocab = preprocess.read_vocab(os.path.join('data', preprocess.WORD_VOCAB_PATH))\n\n # 测试集有标题,读取时注意跳过第一行\n dataset = TextLineDataset(os.path.join('data',preprocess.TEST_PATH))\n dataset = dataset.shuffle(preprocess.TOTAL_TEST_SIZE).batch(self.test_batch_size)\n\n iterator = dataset.make_one_shot_iterator()\n next_element = iterator.get_next()\n\n return dataset, next_element\n\n\n\n\n","sub_path":"rnn_model.py","file_name":"rnn_model.py","file_ext":"py","file_size_in_byte":10733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"251537252","text":"print(\" *** Welcome to the TicTacToe game. ***\")\r\nprint(\" > Each player should enter the number of the square they want to draw on.\")\r\nprint(\" > The player who has 3 drawings in a same column, row or diagonal; wins.\")\r\n\r\nprint(\"\"\" 1 | 2 | 3\r\n---|---|---\r\n 4 | 5 | 6\r\n---|---|---\r\n 7 | 8 | 9 \"\"\")\r\n\r\nturn = 1\r\nb = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\r\n\r\ndef is_valid(move):\r\n valids = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\r\n for i in valids:\r\n if move == i:\r\n return True\r\n if i == '9' and move != '9':\r\n return False\r\n\r\ndef visual_refresh():\r\n print(\"\"\" {} | {} | {}\r\n---|---|---\r\n {} | {} | {}\r\n---|---|---\r\n {} | {} | {} \"\"\".format(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]))\r\n\r\ndef game_control():\r\n col1x = b[0] == b[3] == b[6] == 'X'\r\n col2x = b[1] == b[4] == b[7] == 'X'\r\n col3x = b[2] == b[5] == b[8] == 'X'\r\n row1x = b[0] == b[1] == b[2] == 'X'\r\n row2x = b[3] == b[4] == b[5] == 'X'\r\n row3x = b[6] == b[7] == b[8] == 'X'\r\n dia1x = b[0] == b[4] == b[8] == 'X'\r\n dia2x = b[2] == b[4] == b[6] == 'X'\r\n\r\n col1o = b[0] == b[3] == b[6] == 'O'\r\n col2o = b[1] == b[4] == b[7] == 'O'\r\n col3o = b[2] == b[5] == b[8] == 'O'\r\n row1o = b[0] == b[1] == b[2] == 'O'\r\n row2o = b[3] == b[4] == b[5] == 'O'\r\n row3o = b[6] == b[7] == b[8] == 'O'\r\n dia1o = b[0] == b[4] == b[8] == 'O'\r\n dia2o = b[2] == b[4] == b[6] == 'O'\r\n\r\n thereIsEmpty = b[0] == ' ' or b[1] == ' ' or b[2] == ' ' or b[3] == ' ' or b[4] == ' ' or b[5] == ' ' or b[6] == ' ' or b[7] == ' ' or b[8] == ' '\r\n tie = not thereIsEmpty\r\n\r\n if col1x or col2x or col3x or row1x or row2x or row3x or dia1x or dia2x:\r\n print(\"Player 1 (X), wins the game.\")\r\n e = input()\r\n quit()\r\n \r\n if col1o or col2o or col3o or row1o or row2o or row3o or dia1o or dia2o:\r\n print(\"Player 2 (O), wins the game.\")\r\n e = input()\r\n quit()\r\n\r\n if tie:\r\n print(\"Tie.\")\r\n e = input()\r\n quit()\r\n \r\nwhile True:\r\n while turn == 1:\r\n o1 = input(\"Player 1 (X) : \")\r\n if is_valid(o1):\r\n if b[int(o1) - 1] == ' ':\r\n b[int(o1) - 1] = 'X'\r\n visual_refresh()\r\n game_control()\r\n turn = 2\r\n else:\r\n print(\"The chosen square is not empty.\")\r\n else:\r\n print(\"Please enter a valid number.\")\r\n while turn == 2:\r\n o2 = input(\"Player 2 (O) : \")\r\n if is_valid(o2):\r\n if b[int(o2) - 1] == ' ':\r\n b[int(o2) - 1] = 'O'\r\n visual_refresh()\r\n game_control()\r\n turn = 1\r\n else:\r\n print(\"The chosen square is not empty.\")\r\n else:\r\n print(\"Please enter a valid number.\")\r\n","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"471899085","text":"#!/usr/bin/python\n\nimport sys\n\nfrom pycqed.instrument_drivers.library.Transport import IPTransport\nfrom pycqed.instrument_drivers.physical_instruments.QuTech.CCCore import CCCore\n\n# parameter handling\nccio = 0\nif len(sys.argv)>1:\n ccio = int(sys.argv[1])\n\nval = 0 # 20 ns steps\nif len(sys.argv)>2:\n val = int(sys.argv[2])\n\n# fixed constants\nip = '192.168.0.241'\n\ncc = CCCore('cc', IPTransport(ip)) # NB: CCCore loads much quicker then CC\n#cc.stop()\ncc.set_seqbar_cnt(ccio, val)\n#cc.start()\n","sub_path":"examples/CC_examples/CC_setDioDelay.py","file_name":"CC_setDioDelay.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"242363582","text":"#!/usr/bin/env python\n\nimport os\nimport json\nimport urllib2\nimport datetime\nimport sys\n\nfilepath = os.path.expanduser(\"~/prices.dat\")\n\n# bitcoincharts currency url explanations\n# i = 1-min, 5-min, 15-min, 30-min, Hourly, 2-hour, 6-hour, 12-hour, Daily, Weekly\n# r = days, empty = all data\n# i1 = (large indicators), empty = none\n# i2 = empty = none\n# i3 = empty = none\n# i4 = empty = none\n# v = (show volume bars)\n# cv = (volume in currency)\n# ps = (parabolic sar)\n# l = (log scale)\n# p = (percent scale)\n# example timeframes that work (too much data requested results in ENODATA)\n# i=Weekly&r=\n# i=Daily&r=90\n# i=Hourly&r=7\n# i=15-min&r=30\n# i=5-min&r=10\n\nmetalsdataurl = \"http://services.packetizer.com/spotprices/?f=json\"\n\nexistingprices = file(filepath).readlines()\nexistingprices = dict( [ \" \".join(l.split()[1:4]), l.strip() ] for l in existingprices )\n\ncurrencies = [\n\t[ \"mtgoxCAD\", \"CAD\"],\n\t[ \"mtgoxJPY\", \"JPY\"],\n\t[ \"justLTC\", \"LTC\"],\n\t[ \"mtgoxEUR\", \"EUR\"],\n\t[ \"mtgoxUSD\", \"USD\"],\n\t#[ \"cryptoxUSD\", \"xUSD\"],\n\t[ \"bitstampUSD\", \"bUSD\"],\n\t#[ \"globalUSD\", \"gUSD\"],\n\t[ \"rockUSD\", \"oUSD\"],\n\t[ \"mtgoxAUD\", \"AUD\"],\n\t[ \"mtgoxCHF\", \"CHF\"],\n\t[ \"mtgoxSEK\", \"SEK\"],\n\t[ \"mtgoxCNY\", \"CNY\"],\n\t[ \"mtgoxGBP\", \"GBP\"],\n\t[ \"mtgoxRUB\", \"RUB\"],\n]\n\nbtcprices = dict()\n\nfor cur in currencies:\n btcurl = \"http://bitcoincharts.com/charts/chart.json?m=\" + cur[0] + \"&SubmitButton=Draw&i=Hourly&r=3&c=0&t=S&m1=10&m2=25&x=0&i1=&i2=&i3=&i4=&v=1&cv=0&ps=0&l=0&p=0&\"\n #print \"Starting \" + cur[0] + \",\" + cur[1], \": \", btcurl\n\n bcd = urllib2.urlopen(btcurl).read()\n \n cprices = [ [datetime.datetime.utcfromtimestamp(row[0])] + [row[4]] for row in json.loads(bcd) ]\n sprices = [ ]\n for x,y in cprices:\n #print \"cprices: x = \"+str(x)+\", y = \"+str(y)\n sprices.append((\"P\", x.strftime(\"%Y/%m/%d %H:%M:%S\"), \"BTC\", cur[1], \"%0.2f\"%float(y)))\n sprices.append((\"P\", x.strftime(\"%Y/%m/%d %H:%M:%S\"), cur[1], \"BTC\", \"%0.8f\"%(1/float(y))))\n\n cprices = dict ( [ d[1] + \" \" + d[2] + \" \" + d[3], \" \".join(d) ] for d in sprices )\n btcprices.update( cprices )\n #print \"len(btcprices) = \" + str(len(btcprices))\n\n\n### METALS\n\nmetalscd = urllib2.urlopen(metalsdataurl).read()\nmetalscd = json.loads(metalscd)\ndate = metalscd[\"date\"].replace(\"-\",\"/\") + \" 17:00:00\"\nmetalprices = [\n [ \"P\", date, \"XAU\", \"USD\", metalscd[\"gold\"] ],\n [ \"P\", date, \"XAG\", \"USD\", metalscd[\"silver\"] ],\n [ \"P\", date, \"XPL\", \"USD\", metalscd[\"platinum\"] ],\n [ \"P\", date, \"PAMPAU\", \"USD\", str(float(metalscd[\"gold\"]) + 40) ],\n [ \"P\", date, \"RCMPAU\", \"USD\", str(float(metalscd[\"gold\"]) + 50) ],\n [ \"P\", date, \"ROUNDSAG\", \"USD\", str(float(metalscd[\"silver\"]) + 1.5) ],\n]\nmetalprices = dict( [ d[1] + \" \" + d[2] + \" \" + d[3], \" \".join(d) ] for d in metalprices )\n\nconcatdict = dict(existingprices)\nconcatdict.update(btcprices)\nconcatdict.update(metalprices)\n\nvalues = sorted(concatdict.values())\nstring = \"\\n\".join(values)\ndatafile = file(filepath,\"w\")\ndatafile.write(string)\ndatafile.flush()\n","sub_path":"commodities.py","file_name":"commodities.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"1855576","text":"__all__ = ['encode_data']\n\n\ndef encode_data(data):\n \"\"\"\n Helper that converts :class:`str` or :class:`bytes` to :class:`bytes`.\n :class:`str` are encoded with UTF-8.\n \"\"\"\n # Expect str or bytes, return bytes.\n if isinstance(data, str):\n return data.encode('utf-8')\n elif isinstance(data, bytes):\n return data\n else:\n raise TypeError(\"data must be bytes or str\")","sub_path":"trio_websockets/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"136612748","text":"import pandas as pd\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.svm import SVC\nfrom sklearn.externals import joblib\nfrom joblib import dump\nfrom src.corpus.creator import Trainer\nfrom src.corpus.creator import tokenize_text\nfrom settings import MODEL_PATH, CORPUS_PATH\n\nprint(\"load corpus...\")\nf = open(CORPUS_PATH, 'r')\ncorpus = eval(f.read())\nf.close()\ncorpus_keys = list(corpus.keys())\n\n\ndef train_model(train_df_path):\n\n train = pd.read_csv(train_df_path)\n df_vectorization = CountVectorizer(tokenizer=tokenize_text, ngram_range=(1, 5))\n clf = SVC(kernel='linear')\n\n pipe = Pipeline([('cleanText', Trainer()), ('vectorizer', df_vectorization), ('clf', clf)])\n # data\n train_df = train['Title_Input'].tolist()\n train_labels = train['Tag_Output'].tolist()\n\n pipe.fit(train_df, train_labels)\n joblib.dump(pipe, MODEL_PATH)\n del pipe\n\n return MODEL_PATH\n\n\ndef get_bow_vector(df_titles):\n\n title_vectors = []\n for title in df_titles:\n sentence_tokens = tokenize_text(sample=title)\n sent_vec = [0] * len(corpus)\n\n for token in sentence_tokens:\n if token in corpus_keys:\n index = corpus_keys.index(token)\n sent_vec[index] = 1\n\n title_vectors.append(sent_vec)\n\n return title_vectors\n\n\ndef train_model_bow(train_df_path):\n\n train_df = pd.read_excel(train_df_path)\n train_titles = train_df[\"Title\"].values.tolist()\n train_tags = train_df[\"Tag\"].values.tolist()\n\n bow_vector = get_bow_vector(df_titles=train_titles)\n\n training_model = SVC(kernel='rbf')\n training_model.fit(bow_vector, train_tags)\n dump(training_model, MODEL_PATH)\n\n return MODEL_PATH\n\n\nif __name__ == '__main__':\n\n train_model_bow(train_df_path=\"\")\n","sub_path":"src/model_training/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"383614504","text":"\"\"\"nekroobserver URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/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, include\nfrom . import views as basic_views\n\n\nurlpatterns = [\n path('', basic_views.index, name='index_page'),\n path('admin/', admin.site.urls, name = 'admin'),\n path('about/', basic_views.about, name = 'about'),\n path('source/', basic_views.source, name = 'source'),\n path('home_search//',basic_views.home_search, name='home_search'),\n path('users/',include('users.urls')),\n]\n","sub_path":"nekroobserver/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"185011806","text":"from jsonmodels.models import Base\nfrom .channel import Channel\n\n\nclass Device(Base):\n \"\"\" Contains info about a device and it's channels. \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a Device object by looping through the\n keywords in kwargs and setting them as attributes.\n :param kwargs: Dictionary containing a device.\n \"\"\"\n for keyword in [\"id\", \"naturalId\", \"name\",\n \"thingId\", \"channels\", \"signatures\"]:\n if keyword == \"channels\" and kwargs[keyword] is not None:\n kwargs[keyword] = [Channel(**channel_info)\n for channel_info in kwargs[keyword]]\n setattr(self, keyword, kwargs[keyword])\n","sub_path":"pyninjasphere/logic/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"69928381","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom zeus_core.service import Service\nfrom . import thrift_file\n\nservice = Service(\n name='arch.elee',\n slug='elee',\n timeout=3 * 1000,\n\n thrift=thrift_file,\n service_name='ArgsService',\n\n user_exc=thrift_file.ArgsUserException,\n system_exc=thrift_file.ArgsSystemException,\n unknown_exc=thrift_file.ArgsUnknownException,\n error_code=thrift_file.ArgsErrorCode,\n)\n\nfrom dispatcher import * # noqa Register dispatcher in this.","sub_path":"arch.elee/elee/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"519645949","text":"# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\nfrom scrapy import Field\n\nclass ChdlibItem(scrapy.Item):\n # define the fields for your item here like:\n # name = scrapy.Field()\n ID = Field()\n isbn = Field()\n douban = Field()\n lib = Field()\n 出版发行项 = Field()\n 个人责任者 = Field()\n 中图法分类号 = Field()\n 题名责任者 = Field()\n ISBN及定价 = Field()\n 载体形态项 = Field()\n 其它题名 = Field()\n 学科主题 = Field()\n 出版发行附注 = Field()\n 提要文摘附注 = Field()\n 豆瓣简介 = Field()\n 丛编项 = Field()\n 一般附注 = Field()\n 内容附注 = Field()\n 地名主题 = Field()\n 责任者附注 = Field()\n 书目附注 = Field()\n\n","sub_path":"Spiders/chdlib/chdlib/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"48911356","text":"import json\nimport requests\n\nurl = 'http://news.baidu.com/widget?id=LocalNews&ajax=json&t=1531118166323'\n\nresponse= requests.get(url)\n\nhehe = json.loads(response.text)\n\nhehe = hehe['data']['LocalNews']['data']['rows']['first']\nfor i in hehe:\n for key,value in i.items():\n print(key+':'+value)","sub_path":"爬虫10/爬虫实战/是他吧.py","file_name":"是他吧.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"31126494","text":"def returnNonDuplicate(nums):\n\tunique = 0\n\n\tfor num in nums:\n\t\t# ^= is a XOR operator. Because we know we're going to cancel out each integer by XORing it,\n\t\t# the only one left will be the one that only appears once!\n\t\tunique ^= num\n\n\treturn unique\n\nif __name__ == '__main__':\n\tdelivery_id_confirmations = [3,2,5,7,2,5,7]\n\tprint(returnNonDuplicate(delivery_id_confirmations))","sub_path":"droneConfirmations.py","file_name":"droneConfirmations.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"160423506","text":"import warnings\nwarnings.filterwarnings('ignore')\nimport streamlit as st \nimport re, string, pickle\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport nltk\nfrom nltk.corpus import stopwords\nfrom textblob import Word\nfrom collections import OrderedDict\nfrom wordcloud import WordCloud, STOPWORDS\nimport matplotlib\nimport matplotlib.pyplot as plt \nmatplotlib.use(\"Agg\")\nnltk.download('stopwords')\nnltk.download('wordnet')\nst.set_option('deprecation.showPyplotGlobalUse', False)\n \n\ndef load_pickle_models():\n # Load NN model\n loaded_model = tf.keras.models.load_model('Final_Model_Pkl.h5')\n file = open('target_enc_dict.obj','rb')\n # Load label encoder dictionary\n target_enc_dict = pickle.load(file)\n file.close()\n # Load TF-IDF vectorizer\n file2 = open('tfidf_vec.pkl','rb')\n tfidf_vec = pickle.load(file2)\n file2.close()\n return tfidf_vec, target_enc_dict, loaded_model\n\ndef clean_text(text):\n '''Make text lowercase, remove text in square brackets,remove links,remove punctuation\n and remove words containing numbers.'''\n text=text.replace(('first name: ').lower(),'firstname')\n text=text.replace(('last name: ').lower(),'lastname')\n text=text.replace(('received from:').lower(),'')\n text=text.replace('email:','')\n text=text.replace('email address:','') \n index1=text.find('from:')\n index2=text.find('\\nsddubject:')\n text=text.replace(text[index1:index2],'')\n index3=text.find('[cid:image')\n index4=text.find(']')\n text=text.replace(text[index3:index4],'')\n text=text.replace('subject:','')\n text=text.replace('received from:','')\n text=text.replace('this message was sent from an unmonitored email address', '')\n text=text.replace('please do not reply to this message', '')\n text=text.replace('monitoring_tool@company.com','MonitoringTool')\n text=text.replace('select the following link to view the disclaimer in an alternate language','')\n text=text.replace('description problem', '') \n text=text.replace('steps taken far', '')\n text=text.replace('customer job title', '')\n text=text.replace('sales engineer contact', '')\n text=text.replace('description of problem:', '')\n text=text.replace('steps taken so far', '')\n text=text.replace('please do the needful', '')\n text=text.replace('please note that ', '')\n text=text.replace('please find below', '')\n text=text.replace('date and time', '')\n text=text.replace('kindly refer mail', '')\n text=text.replace('name:', '')\n text=text.replace('language:', '')\n text=text.replace('customer number:', '')\n text=text.replace('telephone:', '')\n text=text.replace('summary:', '')\n text=text.replace('sincerely', '')\n text=text.replace('company inc', '')\n text=text.replace('importance:', '')\n text=text.replace('gmail.com', '')\n text=text.replace('company.com', '')\n text=text.replace('microsoftonline.com', '')\n text=text.replace('company.onmicrosoft.com', '')\n text=text.replace('hello', '')\n text=text.replace('hallo', '')\n text=text.replace('hi it team', '')\n text=text.replace('hi team', '')\n text=text.replace('hi', '')\n text=text.replace('best', '')\n text=text.replace('kind', '')\n text=text.replace('regards', '')\n text=text.replace('good morning', '')\n text=text.replace('good afternoon', '')\n text=text.replace('good evening', '')\n text=text.replace('please', '')\n text=text.replace('regards', '')\n text=text.replace('NaN','')\n text=text.replace('can''t','cannot')\n text=text.replace('i''ve','i have')\n text = re.sub(r'\\S+@\\S+', '', text)\n text = re.sub(r'\\w*\\d\\w*', '', text)\n text = re.sub(r'\\[.*?\\]', '', text)\n text = re.sub(r'https?://\\S+|www\\.\\S+', '', text)\n text = re.sub(r'<.*?>+', '', text)\n text = re.sub(r'[%s]' % re.escape(string.punctuation), ' ', text)\n text = re.sub(r'\\r\\n', '', text)\n text = re.sub(r'\\n', '', text)\n text = re.sub(r'\\S+@\\S+', '', text)\n text = re.sub(r'\\t', '', text)\n\n text = text.lower()\n return text\n\ndef test_data_processing(Short_desc, Desc, Caller):\n \n test_tkt = pd.DataFrame({'Short_desc': [Short_desc], 'Desc': [Desc], 'Caller': [Caller]})\n test_tkt['Full_desc'] = test_tkt['Short_desc'] + ' ' +test_tkt['Desc']\n \n # Clean text from unwanted words punctuation and symbols\n test_tkt['Full_desc'] = test_tkt['Full_desc'].apply(lambda x: clean_text(x))\n \n # Remove caller name from description\n def replace(str1, str2):\n return str1.replace(str2, '')\n test_tkt['Full_desc'] = test_tkt.apply(lambda row: replace(row['Full_desc'], row['Caller']), axis=1)\n test_tkt['Full_desc'] = (test_tkt['Full_desc'].str.split()\n .apply(lambda x: OrderedDict.fromkeys(x).keys())\n .str.join(' '))\n \n # Remove stop words\n stop = stopwords.words('english')\n test_tkt['Full_desc'] = test_tkt['Full_desc'].apply(lambda x: \" \".join(x for x in str(x).split() if x not in stop))\n \n # Lemmatize\n test_tkt['Full_desc']= test_tkt['Full_desc'].apply(lambda x: \" \".join([Word(word).lemmatize() for word in str(x).split()]))\n \n # Tokenization\n tokenizer = nltk.tokenize.RegexpTokenizer(r'\\w+')\n test_tkt['Full_desc'] = test_tkt['Full_desc'].apply(lambda x: tokenizer.tokenize(x))\n def combine_text(list_of_text):\n combined_text = ' '.join(list_of_text)\n return combined_text\n test_tkt['Full_desc'] = test_tkt['Full_desc'].apply(lambda x : combine_text(x))\n \n # Exception when there is insufficient data\n if len((test_tkt.iloc[0]['Full_desc']).split()) < 2:\n raise ValueError(\"Insufficient info\")\n return test_tkt\n \ndef test_vectorizer(test_tkt, tfidf_vec):\n tckt_tfidf_en = tfidf_vec.transform(test_tkt['Full_desc'])\n # collect the tfid matrix in numpy array\n array_en = tckt_tfidf_en.todense()\n df_tfidf_en = pd.DataFrame(array_en)\n X_test = df_tfidf_en.to_numpy()\n return X_test\n\ndef model_prediction(X_test, nn_model, target_enc_dict):\n y_pred_d = nn_model.predict(X_test)\n y_pred_d = np.argmax(y_pred_d, axis=1)\n y_pred_d = pd.DataFrame({'Assignment_group': [y_pred_d]})\n y_pred_d['Assignment_group'] = y_pred_d['Assignment_group'].astype(int)\n y_pred_d['Assignment_group']= y_pred_d['Assignment_group'].map(target_enc_dict)\n Pred_Group = y_pred_d.iloc[0]['Assignment_group']\n return Pred_Group\n\ndef main():\n \"\"\"Ticket Classifier\"\"\"\n html_temp = \"\"\"\n
    \n

    IT Ticket Classifier App

    \n
    \n \"\"\"\n st.markdown(html_temp,unsafe_allow_html=True)\n\n st.info(\"Predicting assignment group based on ticket description test\")\n Short_Description = st.text_input(\"Short Description\",\"Type Here...\")\n Description = st.text_area(\"Full Description\",\"Type Here...\")\n Caller = st.text_input(\"Caller Full Name\",\"Type Here...\")\n tfidf_vec, target_enc_dict, nn_model= load_pickle_models()\n col1, col2 = st.beta_columns(2)\n if col1.button(\"Classify\"):\n try:\n processed_text = test_data_processing(Short_Description, Description, Caller)\n X_test = test_vectorizer(processed_text, tfidf_vec)\n final_result = model_prediction(X_test, nn_model, target_enc_dict)\n st.success(\"Predicted Ticket Assignment Group - {}\".format(final_result))\n st.sidebar.subheader(\"About\")\n st.sidebar.text(\"1. Non-English tickets are not supported. \\n2. Tickets from following Group clubbed \\ninto Miscellaneous.\\nThey are :- \\n* 71 * 54 * 48 * 69 * 57 * 72 * 63 * 49\\n* 56 * 68 * 38 * 58 * 66 * 46 * 42 * 59\\n* 43 * 52 * 55 * 51 * 30 * 65 * 62 * 53\\n* 36 * 50 * 44 * 37 * 27 * 39 * 23 * 33\\n* 47 * 1 * 21 * 11 * 22 * 31 * 28 * 20\\n* 45 * 15 * 41\")\n except ValueError:\n st.error('Insufficient description information')\n if col2.button(\"NLP Word Cloud\"):\n try:\n p_text = test_data_processing(Short_Description, Description, Caller)\n c_text = p_text.iloc[0]['Full_desc']\n wordcloud = WordCloud().generate(c_text)\n plt.imshow(wordcloud,interpolation='bilinear')\n plt.axis(\"off\")\n st.pyplot()\n except ValueError:\n st.error('Insufficient description information')\n \n \nif __name__ == '__main__':\n main()","sub_path":"UI/Streamlit.py","file_name":"Streamlit.py","file_ext":"py","file_size_in_byte":8434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"86801527","text":"import tensorflow as tf\nimport numpy as np\nfrom util import import_data\nfrom util import build_dictionary\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.contrib.tensorboard.plugins import projector\nimport time\nfrom sys import stdout\nimport os\nimport operator\nimport csv\n\n\nclass skipthought(object):\n\n def __init__(self, corpus, embedding_size, hidden_size, hidden_layers, batch_size, keep_prob_dropout, learning_rate, bidirectional, loss_function, sampled_words, num_epochs):\n \n self.corpus = corpus\n self.embedding_size = embedding_size\n self.hidden_size = hidden_size\n self.hidden_layers = hidden_layers\n self.batch_size = batch_size\n self.keep_prob_dropout = keep_prob_dropout\n self.learning_rate = learning_rate\n self.bidirectional = bidirectional\n self.loss_function = loss_function\n self.sampled_words = sampled_words\n self.num_epochs = num_epochs\n\n def embed_data(self, data):\n return tf.nn.embedding_lookup(self.word_embeddings, data)\n\n def encoder(self, sentences_embedded, sentences_lengths, bidirectional = False):\n with tf.variable_scope(\"encoder\") as varscope:\n \n \n if bidirectional:\n cell = tf.contrib.rnn.GRUCell(self.hidden_size//2)\n cell = tf.contrib.rnn.DropoutWrapper(cell, input_keep_prob = self.keep_prob_dropout)\n cell = tf.contrib.rnn.MultiRNNCell([cell]*self.hidden_layers, state_is_tuple=True)\n print('Training bidirectional RNN')\n sentences_outputs, sentences_states = tf.nn.bidirectional_dynamic_rnn(cell, cell, \n inputs = sentences_embedded, sequence_length=sentences_lengths, dtype=tf.float32)\n states_fw, states_bw = sentences_states\n sentences_states_h = tf.concat([states_fw[-1],states_bw[-1]], axis = 1)\n # sentences_states_h = tf.contrib.layers.linear(sentences_states_h, self.hidden_size)\n\n else:\n cell = tf.contrib.rnn.GRUCell(self.hidden_size)\n cell = tf.contrib.rnn.DropoutWrapper(cell, input_keep_prob = self.keep_prob_dropout)\n cell = tf.contrib.rnn.MultiRNNCell([cell]*self.hidden_layers, state_is_tuple=True)\n print('Training one-directional RNN')\n sentences_outputs, sentences_states = tf.nn.dynamic_rnn(cell = cell, \n inputs = sentences_embedded, sequence_length=sentences_lengths, dtype=tf.float32) \n sentences_states_h = sentences_states[-1]\n\n return sentences_states_h\n\n def decoder(self, decoder_inputs, encoder_state, name, lengths= None, train = True):\n\n dec_cell = tf.contrib.rnn.GRUCell(self.embedding_size)\n\n W = self.graph.get_tensor_by_name(name+'/weight:0')\n b = self.graph.get_tensor_by_name(name+'/bias:0')\n\n if train:\n with tf.variable_scope(name) as varscope:\n dynamic_fn_train = tf.contrib.seq2seq.simple_decoder_fn_train(encoder_state)\n outputs_train, state_train, _ = tf.contrib.seq2seq.dynamic_rnn_decoder(dec_cell, decoder_fn = dynamic_fn_train, \n inputs=decoder_inputs, sequence_length = lengths, scope = varscope)\n logits = tf.reshape(outputs_train, [-1, self.embedding_size])\n logits_train = tf.matmul(logits, W) + b\n logits_projected = tf.reshape(logits_train, [self.batch_size, tf.reduce_max(lengths), self.vocabulary_size])\n return logits_projected, outputs_train\n\n else:\n with tf.variable_scope(name, reuse = True) as varscope:\n output_fn = lambda x: tf.nn.softmax(tf.matmul(x, W) + b)\n dynamic_fn_inference = tf.contrib.seq2seq.simple_decoder_fn_inference(output_fn =output_fn, encoder_state = encoder_state, \n embeddings = self.word_embeddings, start_of_sequence_id = 2, end_of_sequence_id = 3, maximum_length = self.max_sent_len, num_decoder_symbols = self.vocabulary_size) \n logits_inference, state_inference,_ = tf.contrib.seq2seq.dynamic_rnn_decoder(dec_cell, decoder_fn = dynamic_fn_inference, scope = varscope)\n return tf.arg_max(logits_inference, 2)\n\n def get_softmax_loss(self, labels, logits):\n \n return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits))\n\n def get_sampled_softmax_loss(self, labels, logits, name):\n\n W = self.graph.get_tensor_by_name(name+'/weight:0')\n b = self.graph.get_tensor_by_name(name+'/bias:0')\n\n logits = tf.stack(logits)\n logits_reshaped = tf.reshape(logits, [-1, self.embedding_size])\n labels_reshaped = tf.reshape(labels, [-1, 1])\n loss = tf.nn.sampled_softmax_loss(weights= tf.transpose(W), biases=b, labels=labels_reshaped, inputs = logits_reshaped, num_sampled = self.sampled_words, \n num_classes = self.vocabulary_size, num_true=1)\n return tf.reduce_mean(loss)\n\n def print_sentence(self, sentence, length):\n\n s = ''\n for i in range(length):\n word = sentence[i]\n s = s+self.reverse_dictionary[word]+' '\n return s\n\n def save_model(self, session, epoch):\n\n if not os.path.exists('./model/'):\n os.mkdir('./model/')\n saver = tf.train.Saver()\n if not os.path.exists('./model/epoch_%d.checkpoint' % epoch):\n saver.save(session, './model/epoch_%d.checkpoint' % epoch)\n else:\n saver.save(session, './model/epoch_%d.checkpoint' % epoch) \n\n def corpus_stats(self):\n\n print('\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n print('Corpus name:', self.corpus)\n print('Vocabulary size:', len(self.dictionary))\n print('Number of sentences:', self.corpus_length)\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n')\n\n def run(self):\n\n # Load corpus\n corpus = import_data(self.corpus)\n self.dictionary, self.reverse_dictionary, sent_lengths, self.max_sent_len, enc_data, dec_data, dec_lab = build_dictionary(corpus)\n\n # Save metadata for visualisation of embedding matrix\n meta_data = sorted(self.dictionary, key=model.dictionary.get)\n print(len(meta_data))\n with open('meta_data.tsv', 'w') as f:\n tsv_writer = csv.writer(f, dialect='excel')\n tsv_writer.writerow(str(i.encode('utf-8')) +'\\n' for i in meta_data)\n\n\n # np.savetxt(\"meta_data.tsv\", meta_data, fmt=\"%s\")\n\n self.dictionary = sorted(self.dictionary.items(), key=operator.itemgetter(1))\n self.vocabulary_size = len(self.dictionary)\n self.max_sent_len += 1\n\n # Create datasets for encoder and decoders\n enc_data = enc_data[1:-1]\n enc_lengths = sent_lengths[1:-1] \n post_lengths = sent_lengths[2:] + 1\n post_data = dec_data[2:]\n post_lab = dec_lab[2:]\n pre_lengths = sent_lengths[:-2] + 1\n pre_data = dec_data[:-2]\n pre_lab = dec_lab[:-2]\n \n # Print summary statistics\n self.corpus_length = len(enc_data)\n self.corpus_stats()\n\n\n self.graph = tf.Graph()\n\n with self.graph.as_default():\n\n print('\\r~~~~~~~ Building model ~~~~~~~\\r')\n self.initializer = tf.random_normal_initializer()\n\n # Variables\n self.word_embeddings = tf.get_variable('embeddings', [self.vocabulary_size, self.embedding_size], tf.float32, initializer = self.initializer)\n self.W_pre = tf.get_variable('precoder/weight', [self.embedding_size, self.vocabulary_size], tf.float32, initializer = self.initializer)\n self.b_pre = tf.get_variable('precoder/bias', [self.vocabulary_size], tf.float32, initializer = self.initializer)\n self.W_post = tf.get_variable('postcoder/weight', [self.embedding_size, self.vocabulary_size], tf.float32, initializer = self.initializer)\n self.b_post = tf.get_variable('postcoder/bias', [self.vocabulary_size], tf.float32, initializer = self.initializer)\n\n global_step = tf.Variable(0, name = 'global_step', trainable = False)\n\n # Encoder placeholders\n sentences = tf.placeholder(tf.int32, [None, None], \"sentences\")\n sentences_lengths = tf.placeholder(tf.int32, [None], \"sentences_lengths\")\n\n # Postcoder placeholders\n post_inputs = tf.placeholder(tf.int32, [None, None], \"post_inputs\")\n post_labels = tf.placeholder(tf.int32, [None, None], \"post_labels\")\n post_sentences_lengths = tf.placeholder(tf.int32, [None], \"post_sentences_lengths\")\n\n # Precoder placeholders\n pre_inputs = tf.placeholder(tf.int32, [None, None], \"pre_inputs\")\n pre_labels = tf.placeholder(tf.int32, [None, None], \"pre_labels\")\n pre_sentences_lengths = tf.placeholder(tf.int32, [None], \"pre_sentences_lengths\")\n\n # Embed sentences\n sentences_embedded = self.embed_data(sentences) \n post_inputs_embedded = self.embed_data(post_inputs)\n pre_inputs_embedded = self.embed_data(pre_inputs)\n\n # Encoder\n encoded_sentences = self.encoder(sentences_embedded, sentences_lengths, self.bidirectional)\n\n # Decoder for following sentence\n post_logits_projected, post_logits = self.decoder(decoder_inputs = post_inputs_embedded, encoder_state = encoded_sentences, \n name = 'postcoder', lengths = post_sentences_lengths, train = True)\n \n # Decoder for previous sentence\n pre_logits_projected, pre_logits = self.decoder(decoder_inputs = pre_inputs_embedded, encoder_state = encoded_sentences, \n name = 'precoder', lengths = pre_sentences_lengths, train = True)\n \n # Compute loss\n if self.loss_function == 'softmax':\n post_loss = self.get_softmax_loss(post_labels, post_logits_projected) \n pre_loss = self.get_softmax_loss(pre_labels, pre_logits_projected) \n else:\n post_loss = self.get_sampled_softmax_loss(post_labels, post_logits, name='postcoder') \n pre_loss = self.get_sampled_softmax_loss(pre_labels, pre_logits, name='precoder') \n\n loss = pre_loss + post_loss\n opt_op = tf.contrib.layers.optimize_loss(loss = loss, global_step = global_step, learning_rate = self.learning_rate, optimizer = 'Adam', clip_gradients=2.0, \n learning_rate_decay_fn=None, summaries = ['loss']) \n\n # Decode sentences at prediction time\n pre_predict = self.decoder(decoder_inputs = pre_inputs_embedded, encoder_state = encoded_sentences, \n name = 'precoder', lengths = pre_sentences_lengths, train = False)\n post_predict = self.decoder(decoder_inputs = post_inputs_embedded, encoder_state = encoded_sentences, \n name = 'postcoder', lengths = post_sentences_lengths, train = False)\n predict = [pre_predict, post_predict]\n\n with tf.Session(graph = self.graph) as session:\n\n self.a= tf.contrib.graph_editor.get_tensors(self.graph)\n train_loss_writer = tf.summary.FileWriter('./tensorboard/train_loss', session.graph)\n\n\n # Use the same LOG_DIR where you stored your checkpoint.\n embedding_writer = tf.summary.FileWriter('./tensorboard/', session.graph)\n\n config = projector.ProjectorConfig()\n embedding = config.embeddings.add()\n embedding.tensor_name = self.word_embeddings.name\n # Link this tensor to its metadata file (e.g. labels).\n embedding.metadata_path = os.path.join('./meta_data.tsv')\n\n # Saves a configuration file that TensorBoard will read during startup.\n projector.visualize_embeddings(embedding_writer, config)\n\n merged = tf.summary.merge_all()\n\n print('\\r~~~~~~~ Initializing variables ~~~~~~~\\r')\n tf.global_variables_initializer().run()\n\n print('\\r~~~~~~~ Starting training ~~~~~~~\\r')\n start_time = time.time()\n \n\n try:\n train_summaryIndex = -1\n\n for epoch in range(self.num_epochs):\n self.is_train = True\n epoch_time = time.time()\n print('----- Epoch', epoch, '-----')\n print('Shuffling dataset')\n\n perm = np.random.permutation(self.corpus_length)\n\n enc_lengths_perm = enc_lengths[perm]\n enc_data_perm = enc_data[perm]\n post_lengths_perm = post_lengths[perm]\n post_inputs_perm = np.array(post_data)[perm]\n post_labels_perm = np.array(post_lab)[perm]\n pre_lengths_perm = pre_lengths[perm]\n pre_inputs_perm = np.array(pre_data)[perm]\n pre_labels_perm = np.array(pre_lab)[perm]\n\n total_loss = 0\n predict_step = 50\n\n for step in range(self.corpus_length // self.batch_size):\n begin = step * self.batch_size\n end = (step + 1) * self.batch_size\n\n batch_enc_lengths = enc_lengths_perm[begin : end]\n batch_enc_inputs = enc_data_perm[begin : end]\n batch_post_lengths = post_lengths_perm[begin : end]\n batch_post_inputs = post_inputs_perm[begin:end, :np.max(batch_post_lengths)]\n batch_post_labels = post_labels_perm[begin:end, :np.max(batch_post_lengths)]\n batch_pre_lengths = pre_lengths_perm[begin : end]\n batch_pre_inputs = pre_inputs_perm[begin:end, :np.max(batch_pre_lengths)]\n batch_pre_labels = pre_labels_perm[begin:end, :np.max(batch_pre_lengths)]\n\n train_dict = {sentences: batch_enc_inputs, \n sentences_lengths: batch_enc_lengths,\n post_inputs: batch_post_inputs,\n post_labels: batch_post_labels,\n post_sentences_lengths: batch_post_lengths,\n pre_inputs: batch_pre_inputs,\n pre_labels: batch_pre_labels,\n pre_sentences_lengths: batch_pre_lengths}\n\n _, loss_val, batch_summary, glob_step = session.run([opt_op, loss, merged, global_step], feed_dict=train_dict)\n train_loss_writer.add_summary(batch_summary, step + (self.corpus_length // self.batch_size)*epoch)\n\n total_loss += loss_val\n\n if glob_step % predict_step == 0:\n # if step > 0:\n print(\"Average loss at step \", glob_step, \": \", total_loss/predict_step)\n total_loss = 0\n\n print('\\nOriginal sequence:\\n')\n print(self.print_sentence(batch_pre_inputs[0, 1:], batch_pre_lengths[0]-1))\n print(self.print_sentence(batch_enc_inputs[0], batch_enc_lengths[0]))\n print(self.print_sentence(batch_post_inputs[0, 1:], batch_post_lengths[0]-1))\n\n test_enc_lengths = np.expand_dims(batch_enc_lengths[0], 0)\n test_enc_inputs = np.expand_dims(batch_enc_inputs[0], 0)\n test_post_lengths = np.expand_dims(batch_post_lengths[0], 0)\n test_post_inputs = np.expand_dims(batch_post_inputs[0], 0)\n test_post_labels = np.expand_dims(batch_post_labels[0], 0)\n test_pre_lengths = np.expand_dims(batch_pre_lengths[0], 0)\n test_pre_inputs = np.expand_dims(batch_pre_inputs[0], 0)\n test_pre_labels = np.expand_dims(batch_pre_labels[0], 0)\n\n test_dict = {sentences_lengths: test_enc_lengths,\n sentences: test_enc_inputs, \n post_sentences_lengths: test_post_lengths,\n post_inputs: test_post_inputs,\n post_labels: test_post_labels,\n pre_sentences_lengths: test_pre_lengths,\n pre_inputs: test_pre_inputs,\n pre_labels: test_pre_labels}\n\n pre_prediction, post_prediction = session.run([predict], feed_dict=test_dict)[0]\n\n print('\\nPredicted previous and following sequence around original sentence:\\n')\n print(self.print_sentence(pre_prediction[0], len(pre_prediction[0])))\n print(self.print_sentence(batch_enc_inputs[0], batch_enc_lengths[0]))\n print(self.print_sentence(post_prediction[0], len(post_prediction[0])))\n\n end_time = time.time()\n print('\\nTime for %d steps: %0.2f seconds' % (predict_step, end_time - start_time))\n start_time = time.time()\n print('\\n\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n\n saver = tf.train.Saver()\n saver.save(session, os.path.join('./tensorboard/', 'model.ckpt'))\n\n except KeyboardInterrupt:\n save = input('save?')\n if 'y' in save:\n self.save_model(session, 0)\n\nif __name__ == '__main__':\n tf.reset_default_graph()\n\n model = skipthought(corpus = './corpus/gingerbread.txt',\n embedding_size = 200, \n hidden_size = 200, \n hidden_layers = 1, \n batch_size = 20, \n keep_prob_dropout = 1.0, \n learning_rate = 0.005, \n bidirectional = False,\n loss_function = 'softmax',\n sampled_words = 500,\n num_epochs = 100)\n\n model.run()\n\n","sub_path":"skipthought.py","file_name":"skipthought.py","file_ext":"py","file_size_in_byte":18356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"582127733","text":"from OWDTestToolkit.global_imports import *\n \nclass main(GaiaTestCase):\n\n def getNetworkConnection(self):\n #\n # Tries several methods to get ANY network connection\n # (either wifi or dataConn).\n #\n \n # The other methods seem to hit a marionette error just now,\n # but gaiatest has this method so I'll stick to that if it works.\n self.connect_to_network()\n return\n \n # make sure airplane mode is off.\n if self.isNetworkTypeEnabled(\"airplane\"):\n self.toggleViaStatusBar(\"airplane\")\n \n # make sure at least dataconn is on.\n if not self.isNetworkTypeEnabled(\"data\"):\n self.toggleViaStatusBar(\"data\")\n \n # Devic eshows data mode in status bar.\n self.waitForStatusBarNew(DOM.Statusbar.dataConn, p_timeOut=60)\n \n \n","sub_path":"OWDTestToolkit/utils/network/getNetworkConnection.py","file_name":"getNetworkConnection.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"512801489","text":"# Copyright (c) 2015 The New Mexico Consortium\n# \n# {{{NMC-LICENSE\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n# DAMAGE.\n#\n# }}}\n\nfrom nmc_probe.command import AsyncCommand, Command\nfrom nmc_probe.log import Log\nimport os\n\nhdparm_cmd='/usr/sbin/hdparm'\n\nclass HDParm:\n def __init__(self, dev):\n self.dev = dev\n # If hdparm is not present, throw an exception\n os.stat(hdparm_cmd)\n\n @property\n def info(self):\n '''Dictionary of disk information, like model number'''\n if getattr(self, '_info', None) is None:\n self._info = self.get_info()\n return self._info\n\n def get_info(self):\n hdparm_attrs = {\n '^\\s*Serial Number:\\s*(.*)\\s*$': 'serial_number',\n '^\\s*Firmware Revision:\\s*(.*)\\s*$': 'firmware',\n '^\\s*Transport:\\s*(.*)\\s*$': 'transport',\n '^\\s*NAA:\\s*(.*)\\s*$': 'naa',\n '^\\s*IEEE OUI:\\s*(.*)\\s*$': 'ieee_oui',\n '^\\s*Unique ID:\\s*(.*)\\s*$': 'unique_id',\n '^\\s*Logical Unit WWN Device Identifier:\\s*(.*)\\s*$': 'wwn',\n '^\\s*Model Number:\\s+(.*)\\s*$': 'model_number',\n '^\\s*CHS current addressable sectors\\s*:\\s*(\\d+)': 'chs_current_addressable_sectors',\n '^\\s*LBA\\s+user\\s+addressable\\s+sectors\\s*:\\s*(\\d+)': 'lba_user_addressable_sectors',\n '^\\s*LBA48 user addressable sectors:\\s*(\\d+)': 'lba48_user_addressable_sectors',\n '^\\s*Logical/Physical Sector size:\\s*(\\d+)': 'sector_size_bytes',\n '^\\s*device size with M = 1024\\*1024:\\s*(\\d+)': 'size_mb',\n}\n\n cmd = [hdparm_cmd, '-I', self.dev]\n\n attrs = Command.run_and_extract_attrs(cmd, hdparm_attrs)\n\n for (key, value) in attrs.iteritems():\n attrs[key] = value.strip()\n\n # Convert integer values to integers\n int_attrs = ['size_mb', 'sector_size_bytes', 'lba48_user_addressable_sectors', 'chs_current_addressable_sectors']\n\n for attr in int_attrs:\n value = attrs.get(attr, None)\n if value is not None:\n attrs[attr] = int(value)\n\n return attrs\n\n def speed_test(self, offset=None):\n cmd = [hdparm_cmd, '-t', '--direct']\n\n if offset:\n cmd.append('--offset')\n cmd.append('%d' % offset)\n\n cmd.append(self.dev)\n \n patterns = {\n '^\\s*Timing.*=\\s*([0-9\\.]+)': 'speed'\n }\n\n attrs = Command.run_and_extract_attrs(cmd, patterns)\n\n float_attrs = ['speed']\n\n for attr in float_attrs:\n value = attrs.get(attr, None)\n if value is not None:\n attrs[attr] = float(value)\n\n return attrs['speed']\n\n\n @property\n def speed(self):\n if getattr(self, '_speed', None) is None:\n self._speed = self.get_speed()\n return self._speed\n\n def get_speed(self, num_samples = 3):\n ten_percent_gb = self.info['size_mb'] / 10240\n\n positions = {\n 'front': ten_percent_gb,\n 'middle': self.info['size_mb'] / 1024 / 2,\n 'end': (self.info['size_mb'] / 1024) - ten_percent_gb\n }\n\n speed = {\n 'front': 0.0,\n 'middle': 0.0,\n 'end': 0.0\n }\n\n for (name, position) in positions.iteritems():\n for i in xrange(num_samples):\n speed[name] = speed[name] + self.speed_test(position)\n\n speed[name] = speed[name] / num_samples\n\n # Average the speed for all positions tested\n sum_speed = 0\n num_categories = 0\n\n for key, value in speed.iteritems():\n sum_speed = sum_speed + value\n num_categories = num_categories + 1\n\n speed['average'] = float(sum_speed) / float(num_categories)\n\n return speed\n","sub_path":"site-packages/nmc_probe/hdparm.py","file_name":"hdparm.py","file_ext":"py","file_size_in_byte":5256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"629564231","text":"# No external imports are allowed other than numpy\nimport numpy as np\nfrom typing import Dict, List, Set, Tuple\n\nfrom collections import defaultdict\n\n\ndef tqdm_s(_iter):\n try:\n from tqdm import tqdm\n return tqdm(_iter)\n except ModuleNotFoundError:\n return _iter\n\n\ndef _get_mapping(adjdict):\n node_set = set()\n for node_id, adjacent in adjdict.items():\n node_set.update([node_id] + adjacent)\n node_id_to_idx = {node_id: idx for idx, node_id in enumerate(node_set)}\n idx_to_node_id = {idx: node_id for idx, node_id in enumerate(node_set)}\n return node_set, node_id_to_idx, idx_to_node_id\n\n\ndef _get_followings_and_followers(adjdict, node_id_to_idx, N):\n to_followings = {}\n to_followers = {idx: [] for idx in range(N)}\n for node_id in adjdict:\n idx = node_id_to_idx[node_id]\n to_followings[idx] = np.asarray([node_id_to_idx[f_id] for f_id in adjdict[node_id]])\n for f_id in adjdict[node_id]:\n to_followers[node_id_to_idx[f_id]].append(idx)\n to_followers = {k: np.asarray(v) for k, v in to_followers.items()}\n return to_followings, to_followers\n\n\ndef scc(adjdict: Dict[int, List[int]]) -> List[Set[int]]:\n \"\"\"\n Return the list of strongly connected components of given graph.\n \n Inputs:\n adjdict: directed input graph in the adjacency dictionary format\n Outputs: a list of the strongly connected components.\n Each SCC is represented as a set of node indices.\n \"\"\"\n\n # Index Mapping\n node_set, node_id_to_idx, idx_to_node_id = _get_mapping(adjdict)\n N = len(node_set)\n\n # to_followings, to_followers: Dict[int, np.ndarray[int]]\n to_followings, _ = _get_followings_and_followers(adjdict, node_id_to_idx, N)\n\n v_scc_list: List[Set[int]] = []\n\n # Each node v is assigned a unique integer v.index,\n # which numbers the nodes consecutively in the order in which they are discovered.\n v_index = np.zeros(N) - 1\n\n # It also maintains a value v.lowlink that represents the smallest index\n # of any node known to be reachable from v through v's DFS subtree, including v itself.\n v_lowlink = np.zeros(N) - 1\n\n stack = []\n v_on_stack = np.zeros(N) - 1\n\n visit_index = 0\n for vid in range(N):\n if v_index[vid] == -1 and vid in to_followings:\n _scc_list, visit_index, v_index, v_lowlink, stack, v_on_stack = _scc_one(\n vid,\n to_followings=to_followings,\n visit_index=visit_index,\n v_index=v_index,\n v_lowlink=v_lowlink,\n stack=stack,\n v_on_stack=v_on_stack,\n )\n v_scc_list += _scc_list\n\n scc_list: List[Set[int]] = []\n for v_scc in v_scc_list:\n scc_list.append({idx_to_node_id[vid] for vid in v_scc})\n\n return scc_list\n\n\ndef _scc_one(vid, to_followings, visit_index, v_index, v_lowlink, stack, v_on_stack) -> Tuple:\n\n _scc_list = list()\n\n _call_stack = []\n _v_to_num_called = defaultdict(lambda: -1)\n\n def _call(*args):\n for x in args:\n _call_stack.append(x)\n _v_to_num_called[x] += 1\n\n _call(vid)\n while len(_call_stack) != 0:\n\n vid = _call_stack.pop()\n\n # Set the depth index for v to the smallest unused index\n if _v_to_num_called[vid] == 0:\n v_index[vid] = visit_index\n v_lowlink[vid] = visit_index\n visit_index += 1\n stack.append(vid)\n v_on_stack[vid] = 1\n\n # Consider successors of vid\n for fid in to_followings[vid][_v_to_num_called[vid]:]:\n # Successor fid has not yet been visited; recurse on it.\n if v_index[fid] == -1 and fid in to_followings:\n _call(vid, fid)\n break\n\n # Successor w is in stack S and hence in the current SCC\n # If w is not on stack, then (v, w) is a cross-edge in the DFS tree and must be ignored\n elif v_on_stack[fid]:\n v_lowlink[vid] = min(v_lowlink[vid], v_index[fid])\n else:\n # If vid is a root node, pop the stack and generate an SCC\n if v_index[vid] == v_lowlink[vid]:\n wid, new_scc = -1, set()\n while wid != vid:\n wid = stack.pop()\n v_on_stack[wid] = 0\n new_scc.add(wid)\n _scc_list.append(new_scc)\n\n if len(_call_stack) != 0:\n vid, fid = _call_stack[-1], vid\n v_lowlink[vid] = min(v_lowlink[vid], v_lowlink[fid])\n\n return _scc_list, visit_index, v_index, v_lowlink, stack, v_on_stack\n\n\ndef _scc_one_recursive(vid, to_followings, visit_index, v_index, v_lowlink, stack, v_on_stack) -> Tuple:\n\n _scc_list = list()\n\n # Set the depth index for v to the smallest unused index\n v_index[vid] = visit_index\n v_lowlink[vid] = visit_index\n visit_index += 1\n stack.append(vid)\n v_on_stack[vid] = 1\n\n # Consider successors of vid\n for fid in to_followings[vid]:\n # Successor fid has not yet been visited; recurse on it.\n if v_index[fid] == -1 and fid in to_followings:\n new_scc_list, visit_index, v_index, v_lowlink, stack, v_on_stack = _scc_one_recursive(\n fid, to_followings, visit_index, v_index, v_lowlink, stack, v_on_stack)\n _scc_list += new_scc_list\n v_lowlink[vid] = min(v_lowlink[vid], v_lowlink[fid])\n\n # Successor w is in stack S and hence in the current SCC\n # If w is not on stack, then (v, w) is a cross-edge in the DFS tree and must be ignored\n elif v_on_stack[fid]:\n v_lowlink[vid] = min(v_lowlink[vid], v_index[fid])\n\n # If vid is a root node, pop the stack and generate an SCC\n if v_index[vid] == v_lowlink[vid]:\n wid, new_scc = -1, set()\n while wid != vid:\n wid = stack.pop()\n v_on_stack[wid] = 0\n new_scc.add(wid)\n _scc_list.append(new_scc)\n\n return _scc_list, visit_index, v_index, v_lowlink, stack, v_on_stack\n\n\ndef load_stanford_dataset(path=\"../web-Stanford.txt\") -> Dict[int, List[int]]:\n stanford_adjdict = {}\n with open(path, \"r\") as f:\n for line in tqdm_s(f):\n if not line.startswith(\"#\"):\n u, v = tuple([int(x) for x in line.strip().split()])\n if u in stanford_adjdict:\n stanford_adjdict[u].append(v)\n else:\n stanford_adjdict[u] = [v]\n print(\"Loaded SNAP\")\n return stanford_adjdict\n\n\nif __name__ == '__main__':\n\n MODE = \"TEST\"\n\n if MODE == \"TEST\":\n test_adjdict = {1: [2],\n 2: [3, 4],\n 3: [4, 6],\n 4: [1, 5],\n 5: [6],\n 6: []}\n test_scc = scc(test_adjdict)\n test_result = [{6}, {5}, {1, 2, 3, 4}]\n assert len(test_result) == len(test_scc)\n for ts, tr in zip(sorted(test_scc), sorted(test_result)):\n assert ts == tr, \"{} != {}\".format(ts, tr)\n\n test_adjdict = {1: [2],\n 2: [3, 4],\n 3: [4, 6],\n 4: [1, 5],\n 5: [6],\n 6: [],\n 7: [8, 9],\n 8: [9, 10, 11],\n 9: [7],\n 10: [],\n 11: [10]}\n test_scc = scc(test_adjdict)\n test_result = [{6}, {5}, {1, 2, 3, 4}, {10}, {11}, {8, 9, 7}]\n assert len(test_result) == len(test_scc)\n for ts, tr in zip(sorted(test_scc), sorted(test_result)):\n assert ts == tr, \"{} != {}\".format(ts, tr)\n print(\"TEST finished\")\n\n else:\n from time import time\n data = load_stanford_dataset()\n start_time = time()\n scc(data)\n print(\"Time for Stanford Dataset: {}s\".format(time() - start_time))\n","sub_path":"hw2/scc.py","file_name":"scc.py","file_ext":"py","file_size_in_byte":7974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"277827112","text":"import pandas as pd\nfrom pandas.core.frame import DataFrame\nfrom sklearn.metrics import precision_score\nfrom sklearn.svm import SVR\nfrom random import sample \nimport numpy as np\nimport warnings\nfrom sklearn.kernel_approximation import Nystroem\n\nwarnings.filterwarnings(\"ignore\", category=FutureWarning, module=\"sklearn\", lineno=196)\n\nimport sys\nimport os\nfrom sklearn.metrics import roc_auc_score, average_precision_score, roc_curve\nfrom sklearn.metrics import roc_curve, auc\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import precision_recall_curve\nfrom fastFM import sgd\nimport scipy.sparse as sp\nimport time\nfrom sklearn.model_selection import KFold, StratifiedKFold\nfrom sklearn import preprocessing\nimport csv\n\n\nstart = time.time()\n\n\nSK = 128\nGN_OM = pd.read_csv('data/test data/bone_marrow_Gene_Ori_Map_%d.tsv' %SK,'\\t',header = None)\n\n\nGN_Y = []\ns = open(\"bonemarrow/gold_standard_for_TFdivide.txt\") # 'mmukegg_new_new_unique_rand_labelx.txt')#) ### read the gene pair and label file\nfor line in s:\n separation = line.split()\n GN_Y.append(separation[2])\n \n\nGN_Y = np.array(GN_Y)\nGN_OY = GN_Y\nprint(GN_OY.shape)\n\n\n\nGN_OM = np.array(GN_OM.values.tolist())\n\n\nprint(GN_OM.shape)\n\nGN_OM = GN_OM/10000000\n\nGN_OY = GN_Y.astype(np.int)\n\nskf = StratifiedKFold(n_splits=10, shuffle=True, random_state=123)\n\navr_auroc_l = [[],[],[],[]]\navr_aupr_l = [[],[],[],[]]\n\nfor train_index, test_index in skf.split(GN_OM,GN_OY):\n\n GN_Mat = GN_OM[train_index]\n\n GN_Y = GN_OY[train_index]\n\n \n GN_MT = GN_Mat[GN_Y == 1]\n GN_MF = GN_Mat[GN_Y == 0]\n\n GN_Mat = np.vstack((GN_MT, GN_MF))\n GN_Y = np.hstack((np.ones(len(GN_MT),dtype = int), np.zeros(len(GN_MF),dtype = int)))\n \n \n print(GN_Y.shape)\n\n \n GN_TMat = GN_OM[test_index]\n GN_TY = GN_OY[test_index]\n\n print(GN_TY.shape)\n \n print(GN_TMat.shape)\n \n \n X_train = sp.csc_matrix(GN_Mat, dtype=np.float64)\n X_test = sp.csc_matrix(GN_TMat, dtype=np.float64)\n GN_B = np.where(GN_Y == 1, 1, -1)\n y_train = np.array(GN_B)\n \n k = 8\n for i in range(1):\n k *= 2\n fm = sgd.FMClassification(n_iter=len(GN_Mat)*10, step_size = 0.1, n_iter1=0, init_stdev=0.1, rank=k, l2_reg_w=0.0, l2_reg_V=0.0, is_w = 1, pr = 0)\n fm.fit(X_train, y_train)\n y_pred = fm.predict(X_test)\n print(k)\n auroc = roc_auc_score(GN_TY,y_pred)\n aupr = average_precision_score(GN_TY,y_pred)\n\n print(\"auroc:\",auroc)\n print(\"aupr:\",aupr)\n avr_auroc_l[i].append(auroc)\n avr_aupr_l[i].append(aupr)\n\n\n\n#print(\"HSIC \",\"auroc:\", avr_auroc, \"aupr:\", avr_aupr)\n\nfor i in range(1):\n print(\"FM\",\"low_rank=\", 2**(i+3), \"auroc:%.4f$\\\\pm$%.2f\" %(np.mean(avr_auroc_l[i]), np.std(avr_auroc_l[i], ddof=1)),\\\n \"aupr:%.4f$\\\\pm$%.2f\" %(np.mean(avr_aupr_l[i]), np.std(avr_aupr_l[i], ddof=1)))\n\nend = time.time()\nprint(\"time:\", end-start)\n \n \n\n\n","sub_path":"marrow_fm.py","file_name":"marrow_fm.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"73372101","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nimport Tkinter as tk\nimport tkMessageBox as tkmb\nfrom tkFileDialog import askopenfilename\nimport time\nfrom datetime import datetime\nimport sys\n\nfrom easymaker import easymaker\nfrom easymaker import tprint\n\n\nclass Interface(tk.Frame):\n def __init__(self, parent=None, ezm=easymaker.Easymaker()):\n tk.Frame.__init__(self, parent)\n self.parent = parent\n self.easymaker = ezm\n\n parent.resizable(width=False, height=False)\n w, h = 250, 420\n ws = self.parent.winfo_screenwidth()\n hs = self.parent.winfo_screenheight()\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n self.parent.geometry('{}x{}+{}+{}'.format(w, h, x, y))\n self.parent.title('Easymaker {}'.format(easymaker.version))\n\n btn_credits = tk.Button(text='Credits', command=self.credits, height=2)\n self.btn_move = tk.Button(text='Move', command=self.move, height=2)\n self.btn_load = tk.Button(text='Load', command=self.load, height=2)\n self.btn_home = tk.Button(text='Home', command=self.home, height=2)\n self.btn_print = tk.Button(text='Print', command=self.execute, height=2)\n self.cnv_progbar = tk.Canvas(height=20, background='#FFFFFF', borderwidth=1, relief=tk.SUNKEN)\n self.t = SimpleTable(self, 7,2)\n\n self.prog_rect = self.cnv_progbar.create_rectangle(0, 0, 0, 0, fill='lightgrey')\n self.cnv_progtext = self.cnv_progbar.create_text(122, 11, anchor=tk.CENTER)\n #self.cnv_progbar.itemconfig(self.cnv_progtext, text=\"100%\")\n\n btn_credits.pack(fill='x', pady=3, padx=3)\n self.btn_move.pack(fill='x', pady=3, padx=3)\n self.btn_home.pack(fill='x', pady=3, padx=3)\n self.btn_load.pack(fill='x', pady=3, padx=3)\n self.btn_print.pack(fill='x', pady=3, padx=3)\n self.cnv_progbar.pack(fill='x', pady=3, padx=3)\n self.t.pack(side='top', fill='x', pady=3, padx=3)\n\n self.t.set(0, 0, 'Elapsed')\n self.t.set(0, 1, 'ETA')\n self.t.set(0, 2, 'Pos X')\n self.t.set(0, 3, 'Pos Y')\n self.t.set(0, 4, 'Pos Z')\n self.t.set(0, 5, 'Extruding')\n self.t.set(0, 6, 'Last')\n\n self.exitprint = False\n\n self.printview = tprint.TPrint()\n\n def move(self):\n pass\n\n def stop_execute(self):\n self.exitprint = True\n\n def execute(self):\n \"\"\"Prints the gcode file loaded with \"load \".\"\"\"\n if self.easymaker.data is None:\n tkmb.showinfo('Message', 'Please load a file.')\n return\n\n self.btn_move.config(state='disabled')\n self.btn_home.config(state='disabled')\n self.btn_load.config(state='disabled')\n self.btn_print.config(text='Cancel', command=self.stop_execute)\n\n if not self.printview.is_alive():\n del self.printview\n self.printview = tprint.TPrint()\n\n starttime = datetime.now()\n\n elapsed = '00:00:00'\n eta = '00:00:00'\n\n try:\n for cb in self.easymaker.execute_gcode():\n if self.exitprint:\n self.exitprint = False\n self.easymaker.cleanup()\n self.btn_move.config(state='normal')\n self.btn_home.config(state='normal')\n self.btn_load.config(state='normal')\n self.btn_print.config(text='Print', command=self.execute)\n return\n\n # FIXME: bad style\n if not isinstance(cb['posX'], float):\n cb['posX'] = 'N/A'\n\n if not isinstance(cb['posY'], float):\n cb['posY'] = 'N/A'\n\n if not isinstance(cb['posZ'], float):\n cb['posZ'] = 'N/A'\n\n sys.stdout.flush()\n self.set_progress(round(cb['progress'], 4))\n self.t.set(1, 0, cb['elapsed'])\n self.t.set(1, 1, cb['eta'])\n self.t.set(1, 2, cb['posX'])\n self.t.set(1, 3, cb['posY'])\n self.t.set(1, 4, cb['posZ'])\n self.t.set(1, 5, ['No', 'Yes'][cb['extruding']])\n self.t.set(1, 6, cb['code'][0])\n\n self.printview.update(cb)\n finally:\n self.easymaker.cleanup()\n\n self.btn_move.config(state='normal')\n self.btn_home.config(state='normal')\n self.btn_load.config(state='normal')\n self.btn_print.config(text='Print', command=self.execute)\n\n def set_progress(self, p):\n max = 241\n self.cnv_progbar.coords(self.prog_rect, 2, 2, max*p, 21)\n self.cnv_progbar.itemconfig(self.cnv_progtext, text=str(p*100)+'%')\n self.update()\n\n def load(self):\n filepath = askopenfilename()\n self.easymaker.loadfile(filepath)\n tkmb.showinfo('Loading', 'Done.\\nInstructions: {}'.format(len(self.easymaker.data)))\n\n def credits(self):\n text = ('Easymaker {}'.format(easymaker.version),\n '\\nBuilt by:',\n '\\n'.join(easymaker.credits['built']),\n '\\nSpecial thanks to:',\n '\\n'.join(easymaker.credits['thanks']))\n tkmb.showinfo('Credits', '\\n'.join(text))\n\n def home(self):\n self.easymaker.codeG28()\n tkmb.showinfo('Message', 'Homing successful.')\n\n\nclass SimpleTable(tk.Frame):\n def __init__(self, parent, rows=10, columns=2):\n # use black background so it \"peeks through\" to\n # form grid lines\n tk.Frame.__init__(self, parent, background='gray')\n self._widgets = []\n for row in range(rows):\n current_row = []\n for column in range(columns):\n #text=\"%s/%s\" % (row, column)\n label = tk.Label(self, borderwidth=0, width=10)\n label.grid(row=row, column=column, sticky=\"nsew\", padx=1, pady=1)\n current_row.append(label)\n self._widgets.append(current_row)\n\n for column in range(columns):\n self.grid_columnconfigure(column, weight=1)\n\n def set(self, column, row, value):\n widget = self._widgets[row][column]\n widget.configure(text=value)\n\n\nif __name__ == '__main__':\n root = tk.Tk()\n app = Interface(root).pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n","sub_path":"src/gui.pyw","file_name":"gui.pyw","file_ext":"pyw","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"360807386","text":"import cv2\nimport sys\nimport os\nimport imutils\nfrom imutils.object_detection import non_max_suppression\n\n# The locatio of the image and the cascade file path\n# imagePath ='/home/unnirajendran/Desktop/face_detect/image1.jpg'\n# cascPath = '/home/unnirajendran/Desktop/face_detect/haarcascade_frontalface_default.xml'\nimagePath = sys.argv[1]\ncascPath = sys.argv[2]\n# Create the haar cascade\ncar_cascade = cv2.CascadeClassifier(cascPath)\n\n# Read the image\nimage = cv2.imread(imagePath)\n\n# Resize the image so it fits in the screen\nimage1 = imutils.resize(image, height=500)\ngray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)\n\n# Detect faces in the image\nfaces = car_cascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n # flags = cv2.cv.CV_HAAR_SCALE_IMAGE\n flags=0\n)\nface = non_max_suppression(faces, probs=None, overlapThresh=0.3)\nif format(len(faces)) == 1:\n print(\"Found {0} face!\".format(len(faces)))\nelse:\n print(\"Found {0} faces!\".format(len(faces)))\n\n# Draw a rectangle around the faces\nfor (x, y, w, h) in face:\n cv2.rectangle(image1, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\ncv2.imshow(\"Faces found\", image1)\ncv2.waitKey(0)\n","sub_path":"scripts/car_detect.py","file_name":"car_detect.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"381507237","text":"import os, sys\n\nsys.path.append(\"/valohai/inputs/models/models-master/research/slim\")\n\nimport tensorflow as tf\nimport numpy as np\nimport tensorflow.contrib.slim as slim\nfrom tensorflow.contrib.slim.nets import resnet_v1\nimport datetime, os, glob, errno\nfrom tensorflow.python.platform import tf_logging as logging\n\n\ndef parser(record):\n \"\"\"Parses input records and returns batch_size samples\n \"\"\"\n\n # each tf.Example object in input .tfrecords file packs image and label as,\n # dictionary with key: 'image', its value: a png-encoded bytearray representation\n # dictionary with key: 'label', its value: a png-encoded bytearray representation,\n # label is a binary image with 255 pixel value for foreground, 0 for background.\n keys_to_features = {\n \"image\": tf.FixedLenFeature((), tf.string, default_value=\"\"),\n \"label\": tf.FixedLenFeature((), tf.string, default_value=\"\")\n }\n\n parsed = tf.parse_single_example(record, keys_to_features)\n\n # input image is a 3-channel RGB image\n decoded_image = tf.image.decode_png(parsed[\"image\"], channels=3)\n\n # input label is a grayscale image\n decoded_label = tf.image.decode_png(parsed[\"label\"], channels=1)\n\n # turn the label to floating-point with [0,1) range.\n decoded_label = tf.image.convert_image_dtype(decoded_label, tf.float32)\n # decoded_label = tf.round(decoded_label)\n decoded_label = tf.to_int32(decoded_label)\n\n # drop the last dimension to get shape (H,W) instead of (H,W,1)\n # decoded_label = tf.squeeze(decoded_label, axis=[2])\n\n # repeat along the last dimension\n decoded_label = tf.concat([decoded_label, 1 - decoded_label], axis=2)\n ch0, ch1 = tf.split(value=decoded_label, num_or_size_splits=2, axis=2)\n decoded_label = tf.concat(values=[ch1, ch0], axis=2)\n\n # per-channel mean values are taken from:\n # https://github.com/yulequan/melanoma-recognition/blob/master/segmentation/ResNet-50-f8s-skin-train-val.prototxt\n mean = tf.constant([184., 153., 138.],\n dtype=tf.float32, shape=[1, 1, 3], name='img_mean')\n\n # center the image with per-channel RGB mean\n decoded_image = tf.to_float(decoded_image)\n im_centered = decoded_image - mean\n # return (im_centered, decoded_label)\n\n # im_centered = tf.image.per_image_standardization(decoded_image)\n\n imagedict = {'image': im_centered}\n labeldict = {'label': decoded_label}\n\n return im_centered, decoded_label\n\n\ndef preproc_train(sample, target):\n seed = np.random.randint(0, 2 ** 32)\n\n cropsize_img = [480, 480, 3]\n cropsize_label = [480, 480, 2]\n\n image = tf.random_crop(sample, cropsize_img, seed=seed, name='crop_mirror_train_img')\n label = tf.random_crop(target, cropsize_label, seed=seed, name='crop_mirror_train_label')\n\n tf.summary.image('crop_mirror_train_img', image)\n tf.summary.image('crop_mirror_train_label', tf.cast(label, dtype=tf.uint8))\n\n image = tf.image.random_flip_left_right(image, seed=seed)\n label = tf.image.random_flip_left_right(label, seed=seed)\n\n return image, label\n\n\ndef preproc_val(sample, target):\n seed = np.random.randint(0, 2 ** 32)\n\n image = tf.image.resize_image_with_crop_or_pad(sample, 480, 480)\n label = tf.image.resize_image_with_crop_or_pad(target, 480, 480)\n\n image = tf.image.random_flip_left_right(image, seed=seed)\n label = tf.image.random_flip_left_right(label, seed=seed)\n\n return image, label\n\n\ndef my_input_fn_train(filename, batch_size, epochs):\n \"\"\" reads the .tfrecords file,\n process data using parser method,\n shuffles data and returns the next batch.\n\n instantiates a tf.Dataset object and obtains a tf.data.Iterator,\n that throws outOfRangeError when next batch goes out of the given epoch limit.\n more info: https://www.tensorflow.org/api_docs/python/tf/data/Dataset\n \"\"\"\n\n dataset = tf.data.TFRecordDataset([filename])\n augmented = dataset.map(parser\n ).map(\n preproc_train\n ).shuffle(\n buffer_size=1000\n ).batch(\n batch_size\n ).repeat(\n epochs\n )\n\n # this returns the next batch from the parser function\n # the returned tuple is a dictionary for image and a dictionary for labels\n features, labels = augmented.make_one_shot_iterator().get_next()\n return {'image': features}, {'label': labels}\n\n\ndef my_input_fn_val(filename, batch_size, epochs):\n \"\"\" reads the .tfrecords file,\n process data using parser method,\n shuffles data and returns the next batch.\n\n instantiates a tf.Dataset object and obtains a tf.data.Iterator,\n that throws outOfRangeError when next batch goes out of the given epoch limit.\n more info: https://www.tensorflow.org/api_docs/python/tf/data/Dataset\n \"\"\"\n\n dataset = tf.data.TFRecordDataset([filename])\n augmented = dataset.map(parser\n ).map(\n preproc_val\n ).batch(\n batch_size\n ).repeat(\n epochs\n )\n\n # this returns the next batch from the parser function\n # the returned tuple is a dictionary for image and a dictionary for labels\n features, labels = augmented.make_one_shot_iterator().get_next()\n return {'image': features}, {'label': labels}\n\n\ndef get_deconv_filter(f_shape):\n \"\"\"initialize a bilinear interpolation filter with\n given shape.\n\n this filter values are trained and updated in the current computation graph.\n \"\"\"\n width = f_shape[0]\n heigh = f_shape[0]\n f = np.ceil(width / 2.0)\n c = (2 * f - 1 - f % 2) / (2.0 * f)\n bilinear = np.zeros([f_shape[0], f_shape[1]])\n for x in range(width):\n for y in range(heigh):\n value = (1 - abs(x / f - c)) * (1 - abs(y / f - c))\n bilinear[x, y] = value\n weights = np.zeros(f_shape)\n for i in range(f_shape[2]):\n weights[:, :, i, i] = bilinear\n\n init = tf.constant_initializer(value=weights,\n dtype=tf.float32)\n var = tf.get_variable(name=\"up_filter\",\n initializer=init,\n shape=weights.shape,\n regularizer=tf.contrib.layers.l2_regularizer(5e-4))\n return var\n\n\ndef upscore_layer(x, shape, num_classes, name, ksize, stride):\n \"\"\"transposed convolution filter to learn upsampling filter values.\n Given a feature map x, initialize a bilinear interpolation filter with\n given shape to upsample the map based on the given stride.\n\n this filter values are trained and updated in the current computation graph.\n \"\"\"\n strides = [1, stride, stride, 1]\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n in_features = x.get_shape()[3].value\n if shape is None:\n in_shape = tf.shape(x)\n h = ((in_shape[1] - 1) * stride) + 1\n w = ((in_shape[2] - 1) * stride) + 1\n new_shape = [in_shape[0], h, w, num_classes]\n else:\n new_shape = [shape[0], shape[1], shape[2], num_classes]\n\n output_shape = tf.stack(new_shape)\n f_shape = [ksize, ksize, num_classes, in_features]\n\n weights = get_deconv_filter(f_shape)\n\n # grp1 = tf.nn.conv2d_transpose(x[:, :, :, :int(in_features/2)], weights[:, :, 0, :], tf.stack([shape[0], shape[1], shape[2], 1]), strides = strides, padding='SAME')\n # grp2 = tf.nn.conv2d_transpose(x[:, :, :, int(in_features/2):], weights[:, :, 1, :], tf.stack([shape[0], shape[1], shape[2], 1]), strides = strides, padding='SAME')\n\n # deconv = tf.concat(axis=3, values=[grp1, grp2])\n\n deconv = tf.nn.conv2d_transpose(x, weights, output_shape, strides=strides, padding='SAME')\n\n return deconv\n\n\ndef score_layer(x, name, num_classes, stddev=0.001):\n \"\"\"receives a feature map and trains a linear scoring filter Wx+b\n\n this result with a new feature map with a consistent shape to be fused (per-pixel addition)\n with the corresponding upsampling result from the same input feature map x.\n \"\"\"\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE) as scope:\n # get number of input channels\n in_features = x.get_shape()[3].value\n shape = [1, 1, in_features, num_classes]\n w_decay = 5e-4\n # init = tf.truncated_normal_initializer(stddev = stddev)\n init = tf.constant_initializer(0.0)\n weights = tf.get_variable(\"weights\",\n shape=shape,\n initializer=init,\n regularizer=tf.contrib.layers.l2_regularizer(w_decay))\n # collection_name = tf.GraphKeys.REGULARIZATION_LOSSES\n\n # if not tf.get_variable_scope().reuse:\n # weight_decay = tf.multiply(tf.nn.l2_loss(weights), w_decay, name='weight_loss')\n # tf.add_to_collection(collection_name, weight_decay)\n\n conv = tf.nn.conv2d(x, weights, [1, 1, 1, 1], padding='SAME')\n\n # Apply bias\n initializer = tf.constant_initializer(0.0)\n conv_biases = tf.get_variable(name='biases', shape=[num_classes], initializer=initializer)\n bias = tf.nn.bias_add(conv, conv_biases)\n\n return bias\n\n\ndef resnet_v1_50_fcn(features, labels, mode, params):\n num_classes = params['num_classes']\n\n # output_stride denotes the rate of downsampling in the resnet network,i.e.,\n # 32 results with a feature map with a 1/32 downsampling rate such as,\n # (224,224) input is decreased to (8,8) resolution.\n # Then, the rest of the code starts upsampling from this output, until reaching\n # the input resolution.\n with slim.arg_scope(resnet_v1.resnet_arg_scope(weight_decay=0.0005)):\n net, end_points = resnet_v1.resnet_v1_50(features['image'],\n global_pool=False,\n output_stride=32)\n\n scale5 = net\n scale4 = end_points['resnet_v1_50/block3/unit_5/bottleneck_v1']\n scale3 = end_points['resnet_v1_50/block2/unit_3/bottleneck_v1']\n scale2 = end_points['resnet_v1_50/block1/unit_2/bottleneck_v1']\n input_x = features['image']\n\n with tf.variable_scope('scale_fcn'):\n\n score_scale5 = score_layer(scale5, \"score_scale5\", num_classes=num_classes)\n upscore2 = upscore_layer(score_scale5, shape=tf.shape(scale4), num_classes=num_classes, name=\"upscore2\",\n ksize=4, stride=2)\n\n score_scale4 = score_layer(scale4, \"score_scale4\", num_classes=num_classes)\n fuse_scale4 = tf.add(upscore2, score_scale4)\n\n upscore4 = upscore_layer(fuse_scale4, shape=tf.shape(scale3), num_classes=num_classes, name=\"upscore4\", ksize=4,\n stride=2)\n score_scale3 = score_layer(scale3, \"score_scale3\", num_classes=num_classes)\n fuse_scale3 = tf.add(upscore4, score_scale3)\n\n upscore32 = upscore_layer(fuse_scale3, shape=tf.shape(input_x), num_classes=num_classes, name=\"upscore32\",\n ksize=16, stride=8)\n\n pred_up = tf.argmax(upscore32, axis=3) # shape: [4 480 480]\n pred = tf.expand_dims(pred_up, dim=3, name='pred') # shape: [4 480 480 1]\n\n # sess = tf.Session()\n # sess.run(tf.global_variables_initializer())\n # sess.run(tf.local_variables_initializer())\n # print(sess.run(tf.shape(scale5)))\n # print(sess.run(tf.shape(upscore32)))\n # print(sess.run(tf.shape(pred_up)))\n # print(sess.run(tf.shape(pred)))\n # sess.close()\n\n tf.summary.image('ground-truth', tf.expand_dims(255.0 * tf.to_float(tf.argmax(labels['label'], axis=3)), axis=3))\n tf.summary.image('prediction', 255.0 * tf.to_float(pred))\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode, predictions=pred_up)\n\n # Using tf.losses, any loss is added to the tf.GraphKeys.LOSSES collection\n # We can then call the total loss easily\n tf.losses.softmax_cross_entropy(onehot_labels=labels['label'],\n logits=upscore32)\n loss = tf.losses.get_total_loss()\n tf.summary.scalar('loss', loss)\n\n ## Compute evaluation metrics.\n # compute mean intersection over union, which corresponds to JA metric in the paper.\n iou_op, update_op = tf.metrics.mean_iou(\n labels=tf.reshape(tf.argmax(labels['label'], axis=3), [-1]),\n num_classes=2,\n predictions=tf.to_int32(tf.reshape(pred_up, [-1])), name=\"acc_op\")\n\n with tf.control_dependencies([update_op]):\n iou = tf.identity(iou_op)\n\n tf.summary.scalar('iou', iou)\n\n if mode == tf.estimator.ModeKeys.EVAL:\n return tf.estimator.EstimatorSpec(\n mode, loss=loss, eval_metric_ops={'iou': (iou_op, update_op)})\n\n # Create training op.\n assert mode == tf.estimator.ModeKeys.TRAIN\n\n global_step = tf.train.get_or_create_global_step()\n\n training_loss = tf.identity(loss, name='training_loss')\n\n # set initial learning rate and\n # scale it by 0.1 in every 3000 steps\n # as stated in https://github.com/yulequan/melanoma-recognition/blob/master/segmentation/solver.prototxt\n boundaries = [i * params['decay_steps'] for i in\n range(1, int(np.ceil(params['max_steps'] / params['decay_steps'])))]\n boundaries[-1] = params['max_steps']\n initial = [params['initial_learning_rate']]\n values = initial + [params['initial_learning_rate'] * (0.1 ** i) for i in range(1, len(boundaries) + 1)]\n lr = tf.train.piecewise_constant(global_step, boundaries, values)\n # lr = tf.constant(params['initial_learning_rate'])\n\n tf.summary.scalar('lr', lr)\n\n # Variables that affect learning rate\n var_resnet_batchnorm = [var for var in tf.trainable_variables()\n if ('conv1/BatchNorm' in var.name or\n 'conv2/BatchNorm' in var.name or\n 'conv3/BatchNorm' in var.name or\n 'shortcut/BatchNorm' in var.name)]\n\n var_upscale = [var for var in tf.trainable_variables()\n if 'score' in var.name and 'bias' not in var.name]\n\n var_score_bias = [var for var in tf.trainable_variables()\n if 'score' in var.name and 'bias' in var.name]\n\n var_rest = [var for var in tf.trainable_variables()\n if var not in var_resnet_batchnorm + var_upscale + var_score_bias]\n\n # this is as stated in the paper and prototxt file,\n # https://github.com/yulequan/melanoma-recognition/blob/master/segmentation/ResNet-50-f8s-skin-train-val.prototxt\n # batchnorm variables placed just after each convolutional layer in each resnet block, are not updated.\n # so we set zero learning for these variables\n # opt1 = tf.train.MomentumOptimizer(0, 0.9)\n\n # this is also due to the prototxt file and the paper,\n # scoring and upsampling filters receive 0.1 * learning rate\n # https://github.com/yulequan/melanoma-recognition/blob/master/segmentation/ResNet-50-f8s-skin-train-val.prototxt\n opt_upscale = tf.train.MomentumOptimizer(lr * 0.1, 0.9)\n\n # rest of the variables receive the current learning rate\n opt_scorebias = tf.train.MomentumOptimizer(lr * 0.2, 0.9)\n\n # rest of the variables receive the current learning rate\n opt_rest = tf.train.MomentumOptimizer(lr, 0.9)\n\n # gradient op: obtain the gradients with loss and given variables\n grads = tf.gradients(loss, var_upscale + var_score_bias + var_rest)\n\n # grads for the first set of variables, currently has no effect due to zero learning rate.\n # grads1 = grads[:len(var_resnet_batchnorm)]\n\n # grads for scoring and upsampling filters. Will get updated based on 0.1*learning_rate\n grads_upscale = grads[:len(var_upscale)]\n\n # for i,val in enumerate(grads2):\n # tf.summary.histogram('upscale_grads_{}'.format(i), val)\n\n # grads for bias variables\n grads_scorebias = grads[len(var_upscale):len(var_upscale) + len(var_score_bias)]\n\n # grads for the rest of variables\n grads_rest = grads[len(var_upscale) + len(var_score_bias):]\n\n # train_op1 = opt1.apply_gradients(zip(grads1, var_resnet_batchnorm), global_step=global_step)\n train_op_upscale = opt_upscale.apply_gradients(zip(grads_upscale, var_upscale), global_step=global_step)\n train_op_scorebias = opt_scorebias.apply_gradients(zip(grads_scorebias, var_score_bias), global_step=global_step)\n train_op_rest = opt_rest.apply_gradients(zip(grads_rest, var_rest), global_step=global_step)\n\n train_op = tf.group(train_op_upscale, train_op_scorebias, train_op_rest)\n\n return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)\n\n\nclass MyLoggingAverageLossHook(tf.train.LoggingTensorHook):\n def __init__(self, tensors, every_n_iter):\n super().__init__(tensors=tensors, every_n_iter=every_n_iter)\n\n # keep track of previous losses\n self.losses = []\n self.every_n_iter = every_n_iter\n\n def after_run(self, run_context, run_values):\n _ = run_context\n\n self._tag = ''\n\n # please put only one loss tensor\n for tag in self._tag_order:\n self.losses.append(run_values.results[tag])\n self._tag = tag\n\n if self._should_trigger:\n self._log_tensors(run_values.results)\n\n self._iter_count += 1\n\n def _log_tensors(self, tensor_values):\n\n if self._iter_count % self.every_n_iter == 0:\n original = np.get_printoptions()\n np.set_printoptions(suppress=True)\n logging.info(\"%s = %s\" % (self._tag, np.mean(self.losses)))\n np.set_printoptions(**original)\n self.losses = []\n\n\ntf.reset_default_graph()\n\n# filename_train = 'melanoma_train_224.tfrecords'\n# filename_val = 'melanoma_val_224.tfrecords'\nfilename_train = '/valohai/inputs/training-data/melanoma_train_v8.tfrecords'\nfilename_val = '/valohai/inputs/validation-data/melanoma_val_v8.tfrecords'\nsave_model_dir = '/valohai/outputs'\nrestore_ckpt_path = '/valohai/inputs/pretrained/resnet_v1_50.ckpt'\nsave_checkpoints_steps = 3000\nparams = {'initial_learning_rate': 1e-3,\n 'num_classes': 2,\n 'decay_steps': 3000,\n 'max_steps': 100000\n }\n\n# with tf.Session() as sess:\n\n# exclude_restore = [var.name for var in tf.global_variables() if not ('logits' in var.name or 'scale_fcn' in var.name or 'Momentum' in var.name) ]\n# variables_to_restore = slim.get_variables_to_restore(exclude=exclude_restore)\n# tf.train.init_from_checkpoint(restore_ckpt_path,\n# {v.name.split(':')[0]: v for v in variables_to_restore})\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nrun_config = tf.estimator.RunConfig(save_checkpoints_steps=save_checkpoints_steps)\n\navg_train_loss_log = {\"average_training_loss\": \"training_loss\"}\n\n# this custom logging hook is created to average last every_n_iter loss values\n# and display the result as an INFO\nmy_averageloss_logging_hook = MyLoggingAverageLossHook(\n tensors=avg_train_loss_log,\n every_n_iter=10)\n\nws = tf.estimator.WarmStartSettings(ckpt_to_initialize_from=restore_ckpt_path,\n vars_to_warm_start='.*resnet_v1.*')\n\nestimator = tf.estimator.Estimator(\n model_fn=resnet_v1_50_fcn,\n model_dir=save_model_dir,\n params=params,\n config=run_config,\n warm_start_from=ws\n)\n\nprint(estimator.eval_dir())\n\nprint(os.listdir(save_model_dir))\n\n# train_spec = tf.estimator.TrainSpec(input_fn=lambda:my_input_fn(filename_train, batch_size=4, epochs=500),\n# max_steps=params['max_steps'],\n# hooks=[my_averageloss_logging_hook])\n\ntrain_spec = tf.estimator.TrainSpec(input_fn=lambda: my_input_fn_train(filename_train, batch_size=4, epochs=500),\n max_steps=params['max_steps'])\n\neval_spec = tf.estimator.EvalSpec(input_fn=lambda: my_input_fn_val(filename_val, batch_size=4, epochs=1),\n steps=None, throttle_secs=50)\n\ntf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n\n\ndef evaluate(filename_test, save_model_dir):\n tf.reset_default_graph()\n\n # filename_test = '/valohai/inputs/test-data/melanoma_test_v8.tfrecords'\n\n # save_model_dir='/valohai/outputs'\n params = {'initial_learning_rate': 1e-3,\n 'num_classes': 2,\n 'decay_steps': 3000,\n 'max_steps': 100000\n }\n\n tf.logging.set_verbosity(tf.logging.INFO)\n\n estimator = tf.estimator.Estimator(\n model_fn=resnet_v1_50_fcn,\n model_dir=save_model_dir,\n params=params)\n\n estimator.evaluate(input_fn=lambda: my_input_fn_val(filename_test, batch_size=4, epochs=1))\n","sub_path":"tf_melanoma_segmentation.py","file_name":"tf_melanoma_segmentation.py","file_ext":"py","file_size_in_byte":20678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"198727232","text":"# ==================================================================================================================\n# utilities.py\n# ==================================================================================================================\n\nfrom pyspark.sql import DataFrame as SparkDataFrame\nfrom pyspark.sql import functions as f\nfrom pyspark.sql import SparkSession\nfrom krbticket import setTicket\nfrom pandas import DataFrame as PandasDataFrame\nfrom pandas import Series as PandasSeries\nimport numpy as np\n\n# Mark: Create Spark session\n# ------------------------------------------------------------------------------------------------------------------\n\ndef createSparkSession (name: str, cores: int = 4, memory: int = 6, instances: int = 10, dynamicAllocation: bool = False) -> SparkSession:\n setTicket()\n\n session = (SparkSession\n .builder\n .config(\"spark.executor.cores\", str(cores))\n .config(\"spark.executor.memory\", str(memory) + \"G\")\n .config(\"spark.executor.instances\", str(instances))\n .config(\"spark.dynamicAllocation.enabled\", str(dynamicAllocation).lower())\n .appName(name)\n .getOrCreate()\n )\n\n return session\n\n# Mark: Close Spark session\n# ------------------------------------------------------------------------------------------------------------------\n\ndef closeSparkSession (session: SparkSession):\n\n session.stop()\n\n# Mark: Inspect function\n# ------------------------------------------------------------------------------------------------------------------\n\ndef inspect (feature: str, inDataSet: SparkDataFrame, withIdVariable: str):\n\n summary = inDataSet.groupby(feature).agg(f.count(withIdVariable).alias('count'))\n summary = summary.withColumn('percentage', f.floor(summary['count']/inDataSet.count()*10000)/100)\n\n print(\"Summary of : \" + feature + \"\\n\")\n\n summary.show()\n\n# Mark: Get modalities function\n# ------------------------------------------------------------------------------------------------------------------\n\ndef getModalities (ofDiscreteVariable: str, inDataSet: SparkDataFrame) -> []:\n\n # Initialize the modality array\n\n modalities = []\n\n groupedTable = inDataSet.groupby(ofDiscreteVariable).agg(f.count(ofDiscreteVariable).alias('count')).sort(f.col(ofDiscreteVariable))\n array = np.array(groupedTable.collect())\n\n for index, row in enumerate(array):\n modalities.append((index,row[0]))\n\n return modalities\n\n# Mark: Create dummies function\n# ------------------------------------------------------------------------------------------------------------------\n\ndef createDummies (forVariable: str, inDataSet: SparkDataFrame, keepOriginal: bool = True) -> SparkDataFrame:\n\n modalities = getModalities(ofDiscreteVariable = forVariable, inDataSet = inDataSet)\n\n dataSet = inDataSet\n\n for modality in modalities[:-1] :\n dataSet = dataSet.withColumn(forVariable + \"_\" + str(modality[0]), f.when(f.col(forVariable) == f.lit(modality[1]), 1).otherwise(0))\n\n if keepOriginal == False:\n dataSet = dataSet.drop(forVariable)\n\n return dataSet\n\n# Mark: Shape function\n# ------------------------------------------------------------------------------------------------------------------\n\ndef shape (ofDataFrame: SparkDataFrame) -> (int,int):\n return (ofDataFrame.count(), len(ofDataFrame.columns))\n\n# Mark: Lift\n# ------------------------------------------------------------------------------------------------------------------\n\ndef lift (dataSet: PandasDataFrame, actuals: str, probability: str, precision: int = 20) -> PandasDataFrame:\n\n summary = cumulativeResponse(dataSet = dataSet, actuals = actuals, probability = probability, precision = precision)\n\n summary[\"Lift\"] = summary[\"Cumulative response\"] / Series(summary[\"Average response\"]).max()\n summary[\"Base\"] = summary[\"Average response\"] / Series(summary[\"Average response\"]).max()\n\n return summary[[\"Quantile\",\"Lift\",\"Base\"]]\n\n# Mark: Cumulative response\n# ------------------------------------------------------------------------------------------------------------------\n\ndef cumulativeResponse (dataSet: PandasDataFrame, actuals: str, probability: str, precision: int = 20) -> PandasDataFrame:\n\n internalSet = equifrequentBinning (dataSet = dataSet[[actuals, probability]], byColumn = probability, into = precision)\n\n internalSet[\"Quantile\"] = internalSet[probability + \"_bin\"] / precision\n internalSet[\"obs\"] = 1\n\n summary = internalSet[[\"Quantile\", actuals, \"obs\"]].groupby([\"Quantile\"], as_index = False).sum().sort_values(by = \"Quantile\", ascending = False)\n\n summary[\"cumulativeTarget\"] = Series(summary[actuals]).cumsum(skipna = False)\n summary[\"cumulativeAll\"] = Series(summary[\"obs\"]).cumsum(skipna = False)\n summary[\"Cumulative response\"] = summary[\"cumulativeTarget\"] / summary[\"cumulativeAll\"]\n summary[\"Average response\"] = Series(summary[\"cumulativeTarget\"]).max() / Series(summary[\"cumulativeAll\"]).max()\n\n return summary[[\"Quantile\",\"Cumulative response\",\"Average response\"]]\n\n# Mark: Cumulative gains\n# ------------------------------------------------------------------------------------------------------------------\n\ndef cumulativeGains (dataSet: PandasDataFrame, actuals: str, probability: str, precision: int = 20) -> PandasDataFrame:\n\n internalSet = equifrequentBinning (dataSet = dataSet[[actuals, probability]], byColumn = probability, into = precision)\n\n internalSet[\"Quantile\"] = internalSet[probability + \"_bin\"] / precision\n internalSet[\"obs\"] = 1\n\n summary = internalSet[[\"Quantile\", actuals, \"obs\"]].groupby([\"Quantile\"], as_index = False).sum().sort_values(by = \"Quantile\", ascending = False)\n\n summary[\"cumulativeTarget\"] = Series(summary[actuals]).cumsum(skipna = False)\n summary[\"cumulativeAll\"] = Series(summary[\"obs\"]).cumsum(skipna = False)\n summary[\"Cumulative gains\"] = summary[\"cumulativeTarget\"] / Series(summary[\"cumulativeTarget\"]).max()\n summary[\"Base\"] = summary[\"Quantile\"]\n\n return summary[[\"Quantile\",\"Cumulative gains\",\"Base\"]]\n\n# Mark: Equifrequent binning\n# ------------------------------------------------------------------------------------------------------------------\n\nclass DataFrame (PandasDataFrame):\n\n def equifrequentBinning (column: str, into: int):\n\n for i in range(into):\n quanitles.append(1 / into * (i))\n\n quantile = self.quantile(quanitles, axis = 0)[column].to_dict()\n\n self[column + \"_bin\"] = 0\n\n for q in quantile:\n upperBound = quantile[q]\n self.loc[self[column] >= upperBound, column + \"_bin\"] = int(q * into + 1)\n\n# Mark: Create incidence table\n# ------------------------------------------------------------------------------------------------------------------\n \ndef createIncidenceTable (self, dataSet: PandasDataFrame, column: str, target: str, saveAs: str) -> PandasDataFrame:\n\n outputSet = DataFrame(dataSet[[column, target]])\n\n outputSet[column] = outputSet[column].fillna(\"missing\")\n\n outputSet = outputSet.groupby([column], as_index = False).mean().sort_values(by = column, ascending = True)\n\n outputSet.to_csv(saveAs, index = False)\n\n return outputSet\n \n# Mark: Replace by incidence\n# ------------------------------------------------------------------------------------------------------------------\n \ndef replaceByIncidence (self, dataSet: PandasDataFrame, column: str, target: str, schemeLocation: str) -> PandasDataFrame:\n \n incidenceTable = pandas.read_csv(schemeLocation)\n \n modalities = dict(zip(incidenceTable[column].astype(str), incidenceTable[target]))\n \n dataSet[column] = dataSet[column].fillna(\"missing\").astype(str)\n \n for modality in modalities:\n incidence = modalities[modality]\n dataSet.loc[ (dataSet[column] == modality), column + \"_incidence\"] = incidence\n \n return dataSet\n\n \n# Mark: YAML to HDFS\n# ------------------------------------------------------------------------------------------------------------------\n \ndef yaml_to_hdfs (yaml_path: str, hdfs_path: str):\n\n with open(yaml_path, \"r\") as file_handle:\n ctypes = yaml.safe_load(file_handle)\n \n df_ctypes = spark.createDataFrame([(key, value) for key, value in ctypes.items()], [\"name\", \"type\"])\n df_ctypes.write.parquet(hdfs_path, mode=\"overwrite\")","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":8603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"598768872","text":"'''5/12/2018 As gill_development.py but for data from JRA-55 and CMAP precip\n'''\n\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\nimport sh\nfrom windspharm.xarray import VectorWind\nfrom data_handling_updates import model_constants as mc\n\ndef pentad_mean_climatology(data, years): # Function to get pentad of year\n pentad_years = np.array([])\n for year in years:\n data_year = data.sel(time=str(year))\n if len(data_year.time)==366:\n pentad = np.repeat(np.arange(1., 74.), 5)\n pentad = np.insert(pentad, 10, 2) \n else:\n pentad = np.repeat(np.arange(1., 74.), 5) \n pentad_years = np.concatenate((pentad_years, pentad))\n \n data = data.assign_coords(pentad = ('time', pentad_years))\n \n data_pentads = data.groupby('pentad').mean(('time'))\n \n return data_pentads\n \ndef plot_gill_dev(lev=85000, qscale=100., windtype='full', ref_arrow=5, mse=False, video=False):\n \n if mse:\n data_t = xr.open_dataset('/scratch/rg419/obs_and_reanalysis/jra_temp_daily_850.nc', chunks={'time': 30}); data_t = data_t['var11'].load().loc['1979-01':'2016-12']\n data_q = xr.open_dataset('/scratch/rg419/obs_and_reanalysis/jra_sphum_daily_850.nc', chunks={'time': 30}); data_q = data_q['var51'].load().loc['1979-01':'2016-12']\n data_h = xr.open_dataset('/scratch/rg419/obs_and_reanalysis/jra_height_daily_850.nc', chunks={'time': 30}); data_h = data_h['var7'].load().loc['1979-01':'2016-12']\n data_t = pentad_mean_climatology(data_t, np.arange(1979,2017))\n data_q = pentad_mean_climatology(data_q, np.arange(1979,2017))\n data_h = pentad_mean_climatology(data_h, np.arange(1979,2017))\n data_mse = (mc.cp_air * data_t + mc.L * data_q + 9.81 * data_h)/1000.\n else:\n data_precip = xr.open_dataset('/scratch/rg419/obs_and_reanalysis/CMAP_precip.pentad.mean.nc', chunks={'time': 30})\n data_precip = data_precip.load()\n data_precip.coords['pentad'] = (('time'), np.tile(np.arange(1,74),38))\n data_precip = data_precip.groupby('pentad').mean('time')\n \n if windtype is not 'none': \n data_u = xr.open_dataset('/scratch/rg419/obs_and_reanalysis/jra_ucomp_daily_850.nc', chunks={'time': 30}); data_u = data_u['var33'].load().loc['1979-01':'2016-12']\n data_v_temp = xr.open_dataset('/scratch/rg419/obs_and_reanalysis/jra_vcomp_daily_850.nc', chunks={'time': 30}); data_v_temp = data_v_temp['var34'].load().loc['1979-01':'2016-12']\n # v has different time coord to u, presumably due to how Stephen has downloaded/averaged. I think the two are equivalent, so just substitute the time dimension into v\n data_v = xr.DataArray(data_v_temp.sel(lev=85000.).values, coords={'time': data_u.time, 'lat': data_u.lat, 'lon': data_u.lon}, dims=('time','lat','lon'))\n data_u = pentad_mean_climatology(data_u, np.arange(1979,2017))\n data_v = pentad_mean_climatology(data_v, np.arange(1979,2017))\n data_u = data_u - data_u.mean('lon')\n data_v = data_v - data_v.mean('lon')\n if windtype is not 'full':\n # Get rotational and divergent components of the flow\n w = VectorWind(data_u, data_v)\n streamfun, vel_pot = w.sfvp()\n uchi, vchi, upsi, vpsi = w.helmholtz()\n #print(uchi.lat)\n #print(data_u.lat)\n uchi_zanom = (uchi - uchi.mean('lon')).sortby('lat')\n vchi_zanom = (vchi - vchi.mean('lon')).sortby('lat')\n upsi_zanom = (upsi - upsi.mean('lon')).sortby('lat')\n vpsi_zanom = (vpsi - vpsi.mean('lon')).sortby('lat')\n \n data_slp = xr.open_dataset('/scratch/rg419/obs_and_reanalysis/jra_slp_daily.nc', chunks={'time': 30}); data_slp = data_slp['var2'].load().loc['1979-01':'2016-12']\n data_slp = data_slp.load()\n data_slp = pentad_mean_climatology(data_slp/100., np.arange(1979,2017))\n data_slp = data_slp - data_slp.mean('lon')\n print('files opened')\n \n \n rcParams['figure.figsize'] = 10, 5\n rcParams['font.size'] = 14\n \n for i in range(73): \n fig, ax1 = plt.subplots()\n title = 'Pentad ' + str(int(data_u.pentad[i]))\n \n if mse:\n f1 = data_mse.sel(pentad=i+1, lev=85000.).plot.contourf(x='lon', y='lat', ax=ax1, add_labels=False, add_colorbar=False, extend='both', cmap='Blues', zorder=1, levels = np.arange(290.,341.,5.))\n else:\n f1 = data_precip.precip[i,:,:].plot.contourf(x='lon', y='lat', ax=ax1, levels = np.arange(2.,15.,2.), add_labels=False, add_colorbar=False, extend='both', cmap='Blues', zorder=1)\n\n ax1.contour(data_slp.lon, data_slp.lat, data_slp[i,:,:], levels = np.arange(0.,16.,3.), colors='0.4', alpha=0.5, zorder=2)\n ax1.contour(data_slp.lon, data_slp.lat, data_slp[i,:,:], levels = np.arange(-15.,0.,3.), colors='0.4', alpha=0.5, linestyle='--', zorder=2)\n if windtype=='div':\n b = ax1.quiver(uchi_zanom.lon[::6], uchi_zanom.lat[::3], uchi_zanom[i,::3,::6], vchi_zanom[i,::3,::6], scale=qscale, angles='xy', width=0.005, headwidth=3., headlength=5., zorder=3)\n ax1.quiverkey(b, 5.,65., ref_arrow, str(ref_arrow) + ' m/s', fontproperties={'weight': 'bold', 'size': 10}, color='k', labelcolor='k', labelsep=0.03, zorder=10)\n elif windtype=='rot':\n b = ax1.quiver(upsi_zanom.lon[::6], upsi_zanom.lat[::3], upsi_zanom[i,::3,::6], vpsi_zanom[i,::3,::6], scale=qscale, angles='xy', width=0.005, headwidth=3., headlength=5., zorder=3)\n ax1.quiverkey(b, 5.,65., ref_arrow, str(ref_arrow) + ' m/s', fontproperties={'weight': 'bold', 'size': 10}, color='k', labelcolor='k', labelsep=0.03, zorder=10)\n elif windtype=='full':\n b = ax1.quiver(data_u.lon[::6], data_u.lat[::3], data_u[i,::3,::6], data_v[i,::3,::6], scale=qscale, angles='xy', width=0.005, headwidth=3., headlength=5., zorder=3)\n ax1.quiverkey(b, 5.,65., ref_arrow, str(ref_arrow) + ' m/s', fontproperties={'weight': 'bold', 'size': 10}, color='k', labelcolor='k', labelsep=0.03, zorder=10)\n else:\n windtype='none'\n ax1.grid(True,linestyle=':')\n ax1.set_ylim(-60.,60.)\n ax1.set_yticks(np.arange(-60.,61.,30.))\n ax1.set_xticks(np.arange(0.,361.,90.))\n ax1.set_title(title)\n land_mask = '/scratch/rg419/python_scripts/land_era/ERA-I_Invariant_0125.nc'\n land = xr.open_dataset(land_mask)\n land.lsm[0,:,:].plot.contour(ax=ax1, x='longitude', y='latitude', levels=np.arange(-1.,2.,1.), add_labels=False, colors='k')\n \n ax1.set_ylabel('Latitude')\n ax1.set_xlabel('Longitude')\n \n plt.subplots_adjust(left=0.1, right=0.97, top=0.93, bottom=0.05, hspace=0.25, wspace=0.2)\n cb1=fig.colorbar(f1, ax=ax1, use_gridspec=True, orientation = 'horizontal',fraction=0.05, pad=0.15, aspect=60, shrink=0.5)\n \n windtypestr=''; msestr=''; vidstr=''\n if windtype != 'full':\n windtypestr = '_' + windtype\n if mse:\n msestr = '_mse'\n if video:\n vidstr='video/'\n \n plot_dir = '/scratch/rg419/plots/zonal_asym_runs/gill_development/jra/' + vidstr + windtype + msestr + '/' \n mkdir = sh.mkdir.bake('-p')\n mkdir(plot_dir)\n \n if video:\n plt.savefig(plot_dir + 'wind_and_slp_zanom_' + str(int(data_u.pentad[i])) + windtypestr + msestr + '.png', format='png')\n else:\n plt.savefig(plot_dir + 'wind_and_slp_zanom_' + str(int(data_u.pentad[i])) + windtypestr + msestr + '.pdf', format='pdf')\n plt.close()\n \n\nimport subprocess \ndef make_video(filepattern, output, startno=20):\n \n command = 'ffmpeg -framerate 5 -y -start_number '+str(startno)+' -i ' + filepattern + ' -vframes 45 -c:v libx264 -r 6 -pix_fmt yuv420p -vf scale=3200:-2 ' + output \n subprocess.call([command], shell=True)\n\nif __name__ == \"__main__\":\n \n plot_gill_dev(mse=True)\n #plot_gill_dev(windtype='none', video=True)\n \n #plot_gill_dev(windtype='rot')\n #plot_gill_dev(windtype='div')\n \n \n #make_video('/scratch/rg419/plots/zonal_asym_runs/gill_development/jra/video/none/wind_and_slp_zanom_%02d_none.png', \n # '/scratch/rg419/plots/zonal_asym_runs/gill_development/jra/video/none/precip_and_slp_anom_sh.mp4', startno=56)\n \n \n ","sub_path":"zonal_asym_runs/monsoon_development_obs_pentad.py","file_name":"monsoon_development_obs_pentad.py","file_ext":"py","file_size_in_byte":8498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"634884052","text":"from pathlib import Path\n\nimport yaml\nimport os\n\nRESULTS_PATH = Path(__file__).resolve().parent.parent / \"results\"\nPROFILING_RESULTS_PATH = RESULTS_PATH / \"profiling\"\nBENCHMARKING_RESULTS_PATH = RESULTS_PATH / \"benchmarking\"\nTIME_REPORT_PATH = RESULTS_PATH / \"time_report.csv\"\nENV_INFO_PATH = RESULTS_PATH / \"env_info.txt\"\nDEFAULT_CONFIG_FILE_PATH = \"config.yml\"\nBASE_LIB = \"sklearn\"\nBENCHMARK_SECONDS_BUDGET = 30\nBENCHMARK_MAX_ITER = 10\nSPEEDUP_COL = \"mean\"\nSTDEV_SPEEDUP_COL = \"stdev\"\nPLOT_HEIGHT_IN_PX = 350\nREPORTING_FONT_SIZE = 12\nDEFAULT_COMPARE_COLS = [SPEEDUP_COL, STDEV_SPEEDUP_COL]\n\n\ndef get_full_config(config_file_path=None):\n if config_file_path is None:\n config_file_path = os.environ.get(\"DEFAULT_CONFIG_FILE_PATH\")\n with open(config_file_path, \"r\") as config_file:\n config = yaml.full_load(config_file)\n return config\n\n\ndef prepare_params(params):\n from sklearn_benchmarks.utils.misc import is_scientific_notation\n\n if \"hyperparameters\" in params:\n for key, value in params[\"hyperparameters\"].items():\n if not isinstance(value, list):\n continue\n for i, el in enumerate(value):\n if is_scientific_notation(el):\n if \"-\" in el:\n params[\"hyperparameters\"][key][i] = float(el)\n else:\n params[\"hyperparameters\"][key][i] = int(float(el))\n\n if \"datasets\" in params:\n for dataset in params[\"datasets\"]:\n dataset[\"n_features\"] = int(float(dataset[\"n_features\"]))\n for i, ns_train in enumerate(dataset[\"n_samples_train\"]):\n dataset[\"n_samples_train\"][i] = int(float(ns_train))\n for i, ns_test in enumerate(dataset[\"n_samples_test\"]):\n dataset[\"n_samples_test\"][i] = int(float(ns_test))\n\n return params\n","sub_path":"sklearn_benchmarks/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"165642048","text":"alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',\r\n 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\r\n# lpha = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25]\r\nzoac = input() # DAIN\r\npointer = 0\r\ncounter = 0\r\nfor i in zoac:\r\n index = alpha.index(i) # 탐색할 값의 인덱스\r\n forward = 0 # 정방향 탐색 가중치\r\n reverse = 0 # 역방향 탐색 가중치\r\n # 정방향 탐색\r\n if index < pointer:\r\n forward = 26 - (pointer - index)\r\n else:\r\n forward = index - pointer\r\n \r\n if index > pointer:\r\n reverse = 26 - (index - pointer)\r\n else:\r\n reverse = pointer - index\r\n\r\n counter += forward if forward <= reverse else reverse\r\n pointer = index\r\n\r\nprint(counter)\r\n","sub_path":"Jan-1/assignment/KangDain-ZOAC2.py","file_name":"KangDain-ZOAC2.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"146215601","text":"#!/usr/bin/env python\n\n# This file find the best model for each species\n# The indices including:\n# 1. GDD (sum(max(T - 5,0)))\n# 2. GDD + CD (GDD - (a + b * exp(-c * CD))), a,b,c is 138.2, 637.2, 0.01 (Jeong et al. 2012)\n# 3. exp(T_avg)\n\n# we use a naive way to calculate the best threshold\n# 1. back-calculate the threshold for each year\n# 2. find the std of each year, search 3 times the range of the std, find the\n# best threshold\n\n\n# import modules\nimport h5py\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime,timedelta\nimport pdb\n\n\n\ntmp_fn = '../Data/hf_temp_1990_2014_daily.csv'\nsp_phen_fn = '../Data/hf003-06-mean-spp.csv'\nyear_array = np.arange(1900,2014+1)\n\n# how to organize the final data?\nfinal_cols = ['Year','BB_DOY','BB_DOY_STD'] # SP will be added at last...\nidx_shift = len(final_cols)\n\nmetric_names = ['GDD_5','GDD_0','exp_avg']\nCD_a,CD_b,CD_c = 138.2,637.2,0.01 # parameters for CD calculations\nexp_a = 0.693 / 10. # equivalent to Q10 = 2.\nT_ref = 25\n\n\nfor i, name in enumerate(metric_names):\n final_cols += [name,'{:s}_margin_before'.format(name),'{:s}_margin_after'.format(name)]\n\n# metric_margin means the (metric 7 days before the BB date + metric 7 days\n# after the BB date) / 2 - metric at the BB date\n\n# read the species phenology_data\nsp_phen_df = pd.read_csv(sp_phen_fn)\n\nfinal_data = np.zeros((sp_phen_df.shape[0],len(final_cols)))\n\n# read the temperature data\ntmp_df = pd.read_csv(tmp_fn)\ntmp_years = tmp_df['Year'].values.astype(float)\n\n# loop over each sp_phen record and calculate the corresponding metrics\nfor irec in np.arange(sp_phen_df.shape[0]):\n print(irec)\n # first read year and BB_DOY\n year = sp_phen_df['year'].values[irec]\n bb_doy = sp_phen_df['bb.jd'].values[irec]\n bb_doy_std = sp_phen_df['sd.bb.jd'].values[irec]\n final_data[irec,0] = year\n final_data[irec,1] = bb_doy\n final_data[irec,2] = bb_doy_std\n\n if np.isnan(bb_doy): continue\n\n bb_doy = int(bb_doy)\n # get temperature of the specific year\n T_avg = tmp_df['T_avg'].values[tmp_years == year].astype(float)\n T_max = tmp_df['T_max'].values[tmp_years == year].astype(float)\n T_min = tmp_df['T_min'].values[tmp_years == year].astype(float)\n\n # calculate the metrics\n for im, mname in enumerate(metric_names):\n if mname == 'GDD_5':\n GD = (T_avg - 5)\n GD[GD < 0] = 0.\n metric_data = np.cumsum(GD)\n elif mname == 'GDD_0':\n GD = (T_avg - 0)\n GD[GD < 0] = 0.\n metric_data = np.cumsum(GD)\n elif mname == 'GDD_CD':\n GD = (T_avg - 5)\n GD[GD < 0] = 0.\n NCD = np.cumsum(T_avg < 5.)\n metric_data = GD - (CD_a + CD_b * np.exp(-CD_c * NCD))\n elif mname == 'exp_avg':\n metric_data = np.cumsum(np.exp(exp_a * (T_avg - T_ref)))\n\n # now calculate the metric at the bb_doy and the margins\n col_idx = np.arange(im*3+idx_shift,(im+1)*3+idx_shift).astype(int)\n final_data[irec,col_idx] = [metric_data[bb_doy-1],\n metric_data[bb_doy-1] - metric_data[bb_doy-8],\n metric_data[bb_doy+6] - metric_data[bb_doy-1],\n ]\n\n# save the data\nfinal_df = pd.DataFrame(final_data,columns=final_cols)\nfinal_df['SP'] = sp_phen_df['species'].values\n\n# re-order the dataframe\nfinal_cols = ['SP'] + final_cols\nfinal_df = final_df[final_cols]\n\nfinal_df.to_csv('../Data/hf_sp_metrics_1990_2014.csv')\n\n\n\n# calculate the threshold and statistical fitness of the phenology models\nstat_cols = ['SP','Model','AIC','R2','RMSE','Threshold']\nsp_list = np.unique(final_df['SP'].values)\n\nstat_data = {\n 'SP' : [],\n 'Model' : [],\n 'AIC' : [],\n 'R2' : [],\n 'RMSE' : [],\n 'Threshold' : []\n}\n\npred_data = {\n 'SP' : [],\n 'Model' : [],\n 'Year' : [],\n 'BB' : [],\n 'BB_STD' : []}\n# loop over sp_list\nfor isp, sp_name in enumerate(sp_list):\n # first get the subset of data for this species\n sp_mask = (final_df['SP'].values == sp_name)\n year_list = final_df['Year'].values[sp_mask]\n if len(year_list) < 15: continue\n bb_doy_list = final_df['BB_DOY'].values[sp_mask]\n bb_doy_std_list = final_df['BB_DOY_STD'].values[sp_mask]\n # set the std nan values as the man std\n\n org_bb_doy_std = bb_doy_std_list.copy()\n # update std, fill zero values\n bb_doy_std_list[(np.isnan(bb_doy_std_list)) | (bb_doy_std_list == 0.)] = np.nanmean(bb_doy_std_list)\n\n # loop over different models\n pred_data['SP'] += ([sp_name] * len(bb_doy_list))\n pred_data['Year'] += year_list.tolist()\n pred_data['BB'] += bb_doy_list.tolist()\n pred_data['BB_STD'] += org_bb_doy_std.tolist()\n pred_data['Model'] += (['OBS'] * len(bb_doy_list))\n\n for im, mname in enumerate(metric_names):\n # get the data series of threshold for this model\n\n m_th_list = final_df[mname].values[sp_mask]\n\n m_th_std = np.nanstd(m_th_list)\n print(sp_name,mname,m_th_std)\n\n step_size = 6. * m_th_std / 500.\n\n # loop over different thereshold to find the best threshold using AIC and the\n # corresponding statistics\n\n m_th_range = np.arange(np.nanmean(m_th_list)-3*m_th_std,\n np.nanmean(m_th_list)+3*m_th_std,\n step_size)\n\n best_aic = 999999.\n best_th = 0.\n best_r2 = 0.\n best_rmse = 0.\n best_bb_predict = None\n for test_th in m_th_range:\n # loop over each year to calculate the predicted bud burst date\n bb_predict = np.zeros_like(bb_doy_list) * np.nan\n\n for iy, year in enumerate(year_list):\n if np.isnan(bb_doy_list[iy]): continue\n\n # get temperature of the specific year\n T_avg = tmp_df['T_avg'].values[tmp_years == year].astype(float)\n #T_max = tmp_df['T_max'].values[tmp_years == year].astype(float)\n #T_min = tmp_df['T_min'].values[tmp_years == year].astype(float)\n\n # calculate the metrics\n if mname == 'GDD_5':\n GD = (T_avg - 5)\n GD[GD < 0] = 0.\n metric_data = np.cumsum(GD)\n elif mname == 'GDD_0':\n GD = (T_avg - 0)\n GD[GD < 0] = 0.\n metric_data = np.cumsum(GD)\n elif mname == 'GDD_CD':\n GD = (T_avg - 5)\n GD[GD < 0] = 0.\n NCD = np.cumsum(T_avg < 5.)\n metric_data = GD - (CD_a + CD_b * np.exp(-CD_c * NCD))\n elif mname == 'exp_avg':\n metric_data = np.cumsum(np.exp(exp_a * (T_avg - T_ref)))\n\n # find the first day that passes the test_th\n doy_idx, = np.where(metric_data >= test_th)\n\n if len(doy_idx) > 0:\n bb_predict[iy] = doy_idx[0] + 1\n else:\n bb_predict[iy] = 365\n\n# pdb.set_trace()\n # calculate AIC\n stat_mask = (~np.isnan(bb_predict)) & (~np.isnan(bb_doy_list)) & (~np.isnan(bb_doy_std_list))\n test_aic = 2 * 1. - 2. * np.nansum(\n -np.log(bb_doy_std_list[stat_mask] * (2. * np.pi) ** 0.5)\n -(bb_predict[stat_mask]-bb_doy_list[stat_mask]) ** 2. \n / (2. * (bb_doy_std_list[stat_mask] ** 2.))\n )\n if best_aic > test_aic:\n best_aic = test_aic\n best_r2 = (1. -\n np.nansum((bb_predict[stat_mask]-bb_doy_list[stat_mask])\n ** 2)\n /\n np.nansum((bb_doy_list[stat_mask] -\n np.nanmean(bb_doy_list[stat_mask])) ** 2))\n best_rmse = (np.nanmean((bb_doy_list[stat_mask] -\n bb_predict[stat_mask]) ** 2))**0.5\n best_th = test_th\n best_bb_predict = bb_predict.copy()\n\n\n pred_data['SP'] += ([sp_name] * len(bb_doy_list))\n pred_data['Year'] += year_list.tolist()\n pred_data['BB_STD'] += ([np.nan] * len(bb_doy_list))\n pred_data['Model'] += ([mname] * len(bb_doy_list))\n pred_data['BB'] += best_bb_predict.tolist()\n\n # need to store the best results\n stat_data['SP'].append(sp_name)\n stat_data['Model'].append(mname)\n stat_data['AIC'].append(best_aic)\n stat_data['RMSE'].append(best_rmse)\n stat_data['R2'].append(best_r2)\n stat_data['Threshold'].append(best_th)\n\n# save the data\nstat_df = pd.DataFrame(stat_data)\nstat_df = stat_df[stat_cols]\nstat_df.to_csv('../Data/hf_sp_stats_1990_2014.csv')\n\npred_df = pd.DataFrame(pred_data)\npred_df.to_csv('../Data/hf_sp_pred_1990_2014.csv')\n","sub_path":"PhenoOpt/physio_model/src/fit_pheno_model.py","file_name":"fit_pheno_model.py","file_ext":"py","file_size_in_byte":8893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"28610541","text":"\"\"\"\n模拟开启多个线程,在多资源情况下共同下载一个文件\n\"\"\"\nimport os\nfrom threading import Thread,Lock\nfrom time import sleep\n\nurls = [\"/home/tarena/桌面/\",\n\"/home/tarena/文档/\",\n\"/home/tarena/音乐/\",\n\"/home/tarena/下载/\",\n\"/home/tarena/视频/\",\n\"/home/tarena/图片/\",\n\"/home/tarena/模板/\",\n]\n\nlock = Lock() # 锁\n\nfilename = input(\"要下载的文件:\")\nexplorer = []\nfor i in urls:\n # 判断资源库路径中文件是否存在\n if os.path.exists(i+filename):\n # 存文件路径\n explorer.append(i+filename)\n\nnum = len(explorer) # 获取有多少资源\nif num == 0:\n print(\"没有资源\")\n os._exit(0)\nsize = os.path.getsize(explorer[0])\nblock_size = size // num + 1\n\n# 共享资源\nfd = open(filename,'wb') # 下载的文件\n\n# 下载文件\ndef load(path,num):\n f = open(path,'rb') # 从资源中读取内容\n seek_types = block_size * num\n f.seek(seek_types)\n size = block_size\n\n lock.acquire() # 上锁\n fd.seek(block_size * num)\n while True:\n # sleep(0.1)\n if size < 1024:\n data = f.read(size)\n fd.write(data)\n break\n else:\n data = f.read(1024)\n fd.write(data)\n size -= 1024\n lock.release()\n\nn = 0 # 给每个线程分配的是第几块\njobs = []\nfor path in explorer:\n t = Thread(target = load,args=(path,n))\n jobs.append(t)\n t.start()\n n += 1\n\nfor i in jobs:\n i.join()\n\n\n\n","sub_path":"day10 (1)/day10/multi_thread_copy.py","file_name":"multi_thread_copy.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"242080234","text":"from django.db import migrations\n\n\ndef forwards_func(apps, schema_editor):\n OldDiagram = apps.get_model(\"diagram\", \"OldDiagram\")\n NewDiagram = apps.get_model(\"diagram\", \"NewDiagram\")\n OldDeviceDiagramRelationship = apps.get_model(\"diagram\", \"OldDeviceDiagramRelationship\")\n for old_diagram in OldDiagram.objects.all():\n new_diagram = NewDiagram.objects.create(\n name=old_diagram.name,\n display_link_descriptions=old_diagram.display_link_descriptions,\n links_default_width=old_diagram.links_default_width,\n highlighted_links_width=old_diagram.highlighted_links_width,\n highlighted_links_range_min=old_diagram.highlighted_links_range_min,\n highlighted_links_range_max=old_diagram.highlighted_links_range_max,\n )\n for device_diagram in OldDeviceDiagramRelationship.objects.filter(diagram=old_diagram.pk):\n new_diagram.devices.add(\n device_diagram.device,\n through_defaults={\n \"device_position_x\": device_diagram.device_position_x,\n \"device_position_y\": device_diagram.device_position_y,\n },\n )\n old_diagram.delete()\n\n\ndef reverse_func(apps, schema_editor):\n OldDiagram = apps.get_model(\"diagram\", \"OldDiagram\")\n NewDiagram = apps.get_model(\"diagram\", \"NewDiagram\")\n NewDeviceDiagramRelationship = apps.get_model(\"diagram\", \"NewDeviceDiagramRelationship\")\n for diagram_to_delete in NewDiagram.objects.all():\n created_diagram = OldDiagram.objects.create(\n name=diagram_to_delete.name,\n display_link_descriptions=diagram_to_delete.display_link_descriptions,\n links_default_width=diagram_to_delete.links_default_width,\n highlighted_links_width=diagram_to_delete.highlighted_links_width,\n highlighted_links_range_min=diagram_to_delete.highlighted_links_range_min,\n highlighted_links_range_max=diagram_to_delete.highlighted_links_range_max,\n )\n for device_diagram in NewDeviceDiagramRelationship.objects.filter(diagram=diagram_to_delete.pk):\n created_diagram.devices.add(\n device_diagram.device,\n through_defaults={\n \"device_position_x\": device_diagram.device_position_x,\n \"device_position_y\": device_diagram.device_position_y,\n },\n )\n diagram_to_delete.delete()\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n (\"diagram\", \"0003_auto_20200610_1308\"),\n ]\n\n operations = [\n migrations.RunPython(forwards_func, reverse_func),\n ]\n","sub_path":"router-map/diagram/migrations/0004_auto_20200610_1308.py","file_name":"0004_auto_20200610_1308.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"73354087","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n# ==============================================================================\n# \\file find-best-epoch.py\n# \\author chenghuige \n# \\date 2018-10-07 10:32:35.416608\n# \\Description \n# ==============================================================================\n\n \nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys \nimport os\n\nimport glob\nimport gezi\n\nmodel_dir = '../' if not len(sys.argv) > 1 else sys.argv[1]\n\nthre = 0.714 if not len(sys.argv) > 2 else float(sys.argv[2])\n\nkey = 'adjusted_f1/mean' if not len(sys.argv) > 3 else sys.argv[3]\n#key = 'loss/mean' if not len(sys.argv) > 3 else sys.argv[3]\n\nprint('model_dir', model_dir, 'thre', thre, 'key', key)\n\nif 'loss' not in key:\n cmp = lambda x, y: x > y \nelse:\n cmp = lambda x, y: x < y\n\n# model.ckpt-3.00-9846.valid.metrics\n# ckpt-4.valid.metrics \nfor dir_ in glob.glob(f'{model_dir}/*/*'):\n if not os.path.isdir(dir_):\n continue\n print(dir_)\n best_score = 0 if 'loss' not in key else 1e10\n best_epoch = None\n best_iepoch = None\n\n in_epoch_dir = True\n files = glob.glob(f'{dir_}/epoch/*.valid.metrics')\n if not files:\n in_epoch_dir = False\n files = glob.glob(f'{dir_}/ckpt/*.valid.metrics')\n\n for file_ in files: \n epoch = gezi.strip_suffix(file_, 'valid.metrics').split('-')[1]\n iepoch = int(float(epoch))\n for line in open(file_):\n name, score = line.strip().split()\n score = float(score)\n if name != key:\n continue \n if cmp(score, best_score):\n best_score = score\n best_epoch = epoch\n best_iepoch = iepoch\n print('best_epoch:', best_epoch, 'best_score:', best_score) \n if best_epoch and best_score > thre:\n if in_epoch_dir:\n command = f'ensemble-cp.py {dir_}/epoch/model.ckpt-{best_epoch}'\n else:\n command = f'ensemble-cp.py {dir_}/ckpt/ckpt-{best_epoch}'\n print(command)\n os.system(command)\n\n","sub_path":"projects/ai/sentiment/tools/cp-best-epochs.py","file_name":"cp-best-epochs.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"326073784","text":"import unittest\n\nfrom veggies import Carrot\n\n\nclass TestSunds(unittest.TestCase):\n def test_list_carrot(self):\n \"\"\"\n Test that carrots are crunch.\n \"\"\"\n c = Carrot(\"winter\",3);\n self.assertEqual(c.get_bite_sound(),\"crunch\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"lecture-15/python_example_package/tests/test_sounds.py","file_name":"test_sounds.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"348015220","text":"import bpy\nfrom cgl.plugins.blender import lumbermill as lm\nfrom pathlib import Path\nclass OpenSelected(bpy.types.Operator):\n \"\"\"\n This class is required to register a button in blender.\n \"\"\"\n bl_idname = 'object.open_selected'\n bl_label = 'Open Selected'\n\n @classmethod\n def poll(cls, context):\n return context.active_object is not None\n\n def execute(self, context):\n run()\n return {'FINISHED'}\n\n\ndef open_selected_library():\n obj = bpy.context.active_object\n\n\n if 'proxy' in obj.name:\n name = obj.name.split('_')[0]\n else:\n if '.' in obj.name:\n name = obj.name.split('.')[0]\n else:\n\n name = obj.name\n\n library = bpy.data.collections[name].library\n libraryPath = bpy.path.abspath(library.filepath)\n filename = Path(bpy.path.abspath(libraryPath)).__str__()\n\n lumber_object = lm.LumberObject(filename)\n lm.save_file()\n lm.open_file(lumber_object.path_root)\n #latestVersion = lumber_object.latest_version().path_root\n\n\ndef run():\n \"\"\"\n This run statement is what's executed when your button is pressed in blender.\n :return:\n \"\"\"\n open_selected_library()\n","sub_path":"cookbook/.stversions/blender/menus/utilities/OpenSelected~20201019-122406.py","file_name":"OpenSelected~20201019-122406.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"261361997","text":"\n# coding=utf-8\n\n__author__ = 'Kevin_Liao'\n__all__ = ['Formats']\n\n# http://www.runoob.com/python/python-strings.html\n\nimport re\nimport struct\nimport json\nimport math\nimport sys\nimport select\nimport numpy as np\nfrom collections import namedtuple\nfrom PyQt4 import QtCore, QtGui, uic\nfrom driver.logger import Logger\nfrom lib import Library\n\nlogger = Logger(__name__)\nlib = Library()\n\nclass Format:\n \n __metaclass__ = lib.singleton()\n\n def __init__(self):\n pass\n\n def tuple(self, data): # abc123 => (97, 98, 99, 49, 50, 51)\n if type(data) == str or type(data) == unicode:\n data = str(data)\n data = struct.unpack(\"B\" * len(data), data)\n elif type(data) == list:\n data = tuple(data)\n return data\n\n def list(self, data): # abc123 => [97, 98, 99, 49, 50, 51]\n if type(data) == unicode:\n data = self.str(data)\n data = self.list(data)\n elif type(data) == str:\n data = self.tuple(data)\n data = list(data)\n elif type(data) == int or type(data) == long:\n data = [data]\n elif type(data) == tuple:\n data = list(data)\n return data\n\n \"\"\"\n def char(self, datalist): # [97, 98, 99, 49, 50, 51] => abc123\n if type(datalist) == list:\n dataout = \"\"\n for data in datalist:\n dataout = dataout + chr(data)\n else:\n dataout = datalist\n return dataout\n \"\"\"\n \n def char(self, datalist): # [97, 98, 99, 49, 50, 51] => abc123\n # logger.info(\"char: %s\" % str(datalist))\n if type(datalist) == int or type(datalist) == long: datalist = self.char([datalist])\n elif type(datalist) == list or type(datalist) == tuple: datalist = struct.pack(\"B\" * len(datalist), *datalist)\n if lib.object.isinstance(datalist, QtCore.QString) or type(datalist) == str: datalist = self.unicode(datalist)\n return datalist\n \n def StrToInt(self, data, type):\n try:\n return int(data, type)\n except:\n return -1\n \n def copy(self, data):\n if type(data) == list: data = data[:] # 使用 value = data[:] 傳值方式,當 value 更動時 data 不同步更新;避免使用 value = data 傳址方式,會造成兩者同步更新\n elif type(data) == dict: data = data.copy()\n return data\n \n def initlist(self, data):\n if data == None: data = []\n return data\n\n def initdict(self, data):\n if data == None: data = {}\n return data\n\n def BulkToData(self, data, delChar, type): # data = Bulk data,delChar = 分割字元,type = 轉換格式\n bulkData = data.split(delChar)\n newBulkData = []\n try:\n for raw in bulkData:\n char = self.StrToInt(raw, type)\n if char >= 0: newBulkData.append(char)\n except:\n pass\n return newBulkData\n\n def Power(self, A, B): # A ^ B 次方\n if type(A) == int and type(B) == int:\n return A ** B\n else:\n return 0\n\n def DecToHex(self, data, datatype):\n # return format(data, '0%dX' % (len))\n if type(data) == int:\n dataout = str(datatype % data)\n else:\n dataout = \"\"\n return dataout\n \n def hex(self, datalist, datatype = \"%02X\", join = \" \"):\n dataout = \"\"\n for data in datalist:\n dataout = dataout + str(datatype % data) + join\n if len(dataout) > 0 and dataout[-1] == join: dataout = dataout[:-(len(join))]\n return dataout\n \n def binary(self, datalist):\n bytearray(b'{\\x03\\xff\\x00d')\n pass\n \n def float(self, data, bit = 4): # 小數點後第 N 位,預設小數點後第 4 位\n bit = int(bit)\n if bit < 0 or bit > 10: bit = 4\n if data == \"-nan\" or data == \"nan\": data = 0\n if type(data) == str: data = float(data)\n bit = \"%0.0\" + str(bit) + \"f\"\n return float(bit % data)\n\n \n\n def unicode(self, data): # 物件顯示中文字元必須是 unicode 模式\n if type(data) == list and len(data) == 2:\n if lib.font.en and len(data) >= 1: data = self.unicode(data[0])\n elif len(data) >= 2: data = self.unicode(data[1])\n if lib.object.isinstance(data, QtCore.QString):\n # Python 在 Windows 命令提示字元輸出時遇到 CP950 錯誤: https://coder.tw/?p=7487\n # Python 在 Windows 下 CP950 編碼使用中文的亂碼處理: https://medium.com/@felixie/python-3-window%E4%B8%8B%E4%B8%AD%E6%96%87%E8%99%95%E7%90%86%E7%9A%84%E4%BA%82%E7%A2%BC-53525614d373 # str to unicode (utf-8)\n data = str(data.toUtf8()) # QString to str\n \"\"\"\n try:\n data = data.decode(\"cp950\", \"ignore\") # 先解碼成 cp950 並忽略終端機會出現的錯誤\n data = data.encode(\"cp950\", \"replace\").decode(\"utf-8\") # 再由 cp950 格式轉換為 utf-8,避免中文出現亂碼\n return data\n except: pass\n \"\"\"\n try:\n data = data.decode(\"utf-8\")\n return data\n except: pass\n elif type(data) == str: \n encodelist = [\"big5\", \"utf-8\", \"cp1252\"]\n for encode in encodelist:\n try:\n data = data.decode(encode) # string to unicode\n break\n except Exception as e:\n pass\n elif type(data) == unicode:\n pass\n else: # int to unicode 或 float to unicode 等等\n data = str(data)\n data = self.unicode(data)\n return data\n \n def str(self, data):\n # http://www.runoob.com/python/python-strings.html\n if type(data) == list and len(data) == 2:\n if lib.font.en and len(data) >= 1: data = self.str(data[0])\n elif len(data) >= 2: data = self.str(data[1])\n elif lib.object.isinstance(data, QtCore.QString):\n data = self.unicode(data) # QString to unicode\n data = self.str(data) # unicode to str\n elif type(data) == unicode:\n encodelist = [\"big5\", \"utf-8\", \"cp1252\"]\n for encode in encodelist:\n try:\n data = data.encode(encode) # string to unicode\n break\n except Exception as e:\n pass\n else:\n data = str(data) # other to str\n return data\n\n def number(self, data):\n try:\n fdata = float(data) # 取得 int 或 float\n idata = int(fdata)\n if fdata == idata: return idata\n else: return fdata\n except: pass\n return data\n \n def isunicode(self, data):\n if type(data) == unicode: return True\n else: return False\n \n def isstr(self, data):\n if lib.object.isinstance(data, QtCore.QString) or type(data) == str: return True\n else: return False\n \n def isnumeric(self, data):\n if type(data) == int or type(data) == long or type(data) == float: return True\n else: return False\n \n def ischinese(self, data):\n data = self.unicode(data)\n for ch in data:\n if u'\\u4e00' <= ch and ch <= u'\\u9fff': return True\n return False\n \n def ischar(self, data):\n data = self.unicode(data)\n if len(data) > 1: # 判斷多字元\n if self.map(self.ischar, data).count(False) == 0: return True\n elif len(data) == 1: # 判斷單字元\n if data >= u\"!\" and data <= u\"~\": return True\n elif ord(data) == 32 or ord(data) == 10 or ord(data) == 13: return True\n return False\n \n def match(self, data, match): \n # 只有英文字: match = \"[a-zA-Z]+\"\n try:\n data = self.unicode(data)\n temp = re.match(match, data)\n if temp != None: return list(temp.span())\n except: pass\n return None\n\n def search(self, data, match): \n # 只有英文字: match = \"[a-zA-Z]+\"\n try:\n data = self.unicode(data)\n temp = re.search(match, data)\n if temp != None: return list(temp.span())\n except: pass\n return None\n\n def isEng(self, data):\n return self.search(data, match = \"[a-zA-Z]+\")\n\n def json(self, data): # string to json format\n return json.loads(data)\n\n def dump(self, data): # json format to string\n return json.dumps(data)\n\n def setBit(self, bit):\n if type(bit) == int:\n return (1 << bit)\n\n def getBit(self, data, bit):\n if type(data) == int and type(bit) == int:\n return (data >> bit) & 0x01\n else:\n return 0x00\n\n def setByte(self, data, length = 1):\n value = []\n if type(data) == int:\n if data < 0: data = 0\n for index in range(4):\n value.append(data % 256)\n data = data >> 8\n if len(value) >= length and data == 0: break\n return value\n \n def getByte(self, data):\n [value, base] = [0, 1]\n if type(data) == list:\n for raw in data:\n value = value + base * raw\n base = base << 8\n return value\n \n def floor(self, data1, data2 = None, padding = 1):\n # 自訂有條件向下取整數,padding = 0 ~ 1,當 padding = 0.5 時,當 data = 1.49 時輸出 1,當 data = 1.5 時,輸出 2\n if padding <= 0: padding = float(max(0.00001, float(padding)))\n if data2 != None: value = self.floor(float(data1) / float(data2))\n else: value = int(math.floor(float(data1) + (1 - float(padding))))\n return value\n\n def ceil(self, data1, data2 = None, padding = 0):\n # 自訂有條件進位,padding = 0 ~ 1,當 padding = 0.5 時,當 data = 1.5 時輸出 1,當 data = 1.51 時,輸出 2\n if padding >= 1: padding = float(min(0.99999, float(padding)))\n if data2 != None: value = self.ceil(float(data1) / float(data2), padding = padding)\n else: value = int(math.ceil(float(data1) - (float(padding))))\n return value\n\n def round(self, *args, **kargs):\n return round(*args, **kargs)\n \n def average(self, datalist, bit = 2): # 取平均\n if type(datalist) == list and len(datalist) > 0:\n return self.float(np.mean(datalist), bit)\n return None\n \n def breakline(self, data):\n if type(data) != str: data = str(data)\n data = data.replace(\"\\n\\r\", \"\\n\")\n data = data.replace(\"\\r\\n\", \"\\n\")\n return data\n \n def numcount(self, value, min = 0, max = 1):\n if value >= max: value = min\n else: value = value + 1\n return value\n \n def checksum(self, datalist): # 計算資料的 checksum 來確保資料正確性\n if type(datalist) == list:\n checksum = 0\n try:\n for index in range(len(datalist)):\n if datalist[index] >= 0: checksum += datalist[index]\n checksum = checksum % 0xFF\n except:\n checksum = -1\n return checksum\n \n def map(self, *args, **kargs):\n # lib.format.map(\"{:.2f}\".format, [1.1, 1.2]) 小數點後第二位顯示\n return map(*args, **kargs)\n \n def sum(self, *args, **kargs):\n return sum(*args, **kargs)\n \n def namedtuple(self, name, item):\n # https://www.itread01.com/articles/1475852721.html\n return namedtuple(name, item)\n \n def enumerate(self, data, start = 0): # 讓列表加入索引\n # http://www.runoob.com/python/python-func-enumerate.html\n # enumerate 函數用於將一個可遍歷的數據對象 (如列表、元組或字符串) 組合為一個索引序列,同時列出數據和數據下標,一般用在 for 循環當中\n # for i, element in enumerate(seq)\n return list(enumerate(data, start))\n \n def select(self, readable, writable, exceptional): \n return select.select(readable, writable, exceptional)","sub_path":"source/driver/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":14252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"308254962","text":"\"\"\"Very quick script to run a few tests\"\"\"\nimport itertools\nimport os\nimport time\nimport shutil\nimport subprocess\n# test comment\ndata_dir = '/local/scratch/pfcm/wp'\n\nweightnorm_values = []#'full', 'input', 'recurrent', 'none',\n #'flat-norm']\nnonlinearity_values = ['linear', 'relu']\n#inits = ['normal', 'identity']\nranks = ['1', '8', '32', '128', '256']\nlr_vals = ['0.002']\ncells = ['cp-gate-combined', 'cp-gate', 'gru', 'lstm', 'tf-vanilla']\n\nprogram_args = [\n 'python',\n 'wp_test.py',\n '--width=128',\n '--num_layers=1',\n '--batch_size=100',\n '--learning_rate_decay=0.95',\n '--start_decay=10000',\n '--dropout=0.6',\n '--momentum=0.95',\n '--num_epochs=50',\n '--model_prefix=rnn' # they all get separate folders so it doesn't matter\n]\n\ngrid_iter = itertools.product(cells, nonlinearity_values,\n ranks, lr_vals)\n\nfor cell, nonlin, rank, lr in grid_iter:\n if 'cp' not in cell and (rank != ranks[0] or nonlin != nonlinearity_values[0]):\n continue\n run_dir = os.path.join(\n data_dir, '{}-{}'.format(cell, nonlin))\n run_dir = os.path.join(\n run_dir, 'rank-{}'.format(rank))\n model_dir = os.path.join(run_dir, 'models')\n sample_dir = os.path.join(run_dir, 'samples')\n # make directories if necessary\n os.makedirs(model_dir, exist_ok=True)\n os.makedirs(sample_dir, exist_ok=True)\n # marshal the arguments\n unique_args = [\n '--results_folder=' + run_dir,\n '--model_folder=' + model_dir,\n '--sample_folder=' + sample_dir,\n '--nonlinearity=' + nonlin,\n '--learning_rate=' + lr,\n '--rank=' + rank,\n '--cell=' + cell\n ]\n args = program_args + unique_args\n # print something flashy\n twidth = shutil.get_terminal_size((80, 20)).columns\n print('/' * twidth)\n print('\\\\' * twidth)\n print('{:/^{}}'.format('STARTING NEW RUN', twidth))\n print('{:\\\\^{}}'.format('({}, {}, {})'.format(\n cell, nonlin, rank), twidth))\n print('{:/^{}}'.format(run_dir, twidth))\n print('/' * twidth)\n print('\\\\' * twidth)\n # and run, letting an except propagate if it fails\n start = time.time()\n subprocess.run(args, check=True)\n end = time.time()\n print('\\n\\n')\n print('/' * twidth)\n print('\\\\' * twidth)\n print('{:/^{}}'.format('done', twidth))\n print('{:\\\\^{}}'.format('({}s)'.format(end-start), twidth))\n print('/' * twidth)\n print('\\\\' * twidth)\n","sub_path":"wn_runner.py","file_name":"wn_runner.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"534367150","text":"import socket\n\n\n\n\nsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nsoc.connect(('localhost',8001))\n\nkey = input('Enter room key: ')\nsoc.sendall(key.encode('utf-8'))\ndata = soc.recv(1024).decode('utf-8')\nwhile 1:\n if data == 'False':\n key = input('Not Auhorised \\nEnter room key: ')\n else:\n break\n\nwhile True:\n\n msg = input('Client : ')\n\n # msg = '+='.join([key,msg])\n soc.sendall(msg.encode('utf-8'))\n\n data = soc.recv(1024).decode('utf-8')\n\n\n\n\n print('Server : {}'.format(data))\n\n\nsoc.close()\n","sub_path":"streak/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"555295338","text":"\"\"\" display_window.py \"\"\"\nimport sys\nimport pygame\nfrom pygame.locals import QUIT\n\n# Pygameモジュールを初期化\npygame.init()\n\n# ウインドウサイズをして、ウィンドウオブジェクト生成\nSURFACE = pygame.display.set_mode((400, 300))\n\n# ウィンドウのタイトル\npygame.display.set_caption(\"Just Window\")\n\n# main関数\ndef main() :\n \"\"\" main routine \"\"\"\n while True :\n # ウィンドウの背景塗りつぶし\n # 黒\n #SURFACE.fill((0, 0, 0))\n # 白\n SURFACE.fill((255, 255, 255))\n # 赤\n #SURFACE.fill((255, 0, 0))\n # 緑\n #SURFACE.fill((0, 255, 0))\n # 青\n #SURFACE.fill((0, 0, 255))\n # 黄\n #SURFACE.fill((255, 255, 0))\n\n # イベントキューからイベントを取得する\n for event in pygame.event.get() :\n # 終了イベント判定\n if event.type == QUIT :\n # PyGameの初期化を解除\n pygame.quit()\n # プログラムを終了\n sys.exit()\n\n # 描画した内容を画面に反映させる\n # これ命令を実行しないと描画が更新されない\n pygame.display.update()\n\n# インポートされた際にプログラムが動かないようにするため\n# __name__ : Pythonファイルのモジュール名が文字列で入っている\n# __main__ : Pythonファイルをスクリプトとして直接実行した場合に自動で設定\nif __name__ == '__main__' :\n main()\n","sub_path":"python/text2/display_window.py","file_name":"display_window.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"386332385","text":"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\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 implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nr\"\"\"Converts a Wikipedia XML dump to JSONL.\n\nThere are two reasons we do this:\n 1. To filter down the dump to articles and redirects.\n 2. JSONL is much more amenable to parallel processing.\n\"\"\"\nimport bz2\nimport json\nimport os\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nfrom language.fruit import wiki_utils\nimport tqdm\n\nflags.DEFINE_string(\"input_xml\", None, \"Input compressed XML file.\")\nflags.DEFINE_string(\"output_jsonl\", None, \"Ouput JSONL file.\")\n\nFLAGS = flags.FLAGS\n\n\ndef main(_):\n openers = {\n \".xml\": open,\n \".bz2\": bz2.open,\n }\n filetype = os.path.splitext(FLAGS.input_xml)[-1]\n opener = openers.get(filetype, open)\n logging.info(\"processing file: %s\", FLAGS.input_xml)\n logging.info(\"filetype: %s\", filetype)\n with opener(FLAGS.input_xml, \"r\") as xml_file, \\\n open(FLAGS.output_jsonl, \"w\") as jsonl_file:\n for page in tqdm.tqdm(wiki_utils.generate_pages(xml_file)):\n page_json = json.dumps(page, ensure_ascii=False)\n print(page_json, file=jsonl_file)\n\n\nif __name__ == \"__main__\":\n app.run(main)\n","sub_path":"language/fruit/scripts/run_convert_to_jsonl.py","file_name":"run_convert_to_jsonl.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"200678353","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('account', '0035_auto_20151021_0912'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='group',\n field=models.ManyToManyField(verbose_name=b'user_group', blank=True, help_text='', related_name='user_set', related_query_name=b'user', to='account.UserGroup'),\n ),\n ]\n","sub_path":"account/migrations/0036_user_group.py","file_name":"0036_user_group.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"425375752","text":"import pandas as pd\nimport numpy as np\nimport os\nimport shutil\nfrom random import random, randint, choice\n\nvar_names = ['open', 'high', 'low', 'close', 'vwap', 'volume', 'amount', 'ret']\n\nunary_list = ['rank','abs', 'log', 'sign', 'sqrt', 'square', 'relu', 'sigmoid', 'sumac', 'prodac']\n\nts_list = ['sum', 'wma', 'tsmax', 'tsmin', 'delay', 'std', 'delta', 'tsrank', 'median',\n 'highday', 'lowday', 'mean', 'decaylinear', 'var', 'ema']\n\nbinary_list = ['min', 'max', '+', '-', '*', '/', '>', '<', '==', '>=', '<=', '&', '||', '^']\n\nbi_ts_list = ['corr', 'covariance', '?', 'sma']\n\nall_func_list = unary_list + ts_list + binary_list + bi_ts_list\n\nfunc_op_num = {'rank':1,'abs': 1, 'log': 1, 'sign': 1, 'sqrt': 1, 'square': 1, 'cube': 1, 'indneutralize': 1,\n 'relu': 1, 'sigmoid': 1, 'sumac': 1, 'prodac': 1, '&': 2, '^': 2, '||': 2,\n 'median': 2, 'sum': 2, 'ma': 2, 'wma': 2, 'tsmax': 2, 'tsmin': 2, 'delay': 2,\n 'tsrank': 2, 'prod': 2, 'std': 2, 'delta': 2, 'highday': 2, 'lowday': 2, 'mean': 2,\n 'decaylinear': 2, 'var': 2, 'ema': 2,\n 'min': 2, 'max': 2, '+': 2, '-': 2, '*': 2, '/': 2,\n '>': 2, '<': 2, '==': 2, '>=': 2, '<=': 2,\n 'corr': 3, 'covariance': 3, 'regbeta': 3, 'regresi': 3, '?': 3, 'sma': 3}\n\nclass fwrapper:\n def __init__(self, childcount, name):\n self.childcount = childcount\n self.name = name\n\nclass node:\n def __init__(self, fw, children):\n self.name = fw.name\n self.children = children\n self.data = None\n\n # def __del__(self):\n # del self.data\n # for child in self.children:\n # del child\n\n def evaluate(self, inp):\n results = [n.evaluate(inp) for n in self.children]\n return self.function(results)\n\n def display(self, indent=0):\n print((' ' * indent) + self.name)\n for c in self.children:\n c.display(indent + 1)\n\nclass paramnode:\n __var_names = ['open', 'high', 'low', 'close', 'vwap', 'volume', 'amount', 'ret']\n\n def __init__(self, idx):\n self.idx = idx\n self.name = self.__var_names[self.idx]\n self.data = None\n\n # def __del__(self):\n # del self.data\n\n # idx is the location in the parameters tuple\n def evaluate(self, inp):\n return inp[self.idx]\n\n # print the index of parameters\n def display(self, indent=0):\n print('%s%s' % (' ' * indent, self.name))\n\nclass constnode:\n def __init__(self, v):\n self.name = v\n self.data = self.name\n\n # def __del__(self):\n # del self.data\n\n def evaluate(self, inp):\n return self.name\n\n def change_value(self, value):\n self.name = value\n self.data = value\n\n def display(self, indent=0):\n print('%s%d' % (' ' * indent, self.name))\ndef do_calculation(tree):\n for child in tree.children:\n if child.data is None:\n child.data = do_calculation(child)\n\n if tree.name == 'abs':\n return tree.children[0].data.abs()\n\n #新加\n elif tree.name == 'rank':\n shapes = tree.children[0].data.shape\n final_df=pd.DataFrame(np.zeros((shapes[0],shapes[1])))\n for i in range(1,shapes[0]):\n final_df.iloc[i]=np.array(tree.children[0].data.iloc[i-1].rank(ascending=True)) \n final_df=pd.DataFrame(final_df.values)\n final_df.index=tree.children[0].data.index\n final_df.columns=tree.children[0].data.columns\n return final_df\n \n elif tree.name == 'log':\n tree.children[0].data[tree.children[0].data<=0]=-(1/tree.children[0].data)\n return np.log(np.abs(tree.children[0].data))\n\n elif tree.name == 'sign':\n return np.sign(tree.children[0].data)\n\n elif tree.name == 'sqrt':\n return np.sqrt(np.abs(tree.children[0].data))\n\n elif tree.name == 'square':\n return np.square(tree.children[0].data)\n\n elif tree.name == 'cube':\n return np.power(tree.children[0].data, 3)\n\n elif tree.name == 'indneutralize':\n data = copy.copy(tree.children[0].data)\n for i in range(len(self.industry_code)):\n if len(self.industry_code[i]) == 1:\n continue\n avg = tree.children[0].data.loc[:, self.industry_code[i]].mean(axis=1, numeric_only=True)\n data.loc[:, self.industry_code[i]] = tree.children[0].data.loc[:, self.industry_code[i]].sub(avg,\n axis='index')\n return data\n\n elif tree.name == 'sigmoid':\n return 1 / (1 + np.exp(-tree.children[0].data))\n\n elif tree.name == 'relu':\n data_tem = tree.children[0].data\n data_tem[data_tem < 0] = 0\n return data_tem\n\n\n\n # -----------------ts_list--------------------#\n elif tree.name == 'sum':\n window = tree.children[1].data\n if window<0:\n window=1\n tree.children[1].data=1\n return tree.children[0].data.rolling(window).sum()\n \n\n elif tree.name == 'wma':\n window = tree.children[1].data\n weight = np.power(0.9, np.arange(start=window, stop=0, step=-1))\n _wma = lambda x: np.nansum(x * weight)\n return tree.children[0].data.rolling(window).apply(_wma)\n\n elif tree.name == 'tsmax':\n window = tree.children[1].data\n return tree.children[0].data.rolling(window).max()\n\n elif tree.name == 'tsmin':\n window = tree.children[1].data\n return tree.children[0].data.rolling(window).min()\n\n elif tree.name == 'delay':\n window = tree.children[1].data\n return tree.children[0].data.shift(window)\n\n elif tree.name == 'std':\n window = tree.children[1].data\n return tree.children[0].data.rolling(window).std()\n\n elif tree.name == 'delta':\n window = tree.children[1].data\n return tree.children[0].data - tree.children[0].data.shift(window)\n\n elif tree.name == 'tsrank':\n window = tree.children[1].data\n _rank = lambda x: (x <= (np.array(x))[-1]).sum() / float(x.shape[0])\n return tree.children[0].data.rolling(window).apply(_rank)\n\n elif tree.name == 'highday':\n window = tree.children[1].data\n def rolling_highday(df):\n return window - 1 - np.argmax(df)\n\n return tree.children[0].data.rolling(window).apply(rolling_highday)\n\n elif tree.name == 'lowday':\n window = tree.children[1].data\n def rolling_highday(df):\n return window - 1 - np.argmin(df)\n\n return tree.children[0].data.rolling(window).apply(rolling_highday)\n\n elif tree.name == 'mean':\n window = tree.children[1].data\n return tree.children[0].data.rolling(window).mean()\n\n elif tree.name == 'decaylinear':\n window = tree.children[1].data\n dividend = window * (window + 1) / 2\n weights = (np.arange(window) + 1) / dividend\n\n def _decay_linear_avg(df):\n return np.nansum(df * weights)\n\n return tree.children[0].data.rolling(window).apply(_decay_linear_avg)\n\n elif tree.name == 'median':\n window = tree.children[1].data\n return tree.children[0].data.rolling(window).median()\n\n elif tree.name == 'var':\n window = tree.children[1].data\n return tree.children[0].data.rolling(window).var()\n\n # ------------------------binary_list-----------------------------#\n elif tree.name == 'max':\n return np.maximum(tree.children[0].data, tree.children[1].data)\n\n elif tree.name == 'min':\n return np.minimum(tree.children[0].data, tree.children[1].data)\n #新加\n elif tree.name== '<':\n return tree.children[0].data < tree.children[1].data\n elif tree.name== '<=':\n return tree.children[0].data <= tree.children[1].data\n elif tree.name== '>':\n return tree.children[0].data > tree.children[1].data\n elif tree.name== '>=':\n return tree.children[0].data >= tree.children[1].data\n elif tree.name== '==':\n return tree.children[0].data == tree.children[1].data\n\n elif tree.name == '+':\n return tree.children[0].data + tree.children[1].data\n\n elif tree.name == '-':\n return tree.children[0].data - tree.children[1].data\n\n elif tree.name == '*':\n return tree.children[0].data * tree.children[1].data\n\n elif tree.name == '/':\n return tree.children[0].data / tree.children[1].data\n elif tree.name == '^':\n return tree.children[0].data ** tree.children[1].data\n \n elif tree.name == '||':\n return (tree.children[0].data | tree.children[1].data)\n \n elif tree.name == '&':\n return (tree.children[0].data & tree.children[1].data)\n\n # -------------------------bi_ts_list------------------------#\n elif tree.name == 'corr':\n window = tree.children[2].data\n return tree.children[0].data.rolling(window).corr(tree.children[1].data)\n\n elif tree.name == 'covariance':\n window = tree.children[2].data\n return tree.children[0].data.rolling(window).cov(tree.children[1].data)\n elif tree.name=='sma':\n n=tree.children[1].data \n m=tree.children[2].data\n #不加的话nan,inf会逐渐累积造成算corr时出现nan\n tree.children[0].data=tree.children[0].data.fillna(0)\n tree.children[0].data=tree.children[0].data.replace(np.inf,0)\n tree.children[0].data=tree.children[0].data.replace(-np.inf,0)\n shapes=tree.children[0].data.shape\n final_df=pd.DataFrame(np.zeros((shapes[0],shapes[1])))\n for i in range(1,shapes[0]):\n final_df.iloc[i]=(np.array(m*tree.children[0].data.iloc[i-1])+np.array((n-m)*final_df.iloc[i-1]))/n\n return final_df\n elif tree.name=='?':\n tree.children[0].data[tree.children[0].data==True]=tree.children[1].data\n tree.children[0].data[tree.children[0].data==False]=tree.children[2].data\n return tree.children[0].data\n else:\n print(\"Cannot recognize tree name\", tree.name)\n exit()\ndef tree_to_formula(tree):\n if isinstance(tree, node):\n if tree.name in ['||','&','+', '-', '*', '/', '>', '<', '==', '>=', '<=', '^']:\n string_1 = tree_to_formula(tree.children[0])\n string_2 = tree_to_formula(tree.children[1])\n return str('(' + string_1 + tree.name + string_2 + ')')\n elif tree.name == '?':\n result = [tree_to_formula(tree.children[0]), '?', tree_to_formula(tree.children[1]), ':',\n tree_to_formula(tree.children[2])]\n return ''.join(result)\n else:\n result = [tree.name, '(']\n for i in range(len(tree.children)):\n string_i = tree_to_formula(tree.children[i])\n result.append(string_i)\n result.append(',')\n result.pop()\n result.append(')')\n return ''.join(result)\n elif isinstance(tree, paramnode):\n return str(tree.name)\n else:\n return str(tree.name)\n\ndef check_sanity(formula):\n count = 0\n for i in range(len(formula)):\n if formula[i] == '(':\n count += 1\n if formula[i] == ')':\n count -= 1\n if count < 0:\n return 0\n if count != 0:\n return 0\n return 1\n\ndef formula_to_tree(formula):\n formula = formula.replace('*-1', '*(0-1)')\n formula = formula.replace('(-1', '((0-1)')\n while(1):\n if formula[0] == '(':\n if check_sanity(formula[1:-1]):\n formula = formula[1:-1]\n else:\n break\n else:\n break\n if formula in var_names:\n return paramnode(var_names.index(formula))\n elif formula.isdigit():\n return constnode(int(formula))\n elif formula[0] == '0' and formula[1] == '.' and len(formula) < 5:\n return constnode(float(formula))\n var_stack = []\n op_stack = []\n count = 0\n pointer = 0\n k = 0\n while k < len(formula):\n if formula[k] == '(' and count == 0:\n for i in range(k, len(formula)):\n if formula[i] == '(': count += 1\n elif formula[i] == ')': count -= 1\n if count == 0: break\n index = i # index points at ')'\n tree_k = formula_to_tree(formula[k:index+1])\n var_stack.append(tree_k)\n if i == len(formula) - 1:\n k = i\n pointer = i\n else:\n k = i\n pointer = i+1\n if formula[k] in ['+', '-', '*', '/', '?', '>', '&', '^']:\n op = formula[k]\n for func in func_list:\n if func.name == op:\n fw_k = func\n break\n op_stack.append(fw_k)\n pointer = k+1\n elif formula[k] == ':':\n pointer = k+1\n count = 0\n flag = 0\n for i in range(k+1, len(formula)):\n if formula[i] == '(':\n count += 1\n flag = 1\n elif formula[i] == ')':\n count -= 1\n if count == 0 and flag == 1:\n # i points at ')'\n var_stack.append(formula_to_tree(formula[pointer:i+1]))\n if i+1 == len(formula):\n pointer = i\n else:\n pointer = i+1\n k = pointer\n break\n elif count < 0 and flag == 0:\n var_stack.append(formula_to_tree(formula[pointer:i]))\n pointer = i\n break\n elif formula[pointer:k+1] in unary_list:\n cnt_tem = 0\n op = formula[pointer:k+1]\n for func in func_list:\n if func.name == op:\n fw = func\n break\n for i in range(k+1, len(formula)):\n if formula[i] == '(':\n cnt_tem += 1\n if formula[i] == ')':\n cnt_tem -= 1\n if cnt_tem == 0:\n children = [formula_to_tree(formula[k+1:i+1])]\n tree_k = node(fw, children)\n var_stack.append(tree_k)\n break\n k = i\n pointer = k+1\n elif formula[pointer:k+1] in ['==', '<', '>=', '<=', '||']:\n op = formula[pointer:k+1]\n for func in func_list:\n if func.name == op:\n fw_k = func\n break\n op_stack.append(fw_k)\n pointer = k+1\n elif (formula[pointer:k+1] in ts_list or formula[pointer:k+1] in binary_list) and formula[k+1] == '(':\n children = []\n cnt_tem = 0\n op = formula[pointer:k+1]\n for func in func_list:\n if func.name == op:\n fw = func\n break\n for i in range(k+1, len(formula)):\n if formula[i] == '(':\n cnt_tem += 1\n if formula[i] == ')':\n cnt_tem -= 1\n if formula[i] == ',' and cnt_tem == 1:\n index = i\n if cnt_tem == 0:\n children.append(formula_to_tree(formula[k+2:index]))\n children.append(formula_to_tree(formula[index+1:i]))\n tree_k = node(fw, children)\n var_stack.append(tree_k)\n break\n k = i\n pointer = k+1\n elif formula[pointer:k+1] in bi_ts_list:\n cnt_tem = 0\n idx_list = []\n children = []\n op = formula[pointer:k+1]\n for func in func_list:\n if func.name == op:\n fw = func\n break\n for i in range(k+1, len(formula)):\n if formula[i] == '(':\n cnt_tem += 1\n if formula[i] == ')':\n cnt_tem -= 1\n if formula[i] == ',' and cnt_tem == 1:\n idx_i = i\n idx_list.append(idx_i)\n if cnt_tem == 0:\n children.append(formula_to_tree(formula[k+2:idx_list[0]]))\n children.append(formula_to_tree(formula[idx_list[0]+1:idx_list[1]]))\n children.append(formula_to_tree(formula[idx_list[1]+1:i+1]))\n tree_k = node(fw, children)\n var_stack.append(tree_k)\n break\n k = i\n pointer = k+1\n elif formula[pointer:k+1] in var_names and (k+1 == len(formula) or not formula[k+1].isalpha()):\n var_stack.append(paramnode(var_names.index(formula[pointer:k+1])))\n pointer = k+1\n elif formula[pointer:k+1].isdigit() and (k+1 == len(formula) or formula[k+1] not in '.0123456789'):\n var_stack.append(constnode(int(formula[pointer:k+1])))\n pointer = k+1\n elif formula[pointer] == '0' and (k+1 == len(formula) or formula[k+1] not in '.0123456789'):\n var_stack.append(constnode(float(formula[pointer:k+1])))\n pointer = k+1\n # elif '.' in formula[pointer:k+1] and (k+1 == len(formula) or formula[k+1] not in '0123456789'):\n # var_stack.append(constnode)\n k += 1\n if len(op_stack) > 0:\n while op_stack[-1].name == '?':\n if len(var_stack) < 3:\n break\n else:\n fw = op_stack.pop()\n rchild = var_stack.pop()\n mchild = var_stack.pop()\n lchild = var_stack.pop()\n children = [lchild, mchild, rchild]\n tree_k = node(fw, children)\n var_stack.append(tree_k)\n if len(op_stack) == 0:\n break\n while len(var_stack) >= 2 and op_stack[-1].name != '?':\n try:\n fw = op_stack.pop()\n rchild = var_stack.pop()\n lchild = var_stack.pop()\n children = [lchild, rchild]\n tree_k = node(fw, children) # k here is to avoid duplicate\n var_stack.append(tree_k)\n except:\n for item in var_stack:\n if isinstance(item, constnode):print(item.name)\n else:print(item.name)\n raise NotImplementedError\n if len(var_stack) != 1 or len(op_stack) != 0:\n print(\"There's an error!\")\n raise NotImplementedError\n return var_stack[0]\n\ndef get_paramnode(tree):\n list = []\n if isinstance(tree, paramnode):\n return [tree]\n elif isinstance(tree, constnode):\n return []\n elif isinstance(tree, node):\n for child in tree.children:\n result = get_paramnode(child)\n list.extend(result)\n return list\ndef get_constnode(tree):\n list = []\n if isinstance(tree, constnode):\n if tree.data < 1:\n return []\n else:\n return [tree]\n elif isinstance(tree, paramnode):\n return []\n else:\n for children in tree.children:\n result = get_constnode(children)\n list.extend(result)\n return list\n\nfunc_list = []\n\nfor i, func in enumerate(all_func_list):\n func_i = fwrapper(func_op_num[func], str(func))\n func_list.append(func_i)\n \n","sub_path":"xtech/Parameter tuning of factors/definition.py","file_name":"definition.py","file_ext":"py","file_size_in_byte":20325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"495459017","text":"\"\"\" Functions for Categorize output file writing.\"\"\"\nimport netCDF4\nfrom cloudnetpy import utils, version\nfrom cloudnetpy.metadata import COMMON_ATTRIBUTES\nfrom cloudnetpy.products import product_tools\n\n\ndef update_attributes(cloudnet_variables, attributes):\n \"\"\"Overrides existing CloudnetArray-attributes.\n\n Overrides existing attributes using hard-coded values.\n New attributes are added.\n\n Args:\n cloudnet_variables (dict): CloudnetArray instances.\n attributes (dict): Product-specific attributes.\n\n \"\"\"\n for key in cloudnet_variables:\n if key in attributes:\n cloudnet_variables[key].set_attributes(attributes[key])\n if key in COMMON_ATTRIBUTES:\n cloudnet_variables[key].set_attributes(COMMON_ATTRIBUTES[key])\n\n\ndef save_product_file(identifier, obj, file_name, copy_from_cat=()):\n \"\"\"Saves a standard Cloudnet product file.\"\"\"\n dims = {'time': len(obj.time), 'height': len(obj.variables['height'])}\n root_group = init_file(file_name, dims, obj.data, zlib=True)\n vars_from_source = ('altitude', 'latitude', 'longitude', 'time', 'height') + copy_from_cat\n copy_variables(obj.dataset, root_group, vars_from_source)\n root_group.title = f\"{identifier.capitalize()} file from {obj.dataset.location}\"\n root_group.source = f\"Categorize file: {product_tools.get_source(obj)}\"\n copy_global(obj.dataset, root_group, ('location', 'day', 'month', 'year'))\n merge_history(root_group, identifier, obj)\n root_group.close()\n\n\ndef merge_history(root_group, file_type, *sources):\n \"\"\"Merges history fields from one or several files and creates a new record.\"\"\"\n new_record = f\"{utils.get_time()} - {file_type} file created\"\n old_history = ''\n for source in sources:\n old_history += f\"\\n{source.dataset.history}\"\n root_group.history = f\"{new_record}{old_history}\"\n\n\ndef init_file(file_name, dimensions, obs, zlib):\n \"\"\"Initializes a Cloudnet file for writing.\"\"\"\n root_group = netCDF4.Dataset(file_name, 'w', format='NETCDF4_CLASSIC')\n for key, dimension in dimensions.items():\n root_group.createDimension(key, dimension)\n _write_vars2nc(root_group, obs, zlib)\n _add_standard_global_attributes(root_group)\n return root_group\n\n\ndef _write_vars2nc(rootgrp, cloudnet_variables, zlib):\n \"\"\"Iterates over Cloudnet instances and write to given rootgrp.\"\"\"\n\n def _get_dimensions(array):\n \"\"\"Finds correct dimensions for a variable.\"\"\"\n if utils.isscalar(array):\n return ()\n variable_size = ()\n file_dims = rootgrp.dimensions\n array_dims = array.shape\n for length in array_dims:\n dim = [key for key in file_dims.keys()\n if file_dims[key].size == length][0]\n variable_size = variable_size + (dim,)\n return variable_size\n\n for key in cloudnet_variables:\n obj = cloudnet_variables[key]\n size = _get_dimensions(obj.data)\n nc_variable = rootgrp.createVariable(obj.name, obj.data_type, size,\n zlib=zlib)\n nc_variable[:] = obj.data\n for attr in obj.fetch_attributes():\n setattr(nc_variable, attr, getattr(obj, attr))\n\n\ndef _add_standard_global_attributes(root_group):\n root_group.Conventions = 'CF-1.7'\n root_group.cloudnetpy_version = version.__version__\n root_group.file_uuid = utils.get_uuid()\n\n\ndef copy_variables(source, target, var_list):\n \"\"\"Copies variables (and their attributes) from one file to another.\"\"\"\n for var_name, variable in source.variables.items():\n if var_name in var_list:\n var_out = target.createVariable(var_name, variable.datatype,\n variable.dimensions)\n var_out.setncatts({k: variable.getncattr(k)\n for k in variable.ncattrs()})\n var_out[:] = variable[:]\n\n\ndef copy_global(source, target, attr_list):\n \"\"\"Copies global attributes from one file to another.\"\"\"\n for attr_name in source.ncattrs():\n if attr_name in attr_list:\n setattr(target, attr_name, source.getncattr(attr_name))\n","sub_path":"cloudnetpy/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"198436049","text":"#!/usr/bin/python\nimport subprocess\nimport re\n\n\ndef check_video_file_type(video, file_ext):\n return get_file_type(video) == file_ext\n\n\ndef get_file_type(file_path):\n \"\"\"\n :param file_path: file path to check with file Linux builtin\n :return: str or None\n :raises BaseException: if file can't be executed\n \"\"\"\n\n with subprocess.Popen(['/usr/bin/file', '-i', file_path.strip()], stdout=subprocess.PIPE) as p:\n # stdout, stderr = p.stdout.read().decode('utf-8')\n\n stdout, stderr = tuple(map(lambda x: x.decode() if hasattr(x, 'decode') else None, p.communicate()))\n if not p.returncode == 0:\n stdout = None\n\n if not stdout:\n raise BaseException(\"Impossible to find file extension for {}\".format(file_path))\n\n assert isinstance(stdout, str)\n\n match = re.search(r':.+/(?P.+);', stdout)\n\n return match.group('ext').strip().lower()\n\n\nif __name__ == \"__main__\":\n # ext = get_file_ext(\"/home/fabrizio/Downloads/2.Broke.Girls.S04E13.HDTV.x264-LOL.mp4\")\n # ext = get_file_ext(\"/home/fabrizio/Downloads/rand_test\")\n ext = get_file_type(\"/home/fabrizio/Downloads/2.Broke.Girls.s04e13.sub.itasa.zip\")\n ext = get_file_type(\"/home/fabrizio/Downloads/Banshee.s03e01.720p.sub.itasa.srt\")\n print(ext)","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"624245621","text":"import urllib.request\r\nfrom random import *\r\n\r\n# replaces spaces to spaces readable by a web link\r\n# (\"%20\" is the equivalent to spaces)\r\ndef spaces_to_undscr(qr):\r\n\tlist_decomp = []\r\n\r\n\tlist_decomp = list(qr)\r\n\tlist_decomp = [w.replace(' ', '%20') for w in list_decomp]\r\n\tqr = ''.join(list_decomp)\r\n\r\n\treturn qr\r\n\r\n# user input added to API\r\nprint(\"Choose a link or some text to transform to a QR code\")\r\nqr = input(\"> \")\r\n\r\nqr = spaces_to_undscr(qr)\r\nqrl = \"https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=\" + qr\r\n\r\n# Random number generated for file name\r\nnm = str(randint(1000,9999))\r\n\r\n# Retrieves QR code to file location\r\nurllib.request.urlretrieve(qrl, nm+\".jpg\")","sub_path":"QRGen/QRGen.py","file_name":"QRGen.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"311760865","text":"# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n# Copyright (c) 2011 and later, The QuTiP Project\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n# of its contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\n\nfrom numpy.testing import assert_, run_module_suite, assert_allclose\nimport numpy as np\n\nfrom qutip import (\n tensor, qeye, sigmaz, sigmax, sigmay, destroy, identity, QobjEvo,\n fidelity, basis\n )\nfrom qutip_qip.device import Processor, SCQubits\nfrom qutip_qip.noise import (\n RelaxationNoise, DecoherenceNoise, ControlAmpNoise, RandomNoise,\n ZZCrossTalk, Noise)\nfrom qutip_qip.pulse import Pulse, Drift\nfrom qutip_qip.circuit import QubitCircuit\n\n\nclass DriftNoise(Noise):\n def __init__(self, op):\n self.qobj = op\n\n def get_noisy_dynamics(self, dims, pulses, systematic_noise):\n systematic_noise.add_coherent_noise(self.qobj, 0, coeff=True)\n # test the backward compatibility\n return pulses\n\n\nclass TestNoise:\n def test_decoherence_noise(self):\n \"\"\"\n Test for the decoherence noise\n \"\"\"\n tlist = np.array([1, 2, 3, 4, 5, 6])\n coeff = np.array([1, 1, 1, 1, 1, 1])\n\n # Time-dependent\n decnoise = DecoherenceNoise(\n sigmaz(), coeff=coeff, tlist=tlist, targets=[1])\n dims = [2] * 2\n pulses, systematic_noise = decnoise.get_noisy_dynamics(dims=dims)\n noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims)\n assert_allclose(c_ops[0].ops[0].qobj, tensor(qeye(2), sigmaz()))\n assert_allclose(c_ops[0].ops[0].coeff, coeff)\n assert_allclose(c_ops[0].tlist, tlist)\n\n # Time-indenpendent and all qubits\n decnoise = DecoherenceNoise(sigmax(), all_qubits=True)\n pulses, systematic_noise = decnoise.get_noisy_dynamics(dims=dims)\n noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims)\n c_ops = [qu.cte for qu in c_ops]\n assert_(tensor([qeye(2), sigmax()]) in c_ops)\n assert_(tensor([sigmax(), qeye(2)]) in c_ops)\n\n # Time-denpendent and all qubits\n decnoise = DecoherenceNoise(\n sigmax(), all_qubits=True, coeff=coeff*2, tlist=tlist)\n pulses, systematic_noise = decnoise.get_noisy_dynamics(dims=dims)\n noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims)\n assert_allclose(c_ops[0].ops[0].qobj, tensor(sigmax(), qeye(2)))\n assert_allclose(c_ops[0].ops[0].coeff, coeff*2)\n assert_allclose(c_ops[0].tlist, tlist)\n assert_allclose(c_ops[1].ops[0].qobj, tensor(qeye(2), sigmax()))\n\n def test_relaxation_noise(self):\n \"\"\"\n Test for the relaxation noise\n \"\"\"\n # only t1\n a = destroy(2)\n dims = [2] * 3\n relnoise = RelaxationNoise(t1=[1., 1., 1.], t2=None)\n systematic_noise = Pulse(None, None, label=\"system\")\n pulses, systematic_noise = relnoise.get_noisy_dynamics(\n dims=dims, systematic_noise=systematic_noise)\n noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims)\n assert_(len(c_ops) == 3)\n assert_allclose(c_ops[1].cte, tensor([qeye(2), a, qeye(2)]))\n\n # no relaxation\n dims = [2] * 2\n relnoise = RelaxationNoise(t1=None, t2=None)\n systematic_noise = Pulse(None, None, label=\"system\")\n pulses, systematic_noise = relnoise.get_noisy_dynamics(\n dims=dims, systematic_noise=systematic_noise)\n noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims)\n assert_(len(c_ops) == 0)\n\n # only t2\n relnoise = RelaxationNoise(t1=None, t2=[0.2, 0.7])\n systematic_noise = Pulse(None, None, label=\"system\")\n pulses, systematic_noise = relnoise.get_noisy_dynamics(\n dims=dims, systematic_noise=systematic_noise)\n noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims)\n assert_(len(c_ops) == 2)\n\n # t1+t2 and systematic_noise = None\n relnoise = RelaxationNoise(t1=[1., 1.], t2=[0.5, 0.5])\n pulses, systematic_noise = relnoise.get_noisy_dynamics(dims=dims)\n noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims)\n assert_(len(c_ops) == 4)\n\n def test_control_amplitude_noise(self):\n \"\"\"\n Test for the control amplitude noise\n \"\"\"\n tlist = np.array([1, 2, 3, 4, 5, 6])\n coeff = np.array([1, 1, 1, 1, 1, 1])\n\n # use proc_qobjevo\n pulses = [Pulse(sigmaz(), 0, tlist, coeff)]\n connoise = ControlAmpNoise(coeff=coeff, tlist=tlist)\n noisy_pulses, systematic_noise = \\\n connoise.get_noisy_dynamics(pulses=pulses)\n assert_allclose(pulses[0].coherent_noise[0].qobj, sigmaz())\n assert_allclose(noisy_pulses[0].coherent_noise[0].coeff, coeff)\n\n def test_random_noise(self):\n \"\"\"\n Test for the white noise\n \"\"\"\n tlist = np.array([1, 2, 3, 4, 5, 6])\n coeff = np.array([1, 1, 1, 1, 1, 1])\n dummy_qobjevo = QobjEvo(sigmaz(), tlist=tlist)\n mean = 0.\n std = 0.5\n pulses = [Pulse(sigmaz(), 0, tlist, coeff),\n Pulse(sigmax(), 0, tlist, coeff*2),\n Pulse(sigmay(), 0, tlist, coeff*3)]\n\n # random noise with operators from proc_qobjevo\n gaussnoise = RandomNoise(\n dt=0.1, rand_gen=np.random.normal, loc=mean, scale=std)\n noisy_pulses, systematic_noise = \\\n gaussnoise.get_noisy_dynamics(pulses=pulses)\n assert_allclose(noisy_pulses[2].qobj, sigmay())\n assert_allclose(noisy_pulses[1].coherent_noise[0].qobj, sigmax())\n assert_allclose(\n len(noisy_pulses[0].coherent_noise[0].tlist),\n len(noisy_pulses[0].coherent_noise[0].coeff))\n\n # random noise with dt and other random number generator\n pulses = [Pulse(sigmaz(), 0, tlist, coeff),\n Pulse(sigmax(), 0, tlist, coeff*2),\n Pulse(sigmay(), 0, tlist, coeff*3)]\n gaussnoise = RandomNoise(lam=0.1, dt=0.2, rand_gen=np.random.poisson)\n assert_(gaussnoise.rand_gen is np.random.poisson)\n noisy_pulses, systematic_noise = \\\n gaussnoise.get_noisy_dynamics(pulses=pulses)\n assert_allclose(\n noisy_pulses[0].coherent_noise[0].tlist,\n np.linspace(1, 6, int(5/0.2) + 1))\n assert_allclose(\n noisy_pulses[1].coherent_noise[0].tlist,\n np.linspace(1, 6, int(5/0.2) + 1))\n assert_allclose(\n noisy_pulses[2].coherent_noise[0].tlist,\n np.linspace(1, 6, int(5/0.2) + 1))\n\n def test_user_defined_noise(self):\n \"\"\"\n Test for the user-defined noise object\n \"\"\"\n dr_noise = DriftNoise(sigmax())\n proc = Processor(1)\n proc.add_noise(dr_noise)\n tlist = np.array([0, np.pi/2.])\n proc.add_pulse(Pulse(identity(2), 0, tlist, False))\n result = proc.run_state(init_state=basis(2, 0))\n assert_allclose(\n fidelity(result.states[-1], basis(2, 1)), 1, rtol=1.0e-6)\n\n def test_zz_cross_talk(self):\n circuit = QubitCircuit(2)\n circuit.add_gate(\"X\", 0)\n processor = SCQubits(2)\n processor.add_noise(ZZCrossTalk(processor.params))\n processor.load_circuit(circuit)\n pulses = processor.get_noisy_pulses(device_noise=True, drift=True)\n for pulse in pulses:\n if not isinstance(pulse, Drift) and pulse.label==\"systematic_noise\":\n assert(len(pulse.coherent_noise) == 1)\n","sub_path":"tests/test_noise.py","file_name":"test_noise.py","file_ext":"py","file_size_in_byte":9096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"378314482","text":"import time\nimport socket\n\nfrom library.log import *\n\nclass tcpConnection():\n def __init__(self, **kwargs):\n self.address = kwargs['address'] if 'address' in kwargs else '127.0.0.1'\n self.port = kwargs['port'] if 'port' in kwargs else 22\n self.socket = socket.socket()\n\n def connect(self, timeout = 0):\n logMessage(\"Connecting to host: [%s][%d]\" % (self.address, self.port))\n start = time.time()\n while True:\n try:\n self.socket.connect((self.address, self.port))\n except socket.error as err:\n logMessage(\"Unable to connect: [%s]\" % err)\n if timeout == 0: return(False)\n else:\n logMessage(\"Connected: [%s][%d]\" % (self.address, self.port))\n break\n elapsed = time.time() - start\n if elapsed >= timeout: return(False)\n time.sleep(1)\n return(True)\n","sub_path":"tcpConnection.py","file_name":"tcpConnection.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"5724797","text":"import pytest\n\nfrom mir.qualia import qualifier\n\n\n@pytest.mark.parametrize(\n 'line,expected', [\n ('', ''),\n ('spam', ''),\n (' spam', ' '),\n ])\ndef test__get_indent(line, expected):\n assert qualifier._get_indent(line) == expected\n\n\n@pytest.mark.parametrize(\n 'lines,expected', [\n ([], ''),\n (['abc', 'def'], ''),\n ([' abc', ' def'], ' '),\n ])\ndef test__common_indent(lines, expected):\n assert qualifier._common_indent(lines) == expected\n","sub_path":"tests/qualifier/test__common_indent.py","file_name":"test__common_indent.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"591982064","text":"\n# Author: Bhalendra Katiyar \n# Date: March 12, 2018\n\nimport pandas as pd\nfrom os import system\nfrom time import sleep\nimport sys\nimport json\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data', type=str, required=True, help='CSV file containing emails in first column without header row')\nparser.add_argument('--start', type=int, required=True, help='starting index')\nparser.add_argument('--end', type=int, required=True, help='ending index')\nparser.add_argument('--chunk', type=int, default=50, help='chunk size')\nparser.add_argument('--timeout', type=int, default=5, help='time gap between chunks in seconds')\nargs = parser.parse_args()\n\n\njson_content = {}\n\njson_content['Source'] = '\"Unanth\" '\njson_content['Template'] = 'template5'\njson_content['ConfigurationSetName'] = 'ConfigSet'\njson_content['DefaultTemplateData'] = '{}'\njson_content['Destinations'] = []\n\ndests = []\n\ndf = pd.read_csv(args.data, usecols=[0], header=None)\n\nclass color:\n PURPLE = '\\033[95m'\n CYAN = '\\033[96m'\n DARKCYAN = '\\033[36m'\n BLUE = '\\033[94m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n RED = '\\033[91m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n END = '\\033[0m'\n\nprint('*'*900)\nprint(color.BOLD + 'The Awesome Automation Mailer Script has been Started...' + color.END)\nprint('*'*900)\nsleep(3)\n\nstart = args.start\nend = args.end\n\nselected_df = df.iloc[start:end+1, :]\n\ncount = 0\nfor index, row in selected_df.iterrows():\n count = count + 1\n print(index, row[0], end=' ')\n dests.append({\n 'Destination': {\n 'ToAddresses': [\n row[0]\n ]\n },\n 'ReplacementTemplateData': '{}'\n })\n if count % args.chunk == 0:\n json_content['Destinations'] = dests\n dests = []\n with open('emails.json', 'w') as f:\n f.write(json.dumps(json_content))\n system('#aws ses send-bulk-templated-email --cli-input-json file://emails.json')\n print('_|_'*args.chunk)\n sleep(args.timeout)\n\nprint('*'*900)\nprint(color.BOLD + 'The Job is Done. :) - Tony' + color.END)\nprint('*'*900)\nsleep(3)\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"593127557","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom random import sample\n\nWINNING_COMBOS = ((1, 2, 3), (4, 5, 6), (7, 8, 9), # horizontals\n (1, 4, 7), (2, 5, 8), (3, 6, 9), # verticals\n (1, 5, 9), (3, 5, 7)) # diagonals\n\n\ndef choose_piece(board, turn, piece):\n \"\"\"Logic CPU uses to determine strategy.\n Returns (piece, cell_index)\n \"\"\"\n cpu = set([index for index in board if board[index] == piece])\n opponent_piece = \"X\" if piece == \"O\" else \"O\"\n opponent = set([index for index in board if board[index] == opponent_piece])\n\n # detect chance for win\n for combo in WINNING_COMBOS:\n # if two in what cpu has and two of a winning solution match\n # and the third one isn't owned by opponent...\n combo = set(combo)\n if len(cpu & combo) == 2 and len((combo - cpu) & opponent) == 0:\n # print \"jugular mode activate\"\n missing = (combo - cpu).pop()\n return (piece, missing)\n\n # detect chance to block: if opponent has two of a winning combo\n for combo in WINNING_COMBOS:\n combo = set(combo)\n if len(opponent & combo) == 2:\n missing = (combo - opponent).pop()\n # if I don't own missing already, block\n if missing not in cpu:\n # print \"nope\"\n return (piece, missing)\n\n corners = set([1, 3, 7, 9])\n untaken_corners = corners - cpu - opponent\n # if turn less than 2 or corners still open...\n if turn < 2 or len(untaken_corners) != 0:\n # pick an untaken corner cell\n random_corner = sample(untaken_corners, 1)[0]\n # print \"<3 corners\"\n return (piece, random_corner)\n\n # naive cpu -- chooses a random unassigned square\n # should only happen if no other winning conditions\n untaken_cells = set(board) - cpu - opponent\n random_cell = sample(untaken_cells, 1)[0]\n # print \"yolo\"\n return (piece, random_cell)\n","sub_path":"cpu_player.py","file_name":"cpu_player.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"86841117","text":"from yaml import load, dump\nimport sys\n\nif len(sys.argv) < 3:\n print(\"\"\"add-nullable.py \n\nExample:\nadd-nullable.py aylien/v1/news/api.yaml merged.yaml\n\nPlease run `speccy resolve` on the result to make sure the file is linted properly.\"\"\")\n sys.exit(0)\n\ns = open(sys.argv[1])\noutput = sys.argv[2]\ndefinition = load(s)\n\nparameters = list(definition['components']['parameters'].values())\n\nfor value in definition['paths'].values():\n parameters += value.get('get', {}).get('parameters', [])\n\nfor value in parameters:\n if not value.get('required', False) and not value.get('$ref', False):\n value['schema'] = value.get('schema', {})\n value['schema']['nullable'] = True\n\nout = open(output, 'w')\ndump(definition, out)\n","sub_path":"scripts/add-nullable.py","file_name":"add-nullable.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"179472861","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.datasets import load_iris\n\n\ndata = load_iris()\n\nfeatureNames = data.feature_names # ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']\nfeatures = data.data # 150 arrays of 4 elements\n# print('features: ', features) # 150 arrays of 4 elements\n\ntargetNames = data.target_names # ['setosa', 'versicolor', 'virginica']\ntarget = data.target # ban do tuong ung giua target - data\n\nlabels = targetNames[target] # => Bien 0 => setosa, 1 => versicolor, 2 => virginica\n\nplength = features[:, 2] # petal length is the feature at position 2\n# print(plength.shape)\nisSetosa = (labels == 'setosa')\n\n# Important step\nmaxSetosa = plength[isSetosa].max()\n# print(plength[isSetosa])\n# print(maxSetora)\nminNonSetosa = plength[~isSetosa].min()\n\nprint('Max of Setosa: {0}'.format(maxSetosa)) # 1.9 \nprint('Min of Others: {0}'.format(minNonSetosa)) # 3.0\n\n# Conclusion => if petal length < 2 then it's Setosa","sub_path":"chapter-2/build-02.py","file_name":"build-02.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"220371912","text":"from collections import defaultdict\r\nfrom datetime import date, timedelta\r\nfrom django.http import HttpResponse, JsonResponse\r\nfrom django.shortcuts import render, redirect, get_object_or_404\r\nfrom django.views import View\r\nfrom rest_framework.utils import json\r\n\r\nfrom sales.forms import ProductForm, CustomerForm, PurchaseForm, LeadForm, InvoiceForm, ProductBoughtForm\r\n# from sales.utils import render_to_pdf\r\nfrom .models import Product, Customer, Lead, Invoice\r\nfrom rest_framework.views import APIView\r\nfrom .serializers import *\r\nfrom rest_framework.response import Response\r\nfrom rest_framework import status, generics\r\nfrom .models import *\r\nimport json\r\nimport requests\r\n\r\n\r\n# Create your views here.\r\ndef add_item(request):\r\n products = Product.objects.all()\r\n if request.method == \"POST\":\r\n product_form = ProductForm(request.POST)\r\n # print(request.POST)\r\n if product_form.is_valid():\r\n product_form.save()\r\n return redirect(\"sales:add_item\")\r\n return HttpResponse(\"Error\")\r\n else:\r\n product_form = ProductForm()\r\n return render(request, 'sales/items.html', {\"product_form\": product_form, \"products\": products})\r\n\r\n\r\ndef remove_product(request, pk):\r\n product = Product.objects.get(itemcode=pk)\r\n product.delete()\r\n return redirect(\"sales:add_item\")\r\n\r\n\r\ndef update_product(request, pk):\r\n product = get_object_or_404(Product, itemcode=pk)\r\n product_form = ProductForm(request.POST or None, instance=product)\r\n if request.method == 'POST':\r\n if product_form.is_valid():\r\n product_form.save()\r\n return redirect(\"sales:add_item\")\r\n else:\r\n pass\r\n # print(product_form.errors)\r\n return render(request, 'sales/update_product.html', {\"product\": product_form})\r\n\r\n\r\ndef detail_product(request, pk):\r\n product = Product.objects.get(itemcode=pk)\r\n product_form = ProductForm(request.POST or None, instance=product)\r\n return render(request, 'sales/product_detail.html', {\"product\": product_form, \"products\": product})\r\n\r\n\r\ndef add_customer(request):\r\n if request.method == \"POST\":\r\n customer_form = CustomerForm(request.POST)\r\n CustomerForm.doj = datetime.date.today()\r\n if customer_form.is_valid():\r\n customer_form.save()\r\n return redirect(\"sales:customer_list\")\r\n else:\r\n pass\r\n # print(customer_form.errors)\r\n # return HttpResponse(\"Error\")\r\n else:\r\n customer_form = CustomerForm()\r\n return render(request, \"sales/addcustomer.html\", {\"customer_form\": customer_form})\r\n\r\n\r\ndef update_customer(request, pk):\r\n customers = Customer.objects.all()\r\n customer = get_object_or_404(Customer, id=pk)\r\n # customer = Customer.objects.get(id=pk)\r\n customer_form = CustomerForm(request.POST or None, instance=customer)\r\n if request.method == 'POST':\r\n if customer_form.is_valid():\r\n customer_form.save()\r\n return redirect(\"sales:customer_list\")\r\n else:\r\n pass\r\n # print(customer_form.errors)\r\n\r\n return render(request, 'sales/update_customer.html', {\"customer\": customer_form})\r\n\r\n\r\ndef customer_list(request):\r\n customers = Customer.objects.all()\r\n\r\n return render(request, \"sales/clist.html\", {\"customers\": customers})\r\n\r\n\r\ndef remove_customer(request, pk):\r\n customer = Customer.objects.get(id=pk)\r\n customer.delete()\r\n return redirect(\"sales:customer_list\")\r\n\r\n\r\n# class GeneratePdf(View):\r\n# def get(self, request, *args, **kwargs):\r\n# customers = Customer.objects.all()\r\n# pdf = render_to_pdf('sales/clist.html', {\"customers\":customers})\r\n# return HttpResponse(pdf, content_type='application/pdf')\r\n\r\ndef customer_detail(request, pk):\r\n customer = Customer.objects.get(id=pk)\r\n customer_form = CustomerForm(request.POST or None, instance=customer)\r\n return render(request, 'sales/customer_detail.html', {\"customer_form\": customer_form, \"customer\": customer})\r\n\r\n\r\n# def purchase_item(request):\r\n# if request.method=='POST':\r\n# purchase_form=PurchaseForm(request.POST)\r\n# if purchase_form.is_valid():\r\n# purchase_form.save()\r\n# purchase_form = PurchaseForm()\r\n# return render(request,'sales/purchase_product.html',{'purchase_form':purchase_form})\r\n# purchase_form = PurchaseForm()\r\n# return render(request,'sales/purchase_product.html',{'purchase_form':purchase_form})\r\n\r\ndef sales_dashboard(request):\r\n department = request.user.employee.dept\r\n customer_val = Customer.objects.count()\r\n product_val = Product.objects.count()\r\n lead_val = Lead.objects.count()\r\n cv = week_chart()\r\n yc = yearly_chart()\r\n yc0 = json.dumps(yc[0])\r\n yc1 = json.dumps(yc[1])\r\n cv1 = json.dumps(cv[1])\r\n cv0 = json.dumps(cv[0])\r\n return render(request, 'sales/sales_dashboard.html',\r\n {'department': department, 'customer_val': customer_val, 'product_val': product_val,\r\n 'lead_val': lead_val, 'cv0': cv0, 'cv1': cv1, 'yc0': yc0, 'yc1': yc1})\r\n\r\n\r\ndef lead_list(request):\r\n leads = Lead.objects.all()\r\n return render(request, \"sales/Llist.html\", {\"leads\": leads})\r\n\r\n\r\ndef add_lead(request):\r\n if request.method == \"POST\":\r\n lead_form = LeadForm(request.POST)\r\n if lead_form.is_valid():\r\n lead_form.save()\r\n return redirect(\"sales:lead_list\")\r\n else:\r\n pass\r\n # print(lead_form.errors)\r\n # return HttpResponse(\"Error\")\r\n else:\r\n lead_form = LeadForm()\r\n return render(request, \"sales/addlead.html\", {\"lead_form\": lead_form})\r\n\r\n\r\ndef update_lead(request, pk):\r\n leads = Lead.objects.all()\r\n lead = get_object_or_404(Lead, id=pk)\r\n # customer = Customer.objects.get(id=pk)\r\n lead_form = LeadForm(request.POST or None, instance=lead)\r\n if request.method == 'POST':\r\n if lead_form.is_valid():\r\n lead_form.save()\r\n return redirect(\"sales:lead_list\")\r\n else:\r\n pass\r\n # print(lead_form.errors)\r\n return render(request, 'sales/update_lead.html', {\"lead_form\": lead_form})\r\n\r\n\r\ndef remove_lead(request, pk):\r\n lead = Lead.objects.get(id=pk)\r\n lead.delete()\r\n return redirect(\"sales:lead_list\")\r\n\r\n\r\nclass CustomerList(APIView):\r\n\r\n def get(self, request):\r\n candidate = Customer.objects.all()\r\n serializer = CustomerSerializer(candidate, many=True)\r\n return Response(serializer.data)\r\n\r\n def post(self, request):\r\n serializer = CustomerSerializer(data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(True)\r\n return Response(False)\r\n\r\n\r\nclass ProductList(APIView):\r\n\r\n def get(self, request):\r\n products = Product.objects.all()\r\n serializer = ProductSerializer(products, many=True)\r\n return Response(serializer.data)\r\n\r\n def post(self, request):\r\n serializer = ProductSerializer(data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(True)\r\n return Response(False)\r\n\r\n\r\nclass LeadList(APIView):\r\n\r\n def get(self, request):\r\n leads = Lead.objects.all()\r\n serializer = LeadSerializer(leads, many=True)\r\n return Response(serializer.data)\r\n\r\n def post(self, request):\r\n serializer = LeadSerializer(data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(True)\r\n return Response(False)\r\n\r\n\r\ndef add_invoice_product(request):\r\n invoice_no = request.session['invoice_no']\r\n invoice = Invoice.objects.get(invoice_no=invoice_no)\r\n products = invoice.productbought_set.all()\r\n if request.method == \"POST\":\r\n product_bought_form = ProductBoughtForm(request.POST)\r\n product = request.POST.get(\"search\")\r\n product = Product.objects.get(itemname=product)\r\n price = product.price\r\n quantity = request.POST.get(\"quantity\")\r\n amount = int(price) * int(quantity)\r\n product_bought_form.invoice = invoice\r\n product_bought_form.amount = amount\r\n pb = ProductBought()\r\n pb.product = product\r\n pb.amount = amount\r\n pb.quantity = quantity\r\n pb.invoice = invoice\r\n invoice.total_amount = invoice.total_amount + amount\r\n invoice.save()\r\n pb.save()\r\n return redirect(\"sales:add_invoice_product\")\r\n # if product_bought_form.is_valid():\r\n # product_bought_form.save()\r\n # redirect(\"sales:add_invoice_product\", invoice_no=invoice_no)\r\n # else:\r\n # return HttpResponse(\"Form is not valid.\" + str(request.session['invoice_no']))\r\n else:\r\n context = {\r\n \"product_bought_form\": ProductBoughtForm(),\r\n \"products\": products,\r\n \"name\": invoice.customer.company_name,\r\n \"date\": invoice.date,\r\n \"invoice\": invoice\r\n }\r\n return render(request, \"sales/add_invoice_product.html\", context)\r\n\r\n\r\ndef add_invoice(request):\r\n if request.method == \"POST\":\r\n invoice_form = InvoiceForm(request.POST)\r\n if invoice_form.is_valid():\r\n inv = invoice_form.save()\r\n # return HttpResponse(\"Invoice Added\")\r\n request.session[\"invoice_no\"] = inv.invoice_no\r\n return redirect(\"sales:add_invoice_product\")\r\n else:\r\n return HttpResponse(\"Error\")\r\n else:\r\n invoice_form = InvoiceForm()\r\n return render(request, \"sales/add_invoice.html\", {\"invoice_form\": invoice_form})\r\n\r\n\r\ndef autocompleteModel(request):\r\n search_qs = Product.objects.filter(itemname__startswith=request.GET['search'])\r\n # print(request.GET['search'])\r\n results = []\r\n for r in search_qs:\r\n results.append(r.itemname)\r\n # print(results)\r\n resp = request.GET['callback'] + '(' + json.dumps(results) + ');'\r\n return HttpResponse(resp, content_type='application/json')\r\n\r\n\r\ndef invoice_list(request):\r\n invoices = Invoice.objects.all()\r\n invoices.reverse()\r\n return render(request, 'sales/invoice_list.html', {'invoices': invoices})\r\n\r\n\r\ndef show_invoice(request, invoice_no):\r\n invoice = Invoice.objects.get(invoice_no=invoice_no)\r\n products = invoice.productbought_set.all()\r\n context = {\r\n \"invoice\": invoice,\r\n \"products\": products,\r\n }\r\n # print(context)\r\n return render(request, 'sales/show_invoice.html', context)\r\n\r\n\r\ndef week_chart():\r\n N = 7\r\n current_date = date.today().isoformat()\r\n\r\n chart_values = defaultdict(float)\r\n for i in range(N):\r\n days_before = (date.today() - timedelta(days=i)).isoformat()\r\n for j in Invoice.objects.filter(date=days_before):\r\n chart_values[days_before] += j.total_amount\r\n cv = []\r\n cv.append(list(chart_values.keys()))\r\n cv.append(list(chart_values.values()))\r\n return cv\r\n\r\n\r\ndef yearly_chart():\r\n chart_values = defaultdict(float)\r\n for i in range(12):\r\n for j in Invoice.objects.filter(date__month=i + 1):\r\n chart_values[j.date.month] += j.total_amount\r\n\r\n ycvx = list(chart_values.keys())\r\n ycvy = list(chart_values.values())\r\n ycvxy = [ycvx, ycvy]\r\n # ycvx = json.dumps(ycvx)\r\n # ycvy = json.dumps(ycvy)\r\n # ycvxy = [ycvx, ycvy]\r\n return ycvxy\r\n\r\n\r\n# week_chart()\r\n\r\nclass WeekGraph(APIView):\r\n\r\n def get(self, request):\r\n leads = week_chart()\r\n return JsonResponse(leads, safe=False)\r\n\r\n\r\nclass YearGraph(APIView):\r\n def get(self, request):\r\n leads = yearly_chart()\r\n return JsonResponse(leads, safe=False)\r\n\r\n\r\n# class get_email_pass(generics.ListCreateAPIView):\r\n# queryset = userlogin.objects.all()\r\n# serializer_class = user_login\r\n\r\n\r\n# class User_api(APIView):\r\n# def user_login(request):\r\n#\r\n# username=\"sana\"\r\n# password=\"san\"\r\n# data = {\r\n# 'username': username,\r\n# 'password': password,\r\n#\r\n# }\r\n# # print(data)\r\n# data = json.dumps(data)\r\n# headers = {\r\n# \"Content-Type\": \"application/json\",\r\n# \"accept\": \"application/json\",\r\n# # 'Authorization': 'JWT ',\r\n# # Authorization: `JWT ${localStorage.getItem('token')}`,\r\n# }\r\n#\r\n# API_ENDPOINT = 'http://127.0.0.1:8000/token-auth/'\r\n# r = requests.post(url=API_ENDPOINT, data=data, headers=headers)\r\n# pastebin_url = r.content\r\n# print(\"The pastebin url is :%s\" % pastebin_url)\r\n# k = r.json()\r\n# # print(k)\r\n# token_data = k[\"token\"]\r\n# # print(token_data)\r\n#\r\n# file = open('token.txt', 'w')\r\n# file.write(token_data)\r\n# file.close()\r\n#\r\n# return HttpResponse('djsabhuhh')\r\n#\r\n# file = open('token.txt', 'r')\r\n# tokendata= file.read()\r\n# file.close()\r\n\r\n# def abcd(request):\r\n# print(tokendata)\r\n# headers = {\r\n# \"Content-Type\": \"application/json\",\r\n# \"accept\": \"application/json\",\r\n# 'Authorization': 'JWT ' + tokendata,\r\n# # Authorization: `JWT ${localStorage.getItem('token')}`,\r\n# }\r\n# username='deepesh'\r\n# email='deepesh.b17@iiits.in'\r\n# first_name='deepesh'\r\n# data={\r\n# 'username':username,\r\n# 'email':email,\r\n# 'first_name':first_name,\r\n# }\r\n# data=json.dumps(data)\r\n# api_url=('')\r\n# class saana(generics.ListCreateAPIView):\r\n# queryset = User.Objects.all()\r\n# serializer_class = userserializer\r\n\r\n# class ProfileUser(generics.ListCreateAPIView):\r\n# queryset = Employee.objects.all()\r\n# serializer_class = userdataSerializer\r\n#\r\n# def get_queryset(self):\r\n# username=self.request.user\r\n# print(username)\r\n# user_instance=User.objects.get(username=username)\r\n# #print(user_instance.email)\r\n# return Employee.objects.filter(user=user_instance)\r\n\r\nclass ProfileUser(APIView):\r\n queryset = Employee.objects.all()\r\n serializer_class = userdataSerializer\r\n\r\n def get(self, request):\r\n username = self.request.user\r\n user_instance = User.objects.get(username=username)\r\n # print(user_instance.email)\r\n list1 = []\r\n list1.append(user_instance.email)\r\n a = Employee.objects.filter(user=user_instance)\r\n for i in a:\r\n list1.append(i.first_name)\r\n list1.append(i.last_name)\r\n list1.append(i.position)\r\n # print(list1)\r\n\r\n return JsonResponse(list1, safe=False)\r\n","sub_path":"BlueTech/Sales/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"234372748","text":"import random\r\n\r\ndef qselect(n, nums):\r\n\tif len(nums)==1:\r\n\t\treturn nums[0]\r\n\tlength = len(nums)\r\n\tif n>length or nums==[]:\r\n\t\treturn None\r\n\tpivot = random.randint(0,length-1)\r\n\tleft = [x for x in nums if x < nums[pivot]]\r\n\tright =[x for x in nums[:pivot]+nums[pivot+1:] if x >= nums[pivot]]\r\n\tif n<=len(left):\r\n\t\treturn qselect(n, left)\r\n\telif n==len(left)+1:\r\n\t\treturn nums[pivot]\r\n\telse:\r\n\t\treturn qselect(n-len(left)-1, right)\r\n\r\n\r\n'''\r\nbest-case: O(n). When the first pivot is the select number, we just need to partition once.\r\nworst-case: O(n2). When every time we choose the biggest number as pivot, but the select number is the smallest one (or sysmatrically choosing smallest number as pivot, but the select number is the biggest).\r\naverage-case: O(n).\r\n'''","sub_path":"qselect.py","file_name":"qselect.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"39110457","text":"n = int(input())\nworks = []\nfor _ in range(n):\n row = list(map(int, input().split(\" \")))\n works.append(row)\n# 가장 빨리 끝내야되는 것들을 우선으로 진행해야함\nworks.sort(key=lambda x: x[1])\n\n\ndef solution(works, n):\n max_time = 0 # 출력값\n for tmp_time in range(0, 1000000): # 24시간이라 했지만 범위가 1000000임\n done = 0 # 끝난 일 개수\n start_time = tmp_time # 시작 시간이 계속 바뀌기 때문에 업데이트\n for work in works:\n end_time = start_time + work[0] # 끝나는 시간 체크\n if end_time <= work[1]:\n start_time = end_time\n done += 1 # 만약 원하는 시간 안으로 끝나면 1 더해준다.\n if done != n and tmp_time == 0: # 0시부터 모든 일을 끝낼 수 없으면 다른 시간에도 끝내지 못함\n return -1\n if done == n: # 다 끝내면 max_time 업데이트\n max_time = tmp_time\n elif done != n: # 언젠가 끝낼 수 없는 시간이 생김. 그땐 max_time 출력\n return max_time\n\n\nprint(solution(works, n))","sub_path":"백준/백준_1263번.py","file_name":"백준_1263번.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"568316382","text":"#SLICES DEMO\n\nprint(\"Slices Demo\"*3)\n\ncolours = [\"Mujtaba\",\"Asif\",\"Imad\",\"Rizwan\",\"Sarfaraz\"]\nprint(len(colours))\nprint(colours[0:len(colours)])\nprint(colours[0:5])\nprint(colours[0:5:1])\nprint(colours[0:5:2])\nprint(colours[0:5:-1])\nprint(colours[0::-1])\nprint(colours[5::-1])\nprint(colours[2::-1])\nprint(colours[:5:-1])\nprint(colours[:3:-1])\nprint(colours[0:5:-1])\nprint(colours[1:4])\n\ntrial = [1,2,3,4,5,6]\nprint(trial)\nprint(trial[0:5])\nprint(trial[6::-1])\nprint(trial[:1:-1])\nprint(trial[6:1:-1])\nprint(trial[5:2:-1])\nprint(colours[4][::-1])\n\n\n#LIST COMPREHENSION\nname = \"Syed Mujtaba Arfat\"\n\nname2 =[char for char in name if char not in \"aeiou\"]\nprint(\"\".join(name2))\n\n\neven = [ num for num in range(1,50) if num%2==0]\nprint(even)\n\nodd = [num for num in range(1,50) if num%2!=0]\nprint(odd)\n\nnum_list = [num*2 if num%2==0 else num *1 for num in range(1,60)]\nprint(num_list)\n\n\n\n#[[1 2 3] [ 1 2 3 ] [1 2 3 ]]\n\ndemo = [[ num for num in range(1,4) ]for val in range(1,5)]\n\nprint(demo)\n\nl1=[1,2,3,4,5,6,7,8,9]\noutput=[]\ni=0;\nwhile i= '2014':\n dirname = 'data/ttw/results/' + dt\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n filename = compId + '_' + compName + '.txt'\n lines = set()\n if os.path.exists(dirname + '/' + filename):\n with open(dirname + '/' + filename, encoding='utf-8') as fin:\n for line in fin:\n lines.add(line.strip())\n if fout:\n fout.close()\n fout = open(dirname + '/' + filename, 'a', encoding='utf-8')\n else:\n break\n else:\n if dt >= '2014':\n name2 = ''\n score = ''\n for i, td in enumerate(tds):\n if i == 0:\n score = td.get_attribute('innerHTML').replace(':', '-')\n elif i == 1:\n name2 = td.find_elements(By.TAG_NAME, \"a\")[0].get_attribute('innerHTML')\n name2 += ';' + td.find_elements(By.TAG_NAME, \"a\")[0].get_attribute('href').split('=')[-1]\n # print([dt, compName, name1, name2, score])\n row = '\\t'.join([dt, compName, name1, name2, score])\n if not (row in lines):\n fout.write(row + '\\n')\n if fout:\n fout.close()\n playersInfo[plId] = [plName, games]\n if cc % 10 == 0:\n with open('data/ttw/players_info.txt', 'w', encoding='utf-8') as fout:\n for k,v in sorted(playersInfo.items(), key = lambda x: x[0]):\n fout.write(k + '\\t' + v[0] + '\\t' + v[1] + '\\n')\n with open('data/ttw/players_info.txt', 'w', encoding='utf-8') as fout:\n for k, v in sorted(playersInfo.items(), key=lambda x: x[0]):\n fout.write(k + '\\t' + v[0] + '\\t' + v[1] + '\\n')\n driver.quit()\n\ndef main():\n playersInfo = dict()\n with open('data/ttw/players_info.txt', encoding='utf-8') as fin:\n for line in fin:\n tokens = line.rstrip().split('\\t')\n playersInfo[tokens[0]] = tokens[1:]\n for e in range(0, 1001, 500):\n url = 'http://ttw.ru/ttw-rs/index.php?litera=rating&page=' + str(e)\n scrappPage(url, playersInfo)\n\nif __name__ == \"__main__\":\n main()","sub_path":"ttw_scrapper.py","file_name":"ttw_scrapper.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"121767992","text":"import numpy as np\nimport os\nimport sys\nimport math\nimport aplpy\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pyfits\n\nfitsfiles={'color':{'fname':'chan1_NW_mask_c18o_pix_2_Tmb.fits','title':'C18O(1-0)','bmaj':0,'bmin':0,'galpa':0},\n 'template':{'fname':'chan1_NW_mask_c18o_pix_2_Tmb.fits'},\n 'channel':{'fname':'../NW_mask_c18o_pix_2_Tmb.fits','title':r'C18O(1-0)','mincolor':1.,'maxcolor':3.},\n }\n\nos.system('cp '+fitsfiles['template']['fname']+' '+'template_'+fitsfiles['template']['fname'])\ntemplatehdulist = pyfits.open('template_'+fitsfiles['template']['fname'])\ntemplatedata = templatehdulist[0].data\nnanpixels = np.isnan(templatedata) # maybe this can be broadcast to the entire channeldata array. tbd\nchannelhdulist = pyfits.open(fitsfiles['channel']['fname'])\nchanneldata = channelhdulist[0].data\n\ndef currentvel(hdulistheader,currentchannel):\n vref = hdulistheader['CRVAL3']\n vdelt= hdulistheader['CDELT3']\n return (vref + (currentchannel - 1) * vdelt)/1.e3\n\nypanels=3\nxpanels=4\nxcenter = 312.5676799\nycenter = 44.5018964\nwid = 0.3561111\nhei = 0.5444445\n\nfirstchannelstart=1\nlastchannel=120\n\nfor startchan in range(firstchannelstart,lastchannel,ypanels*xpanels):\n\n channelstart=startchan # start from which channel, note the different starting index. tbd\n currentchannel=channelstart\n pdfname='NW_chan_c18o'+str(startchan)+'.pdf'\n \n fig=plt.figure(figsize=(3*xpanels,4*ypanels))\n for j in range(0,ypanels): # this order first follows row\n for i in range(0,xpanels):\n templatedata[0,0,:,:]=channeldata[0,currentchannel-1,:,:]\n templatedata[nanpixels] = np.nan\n templatehdulist.writeto('template_channel.fits',output_verify='exception',clobber=True,checksum=False) # use this as template to output every single channel\n subpos=[0.1+0.8/xpanels*i,0.1+0.9/ypanels*(ypanels-1-j),0.8/xpanels*0.99,0.9/ypanels*0.99]\n ff = aplpy.FITSFigure('template_channel.fits',figure=fig,subplot=subpos)\n ff.recenter(xcenter,ycenter,width=wid,height=hei) \n ff.set_theme('publication')\n mincolor = fitsfiles['channel']['mincolor']\n maxcolor = fitsfiles['channel']['maxcolor']\n ff.show_colorscale(vmin=mincolor,vmax=maxcolor,cmap='afmhot',stretch='sqrt')\n ff.tick_labels.set_yformat('dd.d')\n ff.tick_labels.set_xformat('dd.d')\n beamx = xcenter + wid/2.*1.3\n beamy = ycenter - hei/2.*9./10.\n bmaj = channelhdulist[0].header['BMAJ']\n bmin = channelhdulist[0].header['BMIN']\n beamangle = channelhdulist[0].header['BPA'] \n ff.show_ellipses(beamx,beamy,bmaj,bmin,angle=beamangle-90,facecolor='black',edgecolor='black')\n textx = xcenter + wid/2.*4./5.\n texty = ycenter + hei/2.*9./10.\n ff.add_label(textx,texty,'{0:.2f}'.format(currentvel(channelhdulist[0].header,currentchannel))+'km/s',color='black',horizontalalignment='left',verticalalignment='top')\n if j != ypanels-1:\n ff.hide_xaxis_label()\n ff.hide_xtick_labels()\n if i != 0:\n ff.hide_yaxis_label()\n ff.hide_ytick_labels()\n currentchannel = currentchannel + 1\n os.system('rm template_channel.fits')\n ax1 = fig.add_axes([0.90,0.697,0.01,0.9/ypanels])\n cmap = mpl.cm.afmhot\n# norm = mpl.colors.Normalize(vmin=mincolor, vmax=maxcolor)\n norm = mpl.colors.PowerNorm(gamma=0.5,vmin=mincolor, vmax=maxcolor)\n cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap,norm=norm,orientation='vertical',format='%.1f')#,ticks=colorticks)\n \n # close and save file\n fig.canvas.draw()\n os.system('rm '+pdfname)\n #plt.savefig(pdfname)\n plt.savefig(pdfname,bbox_inches='tight')\n plt.close(fig)\n os.system('open '+pdfname)\n os.system('cp '+pdfname+os.path.expandvars(' /Users/shuokong/GoogleDrive/imagesCARMANan/'))\n\ntemplatehdulist.close()\nchannelhdulist.close()\n\n","sub_path":"channelmaps/NW_channelmap.py","file_name":"NW_channelmap.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"605166207","text":"#!/usr/bin/python3\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pickle\nfrom tools.feature_format import featureFormat\n\n### read in data dictionary, convert to numpy array\ndata_dict = pickle.load( open(\"../final_project/final_project_dataset_unix.pkl\", \"rb\") )\nfeatures = [\"salary\", \"bonus\"]\n\n# Quiz 17: Remove outlier\ndata_dict.pop('TOTAL', 0)\n\ndata = featureFormat(data_dict, features)\n\n### plot scatterplot of bonus vs salary\nfor point in data:\n salary = point[0]\n bonus = point[1]\n plt.scatter( salary, bonus )\n\nplt.xlabel(\"salary\")\nplt.ylabel(\"bonus\")\nplt.show()\n\n# Quiz 18: Identify 2 more outliers\ndf = pd.DataFrame.from_dict(data_dict, orient='index')\ndf = df[['salary', 'bonus']]\ndf.bonus = pd.to_numeric(df.bonus, errors='coerce')\ndf.salary = pd.to_numeric(df.salary, errors='coerce')\nprint('\\n----- Quiz 18 -----')\nprint(df[(df.salary > 1000000) & (df.bonus > 5000000)])","sub_path":"08-outliers/17_enron_outliers.py","file_name":"17_enron_outliers.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"21669283","text":"\"\"\"Support for Zope interfaces.\"\"\"\n\nfrom typing import Iterable, Iterator, List, Optional, Union\nimport ast\nimport re\n\nfrom pydoctor import astbuilder, model, epydoc2stan\n\nclass ZopeInterfaceModule(model.Module):\n\n def setup(self) -> None:\n super().setup()\n self.implements_directly: List[str] = []\n\n @property\n def allImplementedInterfaces(self) -> Iterable[str]:\n \"\"\"Return all the interfaces provided by this module\n \"\"\"\n return self.implements_directly\n\n\nclass ZopeInterfaceClass(model.Class):\n isinterface = False\n isschemafield = False\n isinterfaceclass = False\n implementsOnly = False\n\n implementedby_directly: List[Union['ZopeInterfaceClass', ZopeInterfaceModule]]\n \"\"\"Only defined when isinterface == True.\"\"\"\n\n baseobjects: List[Optional['ZopeInterfaceClass']] # type: ignore[assignment]\n subclasses: List['ZopeInterfaceClass'] # type: ignore[assignment]\n\n def setup(self) -> None:\n super().setup()\n self.implements_directly: List[str] = []\n\n @property\n def allImplementedInterfaces(self) -> Iterable[str]:\n \"\"\"Return all the interfaces implemented by this class.\n\n This returns them in something like the classic class MRO.\n \"\"\"\n if self.implementsOnly:\n return self.implements_directly\n r = list(self.implements_directly)\n for b in self.baseobjects:\n if b is None:\n continue\n for interface in b.allImplementedInterfaces:\n if interface not in r:\n r.append(interface)\n return r\n\ndef _inheritedDocsources(obj: model.Documentable) -> Iterator[model.Documentable]:\n if not isinstance(obj.parent, (ZopeInterfaceClass, ZopeInterfaceModule)):\n return\n name = obj.name\n for interface in obj.parent.allImplementedInterfaces:\n io = obj.system.objForFullName(interface)\n if io is not None:\n assert isinstance(io, ZopeInterfaceClass)\n for io2 in io.allbases(include_self=True):\n if name in io2.contents:\n yield io2.contents[name]\n\nclass ZopeInterfaceFunction(model.Function):\n def docsources(self) -> Iterator[model.Documentable]:\n yield from super().docsources()\n yield from _inheritedDocsources(self)\n\nclass ZopeInterfaceAttribute(model.Attribute):\n def docsources(self) -> Iterator[model.Documentable]:\n yield from super().docsources()\n yield from _inheritedDocsources(self)\n\ndef addInterfaceInfoToScope(\n scope: Union[ZopeInterfaceClass, ZopeInterfaceModule],\n interfaceargs: Iterable[ast.expr],\n ctx: model.Documentable\n ) -> None:\n \"\"\"Mark the given class or module as implementing the given interfaces.\n @param scope: class or module to modify\n @param interfaceargs: AST expressions of interface objects\n @param ctx: context in which C{interfaceargs} are looked up\n \"\"\"\n for idx, arg in enumerate(interfaceargs):\n if isinstance(arg, ast.Starred):\n # We don't support star arguments at the moment.\n # But these are valid, so we shouldn't warn about them either.\n continue\n\n fullName = astbuilder.node2fullname(arg, ctx)\n if fullName is None:\n scope.report(\n 'Interface argument %d does not look like a name' % (idx + 1),\n section='zopeinterface')\n else:\n scope.implements_directly.append(fullName)\n\ndef _handle_implemented(\n implementer: Union[ZopeInterfaceClass, ZopeInterfaceModule]\n ) -> None:\n \"\"\"This is the counterpart to addInterfaceInfoToScope(), which is called\n during post-processing.\n \"\"\"\n\n for idx, iface_name in enumerate(implementer.implements_directly):\n try:\n iface = implementer.system.find_object(iface_name)\n except LookupError:\n implementer.report(\n 'Interface \"%s\" not found' % iface_name,\n section='zopeinterface')\n continue\n\n # Update names of reparented interfaces.\n if iface is not None:\n full_name = iface.fullName()\n if full_name != iface_name:\n implementer.implements_directly[idx] = full_name\n\n if isinstance(iface, ZopeInterfaceClass):\n if iface.isinterface:\n iface.implementedby_directly.append(implementer)\n else:\n implementer.report(\n 'Class \"%s\" is not an interface' % iface_name,\n section='zopeinterface')\n elif iface is not None:\n implementer.report(\n 'Supposed interface \"%s\" not detected as a class' % iface_name,\n section='zopeinterface')\n\ndef addInterfaceInfoToModule(\n module: ZopeInterfaceModule,\n interfaceargs: Iterable[ast.expr]\n ) -> None:\n addInterfaceInfoToScope(module, interfaceargs, module)\n\ndef addInterfaceInfoToClass(\n cls: ZopeInterfaceClass,\n interfaceargs: Iterable[ast.expr],\n ctx: model.Documentable,\n implementsOnly: bool\n ) -> None:\n cls.implementsOnly = implementsOnly\n if implementsOnly:\n cls.implements_directly = []\n addInterfaceInfoToScope(cls, interfaceargs, ctx)\n\n\nschema_prog = re.compile(r'zope\\.schema\\.([a-zA-Z_][a-zA-Z0-9_]*)')\ninterface_prog = re.compile(\n r'zope\\.schema\\.interfaces\\.([a-zA-Z_][a-zA-Z0-9_]*)'\n r'|zope\\.interface\\.Interface')\n\ndef namesInterface(system: model.System, name: str) -> bool:\n if interface_prog.match(name):\n return True\n obj = system.objForFullName(name)\n if not isinstance(obj, ZopeInterfaceClass):\n return False\n return obj.isinterface\n\nclass ZopeInterfaceModuleVisitor(astbuilder.ModuleVistor):\n\n def _handleAssignmentInModule(self,\n target: str,\n annotation: Optional[ast.expr],\n expr: Optional[ast.expr],\n lineno: int\n ) -> None:\n super()._handleAssignmentInModule(\n target, annotation, expr, lineno)\n\n if not isinstance(expr, ast.Call):\n return\n funcName = astbuilder.node2fullname(expr.func, self.builder.current)\n if funcName is None:\n return\n ob = self.system.objForFullName(funcName)\n if isinstance(ob, ZopeInterfaceClass) and ob.isinterfaceclass:\n # TODO: Process 'bases' and '__doc__' arguments.\n interface = self.builder.pushClass(target, lineno)\n assert isinstance(interface, ZopeInterfaceClass)\n interface.isinterface = True\n interface.implementedby_directly = []\n interface.bases = []\n interface.baseobjects = []\n self.builder.popClass()\n self.newAttr = interface\n\n def _handleAssignmentInClass(self,\n target: str,\n annotation: Optional[ast.expr],\n expr: Optional[ast.expr],\n lineno: int\n ) -> None:\n super()._handleAssignmentInClass(target, annotation, expr, lineno)\n\n if not isinstance(expr, ast.Call):\n return\n attr: Optional[model.Documentable] = self.builder.current.contents.get(target)\n if attr is None:\n return\n funcName = astbuilder.node2fullname(expr.func, self.builder.current)\n if funcName is None:\n return\n\n if funcName == 'zope.interface.Attribute':\n attr.kind = model.DocumentableKind.ATTRIBUTE\n args = expr.args\n if len(args) == 1 and isinstance(args[0], ast.Str):\n attr.setDocstring(args[0])\n else:\n attr.report(\n 'definition of attribute \"%s\" should have docstring '\n 'as its sole argument' % attr.name,\n section='zopeinterface')\n else:\n if schema_prog.match(funcName):\n attr.kind = model.DocumentableKind.SCHEMA_FIELD\n\n else:\n cls = self.builder.system.objForFullName(funcName)\n if not (isinstance(cls, ZopeInterfaceClass) and cls.isschemafield):\n return\n attr.kind = model.DocumentableKind.SCHEMA_FIELD\n\n # Link to zope.schema.* class, if setup with intersphinx.\n attr.parsed_type = epydoc2stan.AnnotationDocstring(expr.func)\n\n keywords = {arg.arg: arg.value for arg in expr.keywords}\n descrNode = keywords.get('description')\n if isinstance(descrNode, ast.Str):\n attr.setDocstring(descrNode)\n elif descrNode is not None:\n attr.report(\n 'description of field \"%s\" is not a string literal' % attr.name,\n section='zopeinterface')\n\n def visit_Call(self, node: ast.Call) -> None:\n base = astbuilder.node2fullname(node.func, self.builder.current)\n if base is None:\n return\n meth = getattr(self, \"visit_Call_\" + base.replace('.', '_'), None)\n if meth is not None:\n meth(base, node)\n\n def visit_Call_zope_interface_moduleProvides(self, funcName: str, node: ast.Call) -> None:\n if not isinstance(self.builder.current, ZopeInterfaceModule):\n self.default(node)\n return\n\n addInterfaceInfoToModule(self.builder.current, node.args)\n\n def visit_Call_zope_interface_implements(self, funcName: str, node: ast.Call) -> None:\n cls = self.builder.current\n if not isinstance(cls, ZopeInterfaceClass):\n self.default(node)\n return\n addInterfaceInfoToClass(cls, node.args, cls,\n funcName == 'zope.interface.implementsOnly')\n visit_Call_zope_interface_implementsOnly = visit_Call_zope_interface_implements\n\n def visit_Call_zope_interface_classImplements(self, funcName: str, node: ast.Call) -> None:\n parent = self.builder.current\n if not node.args:\n self.builder.system.msg(\n 'zopeinterface',\n f'{parent.description}:{node.lineno}: '\n f'required argument to classImplements() missing',\n thresh=-1)\n return\n clsname = astbuilder.node2fullname(node.args[0], parent)\n cls = None if clsname is None else self.system.allobjects.get(clsname)\n if not isinstance(cls, ZopeInterfaceClass):\n if clsname is None:\n argdesc = '1'\n problem = 'is not a class name'\n else:\n argdesc = f'\"{clsname}\"'\n problem = 'not found' if cls is None else 'is not a class'\n self.builder.system.msg(\n 'zopeinterface',\n f'{parent.description}:{node.lineno}: '\n f'argument {argdesc} to classImplements() {problem}',\n thresh=-1)\n return\n addInterfaceInfoToClass(cls, node.args[1:], parent,\n funcName == 'zope.interface.classImplementsOnly')\n visit_Call_zope_interface_classImplementsOnly = visit_Call_zope_interface_classImplements\n\n def visit_ClassDef(self, node: ast.ClassDef) -> Optional[ZopeInterfaceClass]:\n cls = super().visit_ClassDef(node)\n if cls is None:\n return None\n assert isinstance(cls, ZopeInterfaceClass)\n\n bases = [self.builder.current.expandName(base) for base in cls.bases]\n\n if 'zope.interface.interface.InterfaceClass' in bases:\n cls.isinterfaceclass = True\n\n if any(namesInterface(self.system, b) for b in cls.bases):\n cls.isinterface = True\n cls.kind = model.DocumentableKind.INTERFACE\n cls.implementedby_directly = []\n\n for n, o in zip(cls.bases, cls.baseobjects):\n if schema_prog.match(n) or (o and o.isschemafield):\n cls.isschemafield = True\n\n for fn, args in cls.decorators:\n if fn == 'zope.interface.implementer':\n if args is None:\n cls.report('@implementer requires arguments')\n continue\n addInterfaceInfoToClass(cls, args, cls.parent, False)\n\n return cls\n\n\nclass ZopeInterfaceASTBuilder(astbuilder.ASTBuilder):\n ModuleVistor = ZopeInterfaceModuleVisitor\n\n\nclass ZopeInterfaceSystem(model.System):\n Module = ZopeInterfaceModule\n Class = ZopeInterfaceClass\n Function = ZopeInterfaceFunction\n Attribute = ZopeInterfaceAttribute\n defaultBuilder = ZopeInterfaceASTBuilder\n\n def postProcess(self) -> None:\n super().postProcess()\n\n for mod in self.objectsOfType(ZopeInterfaceModule):\n _handle_implemented(mod)\n\n for cls in self.objectsOfType(ZopeInterfaceClass):\n _handle_implemented(cls)\n","sub_path":"pydoctor/zopeinterface.py","file_name":"zopeinterface.py","file_ext":"py","file_size_in_byte":12848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"648553231","text":"import flask\nimport json\nimport mariadb\napp = flask.Flask(__name__)\napp.config[\"DEBUG\"] = True\n# configuration used to connect to MariaDB\nconfig = {\n 'host': 'root_db_1',\n 'port': 3306,\n 'user': 'root',\n 'password': 'example',\n 'database': 'demo'\n }\n# route to return all people\n\n@app.route('/', methods=['GET'])\ndef hello():\n return \"hello shubahm search /api/people for names from database\"\n\n@app.route('/api/people', methods=['GET'])\ndef index():\n # connection for MariaDB\n conn = mariadb.connect(**config)\n # create a connection cursor\n cur = conn.cursor()\n # execute a SQL statement\n cur.execute(\"select * from people\")\n\n # serialize results into JSON\n row_headers=[x[0] for x in cur.description]\n rv = cur.fetchall()\n json_data=[]\n for result in rv:\n json_data.append(dict(zip(row_headers,result)))\n # return the results!\n return json.dumps(json_data)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\")\n","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"582962412","text":"from django.contrib import admin\nfrom schedule.models import Calendar, Event, MySpecialUser\n# Register your models here.\n\nclass CalendarAdmin(admin.ModelAdmin):\n prepopulated_fields = {\"slug\": (\"name\",)}\n\nadmin.site.register(Calendar, CalendarAdmin)\n\n\nclass EventAdmin(admin.ModelAdmin):\n list_display = ('title', 'start', 'end')\n search_fields = ['title']\n date_hierarchy = 'start'\n\nadmin.site.register(Event, EventAdmin)\n\nadmin.site.register(MySpecialUser)","sub_path":"schedule/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"416807639","text":"# -*- coding: UTF-8 -*-\n\nMOD = 10**9 + 7\n\nN = int(input())\nA = [list(map(int, input().split())) for _ in range(N)]\nans = 1\nfor a in A:\n ans *= sum(a)\n ans %= MOD\nprint(ans)","sub_path":"tenkei90/052.py","file_name":"052.py","file_ext":"py","file_size_in_byte":178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"97300815","text":"# Used To initialized Neural Network\nfrom keras.models import Sequential\nfrom keras.layers import Convolution2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\n\n#my name is ABC de.\n\n\n# Model Creation\nclassifier = Sequential()\n\n# Step 1: Convolution\n# classifier.add(Convolution2D(32(no of convolution), 3(no of row), 3(no of column)\n# , input_shape=(64, 64, 3), activation='relu'))\n\nclassifier.add(Convolution2D(32, 3, 3, input_shape=(64, 64, 3), activation='relu'))\n\n# 32- feature detector into 3*3 matrix\n# reshape transform all image into a single format\n\n# Step 2: Max Pooling\nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\n\n# Step 3: Flattening\nclassifier.add(Flatten()) \n\n# Step 4: Full Connection\n\nclassifier.add(Dense(output_dim=128, activation='relu'))\nclassifier.add(Dense(output_dim=1, activation='sigmoid'))\nclassifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nprint(\"All Step Done\")\n\nfrom keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n 'data/train',\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n 'data/test',\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\nclassifier.fit_generator(\n train_generator,\n steps_per_epoch=8000,\n epochs=1,\n validation_data=validation_generator,\n validation_steps=2000)\n","sub_path":"facerecognition.py","file_name":"facerecognition.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"373776934","text":"from typing import List\n\nimport torch\nimport torch.nn as nn\n\nfrom torecsys.utils.decorator import no_jit_experimental_by_namedtensor\nfrom . import Inputs\n\n\nclass ImageInputs(Inputs):\n r\"\"\"Base Inputs class for image, which embed image by a stack of convalution neural network (CNN) \n and fully-connect layer.\n \"\"\"\n\n @no_jit_experimental_by_namedtensor\n def __init__(self,\n embed_size: int,\n in_channels: int,\n layers_size: List[int],\n kernels_size: List[int],\n strides: List[int],\n paddings: List[int],\n pooling: str = \"avg_pooling\",\n use_batchnorm: bool = True,\n dropout_p: float = 0.0,\n activation: torch.nn.modules.activation = nn.ReLU()):\n r\"\"\"Initialize ImageInputs.\n \n Args:\n embed_size (int): Size of embedding tensor\n in_channel (int): Number of channel of inputs\n layers_size (List[int]): Layers size of CNN\n kernels_size (List[int]): Kernels size of CNN\n strides (List[int]): Strides of CNN\n paddings (List[int]): Paddings of CNN\n pooling (str, optional): Method of pooling layer. \n Defaults to avg_pooling.\n use_batchnorm (bool, optional): Whether batch normalization is applied or not after Conv2d. \n Defaults to True.\n dropout_p (float, optional): Probability of Dropout2d. \n Defaults to 0.0.\n activation (torch.nn.modules.activation, optional): Activation function of Conv2d. \n Defaults to nn.ReLU().\n \n Attributes:\n length (int): Size of embedding tensor.\n model (torch.nn.Sequential): Sequential of CNN-layers.\n fc (torch.nn.Module): Fully-connect layer (i.e. Linear layer) of outputs.\n \n Raises:\n ValueError: when pooling is not in [\"max_pooling\", \"avg_pooling\"]\n \"\"\"\n # refer to parent class\n super(ImageInputs, self).__init__()\n\n # bind length to embed_size\n self.length = embed_size\n\n # stack in_channels and layers_size\n layers_size = [in_channels] + layers_size\n\n # initialize sequential for CNN-layers\n self.model = nn.Sequential()\n\n # create a generator top create CNN-layers\n iterations = enumerate(zip(layers_size[:-1], layers_size[1:], kernels_size, strides, paddings))\n\n # loop through iterations to create CNN-layers\n for i, (in_c, out_c, k, s, p) in iterations:\n # add Conv2d to sequential\n self.model.add_module(\"conv2d_%s\" % i, nn.Conv2d(in_c, out_c, kernel_size=k, stride=s, padding=p))\n\n # add batch norm to sequential\n if use_batchnorm:\n self.model.add_module(\"batchnorm2d_%s\" % i, nn.BatchNorm2d(out_c))\n\n # add dropout to sequential\n self.model.add_module(\"dropout2d_%s\" % i, nn.Dropout2d(p=dropout_p))\n\n # add activation to sequential\n self.model.add_module(\"activation_%s\" % i, activation)\n\n # add pooling to sequential\n if pooling == \"max_pooling\":\n self.model.add_module(\"pooling\", nn.AdaptiveMaxPool2d(output_size=(1, 1)))\n elif pooling == \"avg_pooling\":\n self.model.add_module(\"pooling\", nn.AdaptiveAvgPool2d(output_size=(1, 1)))\n else:\n raise ValueError('pooling must be in [\"max_pooling\", \"avg_pooling\"].')\n\n # initialize linear layer of fully-connect outputs\n self.fc = nn.Linear(layers_size[-1], embed_size)\n\n def forward(self, inputs: torch.Tensor) -> torch.Tensor:\n r\"\"\"Forward calculation of ImageInputs.\n \n Args:\n inputs (T), shape = (B, C, H_{i}, W_{i}), dtype = torch.float: Tensor of images.\n \n Returns:\n T, shape = (B, 1, E): Output of ImageInputs.\n \"\"\"\n # feed forward to sequential of CNN,\n # output's shape of convolution model = (B, C_{last}, 1, 1)\n outputs = self.model(inputs.rename(None))\n outputs.names = (\"B\", \"C\", \"H\", \"W\")\n\n # fully-connect layer to transform outputs,\n # output's shape of fully-connect layers = (B, E)\n outputs = self.fc(outputs.rename(None).squeeze())\n\n # unsqueeze the outputs in dim = 1 and set names to the tensor,\n outputs = outputs.unsqueeze(1)\n outputs.names = (\"B\", \"N\", \"E\")\n\n return outputs\n","sub_path":"torecsys/inputs/base/image_inp.py","file_name":"image_inp.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"551465362","text":"from os import sys, path\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\n\nfrom datetime import datetime\nimport yaml\nfrom utils import RedisSentinelCache, ReferenceDataService\n\n\"\"\"\nScript called by cronjob to update reference data from elasticsearch to local cache\n\"\"\"\n\ndef update_reference_data():\n with open('/home/metax-user/app_config') as app_config:\n app_config_dict = yaml.load(app_config)\n\n redis_settings = app_config_dict.get('REDIS', None)\n es_settings = app_config_dict.get('ELASTICSEARCH', None)\n\n cache = RedisSentinelCache(master_only=True, settings=redis_settings)\n ReferenceDataService.populate_cache_reference_data(cache, settings=es_settings)\n\ndef get_time():\n return str(datetime.now().replace(microsecond=0))\n\ndef log(msg):\n print('%s %s' % (get_time(), msg))\n\nif __name__ == '__main__':\n log('Updating reference data...')\n try:\n update_reference_data()\n except Exception as e:\n log('Reference data update ended in an error: %s' % str(e))\n else:\n log('Reference data updated')\n","sub_path":"src/metax_api/cron/update_reference_data.py","file_name":"update_reference_data.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"457284018","text":"from django.conf.urls import patterns, include, url\nimport settings\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nfrom profiles.forms import RegistrationFormProfile\nfrom profiles import views\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'agri.views.home', name='home'),\n # url(r'^agri/', include('agri.foo.urls')),\n url(r'^$', 'egrain.views.map_view', name='show_map'),\n url(r'^show_history/(?P\\d+)/$', 'egrain.views.history_view', name='show_history'),\n url(r'^add_history/$', 'egrain.views.history_add', name='add_history'),\n url(r'^add_agriculture/$', 'egrain.views.agriculture_add', name='add_agriculture'),\n url(r'^add_manure/$', 'egrain.views.manure_add', name='add_manure'),\n url(r'^add_cornfield/$', 'egrain.views.database_add', name='add_cornfield'),\n\n url(r'^accounts/login/$', 'egrain.views.login', {}, 'login'),\n url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'template_name': 'login.html'}, 'logout'),\n #url(r'^$', 'twitter.views.logout_view'),\n url(r'^accounts/register/$', 'registration.views.register', {'form_class': RegistrationFormProfile, 'backend': 'registration.backends.default.DefaultBackend',}, name='registration_register'),\n url(r'^accounts/', include('registration.urls')),\n\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\nurlpatterns += patterns('',\n url(r'^accounts/profile/(?P\\w+)/$', views.edit_profile, name='profiles_edit_profile'),\n (r'^(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n)","sub_path":"agri/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"59394252","text":"import matplotlib.pyplot as plt\n\nh = []\ntrap = []\nsimp = []\n\nfile = open('convergence.dat','r');\nnext(file)\nfor line in file:\n items = line.split(',')\n dx = 1./(float(items[0])-1)\n h.append(dx)\n trap.append(float(items[1]))\n simp.append(float(items[2]))\n\nplt.figure()\nplt.plot(h,trap,label=\"Trapezoidal\")\nplt.plot(h,simp,label=\"Simpson\")\nplt.plot(h,h,label=\"h\")\nplt.xscale('log')\nplt.yscale('log')\nplt.legend(loc='upper left')\nplt.title(\"Asymptotic Convergence Analysis\")\nplt.xlabel(\"log(h)\")\nplt.ylabel(\"log(|y-erf(x)|)\")\nplt.show()\n","sub_path":"3hw/plot_convergence.py","file_name":"plot_convergence.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"122454573","text":"# Script to calculate storm-centered quantities in order to make composited plots \n# of OLR, SLP, vorticity, and \n# Written on Flurry (to have everything in one place), \n# to be transferred to Discover and run there.\n# Based on Jeff's scripts.\n# Save NetCDF files that can be transferred back to Flurry for additional \n# Do this for just global, not by region\n# Which variables? \n#Want to do slp, olr, precip, and vort850\n#But looks like we might only have slp and vort850 for V1;\n#data have also been moved since Jeff's script.\n#If have fewer variables for V1, forget nested dict for results--\n#or can still do it, just fewer variables to go through in V1.\n\n#Import stuff\nimport xarray as xr\nimport pandas as pd\nimport numpy as np\n\n#Load the model data saved by Read_Zhao_TCs.ipynb\n#(for pointing to where the storms are within the 2D model output)\nds_tracks_v1 = xr.open_dataset('zhao_tracks_v1.nc')\nds_tracks_v2 = xr.open_dataset('zhao_tracks_v2.nc')\n\n#Add variables relevant to peak intensity\nds_tracks_v1['max_wind_kts'] = ds_tracks_v1['wind_kts'].max(dim='date_time')\nds_tracks_v2['max_wind_kts'] = ds_tracks_v2['wind_kts'].max(dim='date_time')\nds_tracks_v1['min_pressure'] = ds_tracks_v1['pressure'].min(dim='date_time')\nds_tracks_v2['min_pressure'] = ds_tracks_v2['pressure'].min(dim='date_time')\nds_tracks_v1['argmax_wind_kts'] = ds_tracks_v1['wind_kts'].argmax(dim='date_time')\nds_tracks_v2['argmax_wind_kts'] = ds_tracks_v2['wind_kts'].argmax(dim='date_time')\n\n#Easiest way to do this would be to just do it at peak intensity,\n#then have a 3D NetCDF file for all the storms, \n#with each variable.\n\n#Number of storms\nnum_storms = {'v1': len(ds_tracks_v1.storm), \n 'v2': len(ds_tracks_v2.storm)}\n\n#Preallocate arrays for each variable and storm\n#One key per variable; How big is the box? 15x15 degree\n#(assuming everything already regridded to 0.5 degrees)\n#(This is what Jeff assumes, with -30 to 30 indices. So 61x61 grid)\ndict_arrays = {'v1': {'slp': np.zeros((61, 61, num_storms['v1'])), \n 'vort850': np.zeros((61, 61, num_storms['v1']))},\n 'v2': {'slp': np.zeros((61, 61, num_storms['v2'])), \n 'olr': np.zeros((61, 61, num_storms['v2'])), \n 'precip': np.zeros((61, 61, num_storms['v2'])),\n 'vort850': np.zeros((61, 61, num_storms['v2']))}}\n \n#Paths to the NetCDF files\npaths = {'v1': '/discover/nobackup/jdstron1/JS_C180_20YearTest/tc_data/',\n 'v2': '/discover/nobackup/jdstron1/JS_C180v2_20YearTest/tc_data/'}\n \n#Are they in different formats for each one?\n\n#Loop through each storm,\n#read the NetCDF file for the time where it had the peak intensity, \n#and fill in that entry in a 61x61 grid in the dicts\n \nds_tracks = {'v1': ds_tracks_v1, \n 'v2': ds_tracks_v2}\n \n# #What the files look like when loaded on ipython on Discover:\n# \n# [378432000 values with dtype=float32]\n# Coordinates:\n# * time (time) object 1995-01-01 06:00:00 ... 1996-01-01 00:00:00\n# * lon (lon) float32 -179.75 -179.25 -178.75 ... 178.75 179.25 179.75\n# * lat (lat) float32 -90.0 -89.25 -88.75 -88.25 ... 88.25 88.75 89.25 90.0\n# Attributes:\n# units: mb\n# long_name: sea-level pressure\n \n#OK so this is in -180 to 180 longitudes, just like the storm tracks.\n\n#Stuff for figuring out the indices:\nmonth_lengths_0 = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30]\nmonth_start_indices = np.cumsum(month_lengths_0)*4\n \nfor v in ['v1', 'v2']:\n print('Obtaining storm-centered grid at peak intensity for version: ' + v)\n for var in dict_arrays[v].keys():\n print('Looping through years for variable: ' + var)\n opened_year=0\n for i in np.arange(num_storms[v]): \n print(str(i)+'th storm')\n #Find the year of peak intensity to get the right file\n #print(ds_tracks[v]['year'])\n #print(ds_tracks[v]['argmax_wind_kts'])\n year_peak = ds_tracks[v]['year'].isel(storm=i, date_time=ds_tracks[v]['argmax_wind_kts'].isel(storm=i))\n #Find the month, day, hour to figure out the index (Jeff did something similar)\n month_peak = ds_tracks[v]['month'].isel(storm=i, date_time=ds_tracks[v]['argmax_wind_kts'].isel(storm=i))\n day_peak = ds_tracks[v]['day'].isel(storm=i, date_time=ds_tracks[v]['argmax_wind_kts'].isel(storm=i))\n hour_peak = ds_tracks[v]['hour'].isel(storm=i, date_time=ds_tracks[v]['argmax_wind_kts'].isel(storm=i))\n index_peak = int(month_start_indices[int(month_peak-1)]+(day_peak-1)*4+hour_peak/6-1)\n #There is an offset by 1 on 0,6,12,18 in the track data vs. 6,12,18,0 in these files.\n #If a storm peaked in the very first observation of the year: look in the previous year's file,\n #which includes it. (Should I ask Jeff about this?)\n if index_peak == -1:\n year_peak = year_peak -1 \n str_year = str(int(year_peak))\n #Find the lat and lon where the storm currently is\n lat_peak = ds_tracks[v]['lat'].isel(storm=i, date_time=ds_tracks[v]['argmax_wind_kts'].isel(storm=i))\n lon_peak = ds_tracks[v]['lon'].isel(storm=i, date_time=ds_tracks[v]['argmax_wind_kts'].isel(storm=i))\n #Open the file and subset to peak time--IF not opened already\n if not year_peak == opened_year:\n print('Opening NetCDF file for variable: ' + var + ' and year: ' + str_year)\n ds_gridded = xr.open_dataset(paths[v]+'atmos.'+str_year+'010100-'+str_year+'123123.'+var+'.nc')\n print('File opened')\n opened_year = year_peak\n ds_gridded_peak_time = ds_gridded.isel(time=index_peak)\n #Reduce to a 15x15 degree (61x61 pixel) grid around the storm, following how Jeff did this\n #How to deal with the date line?\n #Just use indices--Python will take care of the boundaries using negative indices\n #(No, actually it won't have to concatenate)\n #Find the lat/lon indices on the grid closest to where the storm is\n #print(lat_peak)\n #print(ds_gridded_peak_time['lat'])\n lat_index = np.argmin(np.abs(lat_peak.data-ds_gridded_peak_time['lat'].data))\n lon_index = np.argmin(np.abs(lon_peak.data-ds_gridded_peak_time['lon'].data))\n #Extract the (assuming lat, lon dimension order--check this: yes, that's the case)\n len_lat = len(ds_gridded_peak_time['lat'])\n len_lon = len(ds_gridded_peak_time['lon'])\n #Account for lon within 15 degrees of date line (don't have to worry for lat) by concatenating\n if lon_index < 30:\n print('lon_index < 30')\n ds_subset = np.concatenate([ds_gridded_peak_time[var].data[lat_index-30:lat_index+31,lon_index-30:],\n ds_gridded_peak_time[var].data[lat_index-30:lat_index+31,:lon_index+31]], axis=1)\n elif (len_lon-1) - lon_index < 30:\n print('len_lon - lon_index < 30')\n ds_subset = np.concatenate([ds_gridded_peak_time[var].data[lat_index-30:lat_index+31,lon_index-30:],\n ds_gridded_peak_time[var].data[lat_index-30:lat_index+31,:lon_index+31-len_lon]],axis=1)\n else:\n print('middle lons. lat_index: ' + str(lat_index) + ', lon_index: ' + str(lon_index))\n ds_subset = ds_gridded_peak_time[var].data[lat_index-30:lat_index+31, \n lon_index-30:lon_index+31]\n \n #Fill in the layer in the preallocated arrays\n dict_arrays[v][var][:,:,i] = ds_subset\n \n#Print some test output\nfor v in ['v1','v2']:\n for var in dict_arrays[v].keys():\n print('For ' + v + ', variable ' + var +':')\n print('Array shape is: ')\n print(np.shape(dict_arrays[v][var]))\n \n \n#Construct XArray datasets from the arrays and save\nfor v in ['v1', 'v2']:\n da_dict=dict()\n for var in dict_arrays[v].keys():\n da_dict[var] = xr.DataArray(dict_arrays[v][var], name=var,\n coords=[pd.Index(np.linspace(-15, 15, 61), name='lat'), \n pd.Index(np.linspace(-15, 15, 61), name='lon'),\n pd.Index(np.arange(num_storms[v]), name='storm')]) \n ds_merged = xr.merge(da_dict.values())\n ds_merged.to_netcdf('storm_centered_peak_intensity_'+v+'.nc')\n \n \n \n\n \n\n \n \n","sub_path":"Storm_Centered_Plots.py","file_name":"Storm_Centered_Plots.py","file_ext":"py","file_size_in_byte":8941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"292206052","text":"#! /usr/bin/env python\nimport contextlib\nimport os\nimport subprocess\nimport sys\n\nimport numpy as np\nfrom numpy.distutils.fcompiler import new_fcompiler\nfrom setuptools import Extension, find_packages, setup\nfrom setuptools.command.build_ext import build_ext as _build_ext\n\ncommon_flags = {\n \"include_dirs\": [\n np.get_include(),\n os.path.join(sys.prefix, \"include\"),\n ],\n \"library_dirs\": [],\n \"define_macros\": [],\n \"undef_macros\": [],\n \"extra_compile_args\": [],\n \"language\": \"c\",\n}\n\nlibraries = []\n\n# Locate directories under Windows %LIBRARY_PREFIX%.\nif sys.platform.startswith(\"win\"):\n common_flags[\"include_dirs\"].append(os.path.join(sys.prefix, \"Library\", \"include\"))\n common_flags[\"library_dirs\"].append(os.path.join(sys.prefix, \"Library\", \"lib\"))\n\next_modules = [\n Extension(\n \"pymt_prms_surface.lib.prmssurface\",\n [\"pymt_prms_surface/lib/prmssurface.pyx\"],\n libraries=libraries + [\"bmiprmssurface\"],\n extra_objects=[\"pymt_prms_surface/lib/bmi_interoperability.o\"],\n **common_flags\n ),\n]\n\nentry_points = {\n \"pymt.plugins\": [\n \"PRMSSurface=pymt_prms_surface.bmi:PRMSSurface\",\n ]\n}\n\n\n@contextlib.contextmanager\ndef as_cwd(path):\n prev_cwd = os.getcwd()\n os.chdir(path)\n yield\n os.chdir(prev_cwd)\n\n\ndef build_interoperability():\n compiler = new_fcompiler()\n compiler.customize()\n\n cmd = []\n cmd.append(compiler.compiler_f90[0])\n cmd.append(compiler.compile_switch)\n if sys.platform.startswith(\"win\") is False:\n cmd.append(\"-fPIC\")\n for include_dir in common_flags[\"include_dirs\"]:\n if os.path.isabs(include_dir) is False:\n include_dir = os.path.join(sys.prefix, \"include\", include_dir)\n cmd.append(\"-I{}\".format(include_dir))\n cmd.append(\"bmi_interoperability.f90\")\n\n try:\n subprocess.check_call(cmd)\n except subprocess.CalledProcessError:\n raise\n\n\nclass build_ext(_build_ext):\n def run(self):\n with as_cwd(\"pymt_prms_surface/lib\"):\n build_interoperability()\n _build_ext.run(self)\n\n\ndef read(filename):\n with open(filename, \"r\", encoding=\"utf-8\") as fp:\n return fp.read()\n\n\nlong_description = u\"\\n\\n\".join(\n [read(\"README.rst\"), read(\"CREDITS.rst\"), read(\"CHANGES.rst\")]\n)\n\n\nsetup(\n name=\"pymt_prms_surface\",\n author=\"Community Surface Dynamics Modeling System\",\n author_email=\"csdms@colorado.edu\",\n description=\"PyMT plugin for prms_surface\",\n long_description=long_description,\n version=\"0.2.2.dev0\",\n url=\"https://github.com/pymt-lab/pymt_prms_surface\",\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.8\",\n ],\n keywords=[\"bmi\", \"pymt\"],\n install_requires=open(\"requirements.txt\", \"r\").read().splitlines(),\n setup_requires=[\"cython\"],\n ext_modules=ext_modules,\n cmdclass=dict(build_ext=build_ext),\n packages=find_packages(),\n entry_points=entry_points,\n include_package_data=True,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"467914751","text":"# Copyright (c) 2019, ZIH,\n# Technische Universitaet Dresden,\n# Federal Republic of Germany\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# * Neither the name of metricq nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom .exception import raises, NotFoundError\n\nimport asyncio\nimport aiohttp\n\nfrom urllib.parse import quote\n\n\ndef _quote_id(id):\n return quote(id, safe=[])\n\n\ndef _stringify_params(params):\n if params is None:\n return None\n result = {}\n for key, value in params.items():\n if value is None:\n continue\n elif value is True:\n value = \"true\"\n elif value is False:\n value = \"false\"\n\n result[key] = value\n\n return result\n\n\nclass RemoteServer(object):\n def __init__(self, server, user=None, password=None, cookie=None, **kwargs):\n self._server = server\n auth = aiohttp.BasicAuth(user, password) if user else None\n headers = {\"Cookie\": \"AuthSession=\" + cookie} if cookie else None\n self._http_session = aiohttp.ClientSession(headers=headers, auth=auth, **kwargs)\n self._databases = {}\n\n async def _get(self, path, params=None):\n return await self._request(\"GET\", path, params=params)\n\n async def _get_bytes(self, path, params=None):\n return await self._request(\"GET\", path, params=params, return_json=False)\n\n async def _put(self, path, data=None, params=None):\n return await self._request(\"PUT\", path, json=data, params=params)\n\n async def _put_bytes(self, path, data, content_type, params=None):\n return await self._request(\n \"PUT\",\n path,\n data=data,\n params=params,\n headers={\"Content-Type\": content_type},\n )\n\n async def _post(self, path, data, params=None):\n return await self._request(\"POST\", path, json=data, params=params)\n\n async def _delete(self, path, params=None):\n return await self._request(\"DELETE\", path, params=params)\n\n async def _head(self, path, params=None):\n return await self._request(\"HEAD\", path, params=params)\n\n async def _request(\n self,\n method,\n path,\n params,\n return_json=True,\n **kwargs,\n ):\n kwargs[\"params\"] = _stringify_params(params)\n\n async with self._http_session.request(\n method, url=f\"{self._server}{path}\", **kwargs\n ) as resp:\n resp.raise_for_status()\n return resp.headers, await resp.json() if return_json else await resp.read()\n\n @raises(401, \"Invalid credentials\")\n async def _all_dbs(self, **params):\n _, json = await self._get(\"/_all_dbs\", params)\n return json\n\n async def close(self):\n # If ClientSession has TLS/SSL connections, it is needed to wait 250 ms\n # before closing, see https://github.com/aio-libs/aiohttp/issues/1925.\n has_ssl_conn = self._http_session.connector and any(\n any(hasattr(handler.transport, \"_ssl_protocol\") for handler, _ in conn)\n for conn in self._http_session.connector._conns.values()\n )\n await self._http_session.close()\n await asyncio.sleep(0.250 if has_ssl_conn else 0)\n\n @raises(401, \"Invalid credentials\")\n async def _info(self):\n _, json = await self._get(\"/\")\n return json\n\n @raises(401, \"Authentification failed, check provided credentials.\")\n async def _check_session(self):\n return await self._get(\"/_session\")\n\n\nclass RemoteDatabase(object):\n def __init__(self, remote, id):\n self.id = id\n self._remote = remote\n\n @property\n def endpoint(self):\n return f\"/{_quote_id(self.id)}\"\n\n @raises(401, \"Invalid credentials\")\n @raises(403, \"Read permission required\")\n async def _exists(self):\n try:\n await self._remote._head(self.endpoint)\n return True\n except aiohttp.ClientResponseError as e:\n if e.status == 404:\n return False\n else:\n raise e\n\n @raises(401, \"Invalid credentials\")\n @raises(403, \"Read permission required\")\n @raises(404, \"Requested database not found ({id})\")\n async def _get(self):\n _, json = await self._remote._get(self.endpoint)\n return json\n\n @raises(400, \"Invalid database name\")\n @raises(401, \"CouchDB Server Administrator privileges required\")\n @raises(412, \"Database already exists\")\n async def _put(self, **params):\n _, json = await self._remote._put(self.endpoint)\n return json\n\n @raises(400, \"Invalid database name or forgotten document id by accident\")\n @raises(401, \"CouchDB Server Administrator privileges required\")\n @raises(404, \"Database doesn’t exist or invalid database name ({id})\")\n async def _delete(self):\n await self._remote._delete(self.endpoint)\n\n @raises(400, \"The request provided invalid JSON data or invalid query parameter\")\n @raises(401, \"Read permission required\")\n @raises(403, \"Read permission required\")\n @raises(404, \"Invalid database name\")\n @raises(415, \"Bad Content-Type value\")\n async def _bulk_get(self, docs, **params):\n _, json = await self._remote._post(\n f\"{self.endpoint}/_bulk_get\", {\"docs\": docs}, params\n )\n return json\n\n @raises(400, \"The request provided invalid JSON data\")\n @raises(401, \"Invalid credentials\")\n @raises(403, \"Write permission required\")\n @raises(417, \"At least one document was rejected by the validation function\")\n async def _bulk_docs(self, docs, **data):\n data[\"docs\"] = docs\n _, json = await self._remote._post(f\"{self.endpoint}/_bulk_docs\", data)\n return json\n\n @raises(400, \"Invalid request\")\n @raises(401, \"Read privilege required for document '{id}'\")\n @raises(403, \"Read permission required\")\n @raises(500, \"Query execution failed\", RuntimeError)\n async def _find(self, selector, **data):\n data[\"selector\"] = selector\n _, json = await self._remote._post(f\"{self.endpoint}/_find\", data)\n return json\n\n @raises(401, \"Invalid credentials\")\n @raises(403, \"Permission required\")\n async def _get_security(self):\n _, json = await self._remote._get(f\"{self.endpoint}/_security\")\n return json\n\n @raises(401, \"Invalid credentials\")\n @raises(403, \"Permission required\")\n async def _put_security(self, doc):\n _, json = await self._remote._put(f\"{self.endpoint}/_security\", doc)\n return json\n\n\nclass RemoteDocument(object):\n def __init__(self, database, id):\n self._database = database\n self.id = id\n\n @property\n def endpoint(self):\n return f\"{self._database.endpoint}/{_quote_id(self.id)}\"\n\n @raises(401, \"Read privilege required for document '{id}'\")\n @raises(403, \"Read privilege required for document '{id}'\")\n @raises(404, \"Document {id} was not found\")\n async def _head(self):\n await self._database._remote._head(self.endpoint)\n\n @raises(401, \"Read privilege required for document '{id}'\")\n @raises(403, \"Read privilege required for document '{id}'\")\n @raises(404, \"Document {id} was not found\")\n async def _info(self):\n headers, _ = await self._database._remote._head(self.endpoint)\n return {\"ok\": True, \"id\": self._data[\"_id\"], \"rev\": headers[\"Etag\"][1:-1]}\n\n async def _exists(self):\n try:\n await self._head()\n return True\n except NotFoundError:\n return False\n\n @raises(400, \"The format of the request or revision was invalid\")\n @raises(401, \"Read privilege required for document '{id}'\")\n @raises(403, \"Read privilege required for document '{id}'\")\n @raises(404, \"Document {id} was not found\")\n async def _get(self, **params):\n _, json = await self._database._remote._get(self.endpoint, params)\n return json\n\n @raises(400, \"The format of the request or revision was invalid\")\n @raises(401, \"Write privilege required for document '{id}'\")\n @raises(403, \"Write privilege required for document '{id}'\")\n @raises(404, \"Specified database or document ID doesn’t exists ({endpoint})\")\n @raises(\n 409,\n \"Document with the specified ID ({id}) already exists or specified revision \"\n \"{rev} is not latest for target document\",\n )\n async def _put(self, data, **params):\n _, json = await self._database._remote._put(self.endpoint, data, params)\n return json\n\n @raises(400, \"Invalid request body or parameters\")\n @raises(401, \"Write privilege required for document '{id}'\")\n @raises(403, \"Write privilege required for document '{id}'\")\n @raises(404, \"Specified database or document ID doesn’t exists ({endpoint})\")\n @raises(\n 409, \"Specified revision ({rev}) is not the latest for target document '{id}'\"\n )\n async def _delete(self, rev, **params):\n params[\"rev\"] = rev\n _, json = await self._database._remote._delete(self.endpoint, params)\n return json\n\n @raises(400, \"Invalid request body or parameters\")\n @raises(401, \"Read or write privileges required\")\n @raises(403, \"Read or write privileges required\")\n @raises(\n 404, \"Specified database, document ID or revision doesn’t exists ({endpoint})\"\n )\n @raises(\n 409,\n \"Document with the specified ID already exists or specified revision is not \"\n \"latest for target document\",\n )\n async def _copy(self, destination, **params):\n _, json = await self._database._remote._request(\n \"COPY\", self.endpoint, params=params, headers={\"Destination\": destination}\n )\n return json\n\n\nclass RemoteAttachment(object):\n def __init__(self, document, id):\n self._document = document\n self.id = id\n self.content_type = None\n\n @property\n def endpoint(self):\n return f\"{self._document.endpoint}/{_quote_id(self.id)}\"\n\n @raises(401, \"Read privilege required for document '{document_id}'\")\n @raises(403, \"Read privilege required for document '{document_id}'\")\n async def _exists(self):\n try:\n headers = await self._document._database._remote._head(self.endpoint)\n self.content_type = headers[\"Content-Type\"]\n return True\n except aiohttp.ClientResponseError as e:\n if e.status == 404:\n return False\n else:\n raise e\n\n @raises(400, \"Invalid request parameters\")\n @raises(401, \"Read privilege required for document '{document_id}'\")\n @raises(403, \"Read privilege required for document '{document_id}'\")\n @raises(404, \"Document '{document_id}' or attachment '{id}' doesn’t exists\")\n async def _get(self, **params):\n headers, data = await self._document._database._remote._get_bytes(\n self.endpoint, params\n )\n self.content_type = headers[\"Content-Type\"]\n return data\n\n @raises(400, \"Invalid request body or parameters\")\n @raises(401, \"Write privilege required for document '{document_id}'\")\n @raises(403, \"Write privilege required for document '{document_id}'\")\n @raises(404, \"Document '{document_id}' doesn’t exists\")\n @raises(\n 409, \"Specified revision {document_rev} is not the latest for target document\"\n )\n async def _put(self, rev, data, content_type, **params):\n params[\"rev\"] = rev\n _, json = await self._document._database._remote._put_bytes(\n self.endpoint, data, content_type, params\n )\n self.content_type = content_type\n return json\n\n @raises(400, \"Invalid request body or parameters\")\n @raises(401, \"Write privilege required for document '{document_id}'\")\n @raises(403, \"Write privilege required for document '{document_id}'\")\n @raises(404, \"Specified database or document ID doesn’t exists ({endpoint})\")\n @raises(\n 409, \"Specified revision {document_rev} is not the latest for target document\"\n )\n async def _delete(self, rev, **params):\n params[\"rev\"] = rev\n _, json = await self._document._database._remote._delete(self.endpoint, params)\n self.content_type = None\n return json\n\n\nclass RemoteView(object):\n def __init__(self, database, ddoc, id):\n self._database = database\n self.ddoc = ddoc\n self.id = id\n\n @property\n def endpoint(self):\n return (\n f\"{self._database.endpoint}/_design/{_quote_id(self.ddoc)}/_view/\"\n f\"{_quote_id(self.id)}\"\n )\n\n @raises(400, \"Invalid request\")\n @raises(401, \"Read privileges required\")\n @raises(403, \"Read privileges required\")\n @raises(404, \"Specified database, design document or view is missing\")\n async def _get(self, **params):\n _, json = await self._database._remote._get(self.endpoint, params)\n return json\n\n @raises(400, \"Invalid request\")\n @raises(401, \"Write privileges required\")\n @raises(403, \"Write privileges required\")\n @raises(404, \"Specified database, design document or view is missing\")\n async def _post(self, keys, **params):\n _, json = await self._database._remote._post(\n self.endpoint, {\"keys\": keys}, params\n )\n return json\n","sub_path":"aiocouch/remote.py","file_name":"remote.py","file_ext":"py","file_size_in_byte":14665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"517266588","text":"input = open('input.txt', 'r')\ninput_list = input.read().splitlines()\ninput.close()\n\ninput_cable1 = input_list[0].split(',')\ninput_cable2 = input_list[1].split(',')\n\ndef get_points(cable) :\n x = 0\n y = 0\n answer = set()\n for pos in cable :\n operator = pos[0]\n distance = int(pos[1:])\n dx = {'L':-1, 'R':1, 'U':0, 'D':0}\n dy = {'L': 0, 'R': 0, 'U': 1, 'D': -1}\n\n for i in range(distance) :\n x += dx[operator]\n y += dy[operator]\n answer.add((x,y))\n\n return answer\n\nall_pos_cable1 = get_points(input_cable1)\nall_pos_cable2 = get_points(input_cable2)\njoin = all_pos_cable1&all_pos_cable2\n\n# answer = [(x,y) for (x,y) in join]\nanswer = min([abs(x) + abs(y) for (x,y) in join])\nprint(answer)\n\n\n","sub_path":"advent-of-code/03/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"515517277","text":"from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('',\n\t#url(r'a/(\\d+)/report.json$', 'contrib.views.trigger_execution_report', name='trigger_execution_report'),\n\turl(r'a/(\\d+)(?:/([a-z0-9_-]+))?$', 'contrib.views.trigger', name='trigger'),\n\turl(r'contrib/_submit$', 'contrib.views.submit', name='contrib_submit'),\n\turl(r'contrib/_defaults$', 'contrib.views.get_user_defaults', name='contrib_defaults'),\n\turl(r'contrib/_cancel$', 'contrib.views.cancel_pledge', name='cancel_pledge'),\n\turl(r'contrib/_validate_email$', 'contrib.views.validate_email'),\n)\n","sub_path":"contrib/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"135768790","text":"import os\n\nfrom flask import Flask, request, url_for, abort, jsonify\n\napp = Flask(__name__)\napp.debug = True\n\ndb = {}\n\n\n@app.route('/')\ndef show_entries():\n collections = [\n dict(href=url_for('get_collection', cname=cname), cname=cname)\n for cname in db]\n return jsonify(collections=collections)\n\n\n@app.route('/', methods=['GET'])\ndef get_collection(cname):\n collection = db.get(cname)\n if collection is None:\n abort(404)\n docs = [\n dict(href=url_for('get_doc', cname=cname, id=id), id=id)\n for id in collection]\n return jsonify(docs=docs)\n\n\n@app.route('/', methods=['POST'])\ndef post_collection(cname):\n doc = request.get_json()\n collection = db.setdefault(cname, {})\n id = _gen_id()\n collection[id] = doc\n return jsonify(\n href=url_for('get_doc', cname=cname, id=id),\n id=id)\n\n\n@app.route('/', methods=['DELETE'])\ndef drop_collection(cname):\n db.pop(cname, None)\n return jsonify()\n\n\n@app.route('//', methods=['GET'])\ndef get_doc(cname, id):\n collection = db.get(cname)\n if collection is None:\n abort(404)\n doc = collection.get(id)\n if doc is None:\n abort(404)\n return jsonify(doc)\n\n\n@app.route('//', methods=['PUT'])\ndef put_doc(cname, id):\n doc = request.get_json()\n collection = db.setdefault(cname, {})\n collection[id] = doc\n return jsonify(doc)\n\n\n@app.route('//', methods=['DELETE'])\ndef del_doc(cname, id):\n collection = db.get(cname)\n if collection is None:\n abort(404)\n collection.pop(id, None)\n return jsonify()\n\ndef _gen_id():\n return os.urandom(12).encode('base64').strip()\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"examples/Networking/rest-api.py","file_name":"rest-api.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"426696209","text":"\"\"\"\nWrite a function to find the longest common prefix string amongst an array of strings.\n\"\"\"\n\nclass Solution(object):\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n return self.trie_method(strs)\n return self.horizontal_scan(strs)\n \n def trie_method(self, strs):\n trie = {}\n for s in strs:\n if len(s) == 0:\n return \"\"\n layer = trie\n for ch in s:\n if ch not in layer:\n layer[ch] ={}\n layer = layer[ch]\n layer[\"ch\"] = \"end\" \n lcp = \"\"\n layer = trie\n while len(layer) ==1 and ( \"ch\" not in layer):\n for key in layer:\n lcp += key\n layer = layer[key]\n return lcp\n \n def horizontal_scan(self, strs):\n if not strs:\n return \"\"\n lcp = strs[0]\n for s in strs[1:]:\n #print s\n i, j = 0, 0\n while i 0\n\n def _before_save(self):\n self.address = self._formatted(self.address)\n\n @utils.cached_property\n def ip_block(self):\n return IpBlock.get(self.ip_block_id)\n\n def add_inside_locals(self, ip_addresses):\n db.db_api.save_nat_relationships([\n {'inside_global_address_id': self.id,\n 'inside_local_address_id': local_address.id,\n }\n for local_address in ip_addresses])\n\n def deallocate(self):\n LOG.debug(\"Marking IP address for deallocation: %r\" % self)\n self.update(marked_for_deallocation=True,\n allocated=False,\n deallocated_at=utils.utcnow(),\n interface_id=None)\n\n def restore(self):\n LOG.debug(\"Restored IP address: %r\" % self)\n self.update(marked_for_deallocation=False, deallocated_at=None,\n allocated=True)\n\n def inside_globals(self, **kwargs):\n return db.db_query.find_inside_globals(\n IpAddress,\n local_address_id=self.id,\n **kwargs)\n\n def add_inside_globals(self, ip_addresses):\n db.db_api.save_nat_relationships([\n {'inside_global_address_id': global_address.id,\n 'inside_local_address_id': self.id,\n }\n for global_address in ip_addresses])\n\n def inside_locals(self, **kwargs):\n return db.db_query.find_inside_locals(IpAddress,\n global_address_id=self.id,\n **kwargs)\n\n def remove_inside_globals(self, inside_global_address=None):\n return db.db_api.remove_inside_globals(self.id, inside_global_address)\n\n def remove_inside_locals(self, inside_local_address=None):\n return db.db_api.remove_inside_locals(self.id, inside_local_address)\n\n def locked(self):\n return self.marked_for_deallocation\n\n @property\n def version(self):\n return netaddr.IPAddress(self.address).version\n\n @utils.cached_property\n def interface(self):\n return Interface.get(self.interface_id)\n\n @property\n def virtual_interface_id(self):\n return self.interface.virtual_interface_id if self.interface else None\n\n @utils.cached_property\n def mac_address(self):\n return MacAddress.get_by(interface_id=self.interface_id)\n\n @property\n def used_by_device_id(self):\n if self.interface:\n return self.interface.device_id\n\n def data(self, **options):\n data = super(IpAddress, self).data(**options)\n iface = self.interface\n data['used_by_tenant'] = iface.tenant_id\n data['used_by_device'] = iface.device_id\n data['interface_id'] = iface.virtual_interface_id\n return data\n\n def __str__(self):\n return self.address\n\n\nclass IpRoute(ModelBase):\n\n _data_fields = ['destination', 'netmask', 'gateway']\n\n def _validate(self):\n self._validate_presence_of(\"destination\", \"gateway\")\n self._validate_existence_of(\"source_block_id\", IpBlock)\n\n\nclass MacAddressRange(ModelBase):\n\n _data_fields = ['cidr']\n\n @classmethod\n def allocate_next_free_mac(cls, **kwargs):\n ranges = sorted(cls.find_all(),\n key=operator.attrgetter('created_at', 'id'))\n for range in ranges:\n try:\n return range.allocate_mac(**kwargs)\n except NoMoreMacAddressesError:\n LOG.debug(\"no more addresses in range %s\" % range.id)\n raise NoMoreMacAddressesError()\n\n @classmethod\n def mac_allocation_enabled(cls):\n return cls.count() > 0\n\n def allocate_mac(self, **kwargs):\n generator = mac.plugin().get_generator(self)\n if generator.is_full():\n raise NoMoreMacAddressesError()\n\n max_retry_count = int(config.Config.get(\"mac_allocation_retries\", 10))\n for retries in range(max_retry_count):\n next_address = generator.next_mac()\n try:\n return MacAddress.create(address=next_address,\n mac_address_range_id=self.id,\n **kwargs)\n except exception.DBConstraintError as error:\n LOG.debug(\"MAC allocation retry count:{0}\".format(retries + 1))\n LOG.exception(error)\n if generator.is_full():\n raise NoMoreMacAddressesError()\n\n raise ConcurrentAllocationError(\n _(\"Cannot allocate mac address at this time\"))\n\n def contains(self, address):\n address = int(netaddr.EUI(address))\n return (address >= self.first_address() and\n address <= self.last_address())\n\n def length(self):\n base_address, slash, prefix_length = self.cidr.partition(\"/\")\n prefix_length = int(prefix_length)\n return 2 ** (48 - prefix_length)\n\n def first_address(self):\n base_address, slash, prefix_length = self.cidr.partition(\"/\")\n prefix_length = int(prefix_length)\n netmask = (2 ** prefix_length - 1) << (48 - prefix_length)\n base_address = netaddr.EUI(base_address)\n return int(netaddr.EUI(int(base_address) & netmask))\n\n def last_address(self):\n return self.first_address() + self.length() - 1\n\n def no_macs_allocated(self):\n return MacAddress.find_all(mac_address_range_id=self.id).count() == 0\n\n\nclass MacAddress(ModelBase):\n\n @property\n def eui_format(self):\n return str(netaddr.EUI(self.address))\n\n @property\n def unix_format(self):\n return self.eui_format.replace('-', ':')\n\n def _before_save(self):\n self.address = int(netaddr.EUI(self.address))\n\n def _validate_belongs_to_mac_address_range(self):\n if self.mac_range:\n if not self.mac_range.contains(self.address):\n self._add_error('address', \"address does not belong to range\")\n\n def _validate(self):\n self._validate_belongs_to_mac_address_range()\n\n def delete(self):\n if self.mac_range:\n generator = mac.plugin().get_generator(self.mac_range)\n generator.mac_removed(self.address)\n super(MacAddress, self).delete()\n\n @utils.cached_property\n def mac_range(self):\n if self.mac_address_range_id:\n return MacAddressRange.find(self.mac_address_range_id)\n\n\nclass Interface(ModelBase):\n\n _data_fields = [\"device_id\", \"tenant_id\"]\n\n @classmethod\n def find_or_configure(cls, virtual_interface_id=None, device_id=None,\n tenant_id=None, mac_address=None):\n interface = Interface.get_by(id=virtual_interface_id,\n tenant_id=tenant_id)\n if interface:\n return interface\n\n return cls.create_and_configure(virtual_interface_id,\n device_id,\n tenant_id,\n mac_address)\n\n @classmethod\n def create_and_allocate_ips(cls,\n device_id=None,\n network_params=None,\n **kwargs):\n interface = Interface.create_and_configure(device_id=device_id,\n **kwargs)\n\n try:\n if network_params:\n network = Network.find_or_create_by(\n network_params.pop('id'),\n network_params.pop('tenant_id'))\n network.allocate_ips(interface=interface, **network_params)\n except NetworkOverQuotaError:\n interface.delete()\n raise\n return interface\n\n @classmethod\n def create_and_configure(cls, virtual_interface_id=None, device_id=None,\n tenant_id=None, mac_address=None):\n interface = Interface.create(id=virtual_interface_id,\n device_id=device_id,\n tenant_id=tenant_id)\n if mac_address:\n MacAddress.create(address=mac_address, interface_id=interface.id)\n elif MacAddressRange.mac_allocation_enabled():\n MacAddressRange.allocate_next_free_mac(interface_id=interface.id)\n return interface\n\n @classmethod\n def none_object(cls):\n return Interface(id=None, virtual_interface_id=None, device_id=None)\n\n def delete(self):\n mac_address, ips = db.db_api.delete_interface(self)\n\n if mac_address:\n if mac_address.mac_range:\n plugin = mac.plugin()\n generator = plugin.get_generator(mac_address.mac_range)\n generator.mac_removed(mac_address.address)\n # NOTE(jkoelker) notify that the mac was deleted\n mac_address._notify_fields(\"delete\")\n\n for ip in ips:\n # NOTE(jkoelker) notify that the ips were deallocated\n ip._notify_fields(\"update\")\n\n def data(self, **options):\n data = super(Interface, self).data()\n data['id'] = self.virtual_interface_id\n return data\n\n def allow_ip(self, ip):\n if self._ip_cannot_be_allowed(ip):\n err_msg = _(\"Ip %s cannot be allowed on interface %s as \"\n \"interface is not configured \"\n \"for ip's network\") % (ip.address,\n self.virtual_interface_id)\n raise IpNotAllowedOnInterfaceError(err_msg)\n\n db.db_api.save_allowed_ip(self.id, ip.id)\n\n def _ip_cannot_be_allowed(self, ip):\n return (self.plugged_in_network_id() is None\n or self.plugged_in_network_id() != ip.ip_block.network_id)\n\n def disallow_ip(self, ip):\n db.db_api.remove_allowed_ip(interface_id=self.id, ip_address_id=ip.id)\n\n def ips_allowed(self):\n explicitly_allowed = db.db_query.find_allowed_ips(\n IpAddress, allowed_on_interface_id=self.id)\n allocated_ips = IpAddress.find_all_allocated_ips(interface_id=self.id)\n return list(set(allocated_ips) | set(explicitly_allowed))\n\n def find_allowed_ip(self, address):\n ip = utils.find(lambda ip: ip.address == address,\n self.ips_allowed())\n if ip is None:\n raise ModelNotFoundError(\n _(\"Ip Address %(address)s hasnt been allowed \"\n \"on interface %(vif_id)s\")\n % (dict(address=address,\n vif_id=self.virtual_interface_id)))\n return ip\n\n @utils.cached_property\n def network_id(self):\n return self.plugged_in_network_id()\n\n def plugged_in_network_id(self):\n interface_ip = IpAddress.get_by(interface_id=self.id)\n return interface_ip.ip_block.network_id if interface_ip else None\n\n @utils.cached_property\n def mac_address(self):\n return MacAddress.get_by(interface_id=self.id)\n\n @property\n def ip_addresses(self):\n return IpAddress.find_all(interface_id=self.id).all()\n\n @property\n def mac_address_eui_format(self):\n if self.mac_address:\n return self.mac_address.eui_format\n\n @property\n def mac_address_unix_format(self):\n if self.mac_address:\n return self.mac_address.unix_format\n\n def _validate(self):\n self._validate_presence_of(\"tenant_id\")\n self._validate_uniqueness_of_virtual_interface_id()\n\n def _validate_uniqueness_of_virtual_interface_id(self):\n if self.vif_id_on_device is None:\n return\n existing_interface = self.get_by(\n vif_id_on_device=self.vif_id_on_device)\n if existing_interface and self != existing_interface:\n msg = (\"Virtual Interface %s already exists\")\n self._add_error('virtual_interface_id',\n msg % self.virtual_interface_id)\n\n @classmethod\n def find_all_interfaces(cls, **kwargs):\n return db.db_api.find_all_interfaces(**kwargs)\n\n @property\n def virtual_interface_id(self):\n return self.id\n\n @classmethod\n def delete_by(self, **kwargs):\n ifaces = Interface.find_all(**kwargs)\n for iface in ifaces:\n iface.delete()\n\n\nclass Policy(ModelBase):\n\n _data_fields = ['name', 'description', 'tenant_id']\n\n def _validate(self):\n self._validate_presence_of('name', 'tenant_id')\n\n def delete(self):\n IpRange.find_all(policy_id=self.id).delete()\n IpOctet.find_all(policy_id=self.id).delete()\n IpBlock.find_all(policy_id=self.id).update(policy_id=None)\n super(Policy, self).delete()\n\n def create_unusable_range(self, **attributes):\n attributes['policy_id'] = self.id\n return IpRange.create(**attributes)\n\n def create_unusable_ip_octet(self, **attributes):\n attributes['policy_id'] = self.id\n return IpOctet.create(**attributes)\n\n @utils.cached_property\n def unusable_ip_ranges(self):\n return IpRange.find_all(policy_id=self.id).all()\n\n @utils.cached_property\n def unusable_ip_octets(self):\n return IpOctet.find_all(policy_id=self.id).all()\n\n def allows(self, cidr, address):\n if any(ip_octet.applies_to(address)\n for ip_octet in self.unusable_ip_octets):\n return False\n return not any(ip_range.contains(cidr, address)\n for ip_range in self.unusable_ip_ranges)\n\n def find_ip_range(self, ip_range_id):\n return IpRange.find_by(id=ip_range_id, policy_id=self.id)\n\n def find_ip_octet(self, ip_octet_id):\n return IpOctet.find_by(id=ip_octet_id, policy_id=self.id)\n\n def size(self, cidr):\n size = 0\n policies = IpRange.find_all(policy_id=self.id).all()\n policies += IpOctet.find_all(policy_id=self.id).all()\n if policies:\n for p in policies:\n size += p.size(cidr)\n return size\n\n\nclass IpRange(ModelBase):\n\n _fields_for_type_conversion = {'offset': 'integer', 'length': 'integer'}\n _data_fields = ['offset', 'length', 'policy_id']\n\n def contains(self, cidr, address):\n end_index = self.offset + self.length\n end_index_overshoots_length_for_negative_offset = (self.offset < 0\n and end_index >= 0)\n if end_index_overshoots_length_for_negative_offset:\n end_index = None\n return (netaddr.IPAddress(address) in\n netaddr.IPNetwork(cidr)[self.offset:end_index])\n\n def _validate(self):\n self._validate_positive_integer('length')\n\n def size(self, cidr):\n block_size = netaddr.IPNetwork(cidr).size\n if self.offset >= 0:\n if (self.offset + self.length) <= block_size:\n size = self.length\n else:\n size = block_size - self.offset\n else:\n if abs(self.offset) > block_size:\n size = block_size + self.offset + self.length\n elif self.length > abs(self.offset):\n size = abs(self.offset)\n else:\n size = self.length\n return size\n\n\nclass IpOctet(ModelBase):\n\n _fields_for_type_conversion = {'octet': 'integer'}\n _data_fields = ['octet', 'policy_id']\n\n def applies_to(self, address):\n return self.octet == netaddr.IPAddress(address).words[-1]\n\n def size(size, cidr):\n cidr_prefix_length = netaddr.IPNetwork(cidr).prefixlen\n if cidr_prefix_length < 24:\n size = 2 ** (24 - cidr_prefix_length)\n else:\n size = 1\n return size\n\n\nclass Network(ModelBase):\n\n @classmethod\n def find_by(cls, id, **conditions):\n ip_blocks = IpBlock.find_all(network_id=id, **conditions).all()\n sorted_blocks = sorted(ip_blocks,\n key=operator.attrgetter('created_at', 'id'))\n\n if len(sorted_blocks) == 0:\n raise ModelNotFoundError(_(\"Network %s not found\") % id)\n return cls(id=id, ip_blocks=sorted_blocks)\n\n @classmethod\n def find_or_create_by(cls, id, tenant_id):\n try:\n return cls.find_by(id=id, tenant_id=tenant_id)\n except ModelNotFoundError:\n default_cidr = config.Config.get('default_cidr', None)\n if not default_cidr:\n raise ModelNotFoundError(_(\"Network %s not found\") % id)\n\n ip_block = IpBlock.create(cidr=default_cidr,\n network_id=id,\n tenant_id=tenant_id,\n type=IpBlock.PRIVATE_TYPE)\n return cls(id=id, ip_blocks=[ip_block])\n\n def allocated_ips(self, interface_id):\n ips_by_block = [IpAddress.find_all(interface_id=interface_id,\n ip_block_id=ip_block.id).all()\n for ip_block in self.ip_blocks]\n return [ip for sublist in ips_by_block for ip in sublist]\n\n def allocate_ips(self, addresses=None, **kwargs):\n version = kwargs.pop('version', None)\n if version:\n version = int(version)\n\n if addresses:\n return filter(None, [self._allocate_specific_ip(address, **kwargs)\n for address in addresses])\n\n ipv4_blocks = [block for block in self.ip_blocks\n if not block.is_ipv6() and\n (version is None or block.version == version)]\n ipv6_blocks = [block for block in self.ip_blocks\n if block.is_ipv6() and\n (version is None or block.version == version)]\n block_partitions = [ipv4_blocks, ipv6_blocks]\n\n ips = []\n for blocks in block_partitions:\n for block in blocks:\n if block.max_allocation is not None:\n if (block.ips_used >= block.max_allocation):\n raise NetworkOverQuotaError(block.network_id)\n ips.append(self._allocate_first_free_ip(blocks, **kwargs))\n\n if not any(ips):\n raise exception.NoMoreAddressesError(\n _(\"ip blocks in network %(network-id)s are full\")\n % {'network-id': self.id})\n\n return filter(None, ips)\n\n def deallocate_ips(self, interface_id):\n ips = IpAddress.find_all_by_network(self.id, interface_id=interface_id)\n for ip in ips:\n ip.deallocate()\n keep_deallocated_ips = config.Config.get(\n 'keep_deallocated_ips', 'False')\n if not utils.bool_from_string(keep_deallocated_ips):\n LOG.debug(\"Deleting deallocated ips\")\n for block in db.db_api.find_all_blocks_with_deallocated_ips():\n block.delete_deallocated_ips(deallocated_by_func=utils.utcnow)\n\n def find_allocated_ip(self, **conditions):\n for ip_block in self.ip_blocks:\n try:\n return IpAddress.find_by(ip_block_id=ip_block.id, **conditions)\n except ModelNotFoundError:\n pass\n\n raise ModelNotFoundError(_(\"IpAddress with %(conditions)s for \"\n \"network %(network)s not found\")\n % (dict(conditions=conditions,\n network=self.id)))\n\n def _allocate_specific_ip(self, address, **kwargs):\n ip_block = utils.find(lambda ip_block: ip_block.contains(address),\n self.ip_blocks)\n if ip_block:\n try:\n return ip_block.allocate_ip(address=address, **kwargs)\n except DuplicateAddressError:\n pass\n\n def _allocate_first_free_ip(self, ip_blocks, **kwargs):\n for ip_block in ip_blocks:\n if ip_block.omg_do_not_use:\n continue\n try:\n return ip_block.allocate_ip(**kwargs)\n except exception.NoMoreAddressesError:\n pass\n\n\ndef persisted_models():\n return {'IpBlock': IpBlock,\n 'IpAddress': IpAddress,\n 'Policy': Policy,\n 'IpRange': IpRange,\n 'IpOctet': IpOctet,\n 'IpRoute': IpRoute,\n 'MacAddressRange': MacAddressRange,\n 'MacAddress': MacAddress,\n 'Interface': Interface,\n # NOTE(jkoelker) This is here so we can slowly move off the table\n 'AllocatableIp': AllocatableIp,\n }\n\n\nclass DuplicateAddressError(exception.MelangeError):\n\n message = _(\"Address is already allocated\")\n\n\nclass AddressDoesNotBelongError(exception.MelangeError):\n\n message = _(\"Address does not belong here\")\n\n\nclass AddressLockedError(exception.MelangeError):\n\n message = _(\"Address is locked\")\n\n\nclass ModelNotFoundError(exception.MelangeError):\n\n message = _(\"Not Found\")\n\n\nclass AddressDisallowedByPolicyError(exception.MelangeError):\n\n message = _(\"Policy does not allow this address\")\n\n\nclass IpAllocationNotAllowedError(exception.MelangeError):\n\n message = _(\"Ip Block can not allocate address\")\n\n\nclass IpNotAllowedOnInterfaceError(exception.MelangeError):\n\n message = _(\"Ip cannot be allowed on interface\")\n\n\nclass InvalidModelError(exception.MelangeError):\n\n message = _(\"The following values are invalid: %(errors)s\")\n\n def __init__(self, errors, message=None):\n super(InvalidModelError, self).__init__(message, errors=errors)\n\n\nclass ConcurrentAllocationError(exception.MelangeError):\n\n message = _(\"Cannot allocate resource at this time\")\n\n\nclass NetworkOverQuotaError(exception.MelangeError):\n message = _(\"Too many connections on a private network\")\n\n\nclass NoMoreMacAddressesError(exception.MelangeError):\n\n message = _(\"No more mac Addresses\")\n\n\ndef sort(iterable):\n return sorted(iterable, key=lambda model: model.id)\n","sub_path":"melange/ipam/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":48818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"652130954","text":"import os, fnmatch\r\nfrom PIL import Image\r\nimport shutil\r\nfrom zipfile import ZipFile\r\nfrom datetime import datetime\r\n\r\nclass Photo_show:\r\n\r\n\tdef __init__(self, path_location, user, time):\r\n\t\tself.path = path_location\r\n\t\tself.time = time\r\n\t\tself.user = user\r\n\t\tself.extention = '*.jpg'\r\n\t\tself.logg = {}\r\n\r\n\t@staticmethod\r\n\tdef clear():\r\n\t\tos.system('cls')\r\n\r\n\tdef show(self):\r\n\t\tself.clear()\r\n\t\toperation = 'View'\r\n\t\tos.chdir(self.path)\r\n\r\n\t\tfor file in os.listdir(self.path):\r\n\t\t\tif fnmatch.fnmatch(file, self.extention):\r\n\t\t\t\timage = Image.open(file)\r\n\t\t\t\timage.show()\r\n\r\n\t\tself.report(operation, destiny=self.path, type_report = 'Multiple')\r\n\r\n\tdef photo_copy(self, path_d):\r\n\t\tself.clear()\r\n\t\toperation = 'Copy'\r\n\t\t\r\n\t\tprint('''\r\n\t\t-------- Choose ---------\r\n\t\t1 - One File (Copy)\r\n\t\t2 - All Files (Copy)\r\n\t\t\t''')\r\n\t\tcommand = int(input('Your choice:'))\r\n\t\t\r\n\t\tif command == 1:\r\n\t\t\ttype_report_1 = 'Single'\r\n\t\telif command == 2:\r\n\t\t\ttype_report_1 = 'Multiple'\r\n\t\telse:\r\n\t\t\ttype_report_1 = '?'\r\n\r\n\t\tself.path_destiny = path_d\r\n\t\tif command == 1:\t\t\t\r\n\t\t\tc = 0\r\n\t\t\tdicio = {}\r\n\t\t\tfor file in os.listdir(self.path):\r\n\t\t\t\tc += 1\r\n\t\t\t\tdicio[c] = file\r\n\r\n\t\t\tfor keys, value in dicio.items():\r\n\t\t\t\tprint('{} -> {}'.format(keys, value))\r\n\r\n\t\t\tid_choice = int(input('Insert the id value:'))\r\n\t\t\tif id_choice in dicio.keys():\r\n\t\t\t\tpath_final = os.path.join(self.path, dicio[id_choice])\r\n\t\t\t\tshutil.copy(path_final, self.path_destiny)\r\n\r\n\t\t\telse:\r\n\t\t\t\tprint('Inform a valid id')\r\n\r\n\t\telif command == 2:\r\n\t\t\tfor file in os.listdir(self.path):\r\n\t\t\t\tshutil.copy(os.path.join(self.path, file), self.path_destiny)\r\n\r\n\t\telse:\r\n\t\t\tprint('Not valid')\r\n\t\t\r\n\t\tself.report(operation, destiny = self.path_destiny, type_report = type_report_1)\r\n\r\n\tdef photo_delete(self):\r\n\t\tself.clear()\r\n\t\toperation = 'Delete'\r\n\t\tprint('''\r\n\t\t-------- Choose ---------\r\n\t\t1 - One File (Delete)\r\n\t\t2 - All Files (Delete)\r\n\t\t\t''')\r\n\t\tif command == 1:\r\n\t\t\ttype_report_1 = 'Single'\r\n\t\telif command == 2:\r\n\t\t\ttype_report_1 = 'Multiple'\r\n\t\telse:\r\n\t\t\ttype_report_1 = '?'\r\n\r\n\t\tchoice = int(input('Your choice:'))\r\n\t\tif choice == 1:\r\n\t\t\t\r\n\t\t\tdicio = {}\r\n\t\t\tc = 0\r\n\t\t\tfor file in os.listdir(self.path):\r\n\t\t\t\tc += 1\r\n\t\t\t\tdicio[c] = file\r\n\r\n\t\t\tfor keys, values in dicio.items():\r\n\t\t\t\tprint('{} -> {}'.format(keys, values))\r\n\t\t\t\r\n\t\t\tid_choice = int(input('Choose your id:'))\r\n\t\t\tif id_choice in dicio.keys():\r\n\t\t\t\tos.remove(os.path.join(self.path, dicio[id_choice]))\r\n\r\n\t\telif choice == 2:\r\n\t\t\t\r\n\t\t\tfor filefolder, subfolder, filenames in os.walk(self.path): #Will just remove the files not the folders\r\n\t\t\t\tfor filename in filenames:\r\n\t\t\t\t\tpath_created = os.path.join(filefolder, filename)\r\n\t\t\t\t\tos.remove(path_created)\r\n\t\t\t#shutil.rmtree(self.path) #This command will delete everything\r\n\r\n\t\telse:\r\n\t\t\tprint('Not valid')\r\n\r\n\t\tself.report(operation, destiny = self.path, type_report = type_report_1)\r\n\r\n\tdef photo_rename(self):\r\n\t\tself.clear()\r\n\t\tos.chdir(self.path)\r\n\r\n\t\toperation = 'Rename'\r\n\t\tcounter = 0\r\n\t\tchanges = ''\r\n\r\n\t\tfor file in os.listdir(self.path):\r\n\t\t\tfile_name, file_exte = os.path.splitext(file)\r\n\t\t\tnew_name = 'Photo - {}'.format(str(counter).zfill(2))\r\n\t\t\tos.rename(file, (new_name + file_exte))\r\n\t\t\tchanges += file_name + file_exte + ' >> ' + new_name + file_exte +'\\n'\r\n\t\t\tcounter += 1\r\n\t\tprint('Changes:\\n{}'.format(changes))\r\n\r\n\t\tself.report(operation, destiny = self.path, type_report = 'Multiple')\r\n\t\r\n\tdef zip_photo(self):\r\n\t\tself.clear()\r\n\t\t'''\r\n\t\t\t\t The zip will be save in the project folder, not in the especific directory\r\n\t\t\t\t Later: try to save in another path\r\n\t\t'''\r\n\t\toperation = 'Zip'\r\n\r\n\t\twith ZipFile('Zip_photo1.zip', 'w') as zip_obj:\r\n\t\t\tfor folderName, _, filenames in os.walk(self.path):\r\n\t\t\t\tfor filename in filenames:\r\n\t\t\t\t\tfile_path = os.path.join(folderName, filename)\r\n\t\t\t\t\tzip_obj.write(file_path)\r\n\r\n\t\tself.report(operation, destiny = self.path, type_report = 'Multiple')\r\n\r\n\tdef report(self, operation, destiny, type_report):\r\n\t\t\r\n\t\tself.operation = operation\r\n\t\tself.destiny = destiny\r\n\t\tself.type = type_report\t\r\n\r\n\t\tself.logg['USER'] = self.user\r\n\t\tself.logg['TIME'] = self.time\r\n\t\tself.logg['OPERAÇÃO'] = self.operation\r\n\t\tself.logg['ORIGEM'] = self.path\r\n\t\tself.logg['DESTINO'] = self.destiny\r\n\t\tself.logg['TYPE'] = self.type\r\n\t\tos.chdir('C:\\\\Users\\\\Pedro\\\\Desktop\\\\Player (Python)')\r\n\t\tprint(self.logg)\r\n\t\t\r\n\t\ttext_first = '''\r\n _____________________________________________________________________\t\t\t\t\t\r\n|------------------------- REPORT ----------------------------------- |\r\n|_____________________________________________________________________|\r\n\r\n-> Operation [{}, {}]\r\n>> User: {}\r\n>> Origin: {}\r\n>> Destiny: {}\r\n>> Type: {}\\n\r\n'''.format(self.logg['OPERAÇÃO'], \r\n\tself.logg['TIME'],\r\n\tself.logg['USER'],\r\n\tself.logg['ORIGEM'],\r\n\tself.logg['DESTINO'],\r\n\tself.logg['TYPE'])\r\n\t\t\r\n\t\ttext_second = '''\r\n\r\n-> Operation [{}, {}]\r\n>> User: {}\r\n>> Origin: {}\r\n>> Destiny: {}\r\n>> Type: {}\\n\r\n'''.format(self.logg['OPERAÇÃO'], \r\n\tself.logg['TIME'],\r\n\tself.logg['USER'],\r\n\tself.logg['ORIGEM'],\r\n\tself.logg['DESTINO'],\r\n\tself.logg['TYPE'])\r\n\r\n\t\tif os.path.exists('report.txt') != True:\r\n\t\t\twith open('report.txt', 'w+') as file:\r\n\t\t\t\tfile.write(text_first)\r\n\r\n\t\telse:\r\n\t\t\twith open('report.txt', 'a+') as file:\r\n\t\t\t\tfile.write(text_second)\r\n\t\t\r\n\tdef read_report(self):\r\n\t\tself.clear()\r\n\t\twith open('report.txt', 'r') as file:\r\n\t\t\tprint(file.read())\r\n\r\ndef time():\r\n\tnow_time = datetime.now()\r\n\tday_hour = now_time.strftime('%H:%M:%S -> %d/%m/%Y')\r\n\treturn day_hour\t\r\n\r\nif __name__ == '__main__':\r\n\ttime_return = time()\r\n\tuser = input('Username:')\r\n\r\n\twhile True:\r\n\t\tos.system('cls')\r\n\t\tprint('''\r\n\t\t==============================================\r\n--------------------- Photo Displayer ----------------------\r\n\t\t==============================================\r\n\t\r\n\t>> Options (0 -> Exit)\r\n\r\n\t[1] -> Insert another path to your photos (viewer)\r\n\t[2] -> Copy Photos from another path\r\n\t[3] -> Delete Photos\r\n\t[4] -> Rename Photos\r\n\t[5] -> Zip Photos\r\n\t[6] -> Read Report\t\r\n\t\t''')\r\n\t\r\n\t\tchoice = int(input())\r\n\r\n\t\tif choice == 0:\r\n\t\t\tbreak\r\n\r\n\t\tif choice == 1:\r\n\t\t\tpath_insert = input('Path origin location:')\r\n\t\t\tobject_photo = Photo_show(path_insert, user, time_return)\r\n\t\t\tobject_photo.show()\r\n\t\t\tos.system('PAUSE')\r\n\r\n\t\telif choice == 2:\r\n\t\t\tpath_origin = input('Path origin location:')\r\n\t\t\tpath_destiny = input('Path destiny location:')\r\n\t\t\tobject_photo = Photo_show(path_origin, user, time_return)\r\n\t\t\tobject_photo.photo_copy(path_destiny)\r\n\t\t\tos.system('PAUSE')\r\n\r\n\t\telif choice == 3:\r\n\t\t\tpath_origin = input('Path origin location:')\r\n\t\t\tobject_photo = Photo_show(path_origin, user, time_return)\r\n\t\t\tobject_photo.photo_delete()\r\n\t\t\tos.system('PAUSE')\r\n\t\t\r\n\t\telif choice == 4:\r\n\t\t\tpath_to_rename = input('Insert the path of the multiple files to rename:\\n')\r\n\t\t\tobject_photo = Photo_show(path_to_rename, user, time_return)\r\n\t\t\tobject_photo.photo_rename()\r\n\t\t\tos.system('PAUSE')\r\n\r\n\t\telif choice == 5:\r\n\t\t\tpath_to_zip = input('Insert the path to zip:\\n')\r\n\t\t\tobject_photo = Photo_show(path_to_zip, user, time_return)\r\n\t\t\tobject_photo.zip_photo()\r\n\t\t\tos.system('PAUSE')\r\n\r\n\t\telif choice == 6:\r\n\t\t\tobject_photo = Photo_show('', '', '')\r\n\t\t\tobject_photo.read_report()\r\n\t\t\tos.system('PAUSE')","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"615592868","text":"import re\n\nstring = 'www.yahu123.com'\ndata = ('www.lili.net',\n 'www.yahu.com',\n 'www.baddu.edu',\n 'baidu.com')\npattern = r'www.(\\w+|\\d+)(.com|.net|.edu)'\n\nfor datum in data:\n m = re.search(pattern, datum)\n if m != None:\n v = m.group()\n print(v)\n","sub_path":"正则练习/ex6.py","file_name":"ex6.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"62568622","text":"# Multi Layer Perceptron\n# 단순분기(일대다 model)\n\n\n#1. 데이터, 라이브러리 불러오기\nimport numpy as np\n\nx = np.array([range(1, 101), range(101,201), range(301, 401)]) # (3, 100)\n\n# y = np.array([range(1, 101)]) # (1, 100) # 대괄호가 있을 경우 벡터가 아닌 행렬이 된다!\n# y2 = np.array([range(1001, 1101)]) # input과 output의 갯수는 다를 수 있어도 행은 동일해야 한다!\n\ny1 = np.array([range(1, 101), range(101,201), range(301, 401)]) # (3, 100)\ny2 = np.array([range(1001, 1101), range(1101,1201), range(1301, 1401)]) \ny3 = np.array([range(1, 101), range(101,201), range(301, 401)]) \n\n\n# 행, 열 변환(reshape, np.transpose, T)\n# 참고 : https://rfriend.tistory.com/289\nx = x.T \n\ny1 = y1.T \ny2 = y2.T \ny3 = y3.T \n\n\n# 2. test, val, train 데이터 나누기\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test = train_test_split(x, train_size=0.6, shuffle=False) # 전체 데이터에서 train, test 분리(꼭 x, y 두 개만 들어갈 필요는 없음!!)\n# 입력값은 x(x_train과 x_test로 분리), y(y_train과 y_test로 분리)\nx_val, x_test= train_test_split(x_test, test_size=0.5, shuffle=False) # test 데이터의 절반을 validation로 분리\ny1_train, y1_test, y2_train, y2_test, y3_train, y3_test = train_test_split(y1, y2, y3, train_size=0.6, shuffle=False) \ny1_val, y1_test, y2_val, y2_test, y3_val, y3_test = train_test_split(y1_test, y2_test, y3_test, test_size=0.5, shuffle=False)\n\n'''\nprint(x_train.shape)\nprint(x_test.shape)\nprint(x_val.shape)\n\n'''\n\n#3. 모델구성(함수형 model)\nfrom keras.models import Sequential, Model \nfrom keras.layers import Dense, Input \n\n# model=Sequential()# 순차적으로 실행\n\n# Model 1\ninput1 = Input(shape=(3,)) # input layer 형태\ndense1 = Dense(256)(input1) # 바로 앞 layer를 뒷부분에 명시\ndense2 = Dense(64)(dense1)\noutput1 = Dense(4)(dense2)\n\n# Model 2\n# input2 = Input(shape=(3,)) \n# dense21 = Dense(256)(input2) \n# dense22 = Dense(8)(dense21)\n# dense23 = Dense(128)(dense22)\n# output2 = Dense(10)(dense23)\n\n# Concatenate\n# from keras.layers.merge import concatenate # model을 사슬처럼 엮다.\n# merge1 = concatenate([output1, output2]) # list 형식(=[]) # merge layer 역시 hidden layer! 따라서 끝 노드 수를 굳이 맞춰주지 않아도 된다.\n\n\n# Model 3\n# middle1 = Dense(3)(merge1)\n# middle2 = Dense(256)(middle1)\n# middle3 = Dense(1)(middle2) # merge된 마지막 layer\n\n# 분기하기\n# 1번째 output model \noutput_1 = Dense(64)(output1)\noutput_1 = Dense(32)(output_1)\noutput_1 = Dense(3)(output_1)\n\n# 2번째 output model \noutput_2 = Dense(128)(output1)\noutput_2 = Dense(256)(output_2)\noutput_2 = Dense(3)(output_2)\n\n# 3번째 output model\noutput_3 = Dense(8)(output1)\noutput_3 = Dense(4)(output_3)\noutput_3 = Dense(3)(output_3)\n\n\n# 함수형 model 선언\nmodel = Model(inputs = input1,\n outputs = [output_1, output_2, output_3]) # input, output이 다수일 경우 list 형식으로 삽입!\n\n# # model.add(Dense(512, input_dim=3)) # 레이어 추가\n# model.add(Dense(256, input_shape=(3,))) # input_shape = (1,), 벡터가 1개라는 뜻\n# model.add(Dense(256)) # Node 값 조절 \n# model.add(Dense(1)) # regression(=회귀분석) 문제이므로 output은 하나여야 한다. # 열을 기준으로 볼 것!\n\nmodel.summary() # 모델 구조 확인\n\n\n#3. 모델 훈련(지표 두 개를 한번에 확인할 수 있다)\nmodel.compile(loss='mse', optimizer='adam', \n metrics=['mae']) # adam=평타는 침. # metrics는 보여주는 것.\nmodel.fit(x_train, [y1_train, y2_train, y3_train], epochs=100, batch_size=1, validation_data=(x_val, [y1_val, y2_val, y3_val]))\n\n\n#4. 평가예측 \n# a, b, c, d, e, f, g = model.evaluate([x1_test, x2_test],\n# [y1_test, y2_test, y3_test], batch_size=1) # loss는 자동적으로 출력 # 변수를 7개 주면 ok!\n# print(a, b, c, d, e, f, g)\n\ngg = model.evaluate(x_test, [y1_test, y2_test, y3_test], batch_size=1) # loss는 자동적으로 출력\nprint('gg :', gg)\n\n# mae = mean_absolute_error, mse와 다른 손실함수\n# 데이터 크기보다 더 큰 batch size를 줄 경우 데이터 크기로 계산된다.\n\n\n# 새로운 데이터 넣어보기\nx_prd = np.array([[501, 502, 503], [601, 602, 603], [701, 702, 703]]).T\n# x2_prd = np.array([[657, 325, 894], [987, 899, 765], [473, 569, 907]]).T\nggg = model.predict(x_prd, batch_size=1)\nprint(ggg)\n\n\n# RMSE, R2 확인을 위한 변수 생성\ny_predict = model.predict(x_test, batch_size=1)\n\n\n# RMSE 구하기\nfrom sklearn.metrics import mean_squared_error\n\ndef RMSE(x, y): # 실제 정답값(=y_test), 모델을 통한 예측값(=y_predict) \n return np.sqrt(mean_squared_error(x, y))\n\naaa = [RMSE(y1_test, y_predict[0]), RMSE(y2_test, y_predict[1]), RMSE(y3_test, y_predict[2])]\n# print(aaa)\nRMSE_AVG = np.mean(aaa)\nprint('RMSE :', RMSE_AVG)\n\n# # 선생님 풀이\n# a1 = RMSE(y1_test, y_predict[0])\n# a2 = RMSE(y2_test, y_predict[1])\n# a3 = RMSE(y3_test, y_predict[2])\n\n# rmse = (a1 + a2 + a3) / 3\n# print('RMSE :', rmse)\n\n# R2 구하기\n# R2 정의 및 참고 : https://newsight.tistory.com/259\nfrom sklearn.metrics import r2_score\n\nbbb = [r2_score(y1_test, y_predict[0]), r2_score(y2_test, y_predict[1]), r2_score(y3_test, y_predict[2])]\nr2_y_predict = np.mean(bbb)\n\nprint(\"R2 :\", r2_y_predict)\n\n# # 선생님 풀이\n# r1 = r2_score(y1_test, y_predict[0])\n# r2 = r2_score(y2_test, y_predict[1])\n# r3 = r2_score(y3_test, y_predict[2])\n\n# r2_avg = (r1 + r2 + r3) / 3\n# print('R2 score :', rmse)\n\n# visual studio code 참고(https://demun.github.io/vscode-tutorial/shortcuts/)","sub_path":"keras_DNN/keras14_ensamble3.py","file_name":"keras14_ensamble3.py","file_ext":"py","file_size_in_byte":5595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"411642897","text":"# (C) Copyright 2021 ECMWF.\n#\n# This software is licensed under the terms of the Apache Licence Version 2.0\n# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n# In applying this licence, ECMWF does not waive the privileges and immunities\n# granted to it by virtue of its status as an intergovernmental organisation\n# nor does it submit to any jurisdiction.\n#\n\nimport inspect\nimport threading\n\nfrom climetlab.normalisers import NORMALISERS\n\n\nclass parameters:\n def __init__(self, **kwargs):\n self.types = dict()\n for k, v in kwargs.items():\n if isinstance(v, str):\n v = v.split(\":\")\n if hasattr(v[0], \"normalise\"):\n assert len(v) == 1, v\n self.types[k] = v[0]\n else:\n self.types[k] = NORMALISERS[v[0]](*v[1:])\n\n def __call__(self, func):\n\n spec = inspect.getfullargspec(func)\n\n def wrapped(*args, **kwargs):\n\n request = dict()\n request.update(kwargs)\n\n for p, a in zip(spec.args, args):\n request[p] = a\n\n request = self.normalise(request)\n return func(**request)\n\n wrapped.__name__ = func.__name__\n\n return wrapped\n\n def normalise(self, request):\n result = dict(**request)\n\n for k, v in self.types.items():\n if k in request:\n n = v.normalise(request[k])\n if n is not None:\n result[k] = n\n\n return result\n\n\ndef dict_args(func):\n def wrapped(*args, **kwargs):\n m = []\n p = {}\n for q in args:\n if isinstance(q, dict):\n p.update(q)\n else:\n m.append(q)\n p.update(kwargs)\n return func(*m, **p)\n\n wrapped.__name__ = func.__name__\n\n return wrapped\n\n\nLOCK = threading.RLock()\n\n\ndef locked(func):\n def wrapped(*args, **kwargs):\n with LOCK:\n return func(*args, **kwargs)\n\n wrapped.__name__ = func.__name__\n\n return wrapped\n","sub_path":"climetlab/decorators/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"166293986","text":"class Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n intervals = sorted(intervals, key=lambda x: x[0])\n i = 0\n \n while i < len(intervals) - 1:\n curr_interval_begin, curr_interval_end = intervals[i]\n next_interval_begin, next_interval_end = intervals[i+1]\n \n # If there is no overlap, just move the index to the next one\n if curr_interval_end < next_interval_begin:\n i += 1\n # If there is an overlap, combine the currernt interval with the next interval and then delete the next interval\n else:\n intervals[i][1] = max(curr_interval_end, next_interval_end)\n del intervals[i+1]\n \n return intervals","sub_path":"056. Merge Intervals/solution1.py","file_name":"solution1.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"15560420","text":"import tensorflow as tf\r\n\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\n\r\nINPUT_NODE=784\r\nOUTPUT_NODE=10\r\n\r\nLAYER1_NODE=500\r\nBATCH_SIZE=100\r\n\r\nLEARNING_RATE_BASE=0.8\r\nLEARING_RATE_DECAY=0.99\r\nREGULARIZATION_RATE=0.0001\r\nTRAINING_STEPS=30000\r\nMOVING_AVERAGE_DECAY=0.99\r\n\r\ndef inference(input_tensor,avg_class, weights1, biases1,weights2,biases2):\r\n if avg_class==None:\r\n layer1=tf.nn.relu(tf.matmul(input_tensor,weights1)+biases1)\r\n\r\n return tf.matmul(layer1,weights2)+biases2\r\n else:\r\n layer1=tf.nn.relu(\r\n tf.matmul(input_tensor,avg_class.average(weights1))+avg_class.average(biases1)\r\n )\r\n return tf.matmul(layer1,avg_class.average(weights2))+avg_class.average(biases2)\r\n\r\ndef train(mnist):\r\n x=tf.placeholder(tf.float32,[None,INPUT_NODE],name='x-input')\r\n y_=tf.placeholder(tf.float32,[None,OUTPUT_NODE],name='y-input')\r\n#生成隐藏层\r\n weights1=tf.Variable(\r\n tf.truncated_normal([INPUT_NODE,LAYER1_NODE],stddev=0.1))\r\n biases1=tf.Variable(tf.constant(0.1,shape=[LAYER1_NODE]))\r\n#生成输出层\r\n weights2=tf.Variable(\r\n tf.truncated_normal([LAYER1_NODE,OUTPUT_NODE],stddev=0.1)\r\n )\r\n biases2=tf.Variable(tf.constant(0,1,shape=[OUTPUT_NODE]))\r\n#计算当前参数神经网络前向传播结果 滑动平均的类为null\r\n y=inference(x,None,weights1,biases1,weights2,biases2)\r\n#定义存储训练轮数的变量 这里指定这个变量为不可训练的参数 trainable=false\r\n global_step=tf.Variable(0,trainable=False)\r\n#给定训练轮数的变量 初始化滑动平均类\r\n # 可以加快训练早期变量的更新速度\r\n variable_averages=tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,global_step)\r\n\r\n#在所有代表神经网络参数的变量上使用滑动平均。其他辅助变量(比如 global_step)不需要\r\n#tf.trainable_variable_averages\r\n variables_averages_op=variable_averages.apply(\r\n tf.trainable_variables()\r\n )\r\n#计算使用滑动平均之后的前向传播结果 介绍过滑动平均不会改变变量本身的取值,维护一个影子变量 当需要使用这个滑动平均值时,需要明确调用average函数\r\n average_y=inference(\r\n x,variable_averages,weights1,biases1,weights2,biases2)\r\n cross_entropy=tf.nn.sparse_softmax_cross_entropy_with_logits(\r\n logits=y,labels=tf.argmax(y_,1)\r\n )\r\n\r\n cross_entropy_mean=tf.reduce_mean(cross_entropy)\r\n\r\n regularizer=tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)\r\n regularization=regularizer(weights1)+regularizer(weights2)\r\n loss=cross_entropy_mean+regularization\r\n learning_rate=tf.train.exponential_decay(\r\n LEARNING_RATE_BASE,\r\n global_step,\r\n mnist.train.num_examples/BATCH_SIZE,\r\n LEARING_RATE_DECAY\r\n )\r\n\r\n train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy_mean,global_step=global_step)\r\n\r\n with tf.control_dependencies([train_step,variables_averages_op]):\r\n train_op=tf.no_op(name='train')\r\n correct_prediction=tf.equal(tf.argmax(average_y,1),tf.argmax(y_,1))\r\n accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\r\n\r\n with tf.Session() as sess:\r\n tf.global_variables_initializer().run()\r\n validate_feed={x: mnist.validation.images,\r\n y_:mnist.validation.labels}\r\n test_feed={x:mnist.test.images,\r\n y_:mnist.test.labels}\r\n\r\n for i in range(TRAINING_STEPS):\r\n if i%1000==0:\r\n validate_acc=sess.run(accuracy,feed_dict=validate_feed)\r\n test_acc=sess.run(accuracy,feed_dict=test_feed)\r\n print(\"After %d training step(s),validation accuracy\"\r\n \"using average model is %g,test accuracy using averag model is %g\"%(i,validate_acc,test_acc))\r\n xs,ys=mnist.train.next_batch(BATCH_SIZE)\r\n sess.run(train_op,feed_dict={x:xs,y_:ys})\r\n test_acc=sess.run(accuracy,feed_dict=test_feed)\r\n print(\"After %d training step(s), test accuracy using average\"\r\n \"model is %g\"% (TRAINING_STEPS,test_acc))\r\n\r\ndef main(argv=None):\r\n mnist=input_data.read_data_sets(\"D:\\\\program\\\\python\\\\learn_tensorflow.git\\\\trunk\\\\MNIST\",one_hot=True)\r\n train(mnist)\r\n\r\nif __name__=='__main__' :\r\n tf.app.run()","sub_path":"MNIST/MNI.py","file_name":"MNI.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"52129955","text":"def main():\n n = int(input())\n As = list(map(int, input().split()))\n\n ans = 0\n for i in range(n):\n temp = As[i]\n if temp % 2 == 0:\n cnt = 0\n while temp % 2 == 0:\n cnt += 1\n temp //= 2\n ans += cnt\n\n print(ans)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python_codes/p03325/s128905585.py","file_name":"s128905585.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"16536489","text":"\n \nclass Game():\n start_point = [[2,2,0],[2,9,0],[9,2,0],[9,9,0]]\n def __init__(self,names):\n self.p_num = 4\n self.max_x = 10\n self.max_y = 10\n self.max_z = 5\n self.players = [Player(name,Game.start_point[i]) for i,name in enumerate(names)]\n self.tiles = Tiles(self.max_x,self.max_y,self.max_z)\n self.turn_num = 0\n self.helper = Helper(self.tiles,self.players,self)\n\n #初期位置のちぇっく\n for player in self.players:\n self.tiles.check_player_move(player,turn_num=0)\n\n\n\n def get_helper(self):\n return self.helper\n\n #actionを受け取る\n def do_action(self,p_num,action):\n player = self.players[p_num]\n player.move(action)#移動する\n self.tiles.check_player_move(player,self.turn_num)# 移動したときどうなるか\n \n #tileを更新する\n def next_turn(self):\n self.turn_num += 1\n self.tiles.update()\n\n #一人だけ生きてたらtrue\n def is_end(self):\n count = 0\n for player in self.players:\n if player.is_alive:\n count += 1\n return count <= 1\n\n # logを返す\n def get_log(self):\n log = {\n \"turn_num\":self.turn_num,\n \"tiles\": self.tiles.to_log(),\n \"players\": [player.to_log() for player in self.players] \n }\n return log\n\n #最終結果のlog\n def get_result_log(self):\n ranking = []\n order_dead_turn_num = list()\n for p in self.players:\n print(p.dead_turn_num)\n if p.is_alive == True:\n ranking.append({\"name\":p.name,\"order\":1})\n order_dead_turn_num.append(99999)#ダミー\n continue\n order_dead_turn_num.append(p.dead_turn_num)\n order_dead_turn_num =list(reversed(list(sorted(order_dead_turn_num))))\n print(order_dead_turn_num)\n for p in self.players:\n print(p.name)\n print(p.dead_turn_num)\n if p.is_alive == False:\n rank = order_dead_turn_num.index(p.dead_turn_num)\n ranking.append({\"name\":p.name,\"order\":rank+1})\n print(ranking)\n return ranking\n\nclass Tiles():\n def __init__(self,x_max,y_max,z_max):\n self.x_max = x_max\n self.y_max = y_max\n self.z_max = z_max\n self.tiles = []\n for x in range(x_max+2):\n y_li = []\n for y in range(y_max+2):\n x_li = []\n for z in range(z_max+1):\n x_li.append(Tile())\n y_li.append(x_li)\n self.tiles.append(y_li)\n self._create_dead_area()#周りのマスを空にしておく\n self.pressed_tiles = []#更新が必要なタイルたち\n \n #周りに空のエリアを作る\n def _create_dead_area(self): \n for x in range(self.x_max+2):\n for y in range(self.y_max+2):\n for z in range(self.z_max+1):\n if x == 0 or x == self.x_max+1 or y == 0 or y == self.y_max+1 or z == self.z_max:\n self.tiles[x][y][z].is_alive = False\n\n #タイルを更新する 死んだらpressedtileから削除しておく\n def update(self):\n for i in reversed(range(len(self.pressed_tiles))):\n self.pressed_tiles[i].update()\n if self.pressed_tiles[i].is_alive == False:\n self.pressed_tiles.pop(i)\n\n #行動に応じてplayerを行動させる\n def check_player_move(self,player,turn_num):\n point = player.get_point()\n tile = self.tiles[point[0]][point[1]][point[2]]\n if point[2] == self.z_max: #最下層で生きているなら問答無用で殺す\n if player.is_alive == True:\n player.kill(turn_num)\n else:\n if tile.is_alive: # タイルがあればfalling = Falseなければfalling\n player.is_falling = False\n tile.is_pressed = True#タイルを踏んだのでtrueにする\n self.pressed_tiles.append(tile)\n else:\n player.is_falling = True\n\n # 配列にする\n def to_log(self):\n tiles_arr = []\n for x in range(self.x_max+2):\n li_y = []\n for y in range(self.y_max+2):\n li_z = []\n for z in range(self.z_max+1):\n li_z.append(self.tiles[x][y][z].is_alive)\n li_y.append(li_z)\n tiles_arr.append(li_y) \n return tiles_arr\n \n def get_tile(self,point):\n try :\n return self.tiles[point[0]][point[1]][point[2]]\n except :\n dummy = Tile()\n dummy.is_alive = False\n return dummy\n\nclass Tile():\n dead_count = 1 # タイルが消えるまでの時間\n def __init__(self):\n self.is_alive = True\n self.is_pressed = False\n self.count = Tile.dead_count\n \n #countを小さくする 0になったら消える\n def update(self):\n self.count = self.count -1\n if self.count == 0:\n self.is_alive = False\n \n #利用可能ならtrue 利用不可能ならfalse\n def get_is_alive(self):\n return self.is_alive\n\nclass Player():\n def __init__(self,name,start_point):\n self.name = name\n self.point = start_point\n self.is_alive = True # 生きているか\n self.is_falling = False # 落ちているか\n self.before_action = 0\n self.dead_turn_num = 0\n #移動する\n def move(self,action):\n self.before_action = action\n if self.is_alive:\n if self.is_falling:#落ちている状況なら落ちる\n self.point = [self.point[0], self.point[1], self.point[2]+1]\n elif action == 0:\n self.point = [self.point[0], self.point[1]-1, self.point[2]]\n elif action == 1:\n self.point = [self.point[0], self.point[1]+1, self.point[2]]\n elif action == 2:\n self.point = [self.point[0]-1, self.point[1], self.point[2]]\n elif action == 3:\n self.point = [self.point[0]+1, self.point[1], self.point[2]]\n elif action == 4:\n self.point = [self.point[0], self.point[1], self.point[2]]\n else:\n print(action)\n print(self.name)\n print(\"Action Error\")\n \n def to_log(self):\n return {\n \"name\": self.name,\n \"point\": self.point,\n \"is_alive\": self.is_alive,\n \"is_falling\": self.is_falling\n }\n\n def get_point(self):\n return self.point\n\n def kill(self,turn_num):\n self.is_alive = False\n self.dead_turn_num = turn_num\n\n\n\nclass Helper():\n def __init__(self,tiles,players,game):\n self.tiles = tiles\n self.players = players\n self.game = game\n def labeling(self,level):\n #level層目をラベリングしてラベリング結果の2次元配列を返す\n x_max = self.tiles.x_max+2\n y_max = self.tiles.y_max+2\n\n labeled = [[(i*x_max+j if self.tiles.tiles[i][j][level].is_alive else -1)for j in range(y_max)] for i in range(x_max)]\n changed = True\n while changed:\n changed= False\n for i in range(x_max):\n for j in range(y_max):\n candidate = []\n if(labeled[i][j] == -1):\n continue\n if(i>=1 and self.tiles.tiles[i-1][j][level].is_alive):\n candidate+=[labeled[i-1][j]]\n if(j>=1 and self.tiles.tiles[i][j-1][level].is_alive):\n candidate+=[labeled[i][j-1]]\n if(i<=self.tiles.y_max-2 and self.tiles.tiles[i+1][j][level].is_alive):\n candidate+=[labeled[i+1][j]]\n if(j<=self.tiles.x_max-2 and self.tiles.tiles[i][j][level].is_alive):\n candidate+=[labeled[i][j+1]]\n mini = min(candidate)\n if(mini < labeled[i][j]):\n changed = True\n labeled[i][j] = mini\n return labeled\n\n def get_tiles(self):\n return self.tiles\n \n \n def get_players(self):\n return self.players\n \n #敵の座標配列\n def get_enemy_players(self,name):\n stack = []\n for p in self.players:\n if p.name != name:\n stack.append(p)\n return stack\n\n #自分の座標\n def get_my_player(self,name):\n for p in self.players:\n if p.name == name:\n return p\n \n def get_my_point(self,name):\n for p in self.players:\n if p.name == name:\n return p.point\n\n\n #距離の差分* 敵3人\n def get_distance_points_from_me(self,name):\n stack = []\n you = self.get_your_player(name)\n yp = you.get_point()\n for p in self.get_enemy_players():\n pp = p.get_point()\n stack.append([yp[0]-pp[0],yp[1]-pp[1],yp[2]-pp[2]])\n return stack\n \n def get_distance_points_from_point(self,point):\n stack = []\n for p in self.get_enemy_players():\n pp = p.get_point()\n stack.append([point[0]-pp[0],point[1]-pp[1],point[2]-pp[2]])\n return stack\n\n def get_up_point(self,point):\n return [point[0],point[1]-1,point[2]]\n def get_down_point(self,point):\n return [point[0],point[1]+1,point[2]]\n def get_left_point(self,point):\n return [point[0]-1,point[1],point[2]]\n def get_right_point(self,point):\n return [point[0]+1,point[1],point[2]]\n\n def get_up_tile(self,name):\n point = self.get_my_point(name)\n return self.tiles.get_tile(self.get_up_point(point))\n def get_down_tile(self,name):\n point = self.get_my_point(name)\n return self.tiles.get_tile(self.get_down_point(point))\n def get_left_tile(self,name):\n point = self.get_my_point(name)\n return self.tiles.get_tile(self.get_left_point(point))\n def get_right_tile(self,name):\n point = self.get_my_point(name)\n return self.tiles.get_tile(self.get_right_point(point))\n \n def get_players_around_n_tiles(self,name,dis):\n stack = []\n me = self.get_my_player(name)\n for p in self.get_enemy_players(name):\n if p.point[2] == me.point[2] - (abs(p.point[0] - me.point[0]) > dis or abs(p.point[1]-me.point[1]) > dis ) :\n stack.append(p)\n return stack\n\n #ターン数を取得する\n def get_turn_num(self):\n return self.game.turn_num\n\n #dist_pointに最短距離で移動するときに向かうべき方向を返す\n def get_toward_distination(self,frompoint, dist_point):\n x = frompoint[0]-dist_point[0]\n y = frompoint[1]-dist_point[1]\n if x == 0 and y == 0:\n return 5\n if abs(x) >= abs(y):\n if x >0:\n return 2\n if x < 0:\n return 3\n if abs(y) > abs(x):\n if y >0:\n return 0\n if y < 0:\n return 1\n \n #特定プレイヤーの前回の行動を取る\n def get_before_action(self,name):\n p = self.get_my_player(name)\n return p.before_action\n \n #周囲のtile一覧を取得 上下左右の順\n def get_around_tiles(self,name):\n return [self.get_up_tile(name),self.get_down_tile(name),self.get_left_tile(name),self.get_right_tile(name)]\n\n\n","sub_path":"games/square_drop.py","file_name":"square_drop.py","file_ext":"py","file_size_in_byte":11643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"355219853","text":"from django.shortcuts import render\nfrom django.db.models import ProtectedError\nfrom team.serializers import TeamSerializer\nfrom team.serializers import ContestSerializer\nfrom team.serializers import RewardSerializer\nfrom django.http import Http404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom team.models import Team, Contest, TeamContest, Reward\nfrom django.shortcuts import get_object_or_404\n# Create your views here.\n\nclass TeamDetail(APIView):\n \"\"\"队伍View\"\"\"\n\n def get(self, request, pk=None, format=None):\n \"\"\"查询队伍\"\"\"\n if pk is None:\n teams = Team.objects.all()\n serializer = TeamSerializer(teams, many=True)\n else:\n team = get_object_or_404(Team, pk=pk)\n serializer = TeamSerializer(team)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n \"\"\"修改队伍\"\"\"\n team = get_object_or_404(Team, pk=pk)\n serializer = TeamSerializer(team, data=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 def post(self, request, pk=None, format=None):\n \"\"\"增加队伍\"\"\"\n serializer = TeamSerializer(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\n def delete(self, request, pk, format=None):\n \"\"\"删除队伍\"\"\"\n team = get_object_or_404(Team, pk=pk)\n try:\n team.delete()\n except ProtectedError:\n return Response(status=status.HTTP_403_FORBIDDEN)\n return Response(status=status.HTTP_204_NO_CONTENT)\n \n\nclass ContestDetail(APIView):\n \"\"\"比赛view\"\"\"\n def get(self, request, pk=None, format=None):\n \"\"\"\"查询比赛\"\"\"\n if pk is None:\n contests = Contest.objects.all()\n serializer = ContestSerializer(contests, many=True)\n else :\n contest = get_object_or_404(Contest, pk=pk)\n serializer = ContestSerializer(contest)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n \"\"\"修改比赛\"\"\"\n contest = get_object_or_404(Contest,pk=pk)\n serializer = ContestSerializer(contest, data=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 def post(self, request, pk=None, format=None):\n \"\"\"增加比赛\"\"\"\n serializer = ContestSerializer(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 \n def delete(self, request, pk, format=None):\n \"\"\"删除比赛\"\"\"\n contest = get_object_or_404(Contest,pk=pk)\n contest.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass RewardDetail(APIView):\n \"\"\"获奖view\"\"\"\n def get(self, request, pk=None, format=None):\n \"\"\"查询奖项\"\"\"\n if pk is None:\n rewards = Reward.objects.all()\n serializer = RewardSerializer(rewards, many=True)\n else:\n reward = get_object_or_404(Reward, pk=pk)\n serializer = RewardSerializer(reward)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n \"\"\"修改奖项\"\"\"\n reward = get_object_or_404(Reward, pk=pk)\n serializer =ContestSerializer(reward, data=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 def post(self, request, pk=None, format=None):\n \"\"\"增加奖项\"\"\"\n serializer = RewardSerializer(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 \n def delete(self, request, pk, format=None):\n \"\"\"删除奖项\"\"\"\n reward = get_object_or_404(Reward, pk=pk)\n reward.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)","sub_path":"team/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"435979019","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport logging\nimport os\nimport sys\nimport json\nimport time\nimport gzip \n\nimport numpy as np\nimport tensorflow as tf \nfrom tensorflow.contrib.rnn import *\n\nsys.path.append(os.path.dirname(__file__))\nfrom jack_util import load_vocab, batch_process\n\nlogger = logging.getLogger(__name__)\n\nOUTPUT_NODE_NAME = '' \nin_pl_names = []\nin_ph_map = {}\n\n######################################################################################\n##memory profile log file\nfrom memory_profiler import profile \nmem_fp = open('memory_profiler.log','w')\n\n@profile(stream = mem_fp)\ndef load_graph(frozen_graph_filename):\n # We load the protobuf file from the disk and parse it to retrieve the \n # unserialized graph_def\n with tf.gfile.GFile(frozen_graph_filename, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\n # Then, we can use again a convenient built-in function to import a graph_def into the \n # current default Graph\n tf.import_graph_def(\n graph_def, \n input_map=None, \n return_elements=None, \n name= '', \n op_dict=None, \n producer_op_list=None\n )\n\n@profile(stream = mem_fp)\ndef load_serving_model(sess, model_dir):\n tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], model_dir)\n\ndef gather_inout_tensors(graph_map):\n global OUTPUT_NODE_NAME \n global in_pl_names\n with open(graph_map) as fh:\n for line in fh:\n line = line.strip()\n items = line.split(\"->\")\n if items[0].endswith(\"output:0\"): \n OUTPUT_NODE_NAME = items[0] \n else:\n in_pl_names.append(items[0])\n logger.info(\"input nodes: %s\" % \",\".join(in_pl_names))\n logger.info(\"output node: %s\" % OUTPUT_NODE_NAME) \n\ndef init_input_tensor_map(graph): \n logger.info(\"init input tensors list...\")\n global in_ph_map \n global in_pl_names\n for in_pl in in_pl_names: \n ys_names = in_pl\n logger.debug(\"input node name: %s\" % ys_names)\n #remove the prefix\n items = in_pl.split(\"/\")\n items = items[-1].split(\":\")\n in_ph_map[items[0]] = graph.get_tensor_by_name(ys_names) \n\ndef map2TF_input(xy_dict):\n global in_ph_map\n feed_data = {}\n for key in in_ph_map.keys():\n if key not in xy_dict:\n logger.error(\"not found input node key '%s' in [%s]\" % (key, ','.join(xy_dict.keys())))\n raise IOError()\n feed_data[in_ph_map[key]] = xy_dict[key]\n return feed_data \n\n@profile(stream = mem_fp)\ndef run_model(sess, data, ys):\n t0 = time.time()\n output = sess.run(ys, feed_dict=data)[0]\n return output, (time.time()-t0) \n\ndef parse_mem_profile(mem_fp_file, out_file):\n logger.info(\"parsing '%s' ...\" % mem_fp_file)\n m_unit = \"MiB\"; rt_unit = \"MiB\"\n model_size = \"\"\n rt_mem = []; first_incr = float(-1.0)\n with open(mem_fp_file) as fh:\n for line in fh:\n if \"graph_def.ParseFromString\" in line: \n items = line.split()\n model_size = items[3]; m_unit = items[4] \n if \"tf.saved_model.loader.load\" in line: \n items = line.split()\n model_size = items[3]; m_unit = items[4]\n if \"output = sess.run\" in line:\n items = line.split()\n rt_mem.append(float(items[1]))\n rt_unit = items[2]\n if first_incr < 0: first_incr = float(items[3])\n ##remove the last item \n rt_mem.pop()\n base_mem = rt_mem[0] - first_incr \n np_mem = np.array(rt_mem) - base_mem \n mem_avg = np.mean(np_mem)\n mem_std = np.std(np_mem)\n mem_min = np.min(np_mem)\n mem_max = np.max(np_mem)\n logger.info(\"\\n############## memory profiling #################\")\n logger.info(\"loading model size: %s %s\" % (model_size, m_unit))\n logger.info(\"memory occupancy per batch(unit: %s): average(%.3f), std(%.3f), min(%.3f), max(%.3f)\" %\n (rt_unit, mem_avg, mem_std, mem_min, mem_max))\n with open(out_file, \"a\") as fh:\n fh.write(\"\\n############## memory profiling #################\\n\")\n fh.write(\"loading model size: %s %s\\n\" % (model_size, m_unit))\n fh.write(\"memory occupancy per batch(unit: %s): average(%.3f), std(%.3f), min(%.3f), max(%.3f)\\n\" %\n (rt_unit, mem_avg, mem_std, mem_min, mem_max)) \n\n######################################################################################\ndef correct_answers(candidates_per_sample, full_candidates_per_sample, result):\n right = 0; start = 0\n for i in range(len(candidates_per_sample)):\n end = start + full_candidates_per_sample[i]\n cur_scores = result[start: end] \n win_index = np.where(cur_scores == cur_scores.max())\n if win_index[0][0] >= candidates_per_sample[i]: right += 1\n start = end\n \n return right \n\ndef write_result(out_fh, questions, answers, full_candidates_per_sample, result, answers_ids):\n assert (len(questions) == len(full_candidates_per_sample))\n i = 0; j = 0\n for ii in range(len(result)):\n if i == 0: out_fh.write(\"question\\t\" + questions[j] + \"\\n\")\n out_fh.write(\"%.3f\\t\" % result[ii]) \n if len(answers_ids[j]) != 0: out_fh.write(answers_ids[j][i] + '\\t')\n out_fh.write(answers[j][i] + '\\n')\n i += 1\n if i == full_candidates_per_sample[j]: \n i = 0; j+= 1\n\ndef parse_new_json_sample(sample): \n if 'label' in sample: correct_ans_ids = sample['label'] \n else: correct_ans_ids = []\n true_answers = []; true_ids = []\n false_answers = []; false_ids = []\n for candidate in sample['candidates']:\n ##gather title only \n title_list = []\n if 'path' in candidate:\n for section in candidate['path']:\n title_list.append(section[0])\n if 'answer' in candidate: \n for sub_ans in candidate['answer']:\n title_list.append(sub_ans)\n cur_ans = ' '.join(title_list)\n if candidate['id'] in correct_ans_ids: \n true_answers.append(cur_ans); true_ids.append(candidate['id'])\n else: \n false_answers.append(cur_ans); false_ids.append(candidate['id']) \n false_ids.extend(true_ids) \n assert len(false_ids) == len(true_answers) + len(false_answers)\n return true_answers, false_answers, false_ids\n\ndef reranker(sess, graph, token_vocab, char_vocab, batch_size, test_file, output_file, new_json=False):\n # setting output tensor node \n logger.info(\"get the output tensor..\")\n ys_names = OUTPUT_NODE_NAME\n logger.debug(\"output node name: %s\" % ys_names)\n ys = [graph.get_tensor_by_name(ys_names)]\n init_input_tensor_map(graph)\n\n logger.info(\"batch_size: %d\" % batch_size)\n with open(output_file, 'w', encoding = 'utf-8') as out_fh:\n if test_file.endswith(\".gz\"):\n in_fh = gzip.open(test_file, \"rt\", encoding='utf8')\n else: \n in_fh = open(test_file, 'r', encoding='utf-8')\n batch_counter = 0\n candidates_per_sample = [] \n full_candidates_per_sample = [] \n questions = []; answers = []; answers_ids = [] \n total = 0; right = 0\n inferance_time_list = []\n for line in in_fh: \n sample = json.loads(line.strip())\n logger.debug(\"input sample: {}\".format(sample))\n #prepare batch\n questions.append(sample['question'])\n if new_json:\n answers_true, answers_false, answer_ids = parse_new_json_sample(sample)\n else:\n if 'true' not in sample['answer']: answers_true = []\n else: answers_true = sample['answer']['true']\n answers_false = sample['answer']['false'] \n answer_ids = [] \n candidates_per_sample.append(len(answers_false))\n full_candidates_per_sample.append(len(answers_false)+len(answers_true))\n answers.append([])\n answers[-1].extend(answers_false) \n answers[-1].extend(answers_true) \n answers_ids.append(answer_ids)\n\n batch_counter += 1\n if batch_counter == batch_size:\n #preprocess: feed_dict \n feed_data = batch_process(questions, answers, token_vocab, char_vocab)\n\n # hack to allow truth only model to run !!!\n import numpy as np\n feed_data['candidate_1hot_2d'] = np.zeros((6,3),dtype ='int32')\n # hack ends\n\n #map to input tensor \n feed_data = map2TF_input(feed_data)\n #run model \n result, cur_inferance_time = run_model(sess, feed_data, ys) \n inferance_time_list.append(cur_inferance_time)\n #calculate accuracy \n total += batch_size\n right += correct_answers(candidates_per_sample, full_candidates_per_sample, result)\n logger.info(\"current accuracy: %.3f(%d/%d)\" % (float(right)/total, right, total))\n #write back to file \n write_result(out_fh, questions, answers, full_candidates_per_sample, result, answers_ids)\n #clear for next batch\n batch_counter = 0 \n candidates_per_sample.clear() \n full_candidates_per_sample.clear()\n questions.clear(); answers.clear(); answers_ids.clear()\n\n if batch_counter != 0: \n #preprocess: feed_dict \n feed_data = batch_process(questions, answers, token_vocab, char_vocab)\n\n # hack to allow truth only model to run !!!\n import numpy as np\n feed_data['candidate_1hot_2d'] = np.zeros((6,3),dtype ='int32')\n # hack ends\n\n #map to input tensor \n feed_data = map2TF_input(feed_data)\n #run model \n result, cur_inferance_time = run_model(sess, feed_data, ys) \n inferance_time_list.append(cur_inferance_time)\n #calculate accuracy \n total += batch_counter\n right += correct_answers(candidates_per_sample, full_candidates_per_sample, result)\n logger.info(\"current accuracy: %.3f(%d/%d)\" % (float(right)/total, right, total))\n #write back to file \n write_result(out_fh, questions, answers, full_candidates_per_sample, result, answers_ids)\n #clear for next batch\n batch_counter = 0 \n candidates_per_sample.clear() \n full_candidates_per_sample.clear()\n questions.clear(); answers.clear(); answers_ids.clear()\n\n ##report final result, remove the first one \n inferance_time_list.pop(0)\n np_time_list = np.array(inferance_time_list)\n time_avg = np.mean(np_time_list)\n time_std = np.std(np_time_list)\n time_min = min(inferance_time_list)\n time_max = max(inferance_time_list) \n time_str = \"latency: %.3f seconds/batch(%d sample(s)), min(%.3f), max(%.3f), std(%.3f)\"\\\n % (time_avg, batch_size, time_min, time_max, time_std) \n accuracy_str = \"final accuracy: %.3f(%d/%d)\" % (float(right)/total, right, total) \n\n out_fh.write(\"#################################################\\n\")\n out_fh.write(\"#################################################\\n\")\n out_fh.write(time_str + \"\\n\"); out_fh.write(accuracy_str + \"\\n\")\n in_fh.close()\n\n logger.info(\"#################################################\")\n logger.info(\"#################################################\")\n logger.info(time_str); logger.info(accuracy_str)\n\n###################################################################################### \ndef chk_char_embedding(model_folder):\n with open(model_folder + \"/graph_inout.map\", encoding='utf8') as fh: \n for line in fh:\n if 'word_chars' in line: return True \n return False \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--debug', action='store_true', help='increase verbosity')\n parser.add_argument(\"-m\", \"--model\", help=\"Frozen model directory to import\", required=True)\n parser.add_argument(\"-tf\", \"--test-file\", help=\"test json file\", required=True)\n parser.add_argument(\"-bs\", \"--batch-size\", help=\"batch size\", type=int, default=1)\n parser.add_argument(\"-o\", \"--output\", help=\"output file name\", required=True)\n parser.add_argument(\"-ug\", \"--use-gpu\", help=\"use gpu or not, default is True\", default='True') \n parser.add_argument('-nj', '--new-json', action='store_true', help='input file is new json format') \n parser.add_argument('-sm', '--serving-model', action='store_true', help='whether the model is serving')\n args = parser.parse_args() \n\n if args.debug:\n logging.basicConfig(level=logging.DEBUG)\n else:\n logging.basicConfig(level=logging.INFO)\n\n ###check the model directory\n model_name = None; dict_token2id = None; dict_char2id = None\n model_content = os.listdir(args.model)\n if \"token2id.map\" not in model_content: \n logger.error(\"can not find 'token2id.map' in '%s'\" % args.model)\n raise ValueError() \n if \"graph_inout.map\" not in model_content: \n logger.error(\"can not find 'graph_inout.map' in '%s'\" % args.model)\n raise ValueError() \n \n with_char = chk_char_embedding(args.model) \n if with_char:\n if \"char2id.map\" not in model_content: \n logger.error(\"can not find 'char2id.map' in '%s'\" % args.model)\n raise ValueError() \n for f in model_content: \n if f.endswith(\".pb\") or f.endswith(\".pbtxt\"): \n model_name = os.path.join(args.model, f) \n logger.info(\"find model: %s\" % model_name)\n break\n if model_name == None: \n logger.error(\"can not find model file in '%s', the model file is like 'model.Year-Month-Day.pb'\" % args.model)\n raise ValueError()\n\n logger.info(\"loading dictionaries ...\")\n dict_token2id = load_vocab(os.path.join(args.model, 'token2id.map'))\n dict_char2id = load_vocab(os.path.join(args.model, 'char2id.map')) if with_char else {} \n\n logger.info(\"gather in/out tensor nodes ...\")\n gather_inout_tensors(os.path.join(args.model, 'graph_inout.map')) \n\n if args.use_gpu.lower() == 'true':\n logger.info(\"using gpu...\")\n sys.path.append('/lm/tools/tf')\n from devices_tf import reserveSessionAndDevices\n\n gpu_num = int(os.environ['SGE_HGR_gpunum'])\n logger.info('will use {} GPUs'.format(gpu_num))\n sess, _, _ = reserveSessionAndDevices(numDevices = gpu_num, randomWait = 60, reserveGPU = True)\n else:\n logger.info(\"using cpu ...\")\n config = tf.ConfigProto(#device_count={\"CPU\": 2},\n inter_op_parallelism_threads=0,\n intra_op_parallelism_threads=0)\n sess = tf.Session(config=config)\n \n with sess.as_default():\n logger.info(\"loading graph: %s\" % model_name)\n if args.serving_model: \n load_serving_model(sess, args.model) \n else: \n load_graph(model_name)\n graph = sess.graph \n reranker(sess, graph, dict_token2id, dict_char2id, args.batch_size, args.test_file, args.output, args.new_json)\n \n mem_fp.close()\n parse_mem_profile(\"memory_profiler.log\", args.output)\n","sub_path":"AutoQA-ding_merged/tools/model_freeze/test_frozen_model.py","file_name":"test_frozen_model.py","file_ext":"py","file_size_in_byte":15484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"598219293","text":"# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nimport numpy as np\nfrom pyiron_base import Settings\nfrom sklearn.cluster import AgglomerativeClustering\nfrom scipy.sparse import coo_matrix\n\n__author__ = \"Joerg Neugebauer, Sam Waseda\"\n__copyright__ = (\n \"Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - \"\n \"Computational Materials Design (CM) Department\"\n)\n__version__ = \"1.0\"\n__maintainer__ = \"Sam Waseda\"\n__email__ = \"waseda@mpie.de\"\n__status__ = \"production\"\n__date__ = \"Sep 1, 2017\"\n\ns = Settings()\n\ndef get_average_of_unique_labels(labels, values):\n \"\"\"\n\n This function returns the average values of those elements, which share the same labels\n\n Example:\n\n >>> labels = [0, 1, 0, 2]\n >>> values = [0, 1, 2, 3]\n >>> print(get_average_of_unique_labels(labels, values))\n array([1, 1, 3])\n\n \"\"\"\n labels = np.unique(labels, return_inverse=True)[1]\n unique_labels = np.unique(labels)\n mat = coo_matrix((np.ones_like(labels), (labels, np.arange(len(labels)))))\n mean_values = np.asarray(mat.dot(np.asarray(values).reshape(len(labels), -1))/mat.sum(axis=1))\n if np.prod(mean_values.shape).astype(int)==len(unique_labels):\n return mean_values.flatten()\n return mean_values\n\nclass Analyse:\n \"\"\" Class to analyse atom structure. \"\"\"\n def __init__(self, structure):\n \"\"\"\n Args:\n structure (pyiron.atomistics.structure.atoms.Atoms): reference Atom structure.\n \"\"\"\n self._structure = structure\n\n def get_layers(self, distance_threshold=0.01, id_list=None, wrap_atoms=True, planes=None):\n \"\"\"\n Get an array of layer numbers.\n\n Args:\n distance_threshold (float): Distance below which two points are\n considered to belong to the same layer. For detailed\n description: sklearn.cluster.AgglomerativeClustering\n id_list (list/numpy.ndarray): List of atoms for which the layers\n should be considered.\n planes (list/numpy.ndarray): Planes along which the layers are calculated. Planes are\n given in vectors, i.e. [1, 0, 0] gives the layers along the x-axis. Default planes\n are orthogonal unit vectors: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]. If you have a\n tilted box and want to calculate the layers along the directions of the cell\n vectors, use `planes=np.linalg.inv(structure.cell).T`. Whatever values are\n inserted, they are internally normalized, so whether [1, 0, 0] is entered or\n [2, 0, 0], the results will be the same.\n\n Returns: Array of layer numbers (same shape as structure.positions)\n\n Example I - how to get the number of layers in each direction:\n\n >>> structure = Project('.').create_structure('Fe', 'bcc', 2.83).repeat(5)\n >>> print('Numbers of layers:', np.max(structure.analyse.get_layers(), axis=0)+1)\n\n Example II - get layers of only one species:\n\n >>> print('Iron layers:', structure.analyse.get_layers(\n ... id_list=structure.select_index('Fe')))\n \"\"\"\n if distance_threshold <= 0:\n raise ValueError('distance_threshold must be a positive float')\n if id_list is not None and len(id_list)==0:\n raise ValueError('id_list must contain at least one id')\n if wrap_atoms and planes is None:\n positions, indices = self._structure.get_extended_positions(\n width=distance_threshold, return_indices=True\n )\n if id_list is not None:\n id_list = np.arange(len(self._structure))[np.array(id_list)]\n id_list = np.any(id_list[:,np.newaxis]==indices[np.newaxis,:], axis=0)\n positions = positions[id_list]\n indices = indices[id_list]\n else:\n positions = self._structure.positions\n if id_list is not None:\n positions = positions[id_list]\n if wrap_atoms:\n positions = self._structure.get_wrapped_coordinates(positions)\n if planes is not None:\n mat = np.asarray(planes).reshape(-1, 3)\n positions = np.einsum('ij,i,nj->ni', mat, 1/np.linalg.norm(mat, axis=-1), positions)\n layers = []\n for ii,x in enumerate(positions.T):\n cluster = AgglomerativeClustering(\n linkage='complete',\n n_clusters=None,\n distance_threshold=distance_threshold\n ).fit(x.reshape(-1,1))\n first_occurrences = np.unique(cluster.labels_, return_index=True)[1]\n permutation = x[first_occurrences].argsort().argsort()\n labels = permutation[cluster.labels_]\n if wrap_atoms and planes is None and self._structure.pbc[ii]:\n mean_positions = get_average_of_unique_labels(labels, positions)\n scaled_positions = np.einsum(\n 'ji,nj->ni', np.linalg.inv(self._structure.cell), mean_positions\n )\n unique_inside_box = np.all(np.absolute(scaled_positions-0.5+1.0e-8)<0.5, axis=-1)\n arr_inside_box = np.any(\n labels[:,None]==np.unique(labels)[unique_inside_box][None,:], axis=-1\n )\n first_occurences = np.unique(indices[arr_inside_box], return_index=True)[1]\n labels = labels[arr_inside_box]\n labels -= np.min(labels)\n labels = labels[first_occurences]\n layers.append(labels)\n if planes is not None and len(np.asarray(planes).shape)==1:\n return np.asarray(layers).flatten()\n return np.vstack(layers).T\n\n\n","sub_path":"pyiron/atomistics/structure/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":5862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"48282146","text":"# 用以下脚本从test.html 中获取数据\n# \n\n\nITEMS = {\n \"Home\": [\n [\"select\", \"select.png\"],\n [\"AreaSelect\", \"AreaSelect.png\"],\n [\"pen\", \"pen.png\"],\n [\"undergroundmode\", \"undergroundmode.png\"],\n [\"location\", \"location.png\"],\n [\"projectsetting\", \"projectsetting.png\"],\n [\"publish\", \"publish.png\"],\n [\"hideterrain\", \"hideterrain.png\"],\n [\"fov\", \"fov.png\"],\n [\"extracttompt\", \"extracttompt.png\"],\n [\"extracttovrml\", \"extracttovrml.png\"],\n [\"collaboration\", \"collaboration.png\"],\n [\"urbandesign\", \"urbandesign.png\"],\n [\"duplicateobjects\", \"duplicateobjects.png\"],\n [\"imagerycomparison\", \"imagerycomparison.png\"],\n [\"snapshotcomparison\", \"snapshotcomparison.png\"]\n ],\n \"Analysis\": [\n [\"query\", \"query.png\"],\n [\"distance\", \"distance.png\"],\n [\"Hdistance\", \"HRuler02.png\"],\n [\"3Ddistance\", \"3DRuler.png\"],\n [\"area\", \"area.png\"],\n [\"contourmap\", \"contourmap.png\"],\n [\"Areacontourmap\", \"AreaContour.png\"],\n [\"AreaTerrainMap\", \"AreaTerrainMap.png\"],\n [\"slopemap\", \"slopemap.png\"],\n [\"SlopeColorMap\", \"SlopeColorMap.png\"],\n [\"SlopeDirections\", \"SlopeDirections.png\"],\n [\"bestpath\", \"bestpath.png\"],\n [\"terrainprofile\", \"terrainprofile.png\"],\n [\"flood\", \"flood.png\"], [\"volume\", \"volume.png\"],\n [\"lineofsight\", \"lineofsight.png\"],\n [\"viewshed\", \"viewshed.png\"],\n [\"viewshedonroute\", \"viewshedonroute.png\"],\n [\"threatdome\", \"threatdome.png\"],\n [\"shadow\", \"shadow.png\"],\n [\"selectionshadow\", \"selectionshadow.png\"],\n [\"shadowquery\", \"shadowquery.png\"]\n ],\n \"Layers\": [\n [\"loadlayer\", \"loadlayer.png\"],\n [\"datalibrary\", \"datalibrary.png\"],\n [\"osmlayers\", \"osmlayers.png\"],\n [\"newlayer\", \"newlayer.png\"],\n [\"fly\", \"fly.png\"],\n [\"kml\", \"kml.png\"],\n [\"3dml\", \"3dml.png\"],\n [\"bim\", \"bim.png\"],\n [\"pointcloud\", \"pointcloud.png\"],\n [\"imagerylayer\", \"imagerylayer.png\"],\n [\"elevationlayer\", \"elevationlayer.png\"],\n [\"osmmap\", \"osmmap.png\"],\n [\"make3dml\", \"make3dml.png\"],\n [\"makexpl\", \"makexpl.png\"],\n [\"makecpt\", \"makecpt.png\"],\n [\"resolutionpyramid\", \"resolutionpyramid.png\"]\n ],\n \"Objects\": [\n [\"text\", \"text.png\"],\n [\"image\", \"image.png\"],\n [\"videoonterrain\", \"videoonterrain.png\"],\n [\"videobillboard\", \"videobillboard.png\"],\n [\"polyline\", \"polyline.png\"],\n [\"polygon\", \"polygon.png\"],\n [\"3dmodel\", \"3dmodel.png\"], [\"building\", \"building.png\"],\n [\"modifyterrain\", \"modifyterrain.png\"],\n [\"holeonterrain\", \"holeonterrain.png\"],\n [\"groundobject\", \"groundobject.png\"],\n [\"aerialobject\", \"aerialobject.png\"],\n [\"movebytime\", \"movebytime.png\"],\n [\"datalibrary\", \"datalibrary.png\"],\n [\"sketchupwarehouse\", \"sketchupwarehouse.png\"]\n ],\n \"Shapes\": [\n [\"rectangle\", \"rectangle.png\"],\n [\"regularpolygon\", \"regularpolygon.png\"],\n [\"arrow\", \"arrow.png\"],\n [\"circle\", \"circle.png\"],\n [\"ellipse\", \"ellipse.png\"],\n [\"arc\", \"arc.png\"],\n [\"3dpolygon\", \"3dpolygon.png\"],\n [\"box\", \"box.png\"],\n [\"cylinder\", \"cylinder.png\"],\n [\"sphere\", \"sphere.png\"],\n [\"cone\", \"cone.png\"],\n [\"pyramid\", \"pyramid.png\"],\n [\"3darrow\", \"3darrow.png\"]\n ],\n \"Navigation\": [\n [\"3d\", \"3d.png\"],\n [\"2d\", \"2d.png\"],\n [\"2dn\", \"2dn.png\"],\n [\"zoom\", \"zoom.png\"],\n [\"north\", \"north.png\"],\n [\"rotate\", \"rotate.png\"],\n [\"follow\", \"follow.png\"],\n [\"collisiondetection\", \"collisiondetection.png\"],\n [\"slidemode\", \"slidemode.png\"],\n [\"map\", \"map.png\"],\n [\"gps\", \"gps.png\"],\n [\"target\", \"target.png\"],\n [\"multiplecoordsys\", \"multiplecoordsys.png\"],\n [\"lookaround\", \"lookaround.png\"]\n ],\n \"Animation\": [\n [\"customanimation\", \"customanimation.png\"],\n [\"firesmokewhite\", \"firesmokewhite.png\"],\n [\"firesmokeblack\", \"firesmokeblack.png\"],\n [\"bonfire\", \"bonfire.png\"],\n [\"buildingfire\", \"buildingfire.png\"],\n [\"forestfire\", \"forestfire.png\"],\n [\"groundexplosion\", \"groundexplosion.png\"],\n [\"fireworkstwocolors\", \"fireworkstwocolors.png\"],\n [\"fireworksring\", \"fireworksring.png\"],\n [\"fountain\", \"fountain.png\"],\n [\"pipeburst\", \"pipeburst.png\"],\n [\"oceans\", \"oceans.png\"]\n ]\n}\n","sub_path":"app/projects/sidebar_menu.py","file_name":"sidebar_menu.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"4999864","text":"#coding=utf8\nfrom telegram import InlineKeyboardButton,InlineKeyboardMarkup, Update\nfrom telegram.ext import CallbackContext, Dispatcher, CommandHandler, MessageHandler, Filters\nfrom telegram.error import BadRequest\nimport telegram\n\nimport requests\n\nfrom bs4 import BeautifulSoup\n\nfrom io import BytesIO\nfrom PIL import Image\n\nimport numpy as np\n\nimport os\n\nimport random\n\nfrom rq import Queue\nfrom worker import conn\n\nq = Queue(connection=conn)\n\nemojis = \"😂😘😍😊😁😔😄😭😒😳😜😉😃😢😝😱😡😏😞😅😚😌😀😋😆😐😕👍👌👿❤🖤💤🎵🔞\"\n# get a random emoji from emojis\ndef get_random_emoji():\n\treturn emojis[random.randint(0,len(emojis)-1)]\n\n# split a list of string and automatically remove null string\n# [\"a12\", \"1a2\"], \"a\" -> [\"12\", \"1\", \"2\"]\ndef split_list_of_string_by(list_of_string, split_by):\n\toutput = []\n\t# split string in list\n\tfor i in list_of_string:\n\t\toutput += i.split(split_by)\n\n\t# remove null string\n\treturn [i for i in output if i != \"\"]\n\n# extract sticker number from url\n# if sticker number is found, return sticker number\n# else return null string\n# \"https://store.line.me/stickershop/product/3962468/ja\" -> \"3962468\"\ndef get_sticker_number_from_url(url):\n\t# split url into several independent string by common characters\n\tallSplit = split_list_of_string_by([url], \"/\")\n\tallSplit = split_list_of_string_by(allSplit, \"=\")\n\tallSplit = split_list_of_string_by(allSplit, \"?\")\n\n\tprint(allSplit)\n\n\t# get sticker number by common url pattern\n\tfor idx, string in enumerate(allSplit):\n\t\tif string == \"sticker\" or string == \"product\" or string == \"id\":\n\t\t\treturn allSplit[idx + 1]\n\n\t# if not found\n\treturn \"\"\n\n'''\ntypes of sticker (with example):\nNormal Stickers: \t\thttps://store.line.me/stickershop/product/3962468/ja\nEffect Stickers: \t\thttps://store.line.me/stickershop/product/18082/en\nMessage Stickers: \t\thttps://store.line.me/stickershop/product/17092/en\nCustom Stickers: \t\thttps://store.line.me/stickershop/product/14458/en\nBig Stickers: \t\t \thttps://store.line.me/stickershop/product/24202/en\nPop-up Stickers: \t\thttps://store.line.me/stickershop/product/24206/en\nWith voice or sound:\thttps://store.line.me/stickershop/product/17050/en\nAnimated Stickers: \t\thttps://store.line.me/stickershop/product/8549/en\nMusic Stickers: \t\thttps://store.line.me/stickershop/product/17891/en\n'''\n\n'''\nget info of sticker\nlike is_message_sticker, title, image urls\n\nwhen is_message_sticker is False, \n\turls is a list of sting\nwhen is_message_sticker is True, \n\turls is a list of tuples of string standing for pairs of images (background image and text image)\n'''\ndef get_sticker_info(text):\n\t# convert to soup\n\tsoup = BeautifulSoup(text, \"html.parser\")\n\t\n\t# output\n\tis_message_sticker = False\n\ttitle = \"\"\n\turls = []\n\n\t# check if it is a typical sticker url and return result\n\ttry:\n\t\t# message stickers\n\t\tif text.find(\"data-default-text\") != -1:\n\t\t\tclasses = soup.find_all(\"li\", \"mdCMN09Li FnStickerPreviewItem\")\n\t\t\ttexts = [c[\"data-preview\"] for c in classes]\n\t\t\turls = [(i[i.find(\"http\"):i.find(\".png\")+4] for i in t.split(\"customOverlayUrl\")) for t in texts]\n\t\t\tis_message_sticker = True\n\n\t\t# custom stickers\n\t\telif text.find(\"mdCMN09Image FnCustomBase\") != -1:\n\t\t\tclasses = soup.find_all(\"span\", \"mdCMN09Image FnCustomBase\")\n\t\t\ttext = [t[\"style\"] for t in classes]\n\t\t\turls = [t[t.find(\"(\")+1:t.find(\";\")] for t in text]\n\t\t\turls = list(dict.fromkeys(urls))\n\t\t\tis_message_sticker = False\n\n\t\t# other normal stickers\n\t\telse:\n\t\t\tclasses = soup.find_all(\"span\", \"mdCMN09Image\")\n\t\t\ttext = [t[\"style\"] for t in classes]\n\t\t\turls = [t[t.find(\"(\")+1:t.find(\";\")] for t in text]\n\t\t\turls = list(dict.fromkeys(urls))\n\t\t\tis_message_sticker = False\n\t\t\n\t\tc = soup.find(\"p\", \"mdCMN38Item01Ttl\")\n\t\ttitle = c.text\n\texcept:\n\t\tis_message_sticker = False\n\t\ttitle = \"\"\n\t\turls = []\n\n\tif len(urls) > 0:\n\t\tfor idx in range(len(urls)):\n\t\t\turls[idx] = urls[idx].replace(\")\", \"\")\n\n\treturn is_message_sticker, title, urls\n\n# get sticker name from sticker number\ndef get_sticker_name_from_sticker_number(bot, sticker_number):\n\treturn f\"line{sticker_number}_by_{bot.username}\"\n\n# get telegram sticker set based on name of sticker\ndef get_sticker_set(bot, sticker_name):\n\t\n\tresult = None\n\ttry:\n\t\tresult = bot.get_sticker_set(name=sticker_name)\n\texcept:\n\t\tresult = None\n\n\treturn result\n\n# delete all stickers from sticker set to delete a sticker set\ndef delete_sticker_set(bot, sticker_set):\n\tfor sticker in sticker_set.stickers:\n\t\tbot.delete_sticker_from_set(sticker.file_id)\n\n# get image from image url\n# download and convert to image format\ndef get_image_from_url(url):\n\treturn Image.open(BytesIO(requests.get(url).content)).convert('RGBA')\n\n# merge two images with repect to transparency\ndef merge_image(background_image, text_image):\n\tbackground = np.array(background_image)\n\ttext = np.array(text_image)\n\toutput = np.array(text_image)\n\n\tfor y in range(len(background)):\n\t\tfor x in range(len(background[y])):\n\t\t\tpower = text[y][x][3]/255\n\t\t\toutput[y][x] = background[y][x] * (1-power) + text[y][x] * power\n\n\treturn Image.fromarray(output, 'RGBA')\n\n# resize image to have the max dimension be a specific number\n# 5x10, 20 -> 10x20\n# 10x20, 5 -> 3x5 where 3 standing for round(2.5)\ndef resize_image_with_maximum(image, maximum):\n\tw, h = image.size\n\tproportion = 512 / max(w,h)\n\n\tnew_w = round(w * proportion)\n\tnew_h = round(h * proportion)\n\tif new_w >= new_h: new_w = 512\n\tif new_h >= new_w: new_h = 512\n\n\treturn image.resize((new_w, new_h), Image.BICUBIC)\n\n# get image with telegram sticker format from image url \n# when is_message_sticker = False, url should be a image url\n# when is_message_sticker = True, url should be a tuple of image urls\n\n# step:\n# 1. download image\n# (1.5. if is_message_sticker = true, merge images)\n# 2. resize to ??? x 512 or 512 x ??? (where ??? <= 512)\ndef get_sticker_image_from_url(is_message_sticker, url):\n\t# get image from url\n\tif not is_message_sticker:\n\t\timage = get_image_from_url(url)\n\telse:\n\t\tbackground_image = get_image_from_url(url[0])\n\t\ttext_image = get_image_from_url(url[1])\n\t\timage = merge_image(background_image, text_image)\n\n\timage = resize_image_with_maximum(image, 512)\n\treturn image\n\n# main procession of text\n# get page from text, extract sticker's image urls, download image, resize image, upload image\ndef process_text(access_token, user_id, text, output_message_id):\n\n\tbot = telegram.Bot(token=access_token)\n\n\t# check if text is valid\n\ttry:\n\t\t# check if there is a sticker number in text \n\t\tsticker_number = get_sticker_number_from_url(text)\n\t\tif sticker_number == \"\":\n\t\t\traise Exception(\"Can't find any sticker number in text\")\n\t\t\n\t\t# check if text is an url\n\t\tn = requests.get(text)\n\n\texcept Exception as e:\n\t\tprint(e)\n\t\tbot.edit_message_text(\tchat_id = user_id,\n\t\t\t\t\t\t\t\tmessage_id = output_message_id,\n\t\t\t\t\t\t\t\ttext = (\"無效網址\\n\\n\"\n\t\t\t\t\t\t\t\t\t\t\"Invalid URL\"))\n\t\treturn\n\t\t\t\t\n\tis_message_sticker, title, urls = get_sticker_info(n.text)\n\n\t# can't find any sticker\n\tif len(urls) == 0:\n\t\tbot.edit_message_text(chat_id = user_id,\n\t\t\t\t\t\t\tmessage_id = output_message_id,\n\t\t\t\t\t\t\ttext = \t(\"沒有找到任何Line貼圖?!\\n\\n\"\n\t\t\t\t\t\t\t\t\t\"Can't find any line sticker?!\"))\n\t\treturn\n\n\tsticker_name = get_sticker_name_from_sticker_number(bot, sticker_number)\n\n\thas_uploaded_first_image = False\n\t\n\tbackup_count = 0\n\tnew_sticker_name = sticker_name[:]\n\tis_valid_sticker_number = False\t\n\twhile not is_valid_sticker_number:\n\n\t\tprint(new_sticker_name)\n\n\t\t# check if there has been a sticker set\n\t\tsticker_set = get_sticker_set(bot, new_sticker_name)\n\n\t\t# three conditions:\n\t\t# 1. no sticker set -> upload stickers\n\t\t# 2. exist sticker set, and sticker set finished uploading -> return finished sticker set\n\t\t# 3. exist sticker set, but sticker set didn't finish uploading -> delete old sticker set and upload stickers\n\t\tif sticker_set != None:\n\t\t\t# condition 2\n\t\t\tif len(sticker_set.stickers) == len(urls):\n\t\t\t\tbot.edit_message_text(\tchat_id = user_id,\n\t\t\t\t\t\t\t\t\t\tmessage_id = output_message_id,\n\t\t\t\t\t\t\t\t\t\ttext = (\tf\"總算找到了\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tf\"This one?!\\n\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tf\"Line sticker number:{sticker_number}\"))\n\n\t\t\t\tbot.send_sticker(\tchat_id = user_id,\n\t\t\t\t\t\t\t\t\tsticker = sticker_set.stickers[0].file_id,\n\t\t\t\t\t\t\t\t\treply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(\ttext = title, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\turl = f\"https://t.me/addstickers/{new_sticker_name}\")]]))\n\t\t\t\treturn\n\t\t\t# condition 3\n\t\t\telse:\n\t\t\t\tdelete_sticker_set(bot, sticker_set)\n\n\t\t# upload\n\t\tupload_static_text = (\tf\"{title}\\n\"\n\t\t\t\t\t\t\t\tf\"發現{len(urls)}張貼圖\\n\\n\"\n\t\t\t\t\t\t\t\tf\"Found {len(urls)} stickers\\n\")\n\n\t\t# first image for creating a sticker set\n\t\tif not has_uploaded_first_image:\n\t\t\ttry:\n\t\t\t\tsticker_image = get_sticker_image_from_url(is_message_sticker, urls[0])\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\n\n\t\t\tsticker_image.save(f\"{sticker_number}.png\")\n\t\t\tsticker0 = bot.upload_sticker_file(\tuser_id = user_id,\n\t\t\t\t\t\t\t\t\t\t\t\tpng_sticker=open(f\"{sticker_number}.png\", 'rb')).file_id\n\t\t\thas_uploaded_first_image = True\n\n\t\t# create a sticker set\n\t\tis_potential_valid_sticker_name = False\n\n\t\twhile not is_potential_valid_sticker_name:\n\n\t\t\ttry:\n\t\t\t\tbot.create_new_sticker_set(\tuser_id = user_id,\n\t\t\t\t\t\t\t\t\t\t\tname = new_sticker_name,\n\t\t\t\t\t\t\t\t\t\t\ttitle = f\"{title} @RekcitsEnilbot\",\n\t\t\t\t\t\t\t\t\t\t\tpng_sticker = sticker0,\n\t\t\t\t\t\t\t\t\t\t\temojis = get_random_emoji())\n\t\t\t\tis_potential_valid_sticker_name = True\n\t\t\t\tis_valid_sticker_number = True\n\n\t\t\texcept BadRequest as e:\n\n\t\t\t\tif str(e) == \"Shortname_occupy_failed\" or str(e) == \"Sticker set name is already occupied\":\n\t\t\t\t\t# A special error that I don't know what cause it.\n\t\t\t\t\t# Telegram say that this is an internal error.....\n\t\t\t\t\tnew_sticker_name = f\"backup_{backup_count}_{sticker_name}\"\n\t\t\t\t\tbackup_count = backup_count + 1\n\t\t\t\t\tis_potential_valid_sticker_name = True\n\t\t\t\telse:\n\t\t\t\t\tprint(\"??????\")\n\t\t\t\t\tprint(e)\n\t\t\t\t\treturn\n\n\tsticker_name = new_sticker_name[:]\n\n\n\t# the left images to be uploaded\n\tfor idx, url in enumerate(urls[1:]):\n\t\tsticker_image = get_sticker_image_from_url(is_message_sticker, url)\n\n\t\tsticker_image.save(f\"{sticker_number}.png\")\n\n\t\ttry:\n\t\t\tsticker = bot.upload_sticker_file(\tuser_id = user_id,\n\t\t\t\t\t\t\t\t\t\t\t\tpng_sticker=open(f\"{sticker_number}.png\", 'rb')).file_id\n\t\texcept Exception as e:\n\t\t\tw, h = sticker_image.size\n\t\t\tprint(w, h)\n\t\t\tprint(url)\n\t\t\tprint(e)\n\t\t\treturn\n\n\t\tbot.add_sticker_to_set(\tuser_id=user_id,\n\t\t\t\t\t\t\t\tname = sticker_name,\n\t\t\t\t\t\t\t\tpng_sticker = sticker,\n\t\t\t\t\t\t\t\temojis = get_random_emoji())\n\n\t\tupload_text = f\"{upload_static_text}{'*' * (idx + 2)}{'_' * (len(urls) - (idx + 2))}{idx + 2}/{len(urls)}\"\n\t\tbot.edit_message_text(\tchat_id = user_id,\n\t\t\t\t\t\t\t\tmessage_id = output_message_id,\n\t\t\t\t\t\t\t\ttext = upload_text)\n\n\t# delete temporary file\n\tos.remove(f\"{sticker_number}.png\")\n\n\t# finish uploading\n\tbot.send_message(\tchat_id = user_id,\n\t\t\t\t\t\ttext = (f\"噠啦~☆\\n\\n\"\n\t\t\t\t\t\t\t\tf\"Finished!\\n\\n\"\n\t\t\t\t\t\t\t\tf\"Line sticker number:{sticker_number}\\n\"\n\t\t\t\t\t\t\t\tf\"https://t.me/addstickers/{sticker_name}\"))\n\t# send the first sticker of sticker set\n\tbot.send_sticker(\tchat_id = user_id,\n\t\t\t\t\t\tsticker = sticker0,\n\t\t\t\t\t\treply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(\ttext = title,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\turl=f\"https://t.me/addstickers/{sticker_name}\")]]))\n\n\treturn\n\n# when user type \"/start\"\ndef start(update: Update, context: CallbackContext):\n\tupdate.message.reply_text(text = (\t\"這個Bot可以將Line上的貼圖轉換成telegram上的貼圖。\\n\"\n\t\t\t\t\t\t\t\t\t\t\"This bot can transform Line's stickers to Telegram's sticker.\\n\\n\"\n\t\t\t\t\t\t\t\t\t\t\"只需將貼圖商店的網址貼上來就會自動轉換\\n\"\n\t\t\t\t\t\t\t\t\t\t\"Send me URL of line sticker to convert.\\n\\n\"+\n\t\t\t\t\t\t\t\t\t\t\"範例example:\\n\"\n\t\t\t\t\t\t\t\t\t\t\"https://store.line.me/stickershop/product/3962468/ja\"))\n\treturn\n\n# when user type \"/help\"\ndef help_(update: Update, context: CallbackContext):\n\tupdate.message.reply_text(text = (\t\"直接傳網址給我就可以惹\\n\"\n\t\t\t\t\t\t\t\t\t\t\"Just send me the URL.\\n\\n\"\n\t\t\t\t\t\t\t\t\t\t\"像這個Like this:\\n\"\n\t\t\t\t\t\t\t\t\t\t\"https://store.line.me/stickershop/product/3962468/ja\"))\n\n\treturn\n\n# when user type \"/about\"\ndef about(update: Update, context: CallbackContext):\n\tupdate.message.reply_text(text = (\t\"Author: @Homura343\\n\"\n\t\t\t\t\t\t\t\t\t\t\"Channel: https://t.me/ArumohChannel\\n\"\n\t\t\t\t\t\t\t\t\t\t\"Channel Group: https://t.me/ArumohChannelGroup\\n\"\n\t\t\t\t\t\t\t\t\t\t\"Github: https://github.com/Mescury/Teleline-sticker-converter\"))\n\treturn\n\n# when user send message\n# simply send response and enqueue procession\ndef text(update: Update, context: CallbackContext):\n\tmessage = update.message.reply_text(text = (\t\"正在試試看這東西\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Testing this message.\"))\n\n\tq.enqueue(process_text, update.message.bot.token, update.effective_message.chat_id, update.message.text, message.message_id)\n\treturn\n\n# TeleLine's Dispatcher\n# process update from telegram\nclass Dispatcher(Dispatcher):\n\tdef __init__(self, access_token):\n\t\t# initialize the dispatcher\n\t\tself.bot = telegram.Bot(token=access_token)\n\t\tsuper().__init__(self.bot, None)\n\n\t\t# initialize handler\n\t\tsuper().add_handler(CommandHandler('start', start))\n\t\tsuper().add_handler(CommandHandler('help', help_))\n\t\tsuper().add_handler(CommandHandler('about', about))\n\t\tsuper().add_handler(MessageHandler(Filters.text, text))\n\n\tdef process_update(self, data):\n\t\tupdate = Update.de_json(data, self.bot)\n\t\tsuper().process_update(update)","sub_path":"TeleLine.py","file_name":"TeleLine.py","file_ext":"py","file_size_in_byte":13302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"518238473","text":"temperature=float(input(\"enter temperature in celcius\"))\r\ndef cel_to_feh(cel):\r\n if cel<-273.15:\r\n print(\"error\")\r\n else:\r\n feh=cel*9/5+32\r\n print(feh)\r\n \r\ncel_to_feh(temperature)\r\n \r\n","sub_path":"cel_to_feh.py","file_name":"cel_to_feh.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"76290078","text":"# Copyright (c) 2018 PrimeVR\n# Distributed under the MIT software license, see the accompanying\n# file LICENSE or http://www.opensource.org/licenses/mit-license.php\n\n###############################################################################\n# per-addresss data\n###############################################################################\n\nclass AddressInfo(dict):\n def __init__(self, wd, addr):\n super().__init__()\n self.addr = addr\n self.wd = wd\n self.addr_info = self.wd.fetch_addr_info(self.addr)\n\n ins = list(self._get_addr_ins())\n outs = list(self._get_addr_outs())\n self._validate_outs(ins, outs)\n tx_block_map = self._get_tx_block_map(ins, outs)\n for i in ins:\n i['block'] = tx_block_map[i['hash']]\n for o in outs:\n o['block'] = tx_block_map[o['hash']]\n self['spans'] = self._calc_spans(ins, outs)\n self['addr'] = self.addr\n self['p2sh_p2wpkh'] = self.addr[:1] == \"3\"\n self['bech32'] = self.addr[:3] == \"bc1\"\n\n\n def _calc_spans(self, ins, outs):\n spans = {}\n out_lookup = {o['span_id']: o for o in outs}\n for i in ins:\n span_id = i['span_id']\n o = out_lookup[span_id] if span_id in out_lookup.keys() else None\n spans[span_id] = {'funded': i,\n 'defunded': o}\n return spans\n\n def _span_id(self, tx_index, n, value):\n return \"%s %s %s\" % (tx_index, n, value)\n\n def _validate_outs(self, ins, outs):\n # make sure data is consistent by having every out correspond to\n # a previous in.\n i_set = set(t['span_id'] for t in ins)\n o_set = set(t['span_id'] for t in outs)\n #print(i_set)\n #print(o_set)\n for o in o_set:\n assert o in i_set\n\n def _iter_tx_blocks(self, txes):\n hashes = [t['hash'] for t in txes]\n for h in list(set(hashes)):\n d = self.wd.fetch_tx_info(h)\n yield h, d['block_height']\n\n def _get_tx_block_map(self, ins, outs):\n return {h: height for h, height in\n self._iter_tx_blocks(ins + outs)}\n\n def _get_addr_ins(self):\n for tx in self.addr_info['txs']:\n outs = [o for o in tx['out'] if o['addr'] == self.addr]\n for o in outs:\n yield {'n': o['n'],\n 'hash': tx['hash'],\n 'value': o['value'],\n 'tx_index': o['tx_index'],\n 'span_id': self._span_id(o['tx_index'], o['n'],\n o['value'])\n }\n\n def _get_addr_outs(self):\n for tx in self.addr_info['txs']:\n ins = [i for i in tx['inputs'] if\n i['prev_out']['addr'] == self.addr]\n for i in ins:\n n = i['prev_out']['n']\n value = i['prev_out']['value']\n tx_index = i['prev_out'][\"tx_index\"]\n\n yield {'tx_index': tx_index,\n 'n': n,\n 'value': value,\n 'hash': tx['hash'],\n 'span_id': self._span_id(tx_index, n, value)\n }\n","sub_path":"lib/address_info.py","file_name":"address_info.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"170530217","text":"\"\"\" \nThis file contains support function defs for the script 'run_models_main.py'.\n \nCopyright (c) 2020 Charles B. Delahunt. delahunt@uw.edu\nMIT License\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import auc\n\"\"\"\n--------------------------------------------------------------\n--------------------function defs ----------------------------\n--------------------------------------------------------------\n\"\"\"\n#%%\n\ndef plotResultsFunction(probScores, testLabels, balancedAcc, sens, spec, params, fid):\n\n '''\n Plots ROC curves and balanced accuracy plots. let n = number of samples. It is only called from\n within calculateAccuracyStatsOnTestSetFunction().\n Inputs:\n probScores = n x 1 np.array (vector) of floats in [0, 1]\n testLabels = n x 1 np.array (vector) of 0s and 1s\n balancedAcc = n x 1 np.array (vector) of floats in [0, 1]\n sens = n x 1 np.array (vector) of floats in [0, 1]\n spec = n x 1 np.array (vector) of floats in [0, 1]\n params = dict of important parameters\n fid: file id, from open()\n\n Outputs: (depending on flags in 'params')\n Info printed to console\n ROC plot and balanced accuracy (over many thresholds) plot\n '''\n\n def makeRocAndAccuracyPlotsSubFunction(fpr, tpr, auc_score, threshIndex, rocTitleStr, sens,\n spec, balancedAcc, balAccTitleStr):\n ''' Makes two subplots with ROC curve and Balanced accuracies vs thresholds. Each subplot\n uses half of the many argins.\n Inputs:\n fpr: vector of floats\n tpr: vector of floats\n auc_score: float\n threshIndex: int\n rocTitleStr: str\n sens: vector of floats\n spec: vector of floats\n balancedAcc: vector of floats\n balAccTitleStr: str\n Outputs:\n matplotlib figure\n '''\n _, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))\n\n # ROC curve subplot:\n ax1.plot(fpr, tpr, color='black', lw=2, linestyle='--', label=' AUC = %0.2f' % auc_score)\n ax1.plot(fpr[threshIndex], tpr[threshIndex], 'ko', markersize=8)\n ax1.legend(loc='lower right')\n ax1.plot([0, 1], [0, 1], color='gray', linestyle='--')\n ax1.set_xlabel('1 - specificity')\n ax1.set_ylabel('sensitivity')\n\n ax1.set_title(rocTitleStr)\n\n ax1.set_xlim([0.0, 1.0])\n ax1.set_ylim([0.0, 1.0])\n ax1.grid(True)\n\n # Balanced Accuracy subplot\n x = np.linspace(0, 1, 101)\n ax2.plot(x, sens, color='blue', lw=2, linestyle='-', label='sens')\n ax2.plot(x, spec, color='green', lw=2, linestyle='-', label='spec')\n ax2.plot(x, balancedAcc, color='black', lw=2, linestyle='-', label='balanced acc')\n ax2.plot()\n ax2.set_xlabel('accuracy')\n ax2.set_ylabel('threshold')\n ax2.legend(loc='lower right')\n\n ax2.set_title(balAccTitleStr)\n ax2.set_xlim([0.0, 1.0])\n ax2.set_ylim([0.0, 1.0])\n ax2.grid(True)\n plt.show()\n # End of makeAccuracyPlotsFunction sub-function.\n #-------------------------------------------------------------\n\n def printSetupParamsToConsoleAndFileFunction(p, auc_score, fid):\n ''' Print key results and parameters to console and to file.\n Inputs:\n p: dict. \n auc_score: float.\n fid: file ID.\n Outputs:\n print to console and add lines to a text file.\n '''\n numPosTestCases = p['numPosTestCases']\n numNegTestCases = p['numNegTestCases']\n\n print('\\n' + p['modelType'] + ' model for policy domain = ' + p['policyDomainsToKeep'] \\\n + ', startYear ' + str(p['startYearForTest']) + '. hiddenLayers = ' \\\n + str(p['hiddenLayers']))\n print('numPos = ' + str(numPosTestCases) + ', numNeg = ' + str(numNegTestCases) \\\n + ', total = ' + str(numPosTestCases + numNegTestCases))\n print('AUC = ' + str(np.round(auc_score, 2)) + ', maxBalancedAcc = ' \\\n + str(np.round(100*p['maxBalancedAccTrain'], 0)) + ' at thresh = ' \\\n + str(np.round(p['threshForMaxBalancedAcc'], 2)))\n fid.write('\\n' + p['modelType'] + ' model for policy domain = ' + p['policyDomainsToKeep'] \\\n + ', startYear ' + str(p['startYearForTest']) + '. hiddenLayers = ' \\\n + str(p['hiddenLayers']) + '\\n')\n fid.write('numPos = ' + str(numPosTestCases) + ', numNeg = ' + str(numNegTestCases) \\\n + ', total = ' + str(numPosTestCases + numNegTestCases) + '\\n')\n fid.write('AUC = ' + str(np.round(auc_score, 2)) + ', maxBalancedAcc = ' \\\n + str(np.round(100*p['maxBalancedAccTrain'], 0)) + ' at thresh = ' \\\n + str(np.round(p['threshForMaxBalancedAcc'], 2)) + '\\n')\n # End of printSetupParamsToConsoleAndFileFunction sub-function.\n #-------------------------------------------------------------\n\n p = params\n numPosTestCases = p['numPosTestCases']\n numNegTestCases = p['numNegTestCases']\n\n # raw materials for ROC curve:\n fpr, tpr, thresholds = metrics.roc_curve(testLabels, probScores[:, 1], pos_label=1)\n threshIndex = np.where(np.abs(thresholds - p['threshForMaxBalancedAcc']) \\\n == np.min(np.abs(thresholds - p['threshForMaxBalancedAcc'])))[0]\n auc_score = auc(fpr, tpr)\n \n # print stats to console: \n printSetupParamsToConsoleAndFileFunction(p, auc_score, fid)\n\n if p['showAccuracyPlotsFlag']:\n # ROC curve:\n rocTitleStr = 'ROC, ' + p['policyDomainsToKeep'] + ': ' + str(numPosTestCases) + ' Pos, ' \\\n + str(numNegTestCases) + ' neg'\n balAccTitleStr = 'balanced accuracy.' + p['modelType'] + ', startYear ' \\\n + str(p['startYearForTest'])\n makeRocAndAccuracyPlotsSubFunction(fpr, tpr, auc_score, threshIndex, rocTitleStr, sens,\n spec, balancedAcc, balAccTitleStr)\n\n# End of plotResultsFunction.\n#----------------------------------------------------------------------\n\ndef plotFeatureStatsFunction(featureScoresAllRuns, featureOutcomeCorrelationsAllRuns,\n numAtBatsAllRuns, featureNames, titleStr, numFeaturesToPlot,\n numTestCases, fid):\n\n '''\n Plot top N features' importances (based on score mean, not mu/sigma) and also whether features\n have positive or negative correlations with test set outcomes.\n NOTE: feature correlation only makes sense for interest groups.\n Let r = number of runs, m = number of features.\n Inputs:\n featureScoresAllRuns:m x r np.array of floats in [0, 1]. each row are the importances, over\n each run, of a single feature.\n featureOutcomeCorrelationsAllRuns:m x r np.array of floats.\n numAtBatsAllRuns: m x r np.array of ints.\n featureNames: m x 1 np.array of strings.\n titleStr: str. The policy domain name.\n numFeaturesToPlot: int.\n numTestCases: float.\n fid: file id, from open().\n Outputs:\n matplotlib figure: plot of feature importances.\n print to console and file: feature correlations.\n '''\n\n def printResultsToConsoleAndFileSubFunction(resultTypeStr, titleStr, numFeaturesToPlot, means,\n stds, names, fid):\n ''' Print to console and to file.\n Inputs:\n resultTypeStr: str.\n titleStr: str.\n numFeaturesToPlot: int.\n means: vector of floats.\n stds: vector of floats.\n names: vector of strings.\n fid: file identifier.\n Outputs:\n Print str to console.\n Print str to file.\n '''\n\n print('\\n ' + resultTypeStr + ' for ' + titleStr + ' (mean+std): ')\n fid.write('\\n ' + resultTypeStr + ' for ' + titleStr + ' (mean+std): ')\n for i in range(numFeaturesToPlot):\n print(str(np.round(means[i], 3)) + ' +/-' \\\n + str(np.round(stds[i], 3)) + ' : ' + names[i])\n fid.write('\\n' + str(np.round(means[i], 3)) + ' +/-' \\\n + str(np.round(stds[i], 3)) + ' : ' + names[i])\n # End of printResultsToConsoleAndFileSubFunction\n #-------------------------------------------------\n\n featureScoreMeans = np.mean(featureScoresAllRuns, axis=1)\n featureScoreStds = np.std(featureScoresAllRuns, axis=1)\n featureScoreFoms = np.divide(featureScoreMeans, featureScoreStds) # Not currently used. Can be\n # used to rank features.\n # Knock out NaNs:\n featureScoreFoms[np.where(np.isnan(featureScoreFoms))[0]] = 0\n\n atBatMeans = np.mean(numAtBatsAllRuns, axis=1)\n atBatStds = np.std(numAtBatsAllRuns, axis=1)\n\n # Feature correlations: we want to ignore featureCorrelations that are Nan, because these show\n # there were no at-bats in that test set:\n featureCorrelationsMeans = np.zeros([len(featureNames), 1])\n featureCorrelationsStds = np.zeros([len(featureNames), 1])\n for i in range(len(featureNames)):\n temp = featureOutcomeCorrelationsAllRuns[i, :]\n indsToKeep = temp[np.where(np.logical_not(np.isnan(temp)))[0]]\n featureCorrelationsMeans[i] = np.mean(indsToKeep)\n featureCorrelationsStds[i] = np.std(indsToKeep)\n\n # Back to feature scores:\n sortedIndices = np.flip(np.argsort(featureScoreMeans))[0:numFeaturesToPlot] # Flip to make\n # descending\n sortedNames = np.array([featureNames[i] for i in sortedIndices])\n sortedMeans = np.array([featureScoreMeans[i] for i in sortedIndices])\n sortedStds = np.array([featureScoreStds[i] for i in sortedIndices])\n sortedCorrelationsMean = np.array([featureCorrelationsMeans[i] for i in sortedIndices])\n sortedCorrelationsStd = np.array([featureCorrelationsStds[i] for i in sortedIndices])\n sortedAtBatMeans = np.array([atBatMeans[i] for i in sortedIndices])\n sortedAtBatStds = np.array([atBatStds[i] for i in sortedIndices])\n sortedFoms = np.array([featureScoreFoms[i] for i in sortedIndices])\n\n _, ax = plt.subplots(figsize=[8, 4])\n ax.barh(range(numFeaturesToPlot), sortedMeans, xerr=sortedStds, align='center')\n ax.set_yticks(range(len(sortedMeans)))\n ax.set_yticklabels(sortedNames)\n ax.invert_yaxis() # Labels read top-to-bottom\n ax.set_xlabel('Importance score')\n ax.set_title(titleStr)\n plt.show()\n\n # Scatterplot feature score vs number of at-bats for each IG:\n plt.figure()\n plt.plot(atBatMeans[:len(featureScoreMeans)], featureScoreMeans, 'b.', markersize=12)\n plt.xlabel('# at-bats')\n plt.ylabel('feature score')\n plt.title(titleStr)\n plt.xlim([0, numTestCases])\n plt.ylim([0, np.max(featureScoreMeans*1.1)])\n plt.grid(b=True)\n plt.show()\n\n # Print four things to console and file:\n resultTypeStr = 'Feature importance'\n printResultsToConsoleAndFileSubFunction(resultTypeStr, titleStr, numFeaturesToPlot,\n sortedMeans, sortedStds, sortedNames, fid)\n resultTypeStr = 'Figure of merit'\n printResultsToConsoleAndFileSubFunction(resultTypeStr, titleStr, numFeaturesToPlot, sortedFoms,\n np.zeros(sortedFoms.shape), sortedNames, fid)\n resultTypeStr = 'Feature outcome correlations'\n printResultsToConsoleAndFileSubFunction(resultTypeStr, titleStr, numFeaturesToPlot,\n sortedCorrelationsMean, sortedCorrelationsStd,\n sortedNames, fid)\n resultTypeStr = '# at-bats'\n printResultsToConsoleAndFileSubFunction(resultTypeStr, titleStr, numFeaturesToPlot,\n sortedAtBatMeans, sortedAtBatStds, sortedNames, fid)\n\n# End of plotFeatureStatsFunction.\n#----------------------------------------------------------------------\n\ndef generateSetupStringFunction(setupParams):\n '''\n Generate a string that contains setup information (model, features). Strings are constructed\n using booleans from setupParams, so may be empty.\n\n Inputs:\n setupParams = dict\n Outputs:\n setupStr = string\n '''\n sp = setupParams\n\n gunStr = ', ignore gun cases' * sp['ignoreGunCasesFlag']\n forestStr = 'Random forest' + '.xgBoost' * sp['xgBoostFlag']\n policyDomainStr = ', policyDomains' * sp['usePolicyDomainsFlag']\n\n voterPrefsStr = ', 90%ile' * sp['use90PercentFlag'] + ', 50%ile' * sp['use50PercentFlag'] \\\n + ', 10%ile' * sp['use10PercentFlag'] + ', 90-10%ile' * sp['use90Minus10PercentFlag']\n\n interestGroupStr = 'IGNA' * sp['useIGNAFlag']\n if sp['useIndividualInterestGroupsFlag']:\n interestGroupStr = interestGroupStr + ', ' + 'all IGs' * sp['useAllInterestGroupsFlag'] \\\n + str(sp['interestGroupsToKeepGroupedByDomain']) * (not sp['useAllInterestGroupsFlag'])\n\n balancedModelStr = 'UN' * (not sp['useBalancedModelFlag']) + 'balanced model'\n\n if sp['useIndividualInterestGroupsFlag']:\n igSubset = 'all IGs' * sp['useAllInterestGroupsFlag'] \\\n + 'RF-chosen IGs' * sp['useRfChosenInterestGroupsFlag'] \\\n + 'logistic-chosen IGs' * (not sp['useRfChosenInterestGroupsFlag']) \\\n + 'short ' * sp['useShortInterestGroupListFlag'] \\\n + 'medium ' * (not sp['useShortInterestGroupListFlag'])\n else:\n igSubset = 'No individual IGs'\n\n setupStr = 'numRuns ' + str(sp['numRuns']) + '. startYearForTest = ' \\\n + str(sp['startYearForTest']) + ', trainFraction ' + str(sp['trainFraction']) + gunStr + '. ' \\\n + forestStr + ', ' + balancedModelStr + ', ' + igSubset + ', maxDepth ' + str(sp['maxDepth']) \\\n + '. Features = ' + policyDomainStr + voterPrefsStr + interestGroupStr\n\n return setupStr\n\n# End of generateSetupStrFunction.\n#-------------------------------------------------------------------------------\n\ndef generateTrainTestSplitFunction(data, setupParams):\n '''\n Given a dataframe and params, make a train test split.\n\n Inputs:\n data: pandas dataframe. This should be the full (unparsed) dataframe = dataFull.\n setupParams: dict of params\n\n Outputs:\n dataTrainBoolean: boolean vector\n dataTestBoolean: boolean vector\n '''\n\n startYear = setupParams['startYearForTest']\n\n # drop gun dolicy cases and/or MISC policy cases if wished:\n if setupParams['oneModelPerPolicyDomainFlag']:\n inPolicyTrainBoolean = np.logical_and(data.YEAR < startYear,\n data[setupParams['policyDomainsToKeep']] >= 1)\n inPolicyTestBoolean = np.logical_and(data.YEAR >= startYear,\n data[setupParams['policyDomainsToKeep']] >= 1)\n\n else: # Case: Single model for combined policy domains:\n # When combining all (or most) policy domains together, we have several cases depending on\n # which domains are being rejected:\n if setupParams['ignoreMiscCasesFlag']:\n if setupParams['ignoreGunCasesFlag']:\n inPolicyTrainBoolean = np.logical_and.reduce((data.YEAR < startYear,\n data['MISC'] == 0,\n data['GNYN'] == 0))\n inPolicyTestBoolean = np.logical_and.reduce((data.YEAR >= startYear,\n data['MISC'] == 0, data['GNYN'] == 0))\n # Above (and some places below) can use np.all((a,b,c), axis=0) instead of .reduce.\n else: # Keep guns\n inPolicyTrainBoolean = np.logical_and.reduce((data.YEAR < startYear,\n data['MISC'] == 0))\n inPolicyTestBoolean = np.logical_and.reduce((data.YEAR >= startYear,\n data['MISC'] == 0))\n\n else: # We are keeping MISC cases:\n if setupParams['ignoreGunCasesFlag']:\n inPolicyTrainBoolean = np.logical_and.reduce((data.YEAR < startYear,\n data['GNYN'] == 0))\n inPolicyTestBoolean = np.logical_and.reduce((data.YEAR >= startYear,\n data['GNYN'] == 0))\n else: # Keep guns\n inPolicyTrainBoolean = (data.YEAR < startYear).values\n inPolicyTestBoolean = (data.YEAR >= startYear).values\n\n # 'inPolicyTrainID' currently contains all samples before 'startYear'. If startYear > 2003,\n # then inPolicyTestID is empty. In this case we want to define dataTrainID and dataTestID\n # so that they are both randomly drawn from inPolicyTrainID.\n if startYear > 2003:\n dataTrainSubset, dataTestSubset, dummy1, dummy2 = \\\n train_test_split(range(len(inPolicyTrainBoolean)), np.ones(inPolicyTrainBoolean.shape),\n train_size=setupParams['trainFraction'])\n # Replace the existing booleans dataTrainBoolean and dataTestBoolean:\n dataTestBoolean = np.zeros(inPolicyTrainBoolean.shape)\n dataTestBoolean[dataTestSubset] = 1\n dataTestBoolean = dataTestBoolean.astype(bool)\n dataTestBoolean = np.logical_and(dataTestBoolean, inPolicyTrainBoolean) # the AND combines\n # the 1's which show training set and the 1's which show correct policy domain.\n dataTrainBoolean = np.zeros(inPolicyTrainBoolean.shape)\n dataTrainBoolean[dataTrainSubset] = 1\n dataTrainBoolean = dataTrainBoolean.astype(bool)\n dataTrainBoolean = np.logical_and(dataTrainBoolean, inPolicyTrainBoolean)\n else: # Case: no fussing is needed\n dataTrainBoolean = inPolicyTrainBoolean\n dataTestBoolean = inPolicyTestBoolean\n\n # If restricting to high 90-10 disagreement, further restrict dataTrainBoolean and/or\n # dataTestBoolean:\n disagreement = data['pred90 - pred10'].values\n highDisagreementBoolean = np.abs(disagreement) > setupParams['disagreementThreshold']\n if setupParams['restrictTrainToHighDisagreementFlag']:\n dataTrainBoolean = np.logical_and(dataTrainBoolean, highDisagreementBoolean)\n if setupParams['restrictTestToHighDisagreementFlag']:\n dataTestBoolean = np.logical_and(dataTestBoolean, highDisagreementBoolean)\n\n return dataTrainBoolean, dataTestBoolean\n\n# End of generateTrainTestSplitFunction.\n#-----------------------------------------------------------------------------------------------\n\ndef parseDataframeFunction(dataFull, setupParams):\n '''\n Starts with the full dataframe. Removes columns and selects the rows (cases) to keep.\n\n Inputs:\n dataFull: pandas dataframe to be modified\n setupParams: dict containing the necessary flags\n\n Outputs:\n data: pandas dataframe\n '''\n sp = setupParams\n\n data = dataFull # We'll edit and return 'data'.\n\n # Select proper rows and drop switcher\n data = data.drop(['switcher'], axis=1)\n\n # Filter features by dropping columns:\n # 1. Individual interest groups and IntGrpNetAlign:\n interestGroupsToDropColumnIndices = sp['allInterestGroupIndices'] \\\n [np.logical_not(np.isin(sp['allInterestGroupIndices'], sp['combinedInterestGroupsToKeep']))]\n if not sp['useIndividualInterestGroupsFlag']:\n interestGroupsToDropColumnIndices = np.arange(12, 55)\n data = data.drop(data.columns[interestGroupsToDropColumnIndices], axis=1) # Individual interest\n # groups.\n if not sp['useIGNAFlag']:\n data = data.drop(['IntGrpNetAlign'], axis=1)\n\n # 2. Policy domains:\n data = data.drop(['XL_AREA'], axis=1) # Ignore this column for these experiments. But note that\n # the best accuracies in the paper were attained using XL_AREA rather than Policy Domain as a\n # feature.\n if not sp['usePolicyDomainsFlag']:\n data = data.drop(sp['policyDomainList'], axis=1)\n\n if sp['ignoreMiscCasesFlag']:\n data = data.drop(['MISC'], axis=1)\n\n # 3. Public opinions:\n if not sp['use90PercentFlag']:\n data = data.drop(['pred90_sw'], axis=1)\n if not sp['use50PercentFlag']:\n data = data.drop(['pred50_sw'], axis=1)\n if not sp['use10PercentFlag']:\n data = data.drop(['pred10_sw'], axis=1)\n if not sp['use90Minus10PercentFlag']:\n data = data.drop(['pred90 - pred10'], axis=1)\n\n # 4. Get rid of some non-feature columns:\n data = data.drop(['YEAR', 'OutcomeYear'], axis=1)\n\n return data\n#-------------------------------------------------------------------\n\ndef calculateAccuracyStatsOnTestSetFunction(trainProbScores, testProbScores, trainLabels,\n testLabels, setupParams, modelType, fid):\n '''\n Given train and test prob scores, plus params, calculate various accuracy values.\n\n Inputs:\n trainProbScores: np vector\n testProbScoresTest: np vector\n trainLabels = np vector\n testLabels = np vector\n setupParams: dict\n modelType: string (eg 'logistic')\n fid: file id, from open()\n\n Outputs:\n accuracyStats: dict\n Also generated, if flags indicate: balanced acc and auc plots.\n '''\n def chooseBestThresholdsSubFunction(balancedAcc, rawAccTrain, trainLabels, setupParams):\n ''' Find best thresholds for use on the test set, according to training set results.\n There are two methods for choosing test set thresholds.\n Inputs:\n balancedAcc: vector of floats.\n rawAccTrain: vector of floats.\n trainLabels: vector of booleans.\n setupParams: dict.\n Outputs:\n threshForMaxBalancedAcc: float scalar.\n threshForMaxRawAcc: float scalar.\n '''\n x = np.linspace(0, 1, len(balancedAcc))\n if setupParams['useSimpleMaxForThreshFlag']:\n # Method 1 (optimistic, assumes test samples will score as high as train samples.\n # We assume a positive outcome is being optimized by the RF). Take the threshold\n # that gives highest training set accuracy:\n # 1. For balanced accuracy:\n maxBalancedAcc = np.max(balancedAcc)\n indexForMax = np.where(balancedAcc == maxBalancedAcc)[0]\n if len(indexForMax) > 1: # Since 'indexForMax' could be a vector.\n middleInd = int(np.floor(len(indexForMax) / 2)) # Choose the middle index\n indexForMax = indexForMax[middleInd]\n # print('caution: RF/xgBoost returned vector indexForMax: ' + str(indexForMax)\n # + ' (domain = ' + setupParams['policyDomainsToKeep'] + ')')\n threshForMaxBalancedAcc = x[indexForMax]\n\n # 2. For raw accuracy:\n maxRawAcc = np.max(rawAccTrain)\n indexForMax = np.where(rawAccTrain == maxRawAcc)[0]\n if len(indexForMax) > 1:\n middleInd = int(np.floor(len(indexForMax) / 2)) # Choose the middle index\n indexForMax = indexForMax[middleInd]\n # print('caution: RF/xgBoost returned vector indexForMax: ' + str(indexForMax)\n # + ' (domain = ' + setupParams['policyDomainsToKeep'] + ')')\n threshForMaxRawAcc = x[indexForMax]\n\n else:\n # Method 2 (considers the top candidates, and adjusts threshold up or down according to\n # pos:neg balance). We consider all thresholds within 'wobbleFactor' of the top score.\n # These make a plateau. We choose along the plateau according to pos:neg balance.\n uncertaintyValue = setupParams['uncertaintyValue']\n pos = np.sum(trainLabels == 1) # 'pos' is the numPosTrainCases\n neg = np.sum(trainLabels == 0) # 'neg' is the numNegTrainCases\n\n # Threshold for best balanced accuracy:\n maxBalancedAcc = np.max(balancedAcc)\n indsForMax = np.where(balancedAcc >= maxBalancedAcc - uncertaintyValue)[0] # Take the\n # first of these indices.\n left = min(indsForMax)\n right = max(indsForMax)\n indexForMax = int(np.round((pos*left + neg*right) / (pos + neg)))\n threshForMaxBalancedAcc = x[indexForMax]\n\n # Threshold for max raw accuracy:\n maxRawAcc = np.max(rawAccTrain)\n indsForMax = np.where(rawAccTrain >= maxRawAcc - uncertaintyValue)[0] # Take the first\n # of these indices.\n left = min(indsForMax)\n right = max(indsForMax)\n indexForMax = int(np.round((pos*left + neg*right) / (pos + neg)))\n threshForMaxRawAcc = x[indexForMax]\n\n return np.array([threshForMaxBalancedAcc]), np.array([threshForMaxRawAcc])\n # End of chooseBestThresholdsSubFunction\n # ------------------------------------------------------\n\n def calculateSensSpecAtThresholdSubFunction(scores, labels, thresholds):\n ''' Calculate sens, spec, for either a vector of thresholds or a single value.\n Inputs:\n scores: np array vector of floats.\n labels: np array vector of 0s and 1s\n threshold: np array vector of floats.\n Outputs:\n sens: np array vector of float in [0, 1], or maybe -100 as a flag.\n spec: np array vector of float in [0, 1].\n precision: np array vector of float in [0, 1].\n balancedAcc: np array vector of float in [0, 1].\n rawAcc: np array vector of float in [0, 1].\n '''\n precision = np.zeros(thresholds.shape)\n sens = np.zeros(thresholds.shape)\n spec = np.zeros(thresholds.shape)\n balancedAcc = np.zeros(thresholds.shape)\n rawAcc = np.zeros(thresholds.shape)\n for i in range(len(thresholds)):\n TP = np.sum(np.logical_and(scores[:, 1] >= thresholds[i], labels == 1))\n FN = np.sum(np.logical_and(scores[:, 1] < thresholds[i], labels == 1))\n FP = np.sum(np.logical_and(scores[:, 1] >= thresholds[i], labels == 0))\n TN = np.sum(np.logical_and(scores[:, 1] < thresholds[i], labels == 0))\n sens[i] = TP / (TP + FN)\n if TP + FN == 0:\n sens[i] = -100\n spec[i] = TN / (FP + TN)\n precision[i] = TP / (TP + FP)\n balancedAcc[i] = (sens[i] + spec[i]) / 2\n rawAcc[i] = (TP + TN) / len(labels)\n return sens, spec, precision, balancedAcc, rawAcc\n # End of calculateSensSpecAtThresholdSubFunction.\n # --------------------------------------------------------\n\n def plotRawAndBalancedAccuraciesPerRunSubFunction(modelTypeStr, trainRaw, testRaw, trainBal,\n testBal, threshForMaxRawAcc,\n threshForMaxBalancedAcc):\n ''' Plots train accuracy and test accuracy (raw and balanced) vs thresholds.\n Inputs:\n modelTypeStr: str.\n trainRaw: vector floats in [0,1].\n testRaw: vector floats in [0,1].\n trainBal: vector floats in [0,1].\n testBal: vector floats in [0,1].\n threshForMaxRawAcc: float.\n threshFormaxBalancedAcc: float.\n Outputs:\n matplotlib plot with 2 subplots.\n '''\n x = np.linspace(0, 1, 101)\n plt.figure(figsize=(8, 4))\n plt.subplot(1, 2, 1)\n plt.plot(x, trainRaw*100, 'b') # Training\n plt.plot(x, testRaw*100, 'r')\n plt.vlines(threshForMaxRawAcc, 0, 100, colors='k')\n plt.grid(b=True)\n plt.ylim(40, 100)\n plt.title(modelTypeStr + '. Raw accuracy.')\n\n plt.subplot(1, 2, 2)\n plt.plot(x, trainBal*100, 'b')\n plt.plot(x, testBal*100, 'r')\n plt.ylim(40, 100)\n plt.vlines(threshForMaxBalancedAcc, 0, 100, colors='k')\n plt.grid(b=True)\n plt.title('Balanced accuracy. b = train, r = test.')\n plt.show()\n # End of plotRawAndBalancedAccuraciesPerRunSubFunction\n #-------------------------------------------------------\n\n # Using train results, find best thresholds for use on test set:\n _, _, _, balancedAccTrain, rawAccTrain = \\\n calculateSensSpecAtThresholdSubFunction(trainProbScores, trainLabels, np.linspace(0, 1, 101))\n threshForMaxBalancedAcc, threshForMaxRawAcc = \\\n chooseBestThresholdsSubFunction(balancedAccTrain, rawAccTrain, trainLabels, setupParams)\n\n # Now apply these thresholds to the test set: \n sensTest, specTest, precisionTest, balancedAccTest, rawAccTest = \\\n calculateSensSpecAtThresholdSubFunction(testProbScores, testLabels, threshForMaxBalancedAcc) \n # Get vars for AUC here for saving (it gets calc'ed again inside the plotResultsFunction()):\n fpr, tpr, _ = metrics.roc_curve(testLabels, testProbScores[:, 1], pos_label=1)\n\n # Collect the Test Set accuracies. These are single values (found using 'threshForMax*').\n accuracyStats = {'rawAccTest':rawAccTest, 'balancedAccTest':balancedAccTest,\n 'aucScore':auc(fpr, tpr), 'sensTest':sensTest, 'specTest':specTest,\n 'precisionTest':precisionTest}\n\n #---------------------\n\n # If wished, make plots of raw and balanced accuracies, for train and test sets. CAUTION: THIS\n # MAKES LOTS OF PLOTS (numSetups x numRuns x 2).\n if setupParams['plotAccuraciesByThresholdsFlag']:\n # W need vectors of test accuracies:\n _, _, _, balancedAccTest, rawAccTest = \\\n calculateSensSpecAtThresholdSubFunction(testProbScores, testLabels, np.linspace(0, 1, 101))\n modelTypeStr = modelType + ', ' + setupParams['policyDomainsToKeep']\n plotRawAndBalancedAccuraciesPerRunSubFunction(modelTypeStr, rawAccTrain, rawAccTest,\n balancedAccTrain, balancedAccTest,\n threshForMaxRawAcc, threshForMaxBalancedAcc)\n\n # Plot ROC and bal acc-sens-spec, if flags indicate.\n # First make a dict to get params into plotting function:\n # We need a couple strings:\n futurePredictionStr = 'all years' * (setupParams['startYearForTest'] >= 2003) \\\n + ('post-' + str(setupParams['startYearForTest'])) * (setupParams['startYearForTest'] < 2003)\n hiddenLayerStr = setupParams['hiddenLayers'] * (modelType == 'neuralNet')\n # These are parameters associated with training. Results on test set are saved elsewhere.\n params = \\\n {'policyDomainsToKeep':setupParams['policyDomainsToKeep'], 'numPosTestCases':\n np.sum(testLabels == 1), 'numNegTestCases':np.sum(testLabels == 0), 'showAccuracyPlotsFlag':\n setupParams['showAccuracyPlotsFlag'], 'printToConsoleFlag':setupParams['printToConsoleFlag'],\n 'futurePredictionStr':futurePredictionStr, 'threshForMaxBalancedAcc':threshForMaxBalancedAcc[0],\n 'threshForMaxRawAcc':threshForMaxRawAcc[0], 'maxBalancedAccTrain':np.max(balancedAccTrain),\n 'maxRawAccTrain':np.max(rawAccTrain), 'modelType':modelType, 'hiddenLayers':hiddenLayerStr,\n 'startYearForTest':setupParams['startYearForTest']}\n\n # If we are going to make plots, we'll need as argin (to the plotResultsFunction) vectors of\n # sens and spec on the test set:\n if setupParams['showAccuracyPlotsFlag']:\n sensTest, specTest, _, balAccTest, rawAccTest = \\\n calculateSensSpecAtThresholdSubFunction(testProbScores, testLabels, np.linspace(0, 1, 101))\n plotResultsFunction(testProbScores, testLabels, balAccTest, sensTest,\n specTest, params, fid)\n\n return accuracyStats\n\n# calculateAccuracyStatsOnTestSetFunction.\n#---------------------------------------------------------------------------\n\ndef calculatePrintAndSaveModelStatsOverAllRunsFunction(accResultDict, acceptTestResultsMatrix,\n modelStr, setupParams, resultsDataFrame,\n fid):\n '''\n Given the results for many runs using a given setup + domain, calculate accuracy statistics\n over all runs. Then (a) print them to console, (b) write them to a textfile, (c) save them into\n the results dataframe.\n\n Inputs:\n accResultDict: dict with entries as laid out below\n acceptTestResultsMatrix: boolean np.array, numRuns x numToLoop\n rawAcc: numRuns x numModels np.array. NOTE: if the setup combines all domains into a single\n model, numModels = 1. Else numModels = 6. This implicit fact is used to decide how to\n save data.\n balAcc: ditto\n AUC: ditto\n balPrec: ditto (not currently used).\n balRecall: ditto (not currently used).\n balF1: ditto (not currently used).\n modelStr: string (short descriptor of model).\n setupParams: dict (contains model + feature details).\n resultsDataFrame: pandas dataframe, the results dataframe we with to add results to.\n fid: file id, from open().\n\n Outputs:\n resultsDataframe: pandas dataframe, with new rows added.\n '''\n\n def printAccuracySubFunction(mu, med, sigma, tag):\n '''\n Make a string containing results.\n Inputs:\n mu: np vector (maybe with len 1).\n med: ditto.\n std: ditto.\n tag: str.\n Output:\n resultStr: str.\n '''\n tempStr = ''\n medStr = ''\n for i in range(len(mu)):\n tempStr = tempStr + str(mu[i]) + '+' + str(sigma[i])\n medStr = medStr + str(med[i])\n if i < len(mu) -1:\n tempStr = tempStr + ', '\n medStr = medStr + ', '\n tempStr = tempStr + '.'\n medStr = medStr + '.'\n resultStr = tag + ' (mean+std) = ' + tempStr\n\n print(resultStr)\n fid.write('\\n' + resultStr)\n # End of printAccuracySubFunction\n # ------------------------------------------------\n\n def calculateAccuracyStatsSubFunction(acc, acceptTestResultsMatrix):\n ''' Calculate mu and std of various result types. This is done by column (in a loop)\n because sometimes a test set of a particular domain has 0 pos cases and must be ignored\n when calculating stats.\n Inputs:\n acc: np.array, numSetups x numRuns\n acceptTestResultsMatrix: np.array of booleans, numSetups x numRuns\n Outputs:\n means: vector of floats.\n medians: vector of floats.\n stds: vector of floats.\n '''\n numToLoop = acc.shape[1]\n means = np.zeros([1, numToLoop]).flatten()\n medians = np.zeros([1, numToLoop]).flatten()\n stds = np.zeros([1, numToLoop]).flatten()\n for i in range(numToLoop):\n a = acceptTestResultsMatrix[:, i] # 'a' = acceptColumn, ie the column of accepts and\n # rejects for this policy domain.\n means[i] = np.round(100*np.mean(acc[a, i]), 1) # one entry for each domain.\n medians[i] = np.round(100*np.median(acc[a, i]), 1)\n stds[i] = np.round(100*np.std(acc[a, i]), 1)\n return means, medians, stds\n\n # End of calculateAccuracyStatsSubFunction\n #------------------------------------------------\n\n # Construct and print each result string by looping over results vectors. Results for all models\n # (ie for each policy domain) get printed into one line, separated by commas:\n print('\\n' + modelStr + ' results (%): ')\n fid.write('\\n' + modelStr + ' results (%): ')\n # Raw:\n rawAccTestMeans, rawAccTestMedians, rawAccTestStds = \\\n calculateAccuracyStatsSubFunction(accResultDict['rawAcc'], acceptTestResultsMatrix)\n printAccuracySubFunction(rawAccTestMeans, rawAccTestMedians, rawAccTestStds, 'Raw acc')\n # Balanced:\n balAccTestMeans, balAccTestMedians, balAccTestStds = \\\n calculateAccuracyStatsSubFunction(accResultDict['balAcc'], acceptTestResultsMatrix)\n printAccuracySubFunction(balAccTestMeans, balAccTestMedians, balAccTestStds, 'Balanced acc')\n # AUC:\n aucTestMeans, aucTestMedians, aucTestStds = \\\n calculateAccuracyStatsSubFunction(accResultDict['AUC'], acceptTestResultsMatrix)\n printAccuracySubFunction(aucTestMeans, aucTestMedians, aucTestStds, 'AUC')\n # Skip dict keys ['prec'], ['recall'], ['f1'] since their stats are volatile.\n\n # Add rows to the results dataframe, either a single combined model or multiple models:\n sp = setupParams\n policyDomainList = sp['policyDomainList']\n rfMed = sp['useIndividualInterestGroupsFlag'] and sp['useRfChosenInterestGroupsFlag'] \\\n and not sp['useShortInterestGroupListFlag'] and not sp['useAllInterestGroupsFlag']\n rfShort = sp['useIndividualInterestGroupsFlag'] and sp['useRfChosenInterestGroupsFlag'] \\\n and sp['useShortInterestGroupListFlag'] and not sp['useAllInterestGroupsFlag']\n logMed = sp['useIndividualInterestGroupsFlag'] and not sp['useRfChosenInterestGroupsFlag'] \\\n and not sp['useShortInterestGroupListFlag'] and not sp['useAllInterestGroupsFlag']\n logShort = sp['useIndividualInterestGroupsFlag'] and not sp['useRfChosenInterestGroupsFlag'] \\\n and sp['useShortInterestGroupListFlag'] and not sp['useAllInterestGroupsFlag']\n for i in range(len(rawAccTestMeans)): # Either 1 (one model) or 5 (one per policy domain).\n if not sp['oneModelPerPolicyDomainFlag']:\n policyDomain = 'All'\n else:\n policyDomain = policyDomainList[i]\n newRow = \\\n pd.DataFrame({'modelType':[modelStr], 'balanced':[sp['useBalancedModelFlag']],\n 'policyDomain':[policyDomain], 'startYearForTest':[sp['startYearForTest']],\n 'use90':[sp['use90PercentFlag']], 'use50':[sp['use50PercentFlag']],\n 'use10':[sp['use10PercentFlag']],\n 'use90Minus10':[sp['use90Minus10PercentFlag']], 'useIGNA':[sp['useIGNAFlag']],\n 'useIndividualIGs': [sp['useIndividualInterestGroupsFlag']],\n 'useAllIGs':[sp['useAllInterestGroupsFlag']], 'useRfChosenMediumIGs':[rfMed],\n 'useRfChosenShortIGs':[rfShort], 'useLogChosenMediumIGs':[logMed],\n 'useLogChosenShortIGs': [logShort],\n 'usePolicyDomains':[sp['usePolicyDomainsFlag']],\n 'useOnly90Minus10Disagreements':[sp['useOnly90Minus10Disagreements']],\n 'rawAccTestMeans':[rawAccTestMeans[i]], 'rawAccTestMedians':\n [rawAccTestMedians[i]], 'rawAccTestStds':[rawAccTestStds[i]],\n 'balAccTestMeans':[balAccTestMeans[i]], 'balAccTestMedians':\n [balAccTestMedians[i]], 'balAccTestStds':[balAccTestStds[i]],\n 'aucTestMeans':[aucTestMeans[i]], 'aucTestMedians':[aucTestMedians[i]],\n 'aucTestStds':[aucTestStds[i]], 'numRuns':[sp['numRuns']],\n 'trainFraction':[sp['trainFraction']], 'disagreementThreshold':\n [sp['disagreementThreshold']], 'maxDepth':[sp['maxDepth']],\n 'hiddenLayers':[sp['hiddenLayers']],\n 'IGSubsetUsed':[sp['combinedInterestGroupsToKeep']]})\n resultsDataFrame = resultsDataFrame.append(newRow, ignore_index=True, sort=False)\n\n return resultsDataFrame\n\n#-----------------------------------------------------------------------------\n\ndef calculateDifferenceInAccDueToRfChosenVsLogChosenFunction(rawArray, balArray, aucArray,\n modelType,\n oneModelPerPolicyDomainFlag,\n policyDomainList):\n ''' Calculates and prints (via a subfunction) the delta in accuracy from using RF-chosen\n features vs logistic-chosen features.\n Inputs:\n rawArray: numRuns x 4 array of raw accuracies. Each row is a train/test split (run). The\n columns MUST have the following setup order: 0 = rfShort, 1 = rfMedium, 2 = logShort,\n 3 = logMedium').\n balArray: as above, but balanced accuracies.\n aucArray: as above, but AUCs\n Outputs:\n Prints mean (median) and std dev of RF-chosen minus logistic-chosen.\n '''\n\n def printDiffsInAccSubFunction(this, mediumOrShort, rawOrBal):\n\n mu = np.mean(this)\n sigma = np.std(this)\n med = np.median(this)\n mu = np.round(100*mu, 1)\n sigma = np.round(100*sigma, 1)\n med = np.round(100*med, 1)\n print(rawOrBal + ' ' + mediumOrShort + ': ' + str(mu) + '+' + str(sigma))\n\n # ----------------------------------------------------------\n\n # Print reminder warning:\n print('\\nBelow are differences in accuracy RFChosen - logisticChosen. \\n Format is: ' \\\n + 'mean+std (median) \\n CAUTION !!! These results require the following setup order ' \\\n + '(four setups total): 0 = rfShort, 1 = rfMedium, 2 = logShort, 3 = logMedium.\\n')\n\n print('Using ' + modelType + ':')\n # Get the right policy domain list:\n if not oneModelPerPolicyDomainFlag:\n domainList = ['All policy domains combined']\n else:\n domainList = policyDomainList\n\n for i in range(len(domainList)):\n # CAUTION !!! The second indices in each of these assignments and hard-coded and depend\n # absolutely on the order of the setups, viz 0 = rfShort, 1 = rfMedium, 2 = logShort,\n # 3 = logMedium.\n diffRawShort = rawArray[:, 0, i] - rawArray[:, 2, i]\n diffRawMedium = rawArray[:, 1, i] - rawArray[:, 3, i]\n diffBalShort = balArray[:, 0, i] - balArray[:, 2, i]\n diffBalMedium = balArray[:, 1, i] - balArray[:, 3, i]\n diffAucShort = aucArray[:, 0, i] - aucArray[:, 2, i]\n diffAucMedium = aucArray[:, 1, i] - aucArray[:, 3, i]\n\n domain = domainList[i]\n print('\\n' + domain + ':')\n\n # Short IG lists:\n mediumOrShort = 'short'\n print('\\n' + mediumOrShort + ': ')\n printDiffsInAccSubFunction(diffRawShort, mediumOrShort, 'Raw')\n printDiffsInAccSubFunction(diffBalShort, mediumOrShort, 'Balanced')\n printDiffsInAccSubFunction(diffAucShort, mediumOrShort, 'Auc')\n\n # Medium IG lists:\n mediumOrShort = 'medium'\n print('\\n' + mediumOrShort + ': ')\n printDiffsInAccSubFunction(diffRawMedium, mediumOrShort, 'Raw')\n printDiffsInAccSubFunction(diffBalMedium, mediumOrShort, 'Balanced')\n printDiffsInAccSubFunction(diffAucMedium, mediumOrShort, 'Auc')\n\n#--------------------------------------------------------------------------\n\n\"\"\" END OF FUNCTION DEFS\"\"\"\n\n'''\nMIT license:\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and\nassociated documentation files (the \"Software\"), to deal in the Software without restriction,\nincluding without limitation the rights to use, copy, modify, merge, publish, distribute,\nsublicense, and/or sell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all copies or\nsubstantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n'''","sub_path":"support_functions.py","file_name":"support_functions.py","file_ext":"py","file_size_in_byte":44083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"51811418","text":"import random\nfrom random import randint\n\nk = int(input('Введите число - количество элементов списка: '))\nd = int(input('Введите максимальное число k диапозона чисел (1, k): '))\n\ndef forming_list(n, max):\n s = []\n while n != 0:\n t = randint(1, max)\n if t not in s:\n s.append(t)\n n -= 1\n else:\n n = n\n return s\n\ndef sort(list_init):\n list_sort = sorted(list_init)\n return list_sort\n\ndef get_rangers(list_sorted):\n serie = []\n list_fin = []\n for i in range(len(list_sorted)-1): \n if list_sorted[i] + 1 == list_sorted[i+1]: \n serie.append(list_sorted[i])\n serie.append(list_sorted[i+1])\n else:\n if len(serie) > 0:\n list_fin.append(f'{serie[0]}-{serie[-1]}')\n serie = []\n else:\n list_fin.append(f'{list_sorted[i]}')\n if len(serie) > 1:\n list_fin.append(f'{serie[0]}-{serie[-1]}')\n elif len(serie) == 1:\n list_fin.append(f'{serie[0]}')\n else:\n list_fin.append(f\"{list_sorted[-1]}\")\n return list_fin\n\nlist0 = forming_list(k, d)\nprint(f'Список входной: {list0}') \n\nlist1 = sort(list0) \nprint(f'Сортированный список: {list1}')\n\nlist2 = get_rangers(list1)\nprint(f'Список из строк {list2}')\n\nfinal = ', '.join(list2)\nprint(f'Строка серий {final}')","sub_path":"Tasks/Ramanenka_Tasks/HT4/HomeTask4_v2.py","file_name":"HomeTask4_v2.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"115255931","text":"from rest_framework.test import APIClient\nfrom django.urls import reverse\nimport pytest\nfrom unittest import mock\nfrom unittest.mock import MagicMock\n\n\nclass TestView:\n\n @pytest.fixture\n def client(self):\n return APIClient()\n\n @pytest.fixture\n def data(self):\n return {'number': '0710802-55.2018.8.02.0001'}\n\n @pytest.fixture\n def response_data(self):\n return [\n {\n 'title': 'Consulta de Processos de 1º Grau',\n 'category': 'Procedimento Ordinário',\n 'area': 'Cível',\n 'subject': 'Dano Material',\n 'date': '02/05/2018 às 19:01 - Sorteio',\n 'judge': 'Henrique Gomes de Barros Teixeira',\n 'amount': 'R$ 281.178,42',\n 'parts': 'Autor:',\n 'moves': '12/07/2019',\n 'not_found': None\n },\n {\n 'title': 'Consulta de Processos de 2º Grau',\n 'category': None,\n 'area': None,\n 'subject': None,\n 'date': None,\n 'judge': None,\n 'amount': None,\n 'parts': None,\n 'moves': None,\n 'not_found': 'Não existem informações disponíveis para os parâmetros informados.' # noqa\n }\n ]\n\n @pytest.fixture\n def task_id(self):\n return '10488c6b-c15b-488b-b494-4fb19a0ba436'\n\n @pytest.fixture\n def mock_enqueue(self):\n with mock.patch('tribunal.views.django_rq.enqueue') as mock_enqueue:\n yield mock_enqueue\n\n @pytest.fixture\n def mock_get_data_by_task_id(self):\n with mock.patch(\n 'tribunal.views.get_data_by_task_id'\n ) as mock_get_data_by_task_id:\n yield mock_get_data_by_task_id\n\n def test_should_create_task_to_get_crawler_on_tj(\n self,\n client,\n data,\n mock_enqueue,\n task_id\n ):\n expected = task_id\n mock_enqueue.return_value = MagicMock(\n id=expected\n )\n response = client.post(reverse('tribunal-create'), data=data)\n assert response.status_code == 201\n response.json()['task_id'] == expected\n\n def test_should_get_data_with_task_id(\n self,\n client,\n task_id,\n response_data,\n mock_get_data_by_task_id\n ):\n mock_get_data_by_task_id.return_value = MagicMock(\n result=response_data,\n get_status=lambda: 'finished'\n )\n response = client.get(f'/tribunal/{task_id}')\n assert response.status_code == 200\n assert response.json() == response_data\n","sub_path":"tribunal/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"559876847","text":"from random import shuffle as rand_shuffle\nfrom itertools import product\nimport numpy as np\n\nfrom card import Card\nfrom utils import SCORE_KEY\n\n\nclass CardGroup(object):\n \"\"\"generic parent class for a set of cards\"\"\"\n\n def __init__(self, cards=None, decks_in_play=1):\n self.cards = cards\n self.decks_in_play = decks_in_play\n\n def __str__(self):\n return \", \".join([str(c) for c in self.cards])\n\n def shuffle(self):\n \"\"\"shuffle the hand's cards inplace\"\"\"\n rand_shuffle(self.cards)\n\n def sort(self, first='suit'):\n if first == 'suit':\n self.cards = sorted([c.idx for c in self.cards])\n elif first == 'rank':\n self.cards = sorted(self.cards, key=lambda c: c.irank)\n return True\n\n\nclass Deck(CardGroup):\n \"\"\"docstring for Deck\"\"\"\n\n def __init__(self, cards=None, n_decks=1, shuffle=True):\n super(Deck, self).__init__()\n self.n_decks = n_decks\n\n if cards is None:\n all_cards = [Card(s, r) for s, r in product(range(4), range(13))]\n self.cards = all_cards * self.n_decks\n\n if shuffle:\n self.shuffle()\n\n def deal(self, n_cards=1, as_hand=True):\n \"\"\"deal `n_cards` cards from the deck as a new Hand\"\"\"\n outcards = [self.cards.pop() for x in range(n_cards)]\n if as_hand:\n return OnsHand(outcards, decks_in_play=self.n_decks)\n return outcards\n\n\nclass CardHand(CardGroup):\n \"\"\"docstring for CardHand\"\"\"\n\n def __init__(self, cards=None, decks_in_play=1):\n super(CardHand, self).__init__(cards, decks_in_play)\n\n self.init_viewpoint()\n self.see(self.cards)\n\n def draw(self, deck):\n \"\"\"transfer card from `deck` to current hand\"\"\"\n newcard = deck.deal(1, False)\n self.cards += newcard\n self.see(newcard)\n self.sum_total_score()\n\n def init_viewpoint(self):\n \"\"\"create an initial count of the cards in play\"\"\"\n counts = np.zeros((13, 4), dtype=np.int) + self.decks_in_play\n self.viewpoint = counts\n\n def see(self, cards):\n \"\"\"update viewpoint given `card`'s retirement in the game\"\"\"\n for c in cards:\n self.viewpoint[c.irank, c.isuit] -= 1\n self.calc_expected_pointreduction()\n\n def unsee(self, cards):\n \"\"\"update viewpoint given `card`'s retirement in the game\"\"\"\n for c in cards:\n self.viewpoint[c.irank, c.isuit] += 1\n self.calc_expected_pointreduction()\n\n\nclass OnsHand(CardHand):\n \"\"\"a hand (or deck) of cards\"\"\"\n\n def __init__(self, cards, decks_in_play):\n super(OnsHand, self).__init__(cards, decks_in_play)\n self.sum_total_score()\n self.sort('rank')\n\n def __repr__(self):\n return \"\".format(len(self.cards))\n\n def sum_total_score(self):\n \"\"\"calculate this hand's current score\"\"\"\n self.score = reduce(lambda x, y: x + y.score, self.cards, 0)\n\n def calc_proba(self, isuit=None, irank=None):\n \"\"\"calculate the probability of drawing a specific card or type of\n card given the hand's viewpoint\n \"\"\"\n denom = self.viewpoint.sum()\n\n if isuit in [1, 2] and irank == 12:\n numer = 0 # ignore if wild, adding later anyway\n elif irank is not None and isuit is not None:\n numer = self.viewpoint[isuit, irank]\n elif irank is not None:\n numer = self.viewpoint[irank, :].sum()\n elif isuit is not None:\n numer = self.viewpoint[:, isuit].sum()\n\n # add number of remaining wilds to numerator\n numer += self.viewpoint[12, 1:3].sum()\n return(float(numer) / denom)\n\n def calc_expected_pointreduction(self, target='sets', calc_with=None):\n \"\"\"identify potential groupings of cards and the point reductions\n their completion would create\n TODO:\n - just sets for now, needs to look at runs and combos\n - Wilds!\n \"\"\"\n cardlist = self.cards\n if calc_with is not None:\n cardlist.append(calc_with)\n\n ranks = [c.irank for c in cardlist]\n # n_wilds = sum([c.is_wild for c in cardlist])\n final = 0\n\n # CONSIDER WILDCARDS\n for irank in set(ranks):\n n_in_hand = sum([r == irank for r in ranks])\n n_needed = 3 - (n_in_hand % 3)\n point_reduction = n_in_hand * SCORE_KEY[irank]\n prob_draw = self.calc_proba(irank=irank) ** n_needed\n final += point_reduction * prob_draw\n\n return final\n\n\nif __name__ == '__main__':\n d = Deck(n_decks=3)\n h = d.deal(11)\n print(h.calc_expected_pointreduction())\n","sub_path":"pyOnze/hand.py","file_name":"hand.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"38320468","text":"import re\r\nimport time\r\nimport logging\r\nfrom datetime import datetime\r\nfrom datetime import timedelta\r\nfrom functools import partial\r\nfrom collections import namedtuple\r\n\r\nimport numpy as np\r\nfrom miros import Event\r\nfrom numpy import arange\r\nfrom miros import signals\r\nfrom miros import Factory\r\nfrom miros import return_status\r\nimport matplotlib.pyplot as plt\r\nfrom miros import ThreadSafeAttributes\r\nfrom scipy.interpolate import interp1d\r\nimport numpy.polynomial.polynomial as poly\r\n\r\nAmps = namedtuple('Amps', ['amps'])\r\nVolts = namedtuple('Volts', ['volts'])\r\nAmpsHours = namedtuple('AmpHours', ['amp_hours'])\r\nAmpsAndTime = namedtuple('AmpsAndTime', ['amps', 'time'])\r\nVoltsAndTime = namedtuple('VoltsAndTime', ['volts', 'time'])\r\n\r\nclass InstrumentedFactory(Factory):\r\n def __init__(self, name, log_file=None, live_trace=None, live_spy=None):\r\n super().__init__(name)\r\n\r\n self.live_trace = False if live_trace == None else live_trace\r\n self.live_spy = False if live_spy == None else live_spy\r\n self.log_file = 'single_unit_three_charger.log' if log_file == None else log_file\r\n\r\n with open(self.log_file, \"w\") as fp:\r\n fp.write(\"\")\r\n\r\n logging.basicConfig(\r\n format='%(asctime)s %(levelname)s:%(message)s',\r\n filename=self.log_file,\r\n level=logging.DEBUG)\r\n\r\n self.register_live_spy_callback(partial(self.spy_callback))\r\n self.register_live_trace_callback(partial(self.trace_callback))\r\n\r\n def trace_callback(self, trace):\r\n '''trace without datetimestamp'''\r\n trace_without_datetime = re.search(r'(\\[.+\\]) (\\[.+\\].+)', trace).group(2)\r\n print(trace_without_datetime)\r\n logging.debug(\"T: \" + trace_without_datetime)\r\n\r\n def spy_callback(self, spy):\r\n '''spy with machine name pre-pending'''\r\n logging.debug(\"S: [{}] {}\".format(self.name, spy))\r\n\r\n\r\nclass BatteryAttributes(ThreadSafeAttributes):\r\n _attributes = [\r\n 'soc_per',\r\n 'amp_hours', \r\n 'last_sample_time',\r\n 'last_current_amps',\r\n 'open_circuit_volts',\r\n 'last_terminal_volts'\r\n ]\r\n\r\nclass Battery(InstrumentedFactory, BatteryAttributes):\r\n\r\n def __init__(self,\r\n name,\r\n initial_soc_per,\r\n rated_amp_hours,\r\n start_time=None,\r\n ocv_vrs_r_profile_csv=None,\r\n soc_vrs_ocv_profile_csv=None,\r\n live_trace=None,\r\n live_spy=None):\r\n\r\n '''Battery simulator\r\n\r\n **Note**:\r\n This model requires ocv_vrs_r_profile_csv and oc_vrs_ocv_profile_csv\r\n files.\r\n\r\n **Args**:\r\n | ``name`` (str): \r\n | ``initial_soc_per`` (float): initial battery charge %\r\n | ``rated_amp_hours`` (float): battery's rated amps hours\r\n | ``start_time=None`` (datetime): starting time of simulation\r\n | ``ocv_vrs_r_profile_csv=None`` (str): open circuit volts vrs internal\r\n | battery resistance\r\n | ``soc_vrs_ocv_profile_csv=None`` (str): state of charge % vrs\r\n | open circuit voltage\r\n | ``live_trace=None``: enable live_trace feature?\r\n | ``live_spy=None``: enable live_spy feature?\r\n\r\n\r\n **Returns**:\r\n (Battery): \r\n A battery simulator which can be fed Amps, AmpsAndTime, Volts,\r\n VoltsAndTime or AmpHours via the amps, amp_and_time, volts,\r\n volts_and_time and amp_hour signals respectively\r\n\r\n **Example(s)**:\r\n \r\n .. code-block:: python\r\n \r\n battery = Battery(\r\n rated_amp_hours=100,\r\n initial_soc_per=10.0,\r\n name=\"battery_example\",\r\n soc_vrs_ocv_profile_csv='soc_ocv.csv',\r\n ocv_vrs_r_profile_csv='ocv_internal_resistance.csv',\r\n live_trace=True)\r\n\r\n while battery.soc_per < 80.0:\r\n battery.post_fifo(Event(signal=signals.amps, payload=Amps(80.0)))\r\n print(str(battery), end='')\r\n time.sleep(1)\r\n\r\n '''\r\n super().__init__(name, live_trace=live_trace, live_spy=live_spy)\r\n\r\n self.last_terminal_voltage = 0.0\r\n self.last_current_amps = 0.0\r\n self.soc_per = float(initial_soc_per)\r\n self.rated_amp_hours = float(rated_amp_hours)\r\n\r\n self.start_time = datetime.now() if start_time is None else start_time\r\n self.last_sample_time = datetime.now()\r\n\r\n self.ocv_vrs_r_profile_csv = 'ocv_internal_resistance.csv' if \\\r\n ocv_vrs_r_profile_csv is None else ocv_vrs_r_profile_csv\r\n\r\n self.soc_vrs_ocv_profile_csv = \"ocv_soc.csv\" if \\\r\n soc_vrs_ocv_profile_csv is None else soc_vrs_ocv_profile_csv\r\n\r\n self.build_fns_from_data = self.create(state=\"build_fns_from_data\"). \\\r\n catch(signal=signals.ENTRY_SIGNAL,\r\n handler=self.build_fns_from_data_entry_signal). \\\r\n catch(signal=signals.INIT_SIGNAL,\r\n handler=self.build_fns_from_data_init_signal). \\\r\n to_method()\r\n\r\n self.volts_to_amps = self.create(state=\"volts_to_amps\"). \\\r\n catch(signal=signals.INIT_SIGNAL,\r\n handler=self.volts_to_amps_init_signal). \\\r\n catch(signal=signals.volts,\r\n handler=self.volts_to_amps_volts). \\\r\n catch(signal=signals.volts_and_time,\r\n handler=self.volts_to_amps_volts_and_time). \\\r\n to_method()\r\n\r\n self.amps_to_amp_hours = self.create(state=\"amps_to_amp_hours\"). \\\r\n catch(signal=signals.INIT_SIGNAL,\r\n handler=self.amps_to_amp_hours_init_signal). \\\r\n catch(signal=signals.amps,\r\n handler=self.amps_to_amp_hours_amps). \\\r\n catch(signal=signals.amps_and_time,\r\n handler=self.amps_to_amp_hours_amps_and_time). \\\r\n to_method()\r\n\r\n self.update_charge_state = self.create(state=\"update_charge_state\"). \\\r\n catch(signal=signals.amp_hours,\r\n handler=self.update_charge_state_amp_hours). \\\r\n to_method()\r\n\r\n self.nest(self.build_fns_from_data, parent=None). \\\r\n nest(self.volts_to_amps, parent=self.build_fns_from_data). \\\r\n nest(self.amps_to_amp_hours, parent=self.volts_to_amps). \\\r\n nest(self.update_charge_state, parent=self.amps_to_amp_hours)\r\n\r\n self.start_at(self.build_fns_from_data)\r\n\r\n def __str__(self):\r\n '''Turn the battery simulator into a str to describe its characteristics.\r\n\r\n **Returns**:\r\n (str): The state of the battery simulator\r\n\r\n **Example(s)**:\r\n\r\n .. code-block:: python\r\n\r\n # After making a battery obj, you can see its\r\n # state by casting it as a str then printing that str:\r\n\r\n print(str(battery)) # =>\r\n ---\r\n time_s: 7.10\r\n term_v: 13.8614\r\n batt_o: 0.0140\r\n losses_w: 89.6000\r\n amps_a: 80.0000\r\n ocv_v: 12.7416\r\n soc_%: 75.1577\r\n\r\n '''\r\n return \"\"\"\r\n---\r\ntime_s: {0:10.4f}\r\nterm_v: {1:9.4f}\r\nterm_v2: {2:9.4f}\r\nbatt_o: {3:9.4f}\r\nlosses_w: {4:9.4f}\r\namps_a: {5:9.4f}\r\nocv_v: {6:9.4f}\r\nsoc_%: {7:9.4f}\\n\"\"\".format(\r\n (self.last_sample_time-self.start_time).total_seconds(),\r\n self.last_terminal_voltage,\r\n self.terminal_volts_for(current=self.last_current_amps),\r\n self.batt_r_ohms,\r\n self.last_current_amps**2*self.batt_r_ohms,\r\n self.last_current_amps,\r\n self.fn_soc_to_ocv(self.soc_per),\r\n self.soc_per)\r\n\r\n def build_fns_from_data_entry_signal(self, e):\r\n self.last_sample_time = datetime.now()\r\n self.fn_soc_to_ocv = self._create_soc_to_ocv_model(\r\n self.soc_vrs_ocv_profile_csv\r\n )\r\n self.fn_ocv_to_batt_r = self._create_ocv_to_batt_r_model(\r\n self.ocv_vrs_r_profile_csv\r\n )\r\n self.batt_r_ohms = self._ohms_given_soc(self.soc_per)\r\n self.open_circuit_volts = self.fn_soc_to_ocv(self.soc_per)\r\n\r\n return return_status.HANDLED\r\n\r\n def build_fns_from_data_init_signal(self, e):\r\n status = self.trans(self.volts_to_amps)\r\n return status\r\n\r\n def volts_to_amps_init_signal(self, e):\r\n status = self.trans(self.amps_to_amp_hours)\r\n return status\r\n\r\n def volts_to_amps_volts(self, e):\r\n self.post_lifo(\r\n Event(\r\n signal=signals.volts_and_time,\r\n payload=VoltsAndTime(\r\n volts=e.payload.volts,\r\n time=datetime.now()\r\n )\r\n )\r\n )\r\n return return_status.HANDLED\r\n\r\n def volts_to_amps_volts_and_time(self, e):\r\n status = return_status.HANDLED\r\n amps = self._amps_given_terminal_volts(\r\n terminal_volts=e.payload.volts\r\n )\r\n self.last_terminal_voltage = e.payload.volts\r\n self.post_lifo(\r\n Event(\r\n signal=signals.amps_and_time,\r\n payload=AmpsAndTime(\r\n amps=amps,\r\n time=e.payload.time\r\n )\r\n )\r\n )\r\n return status\r\n\r\n def amps_to_amp_hours_init_signal(self, e):\r\n status = self.trans(self.update_charge_state)\r\n return status\r\n\r\n def amps_to_amp_hours_amps(self, e):\r\n status = return_status.HANDLED\r\n self.post_lifo(\r\n Event(\r\n signal=signals.amps_and_time,\r\n payload=AmpsAndTime(\r\n amps=e.payload.amps,\r\n time=datetime.now()\r\n )\r\n )\r\n )\r\n return status\r\n\r\n def amps_to_amp_hours_amps_and_time(self, e):\r\n status = return_status.HANDLED\r\n\r\n amps = e.payload.amps\r\n terminal_volts = amps * self.batt_r_ohms + self.open_circuit_volts\r\n #print(\" {} * {} + {}\".format(str(amps), str(self.batt_r_ohms), str(self.open_circuit_volts)))\r\n self.last_terminal_voltage = terminal_volts\r\n self.last_current_amps = amps\r\n\r\n amp_hours = self._amp_hours_given_amps(\r\n amps=amps,\r\n time=e.payload.time\r\n )\r\n \r\n self.post_lifo(\r\n Event(\r\n signal=signals.amp_hours,\r\n payload=AmpsHours(amp_hours=amp_hours)\r\n )\r\n )\r\n self.last_sample_time = e.payload.time\r\n return status\r\n\r\n def update_charge_state_amp_hours(self, e):\r\n status = return_status.HANDLED\r\n self.amp_hours = \\\r\n self.soc_per / 100.0 * self.rated_amp_hours + e.payload.amp_hours\r\n self.soc_per = self.amp_hours / self.rated_amp_hours * 100.0\r\n self.batt_r_ohms = self._ohms_given_soc(self.soc_per)\r\n self.open_circuit_volts = self.fn_soc_to_ocv(self.soc_per)\r\n return status\r\n\r\n def _amps_given_terminal_volts(self, terminal_volts):\r\n soc_per = self.soc_per\r\n voc = self.fn_soc_to_ocv(soc_per)\r\n #batt_r_ohms = self.fn_ocv_to_batt_r(voc)\r\n v_r_volts = terminal_volts - voc\r\n amps = v_r_volts / self.batt_r_ohms\r\n return amps\r\n\r\n def _amp_hours_given_amps(self, amps, time):\r\n delta_t_sec = (time - self.last_sample_time).total_seconds()\r\n amp_hours = amps * delta_t_sec / 3600.0\r\n return amp_hours\r\n\r\n def _ohms_given_soc(self, soc):\r\n ocv = self.fn_soc_to_ocv(self.soc_per)\r\n batt_r_ohms = self.fn_ocv_to_batt_r(ocv)\r\n return batt_r_ohms\r\n\r\n def _create_soc_to_ocv_model(self, soc_vrs_ocv_profile_csv):\r\n data_ocv_soc = np.genfromtxt(\r\n soc_vrs_ocv_profile_csv,\r\n delimiter=',',\r\n skip_header=1,\r\n names=['state_of_charge', 'open_circuit_voltage'],\r\n dtype=\"float, float\",\r\n )\r\n fn_soc_to_ocv = interp1d(\r\n data_ocv_soc['state_of_charge'],\r\n data_ocv_soc['open_circuit_voltage']\r\n )\r\n return fn_soc_to_ocv\r\n\r\n def _create_ocv_to_batt_r_model(self, soc_vrs_ocv_profile_csv):\r\n data_ocv_internal_resistance = np.genfromtxt(\r\n self.ocv_vrs_r_profile_csv,\r\n delimiter=',',\r\n skip_header=1,\r\n names=['open_circuit_volts', 'resistance_ohms'],\r\n dtype=\"float, float\",\r\n )\r\n\r\n coefs = poly.polyfit(\r\n data_ocv_internal_resistance['open_circuit_volts'],\r\n data_ocv_internal_resistance['resistance_ohms'],\r\n 5,\r\n )\r\n fn_ocv_to_batt_r = poly.Polynomial(coefs)\r\n return fn_ocv_to_batt_r\r\n\r\n def amps_through_terminals(self, amps, sample_time=None):\r\n if sample_time is None:\r\n self.post_fifo(Event(signal=signals.amps, payload=Amps(amps)))\r\n else:\r\n self.post_fifo(Event(signal=signals.amps_and_time,\r\n payload=AmpsAndTime(amps=amps, time=sample_time)))\r\n\r\n def volts_across_terminals(self, volts, sample_time=None):\r\n if sample_time is None:\r\n self.post_fifo(Event(signal=signals.volts, payload=Volts(volts)))\r\n else:\r\n self.post_fifo(Event(signal=signals.volts_and_time,\r\n payload=VoltsAndTime(volts=volts, time=sample_time)))\r\n\r\n def charge_into_battery(self, amp_hours, sample_time=None):\r\n if sample_time is None:\r\n self.post_fifo(Event(signal=signals.amp_hours,\r\n payload=AmpsHours(amps_hours)))\r\n else:\r\n self.post_fifo(Event(signal=signals.amps_and_time,\r\n payload=AmpsAndTime(amps=amps, time=sample_time)))\r\n\r\n def terminal_volts_for(self, current):\r\n batt_r_ohms = self.batt_r_ohms\r\n open_circuit_volts = self.open_circuit_volts\r\n terminal_volts = current * batt_r_ohms + open_circuit_volts\r\n return terminal_volts\r\n\r\n @staticmethod\r\n def time_series(duration_in_sec, start_time=None, time_increment_sec=None):\r\n '''Build a time series \r\n\r\n **Args**:\r\n | ``duration_in_sec`` (int|float): Duration in seconds.\r\n | ``start_time=None`` (datetime): Starting time of series.\r\n | ``time_increments_sec`` (int/float): time increments in second \r\n\r\n\r\n **Returns**:\r\n (list of datetime items): list of times used\r\n\r\n **Example(s)**:\r\n \r\n .. code-block:: python\r\n \r\n series = battery.time_series(duration_in_sec=3600)\r\n\r\n '''\r\n start_time = datetime.now() if start_time is None \\\r\n else start_time\r\n time_increment_sec = 1.0 if time_increment_sec is None \\\r\n else time_increment_sec\r\n\r\n time_series = [\r\n start_time + timedelta(seconds=float(second_inc)) \\\r\n for second_inc in arange(0.0, duration_in_sec, time_increment_sec)\r\n ]\r\n return list(time_series)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n battery = Battery(\r\n rated_amp_hours=100,\r\n initial_soc_per=79.8,\r\n name=\"lead_acid_battery_100Ah\",\r\n soc_vrs_ocv_profile_csv='soc_ocv.csv',\r\n ocv_vrs_r_profile_csv='ocv_internal_resistance.csv',\r\n live_trace=True\r\n )\r\n\r\n hours = 0.02\r\n\r\n time_series = battery.time_series(\r\n duration_in_sec=hours*60*60,\r\n )\r\n for moment in time_series:\r\n if battery.soc_per < 80.0:\r\n battery.amps_through_terminals(33.0, moment)\r\n print(str(battery), end='')\r\n abs_volts = battery.last_terminal_voltage\r\n else:\r\n print(abs_volts)\r\n battery.volts_across_terminals(abs_volts, moment)\r\n print(str(battery), end='')\r\n #time.sleep(0.0001)\r\n","sub_path":"examples/battery_model_2.py","file_name":"battery_model_2.py","file_ext":"py","file_size_in_byte":14333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"158408412","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError, RedirectWarning, ValidationError\n\nclass PurchaseOrderFile(models.Model):\n _inherit = ['sale.order']\n\n dnk_purchase_order_name = fields.Char('- Purchase Order Name')\n dnk_purchase_order_file = fields.Binary('- Purchase Order File', store=True)\n\n @api.model\n def action_confirm(self):\n res =super(PurchaseOrderFile, self).action_confirm()\n if self.partner_id.dnk_purchase_order_required and not self.dnk_purchase_order_name :\n raise ValidationError(_('The settings for this client requires a purchase order file.'))\n return res\n","sub_path":"denker/dnk_sale_purchase_order_file/models/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"552665906","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n# Natoms = 2000\nE0 = [15,20,25,30,35,40,45,50]\n#)path = r\"C:\\\\Users\\\\Daniel White\\\\E0_data500000.csv\" # 5 0's\n\nL = len(E0)\n\ndef Data(a):\n '''[0] is data, [1] is E0 value'''\n df = pd.read_excel('sE0_data{}0.xlsx'.format(a))\n return df,df.columns[1]\n\nHallD,BallD = [],[]\nfor i in range(L):\n B = []\n H = []\n for index,row in Data(E0[i])[0].iterrows():\n B.append(row[0])\n H.append(row[1])\n BallD.append(B)\n HallD.append(H)\n\nplt.title('Density Distribution of Increasing E0\\nw/ 2000 Atoms, 150MHz AOM, 15MHz E0, Beta 1.5',size=19)\nplt.xlabel('Distance from source / m',size=17)\nplt.ylabel('Particle Density',size=17)\n\n# # # # # # # # # # ##\n''' F W H M ''' # ##\nFWHMs = []\nfor i in range(L):\n HallD_ = HallD[i]\n BallD_ = BallD[i]\n Hpeak = [max(HallD_), int(round( np.median(np.where(HallD_==max(HallD_))) ))]\n\n Lmin = max(np.where(HallD_[:Hpeak[1]] == min(HallD_[:Hpeak[1]] ) )[0])\n\n Lmax = max(np.where(HallD_[Hpeak[1]:] == min(HallD_[Hpeak[1]:] ) )[0])\n #print('Index Distance from center to edge R L= ', BallD[Hpeak[1]]-BallD[Lmin], BallD[Lmax]-BallD[Hpeak[1]])\n #vLmin,vLmax = BinFactor* IS IT POSSIBLE TO CONVERT INTO ORGINAL VELOCITY = not needed right now\n FWi = Lmax-Lmin\n Bot = max(HallD_[Lmax],HallD_[Lmin])\n\n HM = Bot + (Hpeak[0]+Bot)/2\n\n lHM = np.abs(HallD_[:Hpeak[1]]-HM).argmin()\n rHM = np.abs(HallD_[Hpeak[1]:]-HM).argmin()+Hpeak[1]\n\n #print(lHM,rHM)\n Skew = -1*(BallD_[Hpeak[1]]-BallD_[lHM]-BallD_[rHM]+BallD_[Hpeak[1]])\n #print('Skew =',Skew,' +=MB')\n FWHM = BallD_[rHM]-BallD_[lHM]\n\n FWHMs.append(FWHM)\n#print(FWHMs)\nc = 3e8\ndef IrE(b):\n xD = c*8.85e-12/2*b**2/10000\n return xD\nfor i in range(1,L):\n col = ( float((i/(L+1)+0.0001)), float((i/(L+1)+0.0001)**2), 0.9-0.5*float((i/(L+5)+0.0001)**0.7))\n plt.plot(BallD[i], HallD[i],c=col,linewidth=5,label='E0 = '+str(E0[i]*10)+', I = '+str(round(IrE(E0[i]*10),3)*1000)+'mW/cm2 {}cm'.format(round(FWHMs[i]*100,4)))\n plt.fill_between(BallD[i], HallD[i],color=col,alpha=0.2)\nplt.legend(fontsize=25)\nplt.show()\n\n# FWHM is a bit broken, need way more bins\n\n''' \n 3 D A t t e m p t \n # # # # # # #\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\nax = fig.add_suBallD(1,1,1,projection='3d')\n'''\n#ax.plot_wireframe(BallD,HallD,E0)\n","sub_path":"Simulation/VisualS/EOM/sE0vary0.py","file_name":"sE0vary0.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"303674157","text":"#función factorial\ndef factorial(x):\n\tf=1\n\tif x > 0:\n\t\tfor i in range(1, x+1):\n\t\t\tf = f * i\n\telif x < 0:\n\t\t#no existe factorial de un número negativo\n\t\tf= -1\n\t\n\treturn f\n\n#función combinatoria\ndef combinatoria(n, m):\n\tif m >= n:\n\t\treturn factorial(m) / ( factorial(n) * factorial(m - n) )\n\telse:\n\t\t#no existe combinatoria para n < m\n\t\treturn -1\n\n#*** PROGRAMA PRINCIPAL ***\na= int(input(\"ingrese el valor de n?: \"))\nb= int(input(\"ingrese el valor de m?: \"))\n\nresultado= combinatoria(a, b)\n\nif resultado != -1:\n\t#str(num): str() es una función que combierte el número (num) en texto\n\tprint(\"\\nEl resultado de \" + str(a) + \"C\" + str(b) + \"= \", resultado)\nelse:\n\tprint(\"\\n>>>Error. Datos inválidos\")\n\t\n","sub_path":"funciones/combinatoria.py","file_name":"combinatoria.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"275420021","text":"import collections\n\nimport galsim\n\n# populated by the `galsim_test_case` decorator\nTEST_CASE_FNS = []\n\nARCSEC_PER_DEGREE = 3600.\nARCSEC_PER_PIXEL = 0.396 # the value used in SDSS (https://github.com/jeff-regier/Celeste.jl/pull/411)\nDEGREES_PER_PIXEL = ARCSEC_PER_PIXEL / ARCSEC_PER_DEGREE\nSTAMP_SIZE_PX = 96\nCOUNTS_PER_NMGY = 1000.0 # a.k.a. \"iota\" in Celeste\n\n# intensity (flux) relative to third band (= \"a\" band = reference)\n# see GalsimBenchmark.typical_band_relative_intensities()\n# these are taken from the current dominant component of the lognormal prior on c_s for stars\nSTAR_RELATIVE_INTENSITIES = [\n 0.1330,\n 0.5308,\n 1,\n 1.3179,\n 1.5417,\n]\n# these are taken from the current dominant component of the lognormal prior on c_s for galaxies\nGALAXY_RELATIVE_INTENSITIES = [\n 0.4013,\n 0.4990,\n 1,\n 1.4031,\n 1.7750,\n]\n\n# fields and logic shared between stars and galaxies\nclass CommonFields(object):\n def __init__(self):\n self.offset_from_center_arcsec = (0, 0)\n self.reference_band_flux_nmgy = 40\n\n def offset_from_center_degrees(self):\n return (\n self.offset_from_center_arcsec[0] / ARCSEC_PER_DEGREE,\n self.offset_from_center_arcsec[1] / ARCSEC_PER_DEGREE,\n )\n\n def position_deg(self):\n image_center_deg = (\n (STAMP_SIZE_PX + 1) / 2.0 * DEGREES_PER_PIXEL\n )\n return (\n image_center_deg + self.offset_from_center_arcsec[0] / ARCSEC_PER_DEGREE,\n image_center_deg + self.offset_from_center_arcsec[1] / ARCSEC_PER_DEGREE,\n )\n\n def add_header_fields(self, header, index_str, star_or_galaxy):\n position_deg = self.position_deg()\n header['CL_X' + index_str] = (position_deg[0], 'X center in world coordinates (deg)')\n header['CL_Y' + index_str] = (position_deg[1], 'Y center in world coordinates (deg)')\n header['CL_FLUX' + index_str] = (\n self.reference_band_flux_nmgy,\n 'reference (=3) band brightness (nMgy)',\n )\n header['CL_TYPE' + index_str] = (star_or_galaxy, '\"star\" or \"galaxy\"?')\n\n# this essentially just serves a documentation purpose\nclass LightSource(object):\n def get_galsim_light_source(self, band_index):\n raise NotImplementedError\n\n def add_header_fields(self, header):\n raise NotImplementedError\n\nclass Star(LightSource):\n def __init__(self):\n self._common_fields = CommonFields()\n\n def offset_arcsec(self, x, y):\n self._common_fields.offset_from_center_arcsec = (x, y)\n return self\n\n def reference_band_flux_nmgy(self, flux):\n self._common_fields.reference_band_flux_nmgy = flux\n return self\n\n def get_galsim_light_source(self, band_index, psf_sigma_degrees):\n flux_counts = (\n self._common_fields.reference_band_flux_nmgy * STAR_RELATIVE_INTENSITIES[band_index]\n * COUNTS_PER_NMGY\n )\n return (\n galsim.Gaussian(flux=flux_counts, sigma=psf_sigma_degrees)\n .shift(self._common_fields.offset_from_center_degrees())\n )\n\n def add_header_fields(self, header, index_str):\n self._common_fields.add_header_fields(header, index_str, 'star')\n\nclass Galaxy(LightSource):\n def __init__(self):\n self._common_fields = CommonFields()\n self._common_fields.reference_band_flux_nmgy = 10\n self._angle_deg = 0\n self._minor_major_axis_ratio = 0.4\n self._half_light_radius_arcsec = 1.5\n\n def offset_arcsec(self, x, y):\n self._common_fields.offset_from_center_arcsec = (x, y)\n return self\n\n def reference_band_flux_nmgy(self, flux):\n self._common_fields.reference_band_flux_nmgy = flux\n return self\n\n def angle_deg(self, angle):\n self._angle_deg = angle\n return self\n\n def minor_major_axis_ratio(self, ratio):\n self._minor_major_axis_ratio = ratio\n return self\n\n def half_light_radius_arcsec(self, radius):\n self._half_light_radius_arcsec = radius\n return self\n\n def get_galsim_light_source(self, band_index, psf_sigma_degrees):\n flux_counts = (\n self._common_fields.reference_band_flux_nmgy * GALAXY_RELATIVE_INTENSITIES[band_index]\n * COUNTS_PER_NMGY\n )\n half_light_radius_deg = self._half_light_radius_arcsec / ARCSEC_PER_DEGREE\n galaxy = (\n galsim.Exponential(half_light_radius=half_light_radius_deg, flux=flux_counts)\n .shear(q=self._minor_major_axis_ratio, beta=self._angle_deg * galsim.degrees)\n .shift(self._common_fields.offset_from_center_degrees())\n )\n psf = galsim.Gaussian(flux=1, sigma=psf_sigma_degrees)\n return galsim.Convolve([galaxy, psf])\n\n def add_header_fields(self, header, index_str):\n self._common_fields.add_header_fields(header, index_str, 'galaxy')\n header['CL_ANGL' + index_str] = (self._angle_deg, 'major axis angle (degrees from x-axis)')\n header['CL_RTIO' + index_str] = (self._minor_major_axis_ratio, 'minor/major axis ratio')\n header['CL_RADA' + index_str] = (\n self._half_light_radius_arcsec,\n 'half-light radius (arcsec)',\n )\n header['CL_RADP' + index_str] = (\n self._half_light_radius_arcsec / ARCSEC_PER_PIXEL,\n 'half-light radius (pixels)',\n )\n\n# A complete description of a GalSim test image, along with logic to generate the image and the\n# \"ground truth\" header fields\nclass GalSimTestCase(object):\n def __init__(self):\n self._light_sources = []\n self.psf_sigma_pixels = 4\n self.sky_level_nmgy = 0.01\n self.include_noise = False\n self.comment = None\n\n # `light_source` must satisfy the LightSource interface\n def add(self, light_source):\n self._light_sources.append(light_source)\n\n def get_galsim_light_source(self, band_index):\n return sum(\n light_source.get_galsim_light_source(band_index)\n for light_source in self._light_sources\n )\n\n def _add_sky_background(self, image):\n image.array[:] = image.array + self.sky_level_nmgy * COUNTS_PER_NMGY\n\n def _add_noise(self, image, uniform_deviate):\n if self.include_noise:\n noise = galsim.PoissonNoise(uniform_deviate)\n image.addNoise(noise)\n\n def construct_image(self, band_index, uniform_deviate):\n image = galsim.ImageF(STAMP_SIZE_PX, STAMP_SIZE_PX, scale=DEGREES_PER_PIXEL)\n for light_source in self._light_sources:\n galsim_light_source = light_source.get_galsim_light_source(\n band_index,\n self.psf_sigma_pixels * DEGREES_PER_PIXEL,\n )\n galsim_light_source.drawImage(image, add_to_image=True)\n self._add_sky_background(image)\n self._add_noise(image, uniform_deviate)\n return image\n\n def get_fits_header(self, case_index, band_index):\n # FITS header fields will be too long if there's a two-digit index\n assert len(self._light_sources) < 10\n header = collections.OrderedDict([\n ('CL_CASEI', (case_index + 1, 'test case index')),\n ('CL_DESCR', (self.comment, 'comment')),\n ('CL_IOTA', (COUNTS_PER_NMGY, 'counts per nMgy')),\n ('CL_SKY', (self.sky_level_nmgy, '\"epsilon\" sky level (nMgy each px)')),\n ('CL_NOISE', (self.include_noise, 'was Poisson noise added?')),\n ('CL_SIGMA', (self.psf_sigma_pixels, 'Gaussian PSF sigma (px)')),\n ('CL_BAND', (band_index + 1, 'color band')),\n ('CL_NSRC', (len(self._light_sources), 'number of sources')),\n ])\n for source_index, light_source in enumerate(self._light_sources):\n light_source.add_header_fields(header, str(source_index + 1))\n return header\n\n# just a trick to set the test case function name as the `GalSimTestCase.comment` field (for\n# inclusion in the FITS header)\ndef galsim_test_case(fn):\n def decorated(test_case):\n fn(test_case)\n test_case.comment = fn.__name__\n decorated.__name__ = fn.__name__\n TEST_CASE_FNS.append(decorated)\n return decorated\n\n# Test cases follow. Each is a function which accepts a test case and adds LightSources and/or sets\n# parameters. Each must be decorated with @galsim_test_case. Function name will be included in the\n# FITS header for reference.\n\n@galsim_test_case\ndef simple_star(test_case):\n test_case.add(Star())\n\n@galsim_test_case\ndef star_position_1(test_case):\n test_case.add(Star().offset_arcsec(-2, 0))\n\n@galsim_test_case\ndef star_position_2(test_case):\n test_case.add(Star().offset_arcsec(0, 2))\n\n@galsim_test_case\ndef dim_star(test_case):\n test_case.add(Star().reference_band_flux_nmgy(20))\n\n@galsim_test_case\ndef bright_star(test_case):\n test_case.add(Star().reference_band_flux_nmgy(80))\n\n@galsim_test_case\ndef star_with_noise(test_case):\n test_case.add(Star().offset_arcsec(-1, 1).reference_band_flux_nmgy(20))\n test_case.sky_level_nmgy = 0.1\n test_case.include_noise = True\n\n@galsim_test_case\ndef angle_and_axis_ratio_1(test_case):\n test_case.add(Galaxy().angle_deg(15).minor_major_axis_ratio(0.2))\n\n@galsim_test_case\ndef angle_and_axis_ratio_2(test_case):\n test_case.add(Galaxy().angle_deg(160).minor_major_axis_ratio(0.4))\n\n@galsim_test_case\ndef round_galaxy(test_case):\n test_case.add(Galaxy().minor_major_axis_ratio(1))\n\n@galsim_test_case\ndef small_galaxy(test_case):\n test_case.add(Galaxy().half_light_radius_arcsec(0.75))\n\n@galsim_test_case\ndef large_galaxy(test_case):\n test_case.add(Galaxy().half_light_radius_arcsec(2.5))\n\n@galsim_test_case\ndef dim_galaxy(test_case):\n test_case.add(Galaxy().reference_band_flux_nmgy(5))\n\n@galsim_test_case\ndef bright_galaxy(test_case):\n test_case.add(Galaxy().reference_band_flux_nmgy(20))\n\n@galsim_test_case\ndef galaxy_with_all(test_case):\n test_case.add(\n Galaxy().offset_arcsec(0.3, -0.7)\n .angle_deg(15)\n .minor_major_axis_ratio(0.4)\n .half_light_radius_arcsec(2.5)\n .reference_band_flux_nmgy(15)\n )\n\n@galsim_test_case\ndef galaxy_with_noise(test_case):\n galaxy_with_all(test_case)\n test_case.include_noise = True\n\n@galsim_test_case\ndef galaxy_with_low_background(test_case):\n galaxy_with_noise(test_case)\n test_case.sky_level_nmgy = 0.1\n\n@galsim_test_case\ndef galaxy_with_high_background(test_case):\n galaxy_with_noise(test_case)\n test_case.sky_level_nmgy = 0.3\n\n@galsim_test_case\ndef overlapping_stars(test_case):\n test_case.add(Star().offset_arcsec(-3, 0))\n test_case.add(Star().offset_arcsec(3, 0))\n\n@galsim_test_case\ndef overlapping_galaxies(test_case):\n test_case.add(Galaxy().offset_arcsec(-2, -2).angle_deg(135).minor_major_axis_ratio(0.2))\n test_case.add(Galaxy().offset_arcsec(3, 3).angle_deg(35).minor_major_axis_ratio(0.5))\n\n@galsim_test_case\ndef overlapping_star_and_galaxy(test_case):\n test_case.add(Star().offset_arcsec(-5, 0))\n test_case.add(Galaxy().offset_arcsec(2, 2).angle_deg(35).minor_major_axis_ratio(0.5))\n\n@galsim_test_case\ndef three_sources_two_overlap(test_case):\n test_case.add(Star().offset_arcsec(-5, 5))\n test_case.add(\n Galaxy().offset_arcsec(2, 5)\n .angle_deg(35)\n .minor_major_axis_ratio(0.2)\n )\n test_case.add(Star().offset_arcsec(10, -10))\n\n@galsim_test_case\ndef three_sources_all_overlap(test_case):\n overlapping_star_and_galaxy(test_case)\n test_case.add(Star().offset_arcsec(8, -1))\n\n@galsim_test_case\ndef smaller_psf(test_case):\n test_case.psf_sigma_pixels = 2\n test_case.add(Star())\n\n@galsim_test_case\ndef larger_psf(test_case):\n test_case.psf_sigma_pixels = 6\n test_case.add(Star())\n","sub_path":"benchmark/galsim/test_case_definitions.py","file_name":"test_case_definitions.py","file_ext":"py","file_size_in_byte":11765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"479723348","text":"def inputs():\n inputs = {}\n inputs['hilbertSpaceList'] = ['flux','sigt']\n inputs['discretization'] = ['feds']\n inputs['numberOfGroups'] = [10,20]\n inputs['xsFileNames'] = ['BarnfireXS_Godiva_502.xml']\n inputs['clustFileName'] = 'clust-500-9.xml'\n inputs['plots'] = ['all']\n return inputs\n\n\n\n\n","sub_path":"src/inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"29850074","text":"from maze.grid import Grid\nfrom algorithms.binary_tree import BinaryTree\nfrom algorithms.sidewinder import Sidewinder\nfrom algorithms.aldous_broder import AldousBroder\nfrom algorithms.wilsons import Wilsons\nfrom algorithms.hunt_and_kill import HuntAndKill\n\n\nalgorithms = [BinaryTree(), Sidewinder(), AldousBroder(), Wilsons(), HuntAndKill()]\n\ntries = 100\nsize = 20\n\naverages = []\nfor algorithm in algorithms:\n print('running {}'.format(algorithm.__class__.__name__))\n\n deadend_counts = []\n for index in range(tries):\n grid = Grid(size, size)\n algorithm.on(grid)\n deadend_counts.append(len(grid.deadends()))\n\n total_deadends = sum(deadend_counts)\n averages.append(total_deadends / len(deadend_counts))\n\ntotal_cells = size * size\nprint()\nprint('Average dead-ends per {0}X{0} maze ({1} cells):'.format(str(size), total_cells))\nprint()\n\nfor algorithm in algorithms:\n percentage = averages[algorithms.index(algorithm)] * 100.0 / (size * size)\n print('{0} : {1}/{2} ({3}%)'.format(algorithm.__class__.__name__, averages[algorithms.index(algorithm)], total_cells, percentage))\n","sub_path":"deadend_counts.py","file_name":"deadend_counts.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"628437718","text":"\nfrom __future__ import annotations\n\nimport asyncio\nimport os\nimport os.path\nimport tempfile\nfrom argparse import ArgumentParser, Namespace\nfrom asyncio import Task, AbstractServer, CancelledError\nfrom typing import Optional\n\nfrom grpclib.server import Server # type: ignore\nfrom pymap.config import IMAPConfig\nfrom pymap.interfaces.backend import BackendInterface, ServiceInterface\n\nfrom .handlers import AdminHandlers\n\n__all__ = ['AdminService']\n\n\nclass AdminService(ServiceInterface): # pragma: no cover\n \"\"\"A pymap service implemented using a `grpc `_ server\n to perform admin functions on a running backend.\n\n \"\"\"\n\n def __init__(self, path: str, server: AbstractServer) -> None:\n super().__init__()\n self._path = path\n self._server = server\n self._task = asyncio.create_task(self._run())\n\n @classmethod\n def get_socket_path(cls) -> str:\n \"\"\"Return the default location of the UNIX socket file listening for\n admin requests.\n\n \"\"\"\n return os.path.join(tempfile.gettempdir(), 'pymap-admin.sock')\n\n @classmethod\n def add_arguments(cls, parser: ArgumentParser) -> None:\n group = parser.add_argument_group('admin service')\n group.add_argument('--admin-socket', metavar='PATH', dest='admin_sock',\n help='path to socket file')\n group.add_argument('--no-filter', action='store_true',\n help='do not filter appended messages')\n\n @classmethod\n async def start(cls, backend: BackendInterface,\n config: IMAPConfig) -> AdminService:\n config = backend.config\n path: Optional[str] = config.args.admin_sock\n handlers = AdminHandlers(backend)\n server = Server([handlers], loop=asyncio.get_event_loop())\n path = await cls._start(path, server)\n cls._chown(path, config.args)\n return cls(path, server)\n\n @classmethod\n async def _start(cls, path: Optional[str], server: Server) -> str:\n if not path:\n path = cls.get_socket_path()\n await server.start(path=path)\n return path\n\n @classmethod\n def _chown(cls, path: str, args: Namespace) -> None:\n uid = args.set_uid or -1\n gid = args.set_gid or -1\n if uid >= 0 or gid >= 0:\n os.chown(path, uid, gid)\n\n @property\n def task(self) -> Task:\n return self._task\n\n def _unlink_path(self) -> None:\n try:\n os.unlink(self._path)\n except OSError:\n pass\n\n async def _run(self) -> None:\n server = self._server\n try:\n await server.wait_closed()\n except CancelledError:\n server.close()\n await server.wait_closed()\n finally:\n self._unlink_path()\n","sub_path":"venv/Lib/site-packages/pymap/admin/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"69144202","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 20 11:45:20 2018\n\n@author: Srinivasan Thangamani\n\"\"\"\n\nimport pandas as pd\nimport datetime\nfrom sklearn import feature_selection\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.feature_selection import RFECV\nimport itertools\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom sklearn.externals import joblib\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import RandomizedSearchCV\n\n\n# Function to calculate age from YOB\ndef age_calc_process(df, lower_limit=10, upper_limit=75):\n df = df.copy(deep=True)\n current_year = datetime.datetime.now().year\n df['age'] = current_year - df['yob']\n df.drop(['yob'], axis=1, inplace=True)\n df = df[(df['age']>=lower_limit) & (df['age']<=upper_limit)]\n return df\n\n# Function to drop columns\ndef drop_cols(df, cols):\n df = df.copy(deep=True)\n df.drop(cols, axis=1, inplace=True)\n return df\n\n# Function to drop NA rows\ndef drop_rows(df, cols):\n df = df.copy(deep=True)\n df.dropna(axis=0, inplace=True,subset=cols)\n return df\n\n# Function to encode the columns\ndef encode_cols(df, cols):\n \"\"\"\n Encode the categorical columns.\n\n Args:\n df : Data frame\n cols (list): list of columns to be encoded\n Returns:\n df_to_encode: Data frame with the encoded columns.\n \"\"\"\n df_to_encode = df.copy(deep=True)\n for i in cols:\n df_to_encode[i] = df_to_encode[i].astype(dtype='category')\n df_to_encode = pd.get_dummies(df_to_encode, columns=[i],\n prefix_sep='_', dummy_na=False)\n return df_to_encode\n\n\n# Function to select the features based on p-Value\ndef select_features(x_train, y_train, pvalue=0.05):\n \"\"\"Select columns based on feature importance.\n\n Args:\n x_train (DataFrame): Independent variables\n y_train (list): Target column\n pvalue (float): Threshold to select the features, default(0.05)\n Returns:\n results (dict): {\"column\": selected_cols, \"n_features\": no_of_features}\n\n \"\"\"\n available_cols = list(x_train.columns)\n f_selector = feature_selection.f_classif(X=x_train, y=y_train)\n p_value = f_selector[1]\n print(p_value)\n index = np.argwhere(p_value < pvalue).tolist()\n pvalue_index = list(itertools.chain.from_iterable(index))\n selected_cols = list(map(lambda x: available_cols[x], pvalue_index))\n no_of_features = len(selected_cols)\n results = {\"column\": selected_cols, \"n_features\": no_of_features,\n \"model\": \"Anova\"}\n return results\n\n\n# Function to perform PCA - Dimensionality Reduction\ndef reduce_dimension(x_train):\n \"\"\"Reduce dimension of the data set.\n\n Args:\n x_train (DataFrame): Independent variables\n Returns:\n results (dict): {\"method\": method name (PCA), \"explained_variance\": explained_variance, \"PCA\": x_pca}\n\n \"\"\"\n pca = PCA(svd_solver='auto', random_state=2017)\n x_pca = pca.fit_transform(x_train)\n explained_variance = pca.explained_variance_ratio_.tolist()\n results = {'method': 'PCA', 'explained_variance': explained_variance, 'PCA': x_pca}\n return results\n\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\n# Function to select features using multivariate analysis - Regression\ndef multivariate_feature_selection(X, Y):\n available_cols = list(X.columns)\n models = {'random_forest':RandomForestRegressor(max_features='log2',n_jobs=-1, random_state=2017)}\n clf = models.get('random_forest')\n selector = RFECV(estimator=clf, step=0.1, cv=5, n_jobs=-1,\n scoring='r2')\n selector = selector.fit(X, Y)\n no_of_features = selector.n_features_\n feature_index = selector.support_.tolist()\n selected_cols = list(itertools.compress(available_cols, feature_index))\n return {\"column\": selected_cols, \"n_features\": no_of_features}\n\n\n# Function to select features using multivariate analysis - Classification\ndef feature_selection_classification(X, Y):\n available_cols = X.columns\n clf = RandomForestClassifier(max_features='log2',\n n_jobs=-1, random_state=2017,\n class_weight='balanced')\n selector = RFECV(estimator=clf, step=0.1, cv=5, n_jobs=-1,\n scoring='accuracy')\n selector = selector.fit(X, Y)\n no_of_features = selector.n_features_\n feature_index = selector.support_.tolist()\n selected_cols = list(itertools.compress(available_cols, feature_index))\n results = {\"column\": selected_cols, \"n_features\": no_of_features}\n return results\n\n\n# Read the source file\ndata_dict = pd.read_excel('data_dictionary.xlsx',sheet_name='features')\nbrq = pd.read_csv('brq.csv')\nuser_app_details = pd.read_csv('user_app_details.csv')\n\n# Merge user_app_details and brq\nresult = pd.merge(user_app_details, brq,left_on='ifa', right_on='ifa')\n\n# Calculate the age and drop the yob column\nm = age_calc_process(df=result)\n# Drop the columns which are not required for processing\ncols_to_remove = ['first_seen', 'last_seen', 'platform','total_conn_brq']\nm = drop_cols(df=m, cols=cols_to_remove)\n# Drop rows which has NA's cannot be imputed\n\nrm_na_cols=['device_category','gender','CELLULAR','WIFI','rog_m',\n 'ANDROID-ART_AND_DESIGN','ANDROID-AUTO_AND_VEHICLES', 'ANDROID-BEAUTY',\n 'ANDROID-BOOKS_AND_REFERENCE', 'ANDROID-BUSINESS', 'ANDROID-COMICS',\n 'ANDROID-COMMUNICATION', 'ANDROID-DATING', 'ANDROID-EDUCATION',\n 'ANDROID-ENTERTAINMENT', 'ANDROID-EVENTS', 'ANDROID-FINANCE',\n 'ANDROID-FOOD_AND_DRINK', 'ANDROID-GAME_ACTION','ANDROID-GAME_ADVENTURE',\n 'ANDROID-GAME_ARCADE', 'ANDROID-GAME_BOARD','ANDROID-GAME_CARD',\n 'ANDROID-GAME_CASINO', 'ANDROID-GAME_CASUAL','ANDROID-GAME_EDUCATIONAL',\n 'ANDROID-GAME_MUSIC', 'ANDROID-GAME_PUZZLE','ANDROID-GAME_RACING',\n 'ANDROID-GAME_ROLE_PLAYING','ANDROID-GAME_SIMULATION','ANDROID-GAME_SPORTS',\n 'ANDROID-GAME_STRATEGY', 'ANDROID-GAME_TRIVIA', 'ANDROID-GAME_WORD',\n 'ANDROID-HEALTH_AND_FITNESS', 'ANDROID-HOUSE_AND_HOME','ANDROID-LIBRARIES_AND_DEMO',\n 'ANDROID-LIFESTYLE','ANDROID-MAPS_AND_NAVIGATION', 'ANDROID-MEDICAL',\n 'ANDROID-MUSIC_AND_AUDIO', 'ANDROID-NEWS_AND_MAGAZINES','ANDROID-PARENTING',\n 'ANDROID-PERSONALIZATION', 'ANDROID-PHOTOGRAPHY','ANDROID-PRODUCTIVITY',\n 'ANDROID-SHOPPING', 'ANDROID-SOCIAL','ANDROID-SPORTS', 'ANDROID-TOOLS',\n 'ANDROID-TRAVEL_AND_LOCAL','ANDROID-VIDEO_PLAYERS','ANDROID-WEATHER']\n\nm = drop_rows(df=m, cols=rm_na_cols)\nm = encode_cols(df=m, cols=['gender','device_category'])\n\nX = m[m.columns.difference(['age','ifa'])]\nY = m.loc[:, ('age')]\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, stratify=Y, test_size=0.15)\n\nresults_uni = select_features(x_train=X_train, y_train=Y_train, pvalue=0.05)\nresults_uni_pd = pd.DataFrame(results_uni)\nresults_uni_pd.to_csv('results_uni.csv', index= False)\n\npca_results = reduce_dimension(x_train=X_train)\npca_data = pca_results.get('PCA')\npca_results.get('explained_variance')\ntop_variance = pca_data[:,:2]\n\nregr = RandomForestRegressor(max_depth=2, random_state=0)\nregr.fit(top_variance, Y_train)\ny_pred_pca = regr.predict(top_variance)\nprint(mean_squared_error(Y_train, y_pred_pca, multioutput='raw_values'))\nprint(mean_absolute_percentage_error(Y_train, y_pred_pca))\n# PCA Results are not satisfactory\n\nregr_uni = RandomForestRegressor(max_depth=2, random_state=0, criterion ='mae', max_features ='log2', n_jobs=-1)\nregr_uni.fit(X_train[results_uni.get('column')], Y_train)\ny_pred_uni = regr_uni.predict(X_train[results_uni.get('column')])\nprint(mean_squared_error(Y_train, y_pred_uni, multioutput='raw_values'))\nprint(mean_absolute_percentage_error(Y_train, y_pred_uni))\njoblib.dump(regr_uni, 'RF_Univariate_Regression.pkl')\n\n\nresults_rfecv = multivariate_feature_selection(X=X_train , Y=Y_train)\nresults_rfecv_pd = pd.DataFrame(results_rfecv)\nresults_rfecv_pd.to_csv('results_rfecv_multi.csv', index= False)\n\n\nregr_multi = RandomForestRegressor(max_depth=5, random_state=0, criterion ='mae', max_features ='log2', n_jobs=-1)\nregr_multi.fit(X_train[results_rfecv.get('column')], Y_train)\ny_pred_multi = regr_multi.predict(X_train[results_rfecv.get('column')])\nprint(mean_squared_error(Y_train, y_pred_multi, multioutput='raw_values'))\nprint(mean_absolute_percentage_error(Y_train, y_pred_multi))\njoblib.dump(regr_multi, 'RF_multivariate_Regression.pkl')\nloaded_model = joblib.load('RF_multivariate_Regression.pkl')\npd.DataFrame({\"Columns\":results_rfecv.get('column'),\"Importance\":loaded_model.feature_importances_}).to_csv(\n 'feature_importance_regression.csv',index=False)\n\ny_pred_multi_test = loaded_model.predict(X_test[results_rfecv.get('column')])\nprint(mean_squared_error(Y_test, y_pred_multi_test, multioutput='raw_values'))\nprint(mean_absolute_percentage_error(Y_test, y_pred_multi_test))\n\ndata_classification = age_calc_process(df=result,lower_limit=18, upper_limit=85)\n# Drop the columns which are not required for processing\ncols_to_remove = ['first_seen', 'last_seen', 'platform','total_conn_brq']\ndata_classification = drop_cols(df=data_classification, cols=cols_to_remove)\n# Drop rows which has NA's cannot be imputed\n\nrm_na_cols=['device_category','gender','CELLULAR','WIFI','rog_m',\n 'ANDROID-ART_AND_DESIGN','ANDROID-AUTO_AND_VEHICLES', 'ANDROID-BEAUTY',\n 'ANDROID-BOOKS_AND_REFERENCE', 'ANDROID-BUSINESS', 'ANDROID-COMICS',\n 'ANDROID-COMMUNICATION', 'ANDROID-DATING', 'ANDROID-EDUCATION',\n 'ANDROID-ENTERTAINMENT', 'ANDROID-EVENTS', 'ANDROID-FINANCE',\n 'ANDROID-FOOD_AND_DRINK', 'ANDROID-GAME_ACTION','ANDROID-GAME_ADVENTURE',\n 'ANDROID-GAME_ARCADE', 'ANDROID-GAME_BOARD','ANDROID-GAME_CARD',\n 'ANDROID-GAME_CASINO', 'ANDROID-GAME_CASUAL','ANDROID-GAME_EDUCATIONAL',\n 'ANDROID-GAME_MUSIC', 'ANDROID-GAME_PUZZLE','ANDROID-GAME_RACING',\n 'ANDROID-GAME_ROLE_PLAYING','ANDROID-GAME_SIMULATION','ANDROID-GAME_SPORTS',\n 'ANDROID-GAME_STRATEGY', 'ANDROID-GAME_TRIVIA', 'ANDROID-GAME_WORD',\n 'ANDROID-HEALTH_AND_FITNESS', 'ANDROID-HOUSE_AND_HOME','ANDROID-LIBRARIES_AND_DEMO',\n 'ANDROID-LIFESTYLE','ANDROID-MAPS_AND_NAVIGATION', 'ANDROID-MEDICAL',\n 'ANDROID-MUSIC_AND_AUDIO', 'ANDROID-NEWS_AND_MAGAZINES','ANDROID-PARENTING',\n 'ANDROID-PERSONALIZATION', 'ANDROID-PHOTOGRAPHY','ANDROID-PRODUCTIVITY',\n 'ANDROID-SHOPPING', 'ANDROID-SOCIAL','ANDROID-SPORTS', 'ANDROID-TOOLS',\n 'ANDROID-TRAVEL_AND_LOCAL','ANDROID-VIDEO_PLAYERS','ANDROID-WEATHER']\n\ndata_classification = drop_rows(df=data_classification, cols=rm_na_cols)\ndata_classification = encode_cols(df=data_classification, cols=['gender','device_category'])\n\n# Separate ages into bins\ndata_classification['age_range'] = pd.cut(data_classification['age'],[17,24,34,44,54,85],labels=[1,2,3,4,5])\n\n# Save the data as csv\ndata_classification.to_csv('data_classification_85.csv', index=False)\n\n# Extract dependent and independent variables\nX_Classification = data_classification[data_classification.columns.difference(['age','ifa','age_range'])]\nY_Classification = data_classification.loc[:, ('age_range')]\n\n# Feature selection\n\nfeatures_classification = feature_selection_classification(X=X_Classification, Y=Y_Classification)\nfeatures_classification_pd = pd.DataFrame(features_classification)\nfeatures_classification_pd.to_csv('features_classification.csv',index=False)\n\n\nX_class_train, X_class_test, Y_class_train, Y_class_test = train_test_split(X_Classification, Y_Classification,\n stratify=Y_Classification, test_size=0.15)\n\n# Classification Using Random Forest Classifier\n\nparam_grid = {}\nrand_cv = {}\nbest_score = 0\nmodels ={}\n\nall_models = {'RandomForest': RandomForestClassifier(n_jobs=-1),\n 'ExtraTreesClassifier': ExtraTreesClassifier(n_jobs=-1)}\n\nparam_grid['RandomForest'] = {'max_features': ['auto', 'log2', None], 'class_weight': ['balanced']}\nparam_grid['ExtraTreesClassifier'] = {'class_weight': ['balanced'], 'max_features': ['auto', 'log2', 'sqrt', None]}\n\nfor name, model in all_models.items():\n rand_cv[name] = RandomizedSearchCV(model,\n param_grid[name],\n cv=5,\n scoring='accuracy',\n n_iter=3,\n random_state=2017,\n refit='accuracy',\n return_train_score=True,\n n_jobs=3)\n # Fit the model\n rand_cv[name].fit(X_class_train[features_classification.get('column')], Y_class_train)\n if rand_cv[name].best_score_ > best_score:\n best_score = rand_cv[name].best_score_\n best_model_name = name\n models[name] = rand_cv[name].best_estimator_\n joblib.dump(models[best_model_name], best_model_name+'.pkl')\n\n# Training data prediction\n\nloaded_model = joblib.load('RandomForest.pkl')\n\nrf_class = loaded_model.predict(X_class_train[features_classification.get('column')])\nprint('Training Data Accuracy:', accuracy_score(Y_class_train, rf_class)*100)\n\nrf_class_test = loaded_model.predict(X_class_test[features_classification.get('column')])\nprint('Test Data Accuracy:',accuracy_score(Y_class_test, rf_class_test)*100)\n\nfeature_importance_pd = pd.DataFrame({\"Feature\":features_classification.get('column'),\n \"Importance\":loaded_model.feature_importances_})\nfeature_importance_pd.to_csv('feature_importance_classification.csv',index=False)\n\n\nloaded_model.predict_proba(X_class_test[features_classification.get('column')])","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":14596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"536503616","text":"import numpy as np\nimport os\nimport unittest\n\nfrom amset.utils.constants import comp_to_dirname\nfrom amset.utils.band_structure import kpts_to_first_BZ, get_closest_k, \\\n remove_duplicate_kpoints, get_bindex_bspin\nfrom amset.utils.band_interpolation import get_energy_args, interpolate_bs, get_bs_extrema\nfrom pymatgen.io.vasp import Vasprun\n\n\ntdir = os.path.join(os.path.dirname(__file__), '..', '..', 'test_files')\nvruns = {c: Vasprun(os.path.join(tdir, comp_to_dirname[c], 'vasprun.xml')) \\\n for c in comp_to_dirname}\ncoeff_files = {c: os.path.join(tdir, comp_to_dirname[c], 'fort.123') \\\n for c in comp_to_dirname}\n\nCHECK_BOLTZTRAP2 = True\n\nclass AmsetToolsTest(unittest.TestCase):\n def setUp(self):\n pass\n\n def listalmostequal(self, list1, list2, places=3):\n for l1, l2 in zip(list1, list2):\n self.assertAlmostEqual(l1, l2, places=places)\n\n def test_get_bs_extrema(self):\n extrema = get_bs_extrema(bs=vruns['GaAs'].get_band_structure(),\n coeff_file=coeff_files['GaAs'], Ecut=1.0)\n # first conduction band extrema:\n self.listalmostequal(extrema['n'][0], [.0, .0, .0], 10)\n self.listalmostequal(extrema['n'][1], [.0, -0.4701101, .0], 4)\n self.assertEqual(len(extrema['n']), 2)\n # last valence band extrema\n self.listalmostequal(extrema['p'][0], [.0, .0, .0], 10)\n self.listalmostequal(extrema['p'][1], [-0.31693, -0.04371, 0.], 4)\n self.assertEqual(len(extrema['p']), 2)\n\n Si_extrema = get_bs_extrema(bs=vruns['Si'].get_band_structure(),\n coeff_file=coeff_files['Si'], Ecut=1.0)\n self.listalmostequal(Si_extrema['n'][0], [0.419204, 0.419204, 0.], 4)\n self.listalmostequal(Si_extrema['n'][1], [-0.4638, -0.4638, -0.4638],4)\n self.listalmostequal(Si_extrema['p'][0], [0.0, 0.0, 0.0], 10)\n self.listalmostequal(Si_extrema['p'][1], [-0.226681, -0.049923, 0.], 3)\n\n PbTe_extrema = get_bs_extrema(bs=vruns['PbTe'].get_band_structure(),\n coeff_file=coeff_files['PbTe'], Ecut=1.0)\n self.listalmostequal(PbTe_extrema['n'][0], [0. , 0.5, 0. ], 10)\n self.listalmostequal(PbTe_extrema['n'][1], [.1522, -.0431, .1522], 4)\n self.listalmostequal(PbTe_extrema['p'][0], [0. , 0.5, 0. ], 10)\n self.listalmostequal(PbTe_extrema['p'][1], [.4784, -.2709, .2278], 3)\n self.listalmostequal(PbTe_extrema['p'][2], [.162054 , .162054, 0.], 3)\n\n InP_extrema = get_bs_extrema(bs=vruns['InP'].get_band_structure(),\n coeff_file=coeff_files['InP'], Ecut=1.0)\n self.listalmostequal(InP_extrema['n'][0], [0. , 0.0, 0. ], 10)\n self.listalmostequal(InP_extrema['n'][1], [0. , 0.5, 0. ], 10)\n self.listalmostequal(InP_extrema['p'][0], [0. , 0.0, 0. ], 10)\n self.listalmostequal(InP_extrema['p'][1], [-0.3843 , -0.0325, 0.], 4)\n\n AlCuS2_extrema = get_bs_extrema(bs=vruns['AlCuS2'].get_band_structure(),\n coeff_file=coeff_files['AlCuS2'], Ecut=1.0)\n self.listalmostequal(AlCuS2_extrema['n'][0], [0. , 0.0, 0.0 ], 10)\n self.listalmostequal(AlCuS2_extrema['n'][1], [0. , 0.0, 0.5 ], 10)\n self.listalmostequal(AlCuS2_extrema['n'][2], [-0.49973, -0.49973, 0.], 4)\n self.listalmostequal(AlCuS2_extrema['n'][3], [0.49047, 0.49047, 0.49818], 4)\n self.listalmostequal(AlCuS2_extrema['p'][0], [0. , 0.0, 0.0 ], 10)\n self.listalmostequal(AlCuS2_extrema['p'][1], [0.28291, 0., -0.40218], 4)\n self.listalmostequal(AlCuS2_extrema['p'][2], [-0.25765, 0.25148, 0.], 4)\n self.listalmostequal(AlCuS2_extrema['p'][3], [-0.49973, -0.49973, 0.], 4)\n\n In2O3_extrema = get_bs_extrema(bs=vruns['In2O3'].get_band_structure(),\n coeff_file=coeff_files['In2O3'], Ecut=1.0)\n self.listalmostequal(In2O3_extrema['n'][0], [0. , 0.0, 0.0 ], 10)\n self.listalmostequal(In2O3_extrema['p'][0], [0. , 0.09631, 0.0 ], 4)\n self.listalmostequal(In2O3_extrema['p'][1], [0.30498, 0.30498, 0.18299], 4)\n\n\n def test_kpts_to_first_BZ(self):\n kpts_orig = [[0.51, 1.00, -0.50], [1.40, -1.20, 0.49]]\n kpts_trns = [[-0.49, 0.00, -0.50], [0.40, -0.20, 0.49]]\n # self.assertListEqual() #doesn't work as they differ at 7th decimal\n for ik, k in enumerate(kpts_to_first_BZ(kpts_orig)):\n np.testing.assert_array_almost_equal(kpts_trns[ik], k, 7)\n self.assertTrue(isinstance(kpts_to_first_BZ(kpts_orig), list))\n\n\n def test_get_closest_k(self):\n kpts = np.array([[0.51, -0.5, 0.5], [0.4, 0.5, 0.51]])\n np.testing.assert_array_equal([0.4 , 0.5, 0.51],\n get_closest_k(np.array([0.5, 0.5, 0.5]), kpts, return_diff=False))\n np.testing.assert_array_almost_equal([0.1 , 0.0, -0.01],\n get_closest_k(np.array([0.5, 0.5, 0.5]), kpts, return_diff=True))\n\n\n def test_remove_duplicate_kpoints(self):\n kpts_orig = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.00999],\n [0.25, 0.25, 0.25], [0.25, 0.25, 0.25],\n [0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [0.5, 0.5, -0.5]]\n kpts_out = [[0.0, 0.0, 0.00999],\n [0.25, 0.25, 0.25],\n [0.5, 0.5, -0.5]]\n # print(remove_duplicate_kpoints(kpts_orig))\n self.assertListEqual(kpts_out, remove_duplicate_kpoints(kpts_orig))\n\n\n def test_interpolate_bs(self):\n bs = vruns['GaAs'].get_band_structure()\n vbm_idx, vbm_bidx = get_bindex_bspin(bs.get_vbm(), is_cbm=False)\n cbm_idx, cbm_bidx = get_bindex_bspin(bs.get_cbm(), is_cbm=True)\n dft_vbm = bs.get_vbm()['energy']\n dft_vb = np.array(bs.bands[vbm_bidx][vbm_idx]) - dft_vbm\n dft_cb = np.array(bs.bands[cbm_bidx][cbm_idx]) - dft_vbm\n vbm_idx += 1 # in boltztrap1 interpolation the first band is 1st not 0th\n cbm_idx += 1\n\n kpts = [k.frac_coords for k in bs.kpoints]\n matrix = vruns['GaAs'].lattice.matrix\n\n # get the interpolation parameters\n interp_params1 = get_energy_args(coeff_files['GaAs'], [vbm_idx, cbm_idx])\n\n # calculate and check the last valence and the first conduction bands:\n vb_en1, vb_vel1, vb_masses1 = interpolate_bs(kpts, interp_params1,\n iband=0, method=\"boltztrap1\", scissor=0.0, matrix=matrix)\n cb_en1, cb_vel1, cb_masses1 = interpolate_bs(kpts, interp_params1,\n iband=1, method=\"boltztrap1\", scissor=0.0, matrix=matrix)\n\n vbm = np.max(vb_en1)\n vb_en1 -= vbm\n cb_en1 -= vbm\n interp_gap1 = min(cb_en1) - max(vb_en1)\n self.assertAlmostEqual(bs.get_band_gap()['energy'], interp_gap1, 4)\n self.assertAlmostEqual(interp_gap1, 0.1899, 4)\n\n # check exact match between DFT energy and interpolated band energy\n self.assertAlmostEqual(np.mean(vb_en1 - dft_vb), 0.0, 4)\n self.assertAlmostEqual(np.std(vb_en1 - dft_vb), 0.0, 4)\n self.assertAlmostEqual(np.mean(cb_en1 - dft_cb), 0.0, 4)\n self.assertAlmostEqual(np.std(cb_en1 - dft_cb), 0.0, 4)\n\n # check the average of the velocity vectors; not isotropic since not all sym. eq. kpoints are sampled\n expected_vb_v = [37199316.52376, 64230953.3495545, 30966751.7547101]\n expected_cb_v = [63838832.347664, 78291298.7589355, 69109280.002242]\n self.listalmostequal(np.mean(vb_vel1, axis=0), expected_vb_v, 0)\n self.listalmostequal(np.mean(cb_vel1, axis=0), expected_cb_v,0)\n\n if CHECK_BOLTZTRAP2:\n from amset.utils.pymatgen_loader_for_bzt2 import PymatgenLoader\n from BoltzTraP2 import sphere, fite\n bz2_data = PymatgenLoader(vruns['GaAs'])\n equivalences = sphere.get_equivalences(atoms=bz2_data.atoms,\n nkpt=len(bz2_data.kpoints) * 10, magmom=None)\n lattvec = bz2_data.get_lattvec()\n coeffs = fite.fitde3D(bz2_data, equivalences)\n interp_params2 = (equivalences, lattvec, coeffs)\n vb_en2, vb_vel2, vb_masses2 = interpolate_bs(kpts, interp_params2,\n iband=vbm_idx, method=\"boltztrap2\", scissor=0.0, matrix=matrix)\n cb_en2, cb_vel2, cb_masses2 = interpolate_bs(kpts, interp_params2,\n iband=cbm_idx, method=\"boltztrap2\", scissor=0.0, matrix=matrix)\n vbm2 = np.max(vb_en2)\n vb_en2 -= vbm2\n cb_en2 -= vbm2\n interp_gap2 = min(cb_en2) - max(vb_en2)\n self.assertAlmostEqual(interp_gap1, interp_gap2, 4)\n self.assertAlmostEqual(np.mean(vb_en1 - vb_en2), 0.0, 4)\n self.assertAlmostEqual(np.std(vb_en1 - vb_en2), 0.0, 4)\n self.assertAlmostEqual(np.mean(cb_en1 - cb_en2), 0.0, 4)\n self.assertAlmostEqual(np.std(cb_en1 - cb_en2), 0.0, 4)\n vb_avg2 = np.mean(vb_vel2, axis=0)\n cb_avg2 = np.mean(cb_vel2, axis=0)\n for i in range(3):\n self.assertLessEqual(1-abs(vb_avg2[i]/expected_vb_v[i]), 0.001)\n self.assertLessEqual(1-abs(cb_avg2[i] / expected_cb_v[i]), 0.001)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"amset/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":9213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"154379332","text":"import tensorflow as tf\nimport numpy as np\n\nfrom typing import List\n\n\ndef max_detection(soft_mask, window_size: List, threshold: float):\n\n sm_shape = soft_mask.get_shape().as_list()\n n_dim = len(sm_shape) - 2\n sm_dims = [sm_shape[i + 1] for i in range(n_dim)]\n w_dims = [window_size[i + 1] for i in range(n_dim)]\n w_dims_padded = [1, *w_dims, 1]\n\n if n_dim == 2:\n data_format = \"NHWC\"\n pool_func = tf.nn.max_pool2d\n conv_transpose = tf.nn.conv2d_transpose\n elif n_dim == 3:\n data_format = \"NDHWC\"\n pool_func = tf.nn.max_pool3d\n conv_transpose = tf.nn.conv3d_transpose\n\n max_pool = pool_func(\n soft_mask, w_dims_padded, w_dims_padded, padding=\"SAME\", data_format=data_format\n )\n\n conv_filter = np.ones([*w_dims, 1, 1])\n\n upsampled = conv_transpose(\n max_pool,\n conv_filter.astype(np.float32),\n [1, *sm_dims, 1],\n w_dims_padded,\n padding=\"SAME\",\n data_format=data_format,\n name=\"nms_conv_0\",\n )\n\n maxima = tf.equal(upsampled, soft_mask)\n threshold_maxima = tf.logical_and(maxima, soft_mask >= threshold)\n maxima = threshold_maxima\n\n # Fix doubles\n # Check the necessary window size and adapt for isotropic vs unisotropic nms:\n double_suppresion_window = [1, *[1 if dim == 1 else 3 for dim in w_dims], 1]\n # add 1 to all local maxima\n sm_maxima = tf.add(tf.cast(maxima, tf.float32), soft_mask)\n\n # sm_maxima smoothed over large window\n max_pool = pool_func(\n sm_maxima,\n double_suppresion_window,\n [1 for _ in range(n_dim + 2)],\n padding=\"SAME\",\n data_format=data_format,\n )\n\n # not sure if this does anything\n conv_filter = np.ones([1 for _ in range(n_dim + 2)])\n upsampled = conv_transpose(\n max_pool,\n conv_filter.astype(np.float32),\n [1, *sm_dims, 1],\n [1 for _ in range(n_dim + 2)],\n padding=\"SAME\",\n data_format=data_format,\n name=\"nms_conv_1\",\n )\n\n reduced_maxima = tf.equal(upsampled, sm_maxima)\n reduced_maxima = tf.logical_and(reduced_maxima, sm_maxima > 1)\n reduced_maxima = tf.reshape(reduced_maxima, sm_shape)\n\n if n_dim == 2:\n return (\n tf.reshape(maxima, sm_dims, name=\"maxima\"),\n tf.reshape(reduced_maxima, sm_dims, name=\"reduced_maxima\"),\n )\n elif n_dim == 3:\n return (\n tf.reshape(maxima, sm_dims, name=\"maxima\"),\n tf.reshape(reduced_maxima, sm_dims, name=\"reduced_maxima\"),\n )\n","sub_path":"neurolight/networks/tensorflow/nms.py","file_name":"nms.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"138642596","text":"import simplemonads as sm\nfrom test_reader import TestReader\n\n\ndef produce_dict(*_):\n item = dict()\n item[\"count\"] = 0\n return item\n\n\nclass Web:\n def popup(self, x):\n try:\n browser = __import__(\"browser\")\n except:\n browser = sm.Printer()\n\n tpl = '\"\n browser.window.Vue.component(\n \"button-counter\",\n {\"data\": produce_dict, \"template\": tpl},\n )\n browser.window.Vue.new({\"el\": \".web1\"})\n\n\n@sm.run\ndef main():\n return TestReader.app() + Web\n","sub_path":"tests/test_web1.py","file_name":"test_web1.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"220218579","text":"# -*- coding: utf-8 -*-\n\"\"\"Tests for the models.model_api of hydromt.\"\"\"\n\nimport os\nfrom os.path import join, isfile\nimport xarray as xr\nimport numpy as np\nfrom affine import Affine\nimport logging\n\nfrom pyflwdir import core_d8\nimport hydromt\nfrom hydromt import raster\nfrom hydromt.models import MODELS\nfrom hydromt.models.model_api import Model\n\n__all__ = [\"TestModel\"]\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestModel(Model):\n _NAME = \"testname\"\n _CONF = \"test.ini\"\n _GEOMS = {}\n _MAPS = {\"elevtn\": \"dem\", \"flwdir\": \"ldd\", \"basins\": \"basins\", \"mask\": \"mask\"}\n _FOLDERS = [\"data\"]\n\n def __init__(\n self, root=None, mode=\"w\", config_fn=None, data_libs=None, logger=logger\n ):\n super().__init__(\n root=root,\n mode=mode,\n config_fn=config_fn,\n data_libs=data_libs,\n logger=logger,\n )\n\n def setup_basemaps(self, region, res=0.5, crs=4326, add_geom=False):\n _maps = {\n \"elevtn\": {\"func\": _rand_float, \"nodata\": -9999.0},\n \"flwdir\": {\"func\": _rand_d8, \"nodata\": core_d8._mv},\n \"mask\": {\"func\": _rand_msk, \"nodata\": -1},\n \"basins\": {\"func\": _rand_msk, \"nodata\": -1},\n }\n ds_base = _create_staticmaps(_maps, region[\"bbox\"], res)\n self.set_crs(crs)\n rmdict = {k: v for k, v in self._MAPS.items() if k in ds_base.data_vars}\n self.set_staticmaps(ds_base.rename(rmdict))\n if add_geom:\n self.set_staticgeoms(self.region, \"region\")\n\n def setup_param(self, name, value):\n nodatafloat = -999\n da_param = xr.where(self.staticmaps[self._MAPS[\"basins\"]], value, nodatafloat)\n da_param.raster.set_nodata(nodatafloat)\n\n da_param = da_param.rename(name)\n self.set_staticmaps(da_param)\n\n def read_staticmaps(self):\n fn = join(self.root, \"staticmaps.nc\")\n if not self._write:\n self._staticmaps = xr.Dataset()\n if fn is not None and isfile(fn):\n self.logger.info(f\"Read staticmaps from {fn}\")\n ds = xr.open_dataset(fn, mask_and_scale=False).load()\n ds.close()\n self.set_staticmaps(ds)\n\n def write_staticmaps(self):\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n ds_out = self.staticmaps\n fn = join(self.root, \"staticmaps.nc\")\n self.logger.info(f\"Write staticmaps to {fn}\")\n ds_out.to_netcdf(fn)\n\n\ndef _rand_float(shape, dtype=np.float32):\n return np.random.rand(*shape).astype(dtype)\n\n\ndef _rand_d8(shape):\n d8 = core_d8._ds.ravel()\n return d8.flat[np.random.randint(d8.size, size=shape)]\n\n\ndef _rand_msk(shape):\n mks = np.array([0, 1, 2], dtype=np.int8)\n return mks[np.random.randint(mks.size, size=shape)]\n\n\ndef _create_staticmaps(_maps, bbox, res):\n w, s, e, n = bbox\n shape = (6, 10)\n transform = Affine(res, w, e, s, res, n)\n data_vars = {n: (_maps[n][\"func\"](shape), _maps[n][\"nodata\"]) for n in _maps}\n ds = raster.RasterDataset.from_numpy(data_vars=data_vars, transform=transform)\n ds.raster.set_crs(4326)\n return ds\n","sub_path":"tests/testclass.py","file_name":"testclass.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"556634157","text":"import os, commands, gzip, argparse\nimport pandas as pd\nparser = argparse.ArgumentParser()\nparser.add_argument(\"tissue\", help=\"tissue being analyzed\")\nparser.add_argument(\"temp\", help=\"Location of temp directory for snakefile flag\")\nparser.add_argument(\"--exclude\", help=\"List of subject IDs to exclude (e.g. non-Europeans\",default=\"None\")\nparser.add_argument(\"--search_terms\", help=\"search terms to identify tissue in E-MTAB-5214. Max of 2\",\n action=\"append\",nargs=\"+\")\nargs = parser.parse_args()\n\n##############Collect tissue-specific expression data#################\n# For a given tissue, this script identifies samples for which there are both GTEx genotype data and gene expression data.\n# It then writes out a subject ID list of these subjects, a sample ID list of the corresponding samples, and a matrix of all the expression values for these samples.\n# These files will be used to make plinks and compute TWAS weights.\n#######################################################################\n\n#Grab every subject ID with a genotype from the *vcf with bcftools\ncmd=\"bcftools query -l /project2/yangili1/GTEx/GTEx_Analysis_2016-01-15_v7_WholeGenomeSeq_635Ind_PASS_AB02_GQ20_HETX_MISS15_PLINKQC.MAF01.vcf.gz\"\nstatus, output = commands.getstatusoutput(cmd)\ngeno_IDs=list(output.split('\\n'))\n\n#If exclude flag, remove ones that aren't white :/\nif args.exclude != \"None\":\n with open(args.exclude,'r') as excl_file:\n exclude_IDs=excl_file.readlines()\n exclude_IDs = ' '.join(exclude_IDs).replace('\\n','').split()\n geno_IDs=list(set(geno_IDs)-set(exclude_IDs))\n\n#Open up output files\nsubject_IDs=open(\"%s/%s_subject_IDs\"%(args.tissue,args.tissue),\"w\")\nsample_IDs=open(\"%s/%s_sample_IDs\"%(args.tissue,args.tissue),\"w\")\ntissue_tpm=open(\"%stemp\"%(args.temp),\"w\")\nwith open(\"GTEx_tpm.gct\") as GTEx_tpm:\n header=GTEx_tpm.readlines()[1]\ntissue_tpm.write(header)\n\n#For every subject with a genotype, find sample IDs from the tissue of interest\nfor subject_ID in geno_IDs:\n terms=args.search_terms[0]\n if len(terms)==1:\n term1=str(terms)\n cmd=\"grep %s /project2/yangili1/GTEx/E-MTAB-5214.sdrf.txt | grep %s | cut -f1 | sort -u\"%(subject_ID,term1)\n else:\n term1,term2=terms\n cmd=\"grep %s /project2/yangili1/GTEx/E-MTAB-5214.sdrf.txt | grep %s | grep %s | cut -f1 | sort -u\"%(subject_ID,term1,term2)\n status, output = commands.getstatusoutput(cmd)\n subject_sample_IDs=list(output.split('\\n'))\n\n #For each sample ID from the tissue of interest for a given subject, look for gene expression data. If found, write sample and subject IDs to file, write gene expression data to file. \n if len(subject_sample_IDs)==1:\n if not len(subject_sample_IDs[0])==0:\n cmd=\"grep %s /project2/yangili1/grace/expression/GTEx_tpm.gct\"%(subject_sample_IDs[0])\n status, output = commands.getstatusoutput(cmd)\n if len(output) != 0:\n subject_IDs.write(subject_ID+'\\t'+subject_ID+'\\n')\n sample_IDs.write(subject_sample_IDs[0]+'\\n')\n tissue_tpm.write(output+'\\n')\n else: \n for subject_sample_ID in subject_sample_IDs:\n cmd=\"grep %s /project2/yangili1/grace/expression/GTEx_tpm.gct\"%(subject_sample_ID)\n status, output = commands.getstatusoutput(cmd)\n if len(output) != 0:\n subject_IDs.write(subject_ID+'\\t'+subject_ID+'\\n')\n sample_IDs.write(subject_sample_ID+'\\n')\n tissue_tpm.write(output+'\\n')\n break\nsubject_IDs.close()\nsample_IDs.close()\ntissue_tpm.close()\n\n#Transpose the output so genes are rows and GTEx IDs are columns\ntransposed=pd.read_csv(\"%stemp\"%(args.temp),sep='\\t',index_col=0).T\nout=gzip.open(\"%s/%s_GTEx_tpm.txt.gz\"%(args.tissue,args.tissue),'w')\ncol_vals='\\t'.join(str(v) for v in transposed.columns.values)\nout.write('chr'+'\\t'+'coord'+'\\t'+'gene'+'\\t'+col_vals+'\\n')\n\n#For each gene, add chr and TSS to start of its row\nfor ln in transposed.itertuples():\n gene=ln[0]\n line='\\t'.join(str(i) for i in ln)\n cmd=\"awk '/\\t'%s'\\t/' coding_genes.bed\"%(gene)\n status, output = commands.getstatusoutput(cmd)\n if len(output) != 0:\n chrom, s, e, gname, dot, strand, ENSG = output.split('\\t')\n c=chrom.split('r')[1]\n if strand == \"+\":\n coord=s\n else:\n coord=e\n row=c+'\\t'+str(coord)+'\\t'+line+'\\n'\n out.write(row)\n\nout.close()\nos.remove(\"%stemp\"%(args.temp))","sub_path":"expression/scripts/grab_expression.py","file_name":"grab_expression.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"144734769","text":"#!/hpcf/apps/python/install/2.7.13/bin/python\n\nimport pandas as pd\nimport sys\nfile=sys.argv[1]\ndf = pd.read_csv(file,sep=\"\\t\",header=None)\ndf[4] = df[0]+\".\"+df[1].astype(str)+\".\"+df[2].astype(str)\ndf = pd.DataFrame(df.groupby(4)[3].sum())\ndf = df.reset_index()\n#print (df.head())\ntmp = pd.DataFrame(df[4].apply(lambda x:x.split(\".\")).tolist())\ntmp[1] = tmp[1].astype(int)\ntmp[2] = tmp[2].astype(int)\ndf[[5,6,7]] = tmp[[0,1,2]]\ndf = df.sort_values([5,6])\ndf[[5,6,7,3]].to_csv(file,sep=\"\\t\",header=False,index=False)\n\n\n","sub_path":"bin/bdg_correction.py","file_name":"bdg_correction.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"417755289","text":"l = []\nr = []\nfor i in range(3):\n cc = input().split()\n l += [cc[0]]\n r += [cc[-1]]\n\nlSet = set(l)\nrSet = set(r)\n\nfor i in lSet:\n if l.count(i) == 1:\n x = i\n break\n\nfor i in rSet:\n if r.count(i) == 1:\n y = i\n break\n\nprint(x, y)","sub_path":"Cetvrta.py","file_name":"Cetvrta.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"470919254","text":"# pack布局-水平排列(从左向右)\r\n# 从左到右水平排列,从右到左水平排列\r\nfrom tkinter import *\r\nwindow = Tk()\r\nwindow.title('设置水平外边距')\r\nwindow['background'] = 'blue'\r\nwindow.geometry('200x200')\r\nw = Label(window,text='复仇者联盟', bg='red',fg='white')\r\nw.pack(side =LEFT,padx=10,pady =10)\r\nw = Label(window,text='超人', bg='green',fg='yellow')\r\nw.pack(side =RIGHT,fill = X,padx=10,pady = 10)\r\nw = Label(window,text='保卫地球', bg='yellow',fg='blue')\r\nw.pack(side =LEFT, padx=10,pady = 10)\r\nmainloop()","sub_path":"Python学习基础知识/高级python篇/第18章:GUI库:tkinter/Pack布局(水平排列).py","file_name":"Pack布局(水平排列).py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"262232407","text":"\"\"\"5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. \n\nOnce 'done' is entered, print out the largest and smallest of the numbers. \n\nIf the user enters anything other than a valid number catch it with a try/except and put out an \nappropriate message and ignore the number. \n\nEnter 7, 2, bob, 10, and 4 and match the output below.\"\"\"\n\nmaximum = None\nminimum = None\n\nwhile True : \n userEntered = input(\"Enter a number: \")\n # testMax = userEntered\n # testMin = userEntered\n \n if userEntered == 'done' :\n break\n try:\n if maximum is None or float(userEntered) > maximum : \n maximum = float(userEntered)\n elif minimum is None or float(userEntered) < minimum : \n minimum = float(userEntered)\n except:\n print(\"Invalid input\")\nprint('Maximum is', int(maximum))\nprint('Minimum is', int(minimum))\n ","sub_path":"5-2a.py","file_name":"5-2a.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"120614668","text":"#!/usr/bin/env python\n\"\"\"\nFactory for generating instances of classes\n\"\"\"\nimport sys\nfrom collections import OrderedDict as odict\nimport inspect\n\ndef factory(type, module=None, **kwargs):\n \"\"\"\n Factory for creating objects. Arguments are passed directly to the\n constructor of the chosen class.\n \"\"\"\n cls = type\n if module is None: module = __name__\n fn = lambda member: inspect.isclass(member) and member.__module__==module\n classes = odict(inspect.getmembers(sys.modules[module], fn))\n members = odict([(k.lower(),v) for k,v in classes.items()])\n \n lower = cls.lower()\n if lower not in members.keys():\n #msg = \"%s not found in:\\n %s\"%(cls,classes.keys())\n #logging.error(msg)\n msg = \"Unrecognized class: %s\"%cls\n raise Exception(msg)\n\n return members[lower](**kwargs)\n\n\nif __name__ == \"__main__\":\n import argparse\n description = __doc__\n parser = argparse.ArgumentParser(description=description)\n args = parser.parse_args()\n","sub_path":"dmsky/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"39386385","text":"QU = 0\nAC = 1\nPE = 2\nWA = 3\nCE = 4\nRE = 5\nTL = 6\nML = 7\nOL = 8\nSE = 9\nRF = 10\nCJ = 11\n\nverdictcode = [\n 'QU', 'AC', 'PE', 'WA', 'CE', 'RE'\n 'TL', 'ML', 'OL', 'SE', 'RF', 'CJ']\n\nverdicttext = [\n \"In Queue\",\n \"Accepted\",\n \"Presentation Error\",\n \"Wrong Answer\",\n \"Compile Error\",\n \"Runtime Error\",\n \"Time Limit Exceeded\",\n \"Memory Limit Exceeded\",\n \"Output Limit Exceeded\",\n \"Submission Error\",\n \"Restricted Function\",\n \"Can't Be Judged\"\n]\n","sub_path":"gulag/verdict.py","file_name":"verdict.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"299943544","text":"# this component is for greeting the user\r\n\r\ndef greet():\r\n \r\n while True:\r\n name = input(\"What's your name? : \")\r\n if name.isalpha():\r\n break\r\n print(\"Please enter characters A-Z only\")\r\ngreet()#calling the greet function\r\n\r\n","sub_path":"version greet.py","file_name":"version greet.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"579309400","text":"# 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 \n# \n# 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 \n# \n# \n# \n# 示例: \n# \n# 给定 1->2->3->4, 你应该返回 2->1->4->3.\n# \n# Related Topics 链表 \n# 👍 547 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def swapPairs(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n \"\"\"\n 1.三指针迭代,一个辅助哨兵节点pre指向实际链表头部,但不可移动,用tmp结点代替移动\n 需要注意,链表有两种情况,奇数个和偶数个\n 时间复杂度O(N),空间复杂度O(1)\n \"\"\"\n # pre = ListNode(0)\n # pre.next = head\n # tmp = pre\n # while tmp.next and tmp.next.next: # 循环交换的条件:偶数个结点\n # slow = tmp.next\n # fast = tmp.next.next\n # # 交换\n # tmp.next = fast\n # slow.next = fast.next\n # fast.next = slow\n # # tmp 指针移动到下一次交换的结点的前一个位置\n # tmp = slow\n # return pre.next\n \"\"\"\n 2.递归\n 最小重复单元:交换完成的子链表\n 终止条件:head或head.next为空指针,当前无节点,或者只有一个结点\n \"\"\"\n if not head or not head.next:\n return head\n next = head.next\n head.next = self.swapPairs(next.next)\n next.next = head\n return next\n\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_01/leetcode/editor/cn/[24]两两交换链表中的节点.py","file_name":"[24]两两交换链表中的节点.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"96574625","text":"import logging\nfrom django.conf import settings\nfrom datetime import datetime\n#from memory_profiler import profile\nfrom sys import getsizeof\n\nlogger = logging.getLogger(settings.AWS_LOGGER_NAME)\n\ndef time_memory(func):\n \"\"\"Returns the execution time and and memory usage of a function. \"\"\"\n def wrapper(*args, **kwargs):\n t1 = datetime.now()\n data = func(*args, **kwargs)\n t2 = datetime.now()\n total_time = 'decorator - Total time: {}'.format(t2 - t1)\n\n logger.debug(\"decorator - function size: %s\" % getsizeof(data))\n logger.debug(\"decorator - function return type: %s\" % type(data))\n logger.debug(total_time)\n return data\n return wrapper\n","sub_path":"api/decorators/timem.py","file_name":"timem.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"233103336","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Read the Docs.\"\"\"\n\nimport os.path\n\nfrom configparser import RawConfigParser\n\n\ndef get_version(setupcfg_path):\n \"\"\"Return package version from setup.cfg.\"\"\"\n config = RawConfigParser()\n config.read(setupcfg_path)\n return config.get('metadata', 'version')\n\n\n__version__ = get_version(\n os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..', 'setup.cfg'),\n ),\n)\n","sub_path":"readthedocs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"385796930","text":"#!/usr/bin/env python\r\n\r\n# Script Name\t: cm13_snapshot_seeker_jfltexx.py\r\n# Author\t\t: Etienne Bauens\r\n# Created\t\t: 18.02.2016\r\n# Last Modified\t: 02.03.2016\r\n# Version\t\t: 1.0\r\n# Description\t: Simple Daemon which checks for the CyanogenMod 13 snapshot release for the jfltexx every hour and\r\n# notifies user in case of release. GUI made possible by wxPython.\r\n\r\n\r\nimport wx\r\nimport urllib\r\nimport re\r\nimport threading\r\nimport os\r\n\r\nTRAY_TOOLTIP = 'CM 13 Snapshot Seeker'\r\nTRAY_ICON = 'icon.png'\r\nURL = 'http://get.cm/?device=jfltexx&type=snapshot'\r\n\r\ndef wait_loop():\r\n threading.Timer(3600, wait_loop).start()\r\n if go_check() == True:\r\n wx.MessageBox('CM 13 Snapshot finally available!')\r\n else:\r\n pass\r\n\r\n\r\ndef go_check():\r\n raw_content = urllib.urlopen(URL)\r\n content = raw_content.read().decode('utf-8')\r\n match = re.search('cm-13', content)\r\n if bool(match) == True:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef create_menu_item(menu, label, func):\r\n item = wx.MenuItem(menu, -1, label)\r\n menu.Bind(wx.EVT_MENU, func, id=item.GetId())\r\n menu.AppendItem(item)\r\n return item\r\n\r\n\r\nclass TaskBarIcon(wx.TaskBarIcon):\r\n def __init__(self):\r\n super(TaskBarIcon, self).__init__()\r\n self.set_icon(TRAY_ICON)\r\n self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)\r\n\r\n def CreatePopupMenu(self):\r\n menu = wx.Menu()\r\n create_menu_item(menu, 'Check for CM 13', self.check)\r\n menu.AppendSeparator()\r\n create_menu_item(menu, 'Exit', self.on_exit)\r\n return menu\r\n\r\n def set_icon(self, path):\r\n icon = wx.IconFromBitmap(wx.Bitmap(path))\r\n self.SetIcon(icon, TRAY_TOOLTIP)\r\n\r\n def on_left_down(self, event):\r\n self.availability()\r\n\r\n def check(self, event):\r\n self.availability()\r\n\r\n\r\n def on_exit(self, event):\r\n wx.CallAfter(self.Destroy)\r\n os.system('taskkill /f /im snapshot_seeker.exe')\r\n\r\n def availability(self):\r\n if go_check() == True:\r\n wx.MessageBox('CM 13 Snapshot finally available!')\r\n else:\r\n wx.MessageBox('No CM 13 Snapshot has been released yet')\r\n\r\n\r\ndef main():\r\n app = wx.App(False)\r\n TaskBarIcon()\r\n if go_check() == True:\r\n wx.MessageBox('CM 13 Snapshot finally available!')\r\n else:\r\n wait_loop()\r\n app.MainLoop()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"src/cm13_snapshot_seeker_jfltexx.py","file_name":"cm13_snapshot_seeker_jfltexx.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"414339796","text":"#!/usr/bin/env python3\n\nimport sys\nsys.path.append(\"..\")\nfrom Bank.BankList import BankList\nimport cgi\n\nform = cgi.FieldStorage()\ndownloadId = form.getvalue('downloadId')\ndownloadName = form.getvalue('downloadName')\noperation = form.getvalue('operation')\noperationName = form.getvalue('operationName')\nvalid = form.getvalue('valid')\nodp = form.getvalue('odp')\nStatus = form.getvalue('Status')\n\nprint(\"Content-type: text/html\")\nprint()\n\nhtml_template = open(\"./cgi-bin/template.html\", \"r\", encoding=\"utf-8\").read()\nhtml_template = html_template.replace(\"{{STYLE}}\", \"\"\"\"\"\")\n\ntinkoff_content = open(\"./cgi-bin/tinkoff/tinkoff.html\", \"r\", encoding=\"utf-8\").read()\n\nhtml_template = html_template.replace(\"{{CONTENT}}\", tinkoff_content)\nhtml_template = html_template.replace(\"{{SCRIPT}}\",\n \"\"\"\\n\"\"\"\n \"\"\"\\n\"\"\")\n\nbank = BankList.get_by_name(\"Тинькофф\")\n\nmain_acc_data = bank.main_acc_data()\n\nmain_acc_header = \"\"\nmain_acc_cont = \"\"\n\nfor field in main_acc_data:\n main_acc_header += \"{}\".format(field)\n main_acc_cont += \"{}\".format(main_acc_data[field])\n\nmain_acc_header += \"\"\nmain_acc_cont += \"\"\n\nhtml_template = html_template.replace(\"{{mainAccountDataHeader}}\", main_acc_header)\nhtml_template = html_template.replace(\"{{mainAccountDataContent}}\", main_acc_cont)\n\nacc_list = bank.acc_list()\n\nacc_header = \"\"\nacc_cont = \"\"\n\nfirst_line = True\n\nfor acc in acc_list:\n acc_cont += \"\"\n\n for field in acc:\n\n if first_line:\n acc_header += \"{}\".format(field)\n\n acc_cont += \"{}\".format(acc[field])\n\n first_line = False\n acc_cont += \"\"\n\nacc_header += \"\"\n\nhtml_template = html_template.replace(\"{{accountDataHeader}}\", acc_header)\nhtml_template = html_template.replace(\"{{accountDataContent}}\", acc_cont)\n\nprint(html_template)\n","sub_path":"cgi-bin/tinkoff/tinkoff.py","file_name":"tinkoff.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"499948190","text":"import re\nimport sys\nimport matplotlib.pyplot as plt\n\nprint('reading: ',sys.argv[1])\niter = []\nloss = []\nfor line in open(sys.argv[1]):\n it = re.search('iteration[\\s\\d]{,9}/[\\s\\d]{,8}',line)\n lm = re.search('lm loss [\\d].[\\d]{,9}E\\+[\\d]{2}',line) \n if lm:\n iter.append(int(it.group(0)[11:18]))\n loss.append(float(lm.group(0)[8:20]))\n #print(int(it.group(0)[11:18]),float(lm.group(0)[8:20]))\nplt.plot(iter,loss)\nplt.xlabel('iterations')\nplt.ylabel('lm loss')\nplt.grid()\nplt.show()\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"167274779","text":"import numpy as np\nimport torch\nimport matplotlib.pyplot as plt\n\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\n\n# number of subprocesses to use for data loading\nnum_workers = 0\n# how many samples per batch to load\nbatch_size = 64\n\n# convert data to torch.FloatTensor\ntransform = transforms.ToTensor()\n\n# get the training datasets\ntrain_data = datasets.MNIST(root='data', train=True,\n download=True, transform=transform)\n\n# prepare data loader\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,\n num_workers=num_workers)\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Discriminator(nn.Module):\n\n def __init__(self, input_size, hidden_dim, output_size):\n super(Discriminator, self).__init__()\n\n # define hidden linear layers\n self.fc1 = nn.Linear(input_size, hidden_dim * 4)\n self.fc2 = nn.Linear(hidden_dim * 4, hidden_dim * 2)\n self.fc3 = nn.Linear(hidden_dim * 2, hidden_dim)\n\n # final fully-connected layer\n self.fc4 = nn.Linear(hidden_dim, output_size)\n\n # dropout layer\n self.dropout = nn.Dropout(0.3)\n\n def forward(self, x):\n # flatten image\n x = x.view(-1, 28 * 28)\n # all hidden layers\n x = F.leaky_relu(self.fc1(x), 0.2) # (input, negative_slope=0.2)\n x = self.dropout(x)\n x = F.leaky_relu(self.fc2(x), 0.2)\n x = self.dropout(x)\n x = F.leaky_relu(self.fc3(x), 0.2)\n x = self.dropout(x)\n # final layer\n out = self.fc4(x)\n\n return out\n\n\nclass Generator(nn.Module):\n\n def __init__(self, input_size, hidden_dim, output_size):\n super(Generator, self).__init__()\n\n # define hidden linear layers\n self.fc1 = nn.Linear(input_size, hidden_dim)\n self.fc2 = nn.Linear(hidden_dim, hidden_dim * 2)\n self.fc3 = nn.Linear(hidden_dim * 2, hidden_dim * 4)\n\n # final fully-connected layer\n self.fc4 = nn.Linear(hidden_dim * 4, output_size)\n\n # dropout layer\n self.dropout = nn.Dropout(0.3)\n\n def forward(self, x):\n # all hidden layers\n x = F.leaky_relu(self.fc1(x), 0.2) # (input, negative_slope=0.2)\n x = self.dropout(x)\n x = F.leaky_relu(self.fc2(x), 0.2)\n x = self.dropout(x)\n x = F.leaky_relu(self.fc3(x), 0.2)\n x = self.dropout(x)\n # final layer with tanh applied\n out = torch.tanh(self.fc4(x))\n\n return out\n\n# Discriminator hyperparams\n\n# Size of input image to discriminator (28*28)\ninput_size = 784\n# Size of discriminator output (real or fake)\nd_output_size = 1\n# Size of last hidden layer in the discriminator\nd_hidden_size = 32\n\n# Generator hyperparams\n\n# Size of latent vector to give to generator\nz_size = 100\n# Size of discriminator output (generated image)\ng_output_size = 784\n# Size of first hidden layer in the generator\ng_hidden_size = 32\n\nD = Discriminator(input_size,d_hidden_size,d_output_size)\nG = Generator(z_size,g_hidden_size,g_output_size)\n\nprint(D)\nprint()\nprint(G)\n\ndef real_loss(D_out,smooth=False):\n batch_size = D_out.size(0)\n if smooth:\n labels = torch.ones(batch_size)*0.9\n else:\n labels = torch.ones(batch_size)\n\n criterion = nn.BCEWithLogitsLoss()\n loss = criterion(D_out.squeeze(),labels)\n\n return loss\n\ndef fake_loss(D_out):\n batch_size = D_out.size(0)\n labels = torch.zeros(batch_size) # fake labels = 0\n criterion = nn.BCEWithLogitsLoss()\n # calculate loss\n loss = criterion(D_out.squeeze(), labels)\n return loss\n\nimport torch.optim as optim\n\nlr = 0.002\nd_optimizer = optim.Adam(D.parameters(),lr)\ng_optimizer = optim.Adam(G.parameters(),lr)\n\n\nimport pickle as pkl\nnum_epoch = 100\n\nsamples =[]\nlosses = []\nprint_every=400\n\nsample_size = 16\nfixed_z = np.random.uniform(-1,1,size=(sample_size,z_size))\nfixed_z = torch.from_numpy(fixed_z).float()\nD.train()\nG.train()\n\"\"\"\n\n\nfor epoch in range(num_epoch):\n for batch_i,(real_images,_) in enumerate(train_loader):\n batch_size = real_images.size(0)\n real_images = real_images*2-1\n\n # 先训练判别器,\n #1.在真实图像上训练\n d_optimizer.zero_grad()\n D_real = D(real_images)\n d_loss_real = real_loss(D_real,smooth=True)\n # 2.在生成图像上训练\n z = np.random.uniform(-1, 1, size=(batch_size, z_size))\n z = torch.from_numpy(z).float()\n fake_images = G(z)\n\n D_fake = D(fake_images)\n d_loss_fake = fake_loss(D_fake)\n\n d_loss = d_loss_fake+d_loss_real\n d_loss.backward()\n d_optimizer.step()\n\n # 训练生成器\n\n g_optimizer.zero_grad()\n # 在真实标签下训练生成器\n # Generate fake images\n z = np.random.uniform(-1, 1, size=(batch_size, z_size))\n z = torch.from_numpy(z).float()\n fake_images = G(z)\n\n # Compute the discriminator losses on fake images\n # using flipped labels!\n D_fake = D(fake_images)\n g_loss = real_loss(D_fake) # use real loss to flip labels\n\n # perform backprop\n g_loss.backward()\n g_optimizer.step()\n # Print some loss stats\n if batch_i % print_every == 0:\n # print discriminator and generator loss\n print('Epoch [{:5d}/{:5d}] | d_loss: {:6.4f} | g_loss: {:6.4f}'.format(\n epoch + 1, num_epoch, d_loss.item(), g_loss.item()))\n\n ## AFTER EACH EPOCH##\n # append discriminator loss and generator loss\n losses.append((d_loss.item(), g_loss.item()))\n\n # generate and save sample, fake images\n G.eval() # eval mode for generating samples\n samples_z = G(fixed_z)\n samples.append(samples_z)\n G.train() # back to train mode\n\n# Save training generator samples\nwith open('train_samples.pkl', 'wb') as f:\n pkl.dump(samples, f)\n\n\"\"\"\n# helper function for viewing a list of passed in sample images\ndef view_samples(epoch, samples):\n fig, axes = plt.subplots(figsize=(7,7), nrows=4, ncols=4, sharey=True, sharex=True)\n for ax, img in zip(axes.flatten(), samples[epoch]):\n img = img.detach()\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n im = ax.imshow(img.reshape((28,28)), cmap='Greys_r')\n\n# Load samples from generator, taken while training\nwith open('train_samples.pkl', 'rb') as f:\n samples = pkl.load(f)\n\n\n# -1 indicates final epoch's samples (the last in the list)\nview_samples(-1, samples)\nplt.show()","sub_path":"GANmnist.py","file_name":"GANmnist.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"4615763","text":"# cook your dish here\nimport math\ntest=int(input())\nfor i in range(0,test):\n n=int(input())\n weights=[int(x) for x in input().split()]\n location=[int(x) for x in input().split()]\n d1=dict();\n for i in range(1,n+1):\n d1[i]=weights.index(i)\n jump=0\n for i in range(2,n+1):\n l1=d1[i];\n l2=d1[i-1];\n l3=0;\n if(l2>=l1):\n l3=math.ceil(((l2-l1+1)/location[l1]));\n jump+=l3;\n d1[i]=d1[i]+l3*location[l1];\n \n print(jump)\n","sub_path":"Codechef/FebLongChallenge/frogsort.py","file_name":"frogsort.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"36912481","text":"# PALINDROME BILDER\n\n# Create a function named create palindrome following your current language's style guide. It should take a string, create a palindrome from it and then return it.\n\n# UI\nimport os\nos.system(\"cls\" if os.name == \"nt\" else \"clear\")\n\nprint(\"Welcome, I am Pali, the Palindrome Creator!\")\n\nword = input(\"Please enter a word and I will creat a palindrome from it: \")\n\n# Function the bauilds the palindrome\ndef create_palindrome(palindrome):\n dorw = word[::-1]\n palindrome = word + dorw\n return palindrome\n\n# Display\nprint(create_palindrome(word))\n","sub_path":"week-02/weekly/palindrome-builder.py","file_name":"palindrome-builder.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"446717503","text":"##Chris Allen\n\nfrom API.Device.DeviceBase.DeviceBase import DeviceBase\nfrom API.Device.DeviceBase.ConfigBase.ConfigBase import Config as ConfigBase\nfrom API.Device.DeviceBase.ConfigBase.ConfigItems.Interfaces import Lan, Internet, WirelessRouterInterface\nfrom API.Device.DeviceBase.PhysicalBase.PhysicalBase import Physical\nfrom API.ComponentBox import ComponentBoxConst\n\nfrom API.Device.DeviceBase.WirelessGuiBase.RouterGui import Gui\n\n\nclass Interface:\n def __init__(self, parent):\n self.squishName = parent.squishName\n self.internet = Internet(self)\n self.lan = Lan(self)\n self.wireless = WirelessRouterInterface(self)\n \n def updateName(self, squishName):\n self.squishName = squishName\n self.internet.updateName(squishName)\n self.lan.updateName(squishName)\n self.wireless.updateName(squishName)\n \nclass Config(ConfigBase):\n def __init__(self, parent):\n self.squishName = parent.squishName\n super(Config, self).__init__(self)\n self.interface = Interface(self)\n \n def updateName(self, squishName):\n self.squishName = squishName\n super(Config, self).updateName(squishName)\n self.interface.updateName(squishName)\n \n\nclass LinksysRouter(DeviceBase):\n def __init__(self, p_model, p_x, p_y, p_displayName):\n self.deviceType = ComponentBoxConst.DeviceType.WIRELESS_DEVICE\n super(LinksysRouter, self).__init__(p_model, p_x, p_y, p_displayName, self.deviceType)\n self.config = Config(self)\n self.physical = Physical(self)\n self.gui = Gui(self)\n \n def updateName(self):\n super(LinksysRouter, self).updateName()\n self.config.updateName(self.squishName)\n self.physical.updateName(self.squishName)\n self.gui.updateName(self.squishName)","sub_path":"trunk/workspace/Squish/src/API/Device/LinksysRouter/LinksysRouter.py","file_name":"LinksysRouter.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"408954847","text":"import torch\nimport torch.nn as nn\n\n\nclass SkipGram(nn.Module):\n def __init__(self, V: int, embedding_dim=100):\n \"\"\"\n :param V: the size of vocabulary\n :param embedding_dim: the number of dimensions of word vector\n \"\"\"\n super(SkipGram, self).__init__()\n\n self.embedding_dim = embedding_dim\n self.in_embeddings = nn.Embedding(V, embedding_dim, sparse=True)\n self.out_embeddings = nn.Embedding(V, embedding_dim, sparse=True)\n self.reset_parameters()\n\n def reset_parameters(self):\n upper = 0.5 / self.embedding_dim\n self.in_embeddings.weight.data.uniform_(-upper, upper)\n self.out_embeddings.weight.data.zero_()\n\n def forward(self, inputs, contexts, negatives):\n \"\"\"\n :param inputs: (#mini_batches, 1)\n :param contexts: (#mini_batches, 1)\n :param negatives: (#mini_batches, #negatives)\n :return:\n \"\"\"\n in_vectors = self.in_embeddings(inputs)\n pos_context_vectors = self.out_embeddings(contexts)\n neg_context_vectors = self.out_embeddings(negatives)\n\n pos = torch.sum(in_vectors * pos_context_vectors, dim=(1, 2))\n neg = torch.sum(in_vectors * neg_context_vectors, dim=2)\n\n return pos, neg\n","sub_path":"pytorch_skipgram/model/sgns.py","file_name":"sgns.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"204391643","text":"\"\"\"\n 如果需要根据现有对象复制出新对象, 并对其做一定的修改, 哪么我们可以使用原型模式\n\n 潜复制:\n\n\"\"\"\nimport copy\nimport sys\n\n\nclass Point:\n __slots__ = (\"x\", \"y\")\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\ndef make_objects(Class, *args, **kwargs):\n return Class(*args, **kwargs)\n\n\nprototype1 = Point(1, 2)\nprototype2 = eval(\"{}({}, {})\".format(\"Point\", 2, 4))\nprototype3 = getattr(sys.modules[__name__], \"Point\")(3, 6)\nprototype4 = globals()[\"Point\"](4, 8)\nprototype5 = make_objects(Point, 4, 5)\n\n# 通过clone 对象, 的确可以实现原型模式, 但是第7种方法更加python\nprototype6 = copy.deepcopy(prototype5)\nprototype6.x = 6\nprototype6.y = 12\n\nprototype7 = prototype1.__class__(7, 14)\n","sub_path":"07patterns/builds/Prototypes.py","file_name":"Prototypes.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"261689328","text":"from tkinter import*\nimport ast\n\nPRAZNO = 0\nJAZ = str(\"Beli\")\nON = str(\"Crni\")\nVELIKOST = 5\n\nclass Tabla():\n def __init__(self, master):\n \n self.canvas = Canvas(master, width=600, height=600)\n self.canvas.grid(row=0, column=0)\n\n self.matrika1 = [[PRAZNO] * VELIKOST for _ in range(VELIKOST)]\n self.matrika2 = [[PRAZNO] * VELIKOST for _ in range(VELIKOST)]\n self.na_vrsti = JAZ\n for i in range(6):\n self.canvas.create_line(50, i*100 + 50, 550,i*100 +50)\n self.canvas.create_line(i*100 +50, 50 , i*100 +50, 500 +50)\n self.canvas.bind(\"\", self.izberi)\n self.napis = StringVar()\n label_napis = Label(master, textvariable=self.napis)\n label_napis.grid(row=1, column=0)\n\n menu = Menu(master)\n master.config(menu=menu)\n \n file_menu = Menu(menu)\n menu.add_cascade(label=\"File\", menu=file_menu)\n file_menu.add_command(label=\"Nova igra\", command=self.nova_igra)\n file_menu.add_command(label=\"Shrani\", command=self.shrani)\n file_menu.add_command(label=\"Odpri\", command=self.odpri)\n file_menu.add_separator() \n file_menu.add_command(label=\"Izhod\", command=master.destroy)\n\n def izberi(self, event):\n self.napis.set(\"\")\n x, y = (event.x - 50) // 100, (event.y - 50) // 100\n \n if self.dovoljeno(x, y, self.na_vrsti):\n if self.na_vrsti == JAZ:\n self.matrika1[x][y] = JAZ\n self.na_vrsti = ON\n self.canvas.create_oval(x * 100 + 60, y * 100 + 60, x * 100 + 140, y * 100 + 140)\n else:\n self.matrika2[x][y] = ON\n self.na_vrsti = JAZ\n self.canvas.create_oval(x * 100 + 60, y * 100 + 60, x * 100 + 140, y * 100 + 140, fill=\"black\")\n\n if self.konec_zabave(self.na_vrsti):\n if self.na_vrsti == JAZ:\n self.na_vrsti = ON\n else:\n self.na_vrsti = JAZ\n self.napis.set(\"Konec igre! Zmagal je {0}!\".format(self.na_vrsti))\n\n else:\n self.napis.set(\"Neveljavna poteza!\")\n \n\n def dovoljeno(self, x, y, na_vrsti):\n if self.na_vrsti == JAZ:\n self.matrika = self.matrika2\n else: self.matrika = self.matrika1\n if x>PRAZNO and x< (VELIKOST - 1) and y>PRAZNO and y< (VELIKOST - 1):\n if self.matrika[x-1][y]==PRAZNO and self.matrika[x][y]==PRAZNO and self.matrika[x+1][y]==PRAZNO and self.matrika[x][y+1]==PRAZNO and self.matrika[x][y-1]==PRAZNO:\n return True\n else:\n return False\n \n \n elif x>PRAZNO and x< (VELIKOST - 1) and y==PRAZNO:\n if self.matrika[x-1][y]==PRAZNO and self.matrika[x][y]==PRAZNO and self.matrika[x+1][y]==PRAZNO and self.matrika[x][y+1]==PRAZNO:\n return True\n else:\n return False\n \n elif x>PRAZNO and x< (VELIKOST - 1) and y==(VELIKOST -1):\n if self.matrika[x-1][y]==PRAZNO and self.matrika[x][y]==PRAZNO and self.matrika[x+1][y]==PRAZNO and self.matrika[x][y-1]==PRAZNO:\n return True\n else:\n return False \n \n \n elif x==PRAZNO and y<(VELIKOST -1)and y>PRAZNO :\n if self.matrika[x+1][y]==PRAZNO and self.matrika[x][y]==PRAZNO and self.matrika[x][y-1]==PRAZNO and self.matrika[x][y+1]==PRAZNO :\n return True\n else:\n return False\n \n \n elif x== (VELIKOST - 1) and y<(VELIKOST -1)and y>PRAZNO :\n if self.matrika[x-1][y]==PRAZNO and self.matrika[x][y]==PRAZNO and self.matrika[x][y-1]==PRAZNO and self.matrika[x][y+1]==PRAZNO :\n return True\n else:\n return False\n\n elif x== (VELIKOST - 1) and y==(VELIKOST -1):\n if self.matrika[x-1][y]==PRAZNO and self.matrika[x][y]==PRAZNO and self.matrika[x][y-1]==PRAZNO:\n return True\n else:\n return False\n\n elif x== (VELIKOST - 1) and y==PRAZNO:\n if self.matrika[x-1][y]==PRAZNO and self.matrika[x][y]==PRAZNO and self.matrika[x][y+1]==PRAZNO:\n return True\n else:\n return False\n\n elif x==PRAZNO and y==PRAZNO:\n if self.matrika[x+1][y]==PRAZNO and self.matrika[x][y]==PRAZNO and self.matrika[x][y+1]==PRAZNO:\n return True\n else:\n return False\n\n elif x==PRAZNO and y==(VELIKOST -1):\n if self.matrika[x+1][y]==PRAZNO and self.matrika[x][y]==PRAZNO and self.matrika[x][y-1]==PRAZNO:\n return True\n else:\n return False\n\n def konec_zabave(self, na_vrsti):\n if self.na_vrsti == JAZ:\n self.matrika3 = self.matrika1\n else:\n self.matrika3 = self.matrika2\n \n for x in range(len(self.matrika3)):\n for y in range(len(self.matrika3)):\n if self.matrika3[x][y] == 0 and self.dovoljeno(x, y, self.na_vrsti):\n return False\n return True\n\n def nova_igra(self):\n self.matrika1 = [[PRAZNO] * VELIKOST for _ in range(VELIKOST)]\n self.matrika2 = [[PRAZNO] * VELIKOST for _ in range(VELIKOST)]\n self.canvas.delete(\"all\")\n self.napis.set(\"\")\n self.na_vrsti = JAZ\n for i in range(6):\n self.canvas.create_line(50, i*100 + 50, 550,i*100 +50)\n self.canvas.create_line(i*100 +50, 50 , i*100 +50, 500 +50)\n\n def shrani(self):\n ime = filedialog.asksaveasfilename()\n if ime == \"\":\n return\n with open(ime, \"wt\", encoding=\"utf8\") as f:\n print(self.matrika1, file=f)\n print(self.matrika2, file=f)\n print(self.na_vrsti, file=f)\n\n def odpri(self):\n ime = filedialog.askopenfilename()\n self.nova_igra()\n s = open(ime, encoding=\"utf8\")\n sez = s.readlines()\n s.close\n\n self.matrika1 = ast.literal_eval(sez[0].strip())\n self.matrika2 = ast.literal_eval(sez[1].strip())\n KDO = sez[2].strip()\n if KDO == str(\"Beli\"):\n self.na_vrsti = JAZ\n else: self.na_vrsti = ON\n \n for i in range(VELIKOST):\n for j in range(VELIKOST):\n if self.matrika1[i][j] != 0:\n self.canvas.create_oval(i * 100 + 60, j * 100 + 60, i * 100 + 140, j * 100 + 140)\n if self.matrika2[i][j] != 0:\n self.canvas.create_oval(i * 100 + 60, j * 100 + 60, i * 100 + 140, j* 100 + 140, fill=\"black\")\n \nroot = Tk()\naplikacija = Tabla(root)\n\nroot.mainloop() \n","sub_path":"Tabla.py","file_name":"Tabla.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"582738497","text":"\"\"\"Drop link for Actor and Movie\n\nRevision ID: d6435ddb762e\nRevises: 16a63d60259f\nCreate Date: 2020-08-25 15:21:06.793730\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd6435ddb762e'\ndown_revision = '16a63d60259f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('Actor', 'imagelink')\n op.drop_column('movie', 'imagelink')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('movie', sa.Column('imagelink', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.add_column('Actor', sa.Column('imagelink', sa.VARCHAR(), autoincrement=False, nullable=True))\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/d6435ddb762e_drop_link_for_actor_and_movie.py","file_name":"d6435ddb762e_drop_link_for_actor_and_movie.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"607417349","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.forms import widgets\n\nfrom .models import Article\n\n\nclass ArticleForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(ArticleForm, self).__init__(*args, **kwargs)\n self.fields['article_header'].widget.attrs = {\n 'class': 'form-control', 'rows': '2',\n 'placeholder':'Окно растягивается за правый нижний угол.'\n }\n self.fields['article'].widget.attrs = {\n 'class': 'form-control', 'rows': '6',\n 'placeholder':'Окно растягивается за правый нижний угол.'\n }\n\n class Meta:\n model = Article\n fields = [\"article_image\", \"article_header\", \"article\",]\n \n\n\n","sub_path":"advice/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"425081149","text":"import time\nimport random\nimport os\nimport logging\nimport subprocess\n\nfrom env.env_manager import EnvManager\nfrom env.env_client import EnvClient\n\n\nclass EnvRunner(object):\n def __init__(self, env_id, server_port, agents, config, replay):\n \"\"\"对战环境初始化\"\"\"\n # env_id为仿真环境编号; server_port为基准端口号, 由此生成映射到容器内部各端口的宿主机端口号\n # agents为描述对战双方智能体的字典; config为仿真环境的基本配置信息(想定、镜像名等)\n super().__init__()\n\n random.seed(os.getpid() + env_id)\n\n self.env_id = env_id\n self.server_port = server_port + env_id\n self.config = config\n self.volume_list = self.config['volume_list']\n self.max_game_len = self.config['max_game_len']\n\n scene_name = self.config['scene_name']\n prefix = self.config['prefix']\n image_name = self.config['image_name']\n # 构建管理本地容器化仿真环境的实例对象\n self.env_manager = EnvManager(self.env_id, server_port, scene_name, prefix, image_name=image_name)\n\n self.env_client = None\n self.agents_conf = agents\n self.agents = self._init_agents()\n # 记录出错信息\n logger_name = \"exceptions\"\n self.logger = logging.getLogger(logger_name)\n self.logger.setLevel(level=logging.DEBUG)\n log_path = \"./logs.txt\"\n handler = logging.FileHandler(log_path)\n handler.setLevel(logging.DEBUG)\n self.logger.addHandler(handler)\n\n # 回放记录与保存路径\n self.save_replay = replay['save_replay']\n self.replay_dir = replay['replay_dir']\n\n def __del__(self):\n self.env_manager.stop_docker() # 停止并删除旧环境\n pass\n\n def _start_env(self):\n \"\"\"启动仿真环境\"\"\"\n # 查找是否存在同名的旧容器, 有的话先删除再启动新环境\n docker_name = 'env_{}'.format(self.env_id)\n docker_search = 'docker ps -a --filter name=^/{}$'.format(docker_name)\n # 捕获终端输出结果\n p = subprocess.Popen(docker_search, stdout=subprocess.PIPE, shell=True)\n out, err = p.communicate()\n # decode()将bytes对象转成str对象, strip()删除头尾字符空白符\n # split()默认以分隔符, 包括空格, 换行符\\n, 制表符\\t来对字符串进行分割\n out_str = out.decode()\n str_split = out_str.strip().split()\n if docker_name in str_split:\n print('存在同名旧容器,先删除之\\n', out_str)\n self.env_manager.stop_docker()\n self.env_manager.start_docker(self.volume_list) # 启动新环境\n time.sleep(10)\n\n def _init_agents(self):\n \"\"\"根据配置信息构建红蓝双方智能体\"\"\"\n agents = []\n for name, agent_conf in self.agents_conf.items():\n cls = agent_conf['class']\n agent = cls(name, agent_conf)\n agents.append(agent)\n return agents\n\n def _reset(self):\n \"\"\"智能体重置\"\"\"\n for agent in self.agents:\n agent.reset()\n\n def _run_env(self):\n pass\n\n def _get_observation(self):\n \"\"\"态势获取\"\"\"\n return self.env_client.get_observation()\n\n def _run_actions(self, actions):\n \"\"\"客户端向服务端发送指令\"\"\"\n self.env_client.take_action(actions)\n\n def _run_agents(self, observation):\n \"\"\"调用智能体的step方法生成指令, 然后发送指令\"\"\"\n for agent in self.agents:\n side = agent.side\n sim_time = observation['sim_time']\n obs_red = observation['red']\n obs_blue = observation['blue']\n if side == 'red':\n actions = agent.step(sim_time, obs_red)\n self._action_validate(actions, obs_red, side, sim_time)\n self._run_actions(actions)\n else:\n actions = agent.step(sim_time, obs_blue)\n self._action_validate(actions, obs_blue, side, sim_time)\n self._run_actions(actions)\n\n @staticmethod\n def _get_done(observation):\n \"\"\"推演是否结束\"\"\"\n sim_time = observation['sim_time']\n obs_blue = observation['blue']\n obs_red = observation['red']\n cmd_posts = [u for u in obs_blue['units'] if u['LX'] == 41]\n blue_score = (len([u for u in obs_blue['units'] if u['LX'] != 41])+obs_blue['airports'][0]['NM'])/27*10 + len(cmd_posts)*30\n red_score = (len([u for u in obs_red['units'] if u['LX'] != 41])+obs_red['airports'][0]['NM'])/41*10 + (2-len(cmd_posts))*30\n done = [False, 0, 0] # [对战是否结束, 红方得分, 蓝方得分]\n # 若蓝方态势平台信息里没有指挥所, 说明两个指挥所已经被打掉\n if len(cmd_posts) == 0 or sim_time >= 9000:\n done[0] = True\n if blue_score < red_score: # red win\n done[1:] = [1, -1]\n elif blue_score > red_score: # blue win\n done[1:] = [-1, 1]\n return done\n\n def _action_validate(self, actions, obs_own, side, sim_time):\n \"\"\"指令有效性基本检查\"\"\"\n # 检查项: 执行主体, 目标, 护航对象, 机场相关指令是否有效,\n # 同时检查速度设置是否越界\n # 检查项: 地防/护卫舰的初始部署位置只能在己方半场, 且只允许在开局2分钟内进行调整;\n for action in actions:\n maintype = action['maintype']\n if maintype in ['Ship_Move_Deploy', 'Ground_Move_Deploy']:\n pos2d = (action['point_x'], action['point_y'])\n self._validate_deploy(side, pos2d, sim_time)\n if 'self_id' in action:\n speed = int(action['speed']) if 'speed' in action else None\n self_id = int(action['self_id'])\n self._validate_self_id(maintype, self_id, speed, obs_own)\n if 'target_id' in action:\n target_id = int(action['target_id'])\n self._validate_target_id(target_id, obs_own)\n if 'cov_id' in action:\n cov_id = int(action['cov_id'])\n self._validate_cov_id(cov_id, obs_own)\n if 'airport_id' in action:\n airport_id = int(action['airport_id'])\n speed = int(action['speed']) if 'speed' in action else None\n self._validate_airport(airport_id, speed, action, obs_own)\n\n @staticmethod\n def _validate_deploy(side, pos2d, sim_time):\n assert sim_time <= 120\n if side == 'red':\n assert pos2d[0] >= 0\n else:\n assert pos2d[0] <= 0\n\n def _validate_self_id(self, maintype, self_id, speed, obs_own):\n \"\"\"判断执行主体是否有效\"\"\"\n # 空中拦截指令(make_airattack)执行主体只能是单平台(需要选手考虑目标分配问题)\n # 返航指令(make_returntobase)执行主体可以是单平台也可以是编队(考虑编队内单机油量不足提前返航)\n # 其他指令执行主体原则上必须是编队, 为防止出错目前服务端也支持给单平台下指令.\n unit = [u for u in obs_own['units'] if u['ID'] == self_id]\n team = [u for u in obs_own['teams'] if u['TMID'] == self_id]\n if maintype == 'airattack':\n if len(unit) == 0:\n raise Exception(\"无效平台编号%s\" % self_id)\n else:\n if len(unit) == 0 and len(team) == 0:\n raise Exception(\"无效执行主体编号%s\" % self_id)\n else:\n obj = unit[0] if len(unit) > 0 else team[0]\n if obj['LX'] not in type4cmd[maintype]:\n raise Exception(\"类型为%s的平台或者编队%s无法执行%s指令\" % (obj['LX'], self_id, maintype))\n # 检查速度设置是否越界\n if speed is not None:\n self._validate_speed(obj['LX'], speed)\n\n @staticmethod\n def _validate_target_id(target_id, obs_own):\n \"\"\"判断目标编号是否合法\"\"\"\n # 所有指令的目标编号, 必须是敌方单平台号\n unit = [u for u in obs_own['qb'] if u['ID'] == target_id]\n if len(unit) == 0:\n raise Exception(\"无效目标平台编号%s\" % target_id)\n\n @staticmethod\n def _validate_cov_id(cov_id, obs_own):\n \"\"\"护航对象是否有效\"\"\"\n # 护航对象编号, 必须为己方编队号\n team = [u for u in obs_own['teams'] if u['TMID'] == cov_id]\n if len(team) == 0:\n raise Exception(\"无效护航对象编号%s\" % cov_id)\n else:\n type4cov = [12, 13, 15]\n if int(team[0]['LX']) not in type4cov:\n raise Exception(\"非法护航目标类型%s\" % team[0]['LX'])\n\n def _validate_airport(self, airport_id, speed, action, obs_own):\n \"\"\"判断机场相关指令的有效性\"\"\"\n airports = obs_own['airports']\n airport = [u for u in airports if u['ID'] == airport_id]\n # 根据机场情况判断指令合法性\n maintype = action['maintype']\n if len(airport) == 0:\n raise Exception(\"无效机场编号%s\" % airport_id)\n elif maintype == 'returntobase':\n pass\n else:\n obj = airport[0]\n if not obj['WH']:\n raise Exception(\"机场%s修复中无法执行起飞指令\" % obj['ID'])\n if maintype == 'takeoffprotect':\n fly_type = 11 # 起飞护航指令默认起飞歼击机\n elif maintype in ['takeoffareahunt', 'takeofftargethunt']:\n fly_type = 15 # 起飞突击类指令默认起飞轰炸机\n else:\n fly_type = action['fly_type']\n fly_num = action['fly_num']\n if int(fly_type) not in type4cmd[maintype]:\n raise Exception(\"机场无法起降类型为%s的单位\" % fly_type)\n type_map = {11: 'AIR', 12: 'AWCS', 13: 'JAM', 14: 'UAV', 15: 'BOM'}\n attr = type_map[fly_type]\n if fly_num > obj[attr]:\n print('指令>>>', action)\n raise Exception(\"起飞数量%d大于机场可起飞数量%d\" % (fly_num, obj[attr]))\n # 检查速度设置是否越界\n if speed is not None:\n self._validate_speed(fly_type, speed)\n\n @staticmethod\n def _validate_speed(unit_type, speed):\n \"\"\"判断速度设置是否越界(单位: m/s),范围适当放宽\"\"\"\n speed_range = {\n 11: [100, 300], # 歼击机速度约为900-1000km/h\n 12: [100, 250], # 预警机速度约为600-800km/h\n 13: [100, 250], # 预警机速度约为600-800km/h\n 14: [50, 100], # 无人机速度约为180-350km/h\n 15: [100, 250], # 轰炸机速度约为600-800km/h\n 21: [0, 20], # 舰船速度约为0-30节(白皮书书写有误), 等价于0-54km/h\n 31: [0, 30] # 地防速度约为0-90km/h(白皮书书写有误)\n }\n sp_limit = speed_range[unit_type]\n assert sp_limit[0] <= speed <= sp_limit[1]\n\n\n# 不同指令可执行主体的类型列表\ntype4cmd = {\n # 作战飞机\n \"areapatrol\": [11, 12, 13, 14, 15],\n \"takeoffareapatrol\": [11, 12, 13, 14, 15],\n \"linepatrol\": [11, 12, 13, 14, 15],\n \"takeofflinepatrol\": [11, 12, 13, 14, 15],\n \"areahunt\": [15],\n \"takeoffareahunt\": [15],\n \"targethunt\": [15],\n \"takeofftargethunt\": [15],\n \"protect\": [11],\n \"takeoffprotect\": [11],\n \"airattack\": [11],\n \"returntobase\": [11, 12, 13, 14, 15],\n # 地防\n \"Ground_Add_Target\": [31],\n \"Ground_Remove_Target\": [31],\n \"GroundRadar_Control\": [31],\n \"Ground_Set_Direction\": [31],\n \"Ground_Move_Deploy\": [31],\n # 护卫舰\n \"Ship_Move_Deploy\": [21],\n \"Ship_areapatrol\": [21],\n \"Ship_Add_Target\": [21],\n \"Ship_Remove_Target\": [21],\n \"Ship_Radar_Control\": [21],\n # 预警机\n \"awcs_areapatrol\": [12],\n \"awcs_linepatrol\": [12],\n \"awcs_mode\": [12],\n \"awcs_radarcontrol\": [12],\n \"awcs_cancledetect\": [12],\n # 干扰机\n \"area_disturb_patrol\": [13],\n \"line_disturb_patrol\": [13],\n \"set_disturb\": [13],\n \"close_disturb\": [13],\n \"stop_disturb\": [13],\n # 无人侦察机\n \"uav_areapatrol\": [14],\n \"uav_linepatrol\": [14],\n \"uav_cancledetect\": [14],\n # 地面雷达\n \"base_radarcontrol\": [32]\n}\n","sub_path":"rl_coach/environments/army_match/env_framework/env/env_runner.py","file_name":"env_runner.py","file_ext":"py","file_size_in_byte":12512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"323266337","text":"import os\n\nimport requests\n\n\nclass AirQoApi:\n def __init__(self):\n self.AIRQO_BASE_URL = os.getenv(\"AIRQO_BASE_URL\")\n self.AIRQO_API_KEY = f\"JWT {os.getenv('AIRQO_API_KEY')}\"\n\n def get_events(self, tenant, start_time, end_time):\n headers = {'Authorization': self.AIRQO_API_KEY}\n\n params = {\n \"tenant\": tenant,\n \"start_time\": start_time,\n \"end_time\": end_time\n }\n\n api_request = requests.get(\n '%s%s' % (self.AIRQO_BASE_URL, 'devices/events'),\n params=params,\n headers=headers,\n verify=False,\n )\n\n if api_request.status_code == 200 and \"measurements\" in api_request.json():\n return api_request.json()[\"measurements\"]\n\n print(api_request.request.url)\n print(api_request.request.body)\n print(api_request.content)\n return []\n","sub_path":"src/data-mgt/python/cron-jobs/airqo_api.py","file_name":"airqo_api.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"600114890","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"Get DECALS JPEG Cutout Images.\"\"\"\n\nimport os\nimport argparse\n\nfrom astropy.table import Table\n\nDECALS_API = \"http://legacysurvey.org/viewer/jpeg-cutout/?\"\n\n\ndef getDecalsCutout(ra, dec, name=None, zoom=13):\n \"\"\"\n Get DECaLS cutout JPEG images.\n \"\"\"\n\n if name is None:\n name = \"decals_ra-%s_dec-%sf\" % (('%8.4f' % ra).strip(),\n ('%8.4f' % dec).strip())\n\n # Organize the URL of the JPEG file\n raStr = (\"%10.5f\" % ra).strip()\n decStr = (\"%10.5f\" % dec).strip()\n zoomStr = (\"%2d\" % zoom).strip()\n\n decalsStr = \"ra=%s&dec=%s&zoom=%s&layer=decals-dr3\" % (raStr,\n decStr,\n zoomStr)\n\n try:\n # URL of the JPG file\n jpgUrl = DECALS_API + decalsStr\n\n # Name of the JPG file\n jpgName = '%s.jpg' % name\n\n # Download the JPG file using wget\n jpgCommand = 'wget \"' + jpgUrl + '\" -O ' + jpgName\n os.system(jpgCommand)\n\n except KeyError:\n pass\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"table\", type=str, help=\"Name of the FITS table\")\n parser.add_argument(\"--ra_col\", type=str, help=\"Column name for RA\",\n default='ra', dest='ra_col')\n parser.add_argument(\"--dec_col\", type=str, help=\"Column name for Dec\",\n default='dec', dest='dec_col')\n parser.add_argument(\"--name_col\", type=str,\n help=\"Column Name for ID\",\n default='object_id', dest='name_col')\n parser.add_argument('--zoom', type=int, help=\"Zoom in level\",\n default=13, dest='zoom')\n\n args = parser.parse_args()\n\n data = Table.read(args.table, format='fits')\n\n for obj in data:\n if args.name_col in data.colnames:\n getDecalsCutout(obj[args.ra_col],\n obj[args.dec_col],\n name=obj[args.name_col],\n zoom=args.zoom)\n else:\n getDecalsCutout(obj[args.ra_col],\n obj[args.dec_col],\n name=None,\n zoom=args.zoom)\n","sub_path":"PhotometricCatalog/download_decals_jpeg.py","file_name":"download_decals_jpeg.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"134654567","text":"i = input()\ni = i.split(' ')\n\nn1 = float(i[0])\nn2 = float(i[1])\nn3 = float(i[2])\nn4 = float(i[3])\nm = (2*n1+3*n2+4*n3+n4)/10\nprint(\"Media: {:.1f}\".format(m))\nif(m >= 7):\n print(\"Aluno aprovado.\")\nelif(m < 5):\n print(\"Aluno reprovado.\")\nelse:\n print(\"Aluno em exame.\")\n e = float(input())\n print(\"Nota do exame: {:.1f}\".format(e))\n if(e >= 5):\n print(\"Aluno aprovado.\")\n me = (e + m)/2\n print(\"Media final: {:.1f}\".format(me))\n else:\n print(\"Aluno reprovado.\")\n","sub_path":"solutions/uri/1040.py","file_name":"1040.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"650008823","text":"import tkinter as tk\n\nfrom BribeNet.gui.apps.static.wizard.algos.barabasi_albert import BarabasiAlbert\nfrom BribeNet.gui.apps.static.wizard.algos.composite import Composite\nfrom BribeNet.gui.apps.static.wizard.algos.watts_strogatz import WattsStrogatz\n\nALGO_SUBFRAMES = (BarabasiAlbert, Composite, WattsStrogatz)\nALGO_DICT = {v: k for k, v in enumerate([a.name for a in ALGO_SUBFRAMES])}\n\n\nclass StaticGeneration(tk.Frame):\n\n def __init__(self, parent):\n super().__init__(parent)\n self.parent = parent\n self.graph_type = tk.StringVar(self)\n\n title_label = tk.Label(self, text='Graph Generation Algorithm')\n title_label.grid(row=0, column=0, pady=10)\n\n self.subframes = tuple(c(self) for c in ALGO_SUBFRAMES)\n self.options = tuple(f.get_name() for f in self.subframes)\n\n self.dropdown = tk.OptionMenu(self, self.graph_type, *self.options)\n self.dropdown.grid(row=1, column=0, pady=10, sticky='nsew')\n\n self.graph_type.set(self.options[0])\n for f in self.subframes:\n f.grid(row=2, column=0, sticky=\"nsew\")\n\n self.graph_type.trace('w', self.switch_frame)\n\n self.show_subframe(0)\n\n def show_subframe(self, page_no):\n frame = self.subframes[page_no]\n frame.tkraise()\n\n # noinspection PyUnusedLocal\n def switch_frame(self, *args):\n self.show_subframe(ALGO_DICT[self.graph_type.get()])\n\n def get_args(self):\n return self.subframes[ALGO_DICT[self.graph_type.get()]].get_args()\n\n def get_graph_type(self):\n return self.graph_type.get()\n","sub_path":"src/BribeNet/gui/apps/static/wizard/generation.py","file_name":"generation.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"285870579","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# This module uses OpenERP, Open Source Management Solution Framework.\n# Copyright (C) 2014-Today BrowseInfo ()\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 3 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, see \n#\n##############################################################################\n\nimport time\nimport operator\nimport itertools\nfrom datetime import datetime\nfrom dateutil import relativedelta\nimport xlwt\nfrom xlsxwriter.workbook import Workbook\nfrom tools.translate import _\nfrom cStringIO import StringIO\nimport base64\nimport netsvc\nfrom openerp import tools\n\nfrom osv import fields, osv\n\nclass sale_order_excel_wizard(osv.osv_memory):\n _name ='sale.order.excel'\n \n def print_sale_order_excel(self, cr, uid, ids, context=None):\n \n sale_ids = context.get('active_ids')\n sale_order_obj = self.pool.get('sale.order')\n result = []\n for order in sale_order_obj.browse(cr, uid, sale_ids, context=context):\n sale = {\n 'origin': order.name,\n 'type': 'out',\n 'partner_id': order.partner_id.id and order.partner_id.name or '' ,\n 'partner_invoice_id' : order.partner_invoice_id.id and order.partner_invoice_id.name or '' ,\n 'partner_shipping_id' : order.partner_shipping_id.id and order.partner_shipping_id.name or '' ,\n 'date_order' : order.date_order,\n 'shop_id' : order.shop_id.id and order.shop_id.name or '',\n 'client_order_ref' : order.client_order_ref or '',\n 'squre_meter': order.squre_meter,\n 'distance': order.distance,\n 'type': order.type or '',\n 'project_sale_id': order.project_sale_id.name or '',\n 'pricelist_id': order.pricelist_id.name,\n 'exchange_rate': order.exchange_rate,\n 'amount_untaxed': order.amount_untaxed,\n 'factor_total': order.factor_total,\n 'amount_tax': order.amount_tax,\n 'amount_total': order.amount_total,\n 'tot_volume': order.tot_volume,\n 'avg_volume': order.avg_volume, \n }\n for line in order.order_line:\n result.append(\n { \n 'project_desc': line.project_desc or '',\n 'project_qty': line.project_qty,\n 'discription': line.product_id.name,\n 'rubros_uom_id': line.rubros_uom_id.name,\n 'product_uom_qty': line.product_uom_qty,\n 'product_uom': line.product_uom.name,\n 'purchase_price': line.purchase_price, \n 'labor_cost': line.labor_cost,\n 'price_subtotal': line.price_subtotal,\n 'subtotal_taxes': line.subtotal_taxes,\n 'factor_cost_price': line.factor_cost_price,\n 'factor_labor_cost': line.factor_labor_cost,\n 'subtotal_factor': line.subtotal_factor,\n })\n\n # Create an new Excel file and add a worksheet.\n import base64\n filename = 'sale_order_report.xls'\n workbook = xlwt.Workbook()\n style = xlwt.XFStyle()\n tall_style = xlwt.easyxf('font:height 720;') # 36pt\n # Create a font to use with the style\n font = xlwt.Font()\n font.name = 'Times New Roman'\n font.bold = True\n font.height = 250\n style.font = font\n worksheet = workbook.add_sheet('Sheet 1')\n worksheet.write(0,6, 'Sale Order', style)\n first_row = worksheet.row(1)\n first_row.set_style(tall_style)\n first_col = worksheet.col(1)\n first_col.width = 156 * 30\n second_row = worksheet.row(0)\n second_row.set_style(tall_style)\n second_col = worksheet.col(0)\n second_col.width = 236 * 30\n worksheet.write(1,1, sale.get('origin'), style)\n \n worksheet.write(3,0, 'Customer', style)\n worksheet.write(3,1, tools.ustr(sale.get('partner_id')))\n \n worksheet.write(3,3, 'Date', style)\n worksheet.write(3,4, sale.get('date_order'))\n \n \n worksheet.write(4,0, 'Invoice Address', style)\n worksheet.write(4,1, tools.ustr(sale.get('partner_invoice_id')))\n \n \n worksheet.write(4,3, 'Shop', style)\n worksheet.write(4,4, sale.get('shop_id') ) \n \n worksheet.write(5,0, 'Delivery Address', style)\n worksheet.write(5,1, tools.ustr(sale.get('partner_shipping_id')))\n\n worksheet.write(5,3, 'Customer Reference', style)\n worksheet.write(5,4, tools.ustr(sale.get('client_order_ref')))\n \n worksheet.write(6,0, 'Squre Metesale.extendsr', style)\n worksheet.write(6,1, sale.get('squre_meter'))\n\n worksheet.write(6,3, 'Project', style)\n worksheet.write(6,4, tools.ustr(sale.get('project_sale_id')))\n \n worksheet.write(7,0, 'Distance', style)\n worksheet.write(7,1, sale.get('distance'))\n\n worksheet.write(7,3, 'Pricelist', style)\n worksheet.write(7,4, sale.get('pricelist_id'))\n \n worksheet.write(8,0, 'Type', style)\n worksheet.write(8,1, tools.ustr(sale.get('type')))\n\n worksheet.write(8,3, 'Exchange Rate', style)\n worksheet.write(8,4, sale.get('exchange_rate'))\n \n worksheet.write(10,0, 'NO', style)\n worksheet.write(10,1, 'Rubros Description', style)\n worksheet.write(10,2, 'Rubros Quantity', style)\n worksheet.write(10,3, 'Rubros UOM', style)\n worksheet.write(10,4, 'Description', style)\n worksheet.write(10,5, 'Quantity', style)\n# worksheet.write(10,6, 'Unit of Measure', style)\n# worksheet.write(10,7, 'Cost Price', style)\n# worksheet.write(10,8, 'Labor Cost', style)\n# worksheet.write(10,9, 'Subtotal', style)\n# worksheet.write(10,10, 'Subtotal with Taxes', style)\n# worksheet.write(10,11, 'Factor Cost Price', style)\n# worksheet.write(10,12, 'Factor Labor Cost', style)\n worksheet.write(10,6, 'Subtotal with Factor', style)\n \n row_2 = 11\n no = 1\n \n for val in result:\n worksheet.write(row_2, 0, no)\n worksheet.write(row_2, 1, tools.ustr(val['project_desc']))\n worksheet.write(row_2, 2, val['project_qty'])\n worksheet.write(row_2, 3, val['rubros_uom_id'])\n worksheet.write(row_2, 4, tools.ustr(val['discription']))\n worksheet.write(row_2, 5, val['product_uom_qty'])\n# worksheet.write(row_2, 6, val['product_uom'])\n# worksheet.write(row_2, 7, val['purchase_price'])\n# worksheet.write(row_2, 8, val['labor_cost'])\n# worksheet.write(row_2, 9, val['price_subtotal'])\n# worksheet.write(row_2, 10, val['subtotal_taxes'])\n# worksheet.write(row_2, 11, val['factor_cost_price'])\n# worksheet.write(row_2, 12, val['factor_labor_cost'])\n worksheet.write(row_2, 6, val['subtotal_factor'])\n row_2+=1\n no+=1\n \n worksheet.write(row_2+2,5, 'Untaxed Amount', style)\n worksheet.write(row_2+3,5, 'Total of Subtotal with Factor', style)\n worksheet.write(row_2+4,5, 'Taxes', style)\n worksheet.write(row_2+5,5, 'Total', style) \n worksheet.write(row_2+6,5, 'Total Volume', style)\n worksheet.write(row_2+7,5, 'Average Volume', style)\n \n \n worksheet.write(row_2+2,6, sale.get('amount_untaxed'))\n worksheet.write(row_2+3,6, sale.get('factor_total'))\n worksheet.write(row_2+4,6, sale.get('amount_tax'))\n worksheet.write(row_2+5,6, sale.get('amount_total'))\n worksheet.write(row_2+6,6, sale.get('tot_volume'))\n worksheet.write(row_2+7,6, sale.get('avg_volume'))\n \n fp = StringIO()\n workbook.save(fp)\n export_id = self.pool.get('sale.excel').create(cr, uid, {'excel_file': base64.encodestring(fp.getvalue()), 'file_name': filename}, context=context)\n fp.close()\n return {\n 'view_mode': 'form',\n 'res_id': export_id,\n 'res_model': 'sale.excel',\n 'view_type': 'form',\n 'type': 'ir.actions.act_window',\n 'context': context,\n 'target': 'new',\n }\n return True\n \nsale_order_excel_wizard()\n\n\nclass sale_excel(osv.osv_memory):\n _name= \"sale.excel\"\n _columns= {\n 'excel_file': fields.binary('Excel Report for sale order'),\n 'file_name': fields.char('Excel File', size=64),\n }\n\nsale_excel()\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"approve_sale_order_excel_report/wizard/approve_sale_order_excel_wizard.py","file_name":"approve_sale_order_excel_wizard.py","file_ext":"py","file_size_in_byte":9481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"415704575","text":"from gensim.models import Word2Vec \nfrom backend.utils.params import params\nfrom tqdm import tqdm\n\ndef get_weight_and_word_vec_file():\n \"\"\"\n weight_file.txt: each line is w word and its frequency, separate by space\n word_vec_file.txt: each line is a word and its word vector, \n line[0] is word, line[1:] is vector, separate by space\n \"\"\"\n p = params()\n with open(p.stop_words_path, 'r') as f:\n stop_words = set([line[:-1] for line in f.readlines()])\n stop_words.add('\\n')\n model = Word2Vec.load(str(p.word2vec_path))\n vlookup = model.wv.vocab\n min_df = 8\n total_words = sum(\n vlookup[word].count for word in vlookup if word not in stop_words and vlookup[word].count > min_df\n )\n weight_file = open(p.word2vec_path.parent.parent / 'weight_file.txt', 'w', encoding='utf8')\n word_vec_file = open(p.word2vec_path.parent.parent / 'word_vec_file.txt', 'w', encoding='utf8')\n for word in tqdm(vlookup):\n if word in stop_words or vlookup[word].count <= min_df: continue\n frequency = vlookup[word].count / total_words\n weight_file.write(word + ' ' + str(frequency) + '\\n')\n word_vec_file.write(word + ' ' + ' '.join(map(str, model.wv[word])) + '\\n')\n weight_file.close()\n word_vec_file.close()\n\n\nif __name__ == \"__main__\":\n # get_weight_and_word_vec_file()\n import jieba\n import numpy as np\n from sklearn.metrics.pairwise import cosine_similarity\n from sklearn.decomposition import TruncatedSVD\n p = params()\n model = Word2Vec.load(str(p.word2vec_path))\n a = '你好美丽'\n b = '你好漂亮'\n a_cut = list(jieba.cut(a))\n b_cut = list(jieba.cut(b))\n a_weight = np.array([3.1264584255315635e-06, 5.309067952431014e-05])\n b_weight = np.array([3.1264584255315635e-06, 1.0607626800910661e-05])\n a_embedding = np.zeros((1, 300))\n b_embedding = np.zeros((1, 300))\n for i, word in enumerate(a_cut):\n if word in model.wv:\n a_embedding += model.wv[word] * a_weight[i]\n for i, word in enumerate(b_cut):\n if word in model.wv:\n b_embedding += model.wv[word] * b_weight[i]\n print(cosine_similarity(a_embedding.reshape(1, -1), b_embedding.reshape(1, -1)))\n a_embedding /= 2\n b_embedding /= 2\n sentences = np.concatenate([a_embedding, b_embedding], axis=0)\n svd = TruncatedSVD(1, random_state=1)\n x = svd.fit(sentences)\n v = svd.components_.reshape(-1, 1)\n sentences = sentences @ (v@v.T)\n print(cosine_similarity(sentences[0].reshape(1, -1), sentences[1].reshape(1, -1)))\n\n\n","sub_path":"backend/utils/get_word_weight.py","file_name":"get_word_weight.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"281005314","text":"import os\nimport re\nimport json\nfrom bs4 import BeautifulSoup\nfrom login import get_session\n\nimport sys\nsys.path.append(\"..\")\nimport utils\n\n'''\ntodo list:\n\n'''\n\nagent = 'Mozilla/5.0 (Windows NT 5.1; rv:33.0) Gecko/20100101 Firefox/33.0'\n\nheaders = {\n \"User-Agent\": agent,\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Connection': 'keep-alive'\n}\n\nbase_url = 'http://weibo.com/p/100505{}/info?mod=pedit_more'\n\nuser_info = {\n 'uid': None,\n 'nick': '',\n 'current': [],\n 'sex': 'null',\n 'birth': [],\n 'description': '',\n 'register_time': [],\n 'follows_num': None,\n 'fans_num': None,\n 'level': None,\n 'tags': '',\n 'work_info': '',\n 'education_info': {},\n 'head_img': '',\n 'contact_info': {},\n}\nsession = get_session()\n\n\ndef get_html(url):\n res = session.get(url, headers=headers)\n html = res.content.decode(\"UTF-8\")\n return html\n\n\ndef get_userinfo_html(user_id):\n url = base_url.format(user_id)\n html = get_html(url)\n return html\n\n\ndef get_left(html):\n \"\"\"\n The left part of the page, which is public\n \"\"\"\n soup = BeautifulSoup(html, \"html.parser\")\n scripts = soup.find_all('script')\n pattern = re.compile(r'FM.view\\((.*)\\)')\n cont = ''\n l_id = ''\n # first ensure the left part\n for script in scripts:\n m = pattern.search(script.string)\n if m and 'WB_frame_b' in script.string:\n all_info = m.group(1)\n cont = json.loads(all_info)['html']\n lsoup = BeautifulSoup(cont, 'html.parser')\n l_id = lsoup.find(attrs={'class': 'WB_frame_b'}).div['id']\n for script in scripts:\n m = pattern.search(script.string)\n if m and l_id in script.string:\n all_info = m.group(1)\n try:\n cont = json.loads(all_info)['html']\n except KeyError:\n return ''\n return cont\n\n\ndef get_right(html):\n \"\"\"\n Parse the right part of user detail\n :param html: page source\n :return: the right part of user info page\n \"\"\"\n soup = BeautifulSoup(html, \"html.parser\")\n scripts = soup.find_all('script')\n pattern = re.compile(r'FM.view\\((.*)\\)')\n cont = ''\n # first ensure right part,enterprise users may have two r_id\n rids = []\n for script in scripts:\n m = pattern.search(script.string)\n if m and 'WB_frame_c' in script.string:\n all_info = m.group(1)\n cont = json.loads(all_info).get('html', '')\n if not cont:\n return ''\n rsoup = BeautifulSoup(cont, 'html.parser')\n r_ids = rsoup.find(attrs={'class': 'WB_frame_c'}).find_all('div')\n for r in r_ids:\n rids.append(r['id'])\n for script in scripts:\n for r_id in rids:\n m = pattern.search(script.string)\n if m and r_id in script.string:\n all_info = m.group(1)\n cont += json.loads(all_info).get('html', '')\n\n return cont\n\n\ndef get_max_page(html):\n \"\"\"\n Get the max page we can crawl\n :param html: current page source\n :return: max page number we can crawl\n \"\"\"\n if html == '':\n return 1\n\n pattern = re.compile(r'FM.view\\((.*)\\)')\n soup = BeautifulSoup(html, \"html.parser\")\n scripts = soup.find_all('script')\n length = 1\n\n for script in scripts:\n m = re.search(pattern, script.string)\n\n if m and 'pl.content.followTab.index' in script.string:\n all_info = m.group(1)\n cont = json.loads(all_info).get('html', '')\n soup = BeautifulSoup(cont, 'html.parser')\n pattern = 'uid=(.*?)&'\n\n if 'pageList' in cont:\n urls2 = soup.find(attrs={'node-type': 'pageList'}).find_all(attrs={\n 'class': 'page S_txt1', 'bpfilter': 'page'})\n length += len(urls2)\n return length\n\n\ndef get_userinfo(html):\n cont = get_right(html)\n user = user_info\n if cont == '':\n return {}\n soup = BeautifulSoup(cont, 'html.parser')\n basic_modules = soup.find_all(attrs={'class': 'WB_cardwrap S_bg2'})\n basic_info = soup.find_all(attrs={'class': 'li_1 clearfix'})\n for each_module in basic_modules:\n try:\n basic_str = each_module.find(attrs={'class': 'main_title W_fb W_f14'}).get_text()\n if '基本信息' in basic_str:\n for each in basic_info:\n each_str = each.get_text()\n if '昵称:' in each_str:\n user['nick'] = each.find(attrs={'class': 'pt_detail'}).get_text()\n elif '所在地:' in each_str:\n user['current'] = each.find(attrs={'class': 'pt_detail'}).get_text()\n elif '性别:' in each_str:\n gender = each.find(attrs={'class': 'pt_detail'}).get_text()\n if gender == '男':\n user['sex'] = \"men\"\n elif gender == '女':\n user['sex'] = \"female\"\n else:\n user['sex'] = \"null\"\n elif '生日:' in each_str:\n user['birth'] = each.find(attrs={'class': 'pt_detail'}).get_text()\n elif '简介:' in each_str:\n description = each.find(attrs={'class': 'pt_detail'}).get_text()\n user['description'] = description.encode('gbk', 'ignore').decode('gbk')\n elif '注册时间:' in each_str:\n user['register_time'] = each.find(attrs={'class': 'pt_detail'}).get_text().replace('\\t',\n '').replace(\n '\\r\\n', '')\n\n if '标签信息' in basic_str:\n basic_info = each_module.find_all(attrs={'class': 'li_1 clearfix'})\n for each in basic_info:\n if '标签:' in each.get_text():\n user['tags'] = each.find(attrs={'class': 'pt_detail'}).get_text().replace('\\t', '').replace(\n '\\n\\n\\n', '').strip().replace('\\r\\n', ';')\n\n if '教育信息' in basic_str:\n basic_info = each_module.find_all(attrs={'class': 'li_1 clearfix'})\n for each in basic_info:\n if '大学:' in each.get_text():\n user['education_info']['collage'] = each.find(attrs={'class': 'pt_detail'}).get_text().replace('\\r\\n', ',') \\\n .replace('\\t', '').replace('\\n', ';').lstrip(';').rstrip(';')\n if '高中:' in each.get_text():\n user['education_info']['highschool'] = each.find(attrs={'class': 'pt_detail'}).get_text().replace('\\r\\n', ',') \\\n .replace('\\t', '').replace('\\n', ';').lstrip(';').rstrip(';')\n\n if '工作信息' in basic_str:\n basic_info = each_module.find_all(attrs={'class': 'li_1 clearfix'})\n jobs_info = []\n for each in basic_info:\n if '公司:' in each.get_text():\n jobs = each.find_all(attrs={'class': 'pt_detail'})\n for job in jobs:\n jobs_info.append(job.get_text().replace('\\r\\n', '').replace('\\t', '').replace('\\n', ''))\n user['work_info'] = ';'.join(jobs_info)\n\n if '联系信息' in basic_str:\n basic_info = each_module.find_all(attrs={'class': 'li_1 clearfix'})\n contact_info = []\n for each in basic_info:\n if 'QQ:' in each.get_text():\n user['contact_info']['qq'] = each.find(attrs={'class': 'pt_detail'}).get_text().replace('\\n', '')\n if '邮箱:' in each.get_text():\n user['contact_info']['email'] = each.find(attrs={'class': 'pt_detail'}).get_text()\n if 'MSN:' in each.get_text():\n user['contact_info']['MSN'] = each.find(attrs={'class': 'pt_detail'}).get_text()\n except Exception as why:\n print('解析出错,具体原因为{why}'.format(why=why))\n return user\n\n\ndef get_fans_or_follows(html):\n \"\"\"\n Get fans or follows and store their relationships\n :param html: current page source\n :param uid: current user id\n :param type: type of relations, 1 stands for fans,2 stands for follows\n :return: list of fans or followers\n \"\"\"\n if html == '':\n return list()\n\n pattern = re.compile(r'FM.view\\((.*)\\)')\n soup = BeautifulSoup(html, \"html.parser\")\n scripts = soup.find_all('script')\n\n user_ids = list()\n for script in scripts:\n m = re.search(pattern, script.string)\n\n if m and 'pl.content.followTab.index' in script.string:\n all_info = m.group(1)\n cont = json.loads(all_info).get('html', '')\n soup = BeautifulSoup(cont, 'html.parser')\n follows = soup.find(attrs={'class': 'follow_box'}).find_all(attrs={'class': 'follow_item'})\n pattern = 'uid=(.*?)&'\n for follow in follows:\n m = re.search(pattern, str(follow))\n if m:\n r = m.group(1)\n # filter invalid ids\n if r.isdigit():\n user_ids.append(r)\n return user_ids\n\n\ndef get_follows_num(html):\n \"\"\"\n :param html:\n :return: 返回关注数\n \"\"\"\n cont = get_left(html)\n if cont == '':\n return 0\n else:\n soup = BeautifulSoup(cont, 'html.parser')\n try:\n return int(soup.find_all('strong')[0].get_text())\n except Exception:\n return 0\n\n\ndef get_follows(user_id):\n follows_url = 'http://weibo.com/p/100505{}/follow?page={}#Pl_Official_HisRelation__60'\n cur_page = 1\n max_page = 1\n user_ids = list()\n while 1:\n if cur_page <= max_page:\n url = follows_url.format(user_id, cur_page)\n page = get_html(url)\n if cur_page == 1:\n max_page = get_max_page(page)\n\n # get ids and store relations\n user_ids.extend(get_fans_or_follows(page))\n\n cur_page += 1\n else:\n break\n\n return user_ids\n\n\ndef get_fans_num(html):\n \"\"\"\n :param html:\n :return: 返回粉丝数\n \"\"\"\n cont = get_left(html)\n if cont == '':\n return 0\n else:\n soup = BeautifulSoup(cont, 'html.parser')\n try:\n return int(soup.find_all('strong')[1].get_text())\n except Exception:\n return 0\n\n\ndef get_fans(user_id):\n\n fans_url = 'http://weibo.com/p/100505{}/follow?relate=fans&page={}#Pl_Official_HisRelation__60'\n cur_page = 1\n max_page = 1\n user_ids = list()\n while 1:\n if cur_page <= max_page:\n url = fans_url.format(user_id, cur_page)\n page = get_html(url)\n if cur_page == 1:\n max_page = get_max_page(page)\n\n # get ids and store relations\n user_ids.extend(get_fans_or_follows(page))\n\n cur_page += 1\n else:\n break\n\n return user_ids\n\n\ndef get_level(html):\n \"\"\"\n Get the level of users\n \"\"\"\n pattern = 'Lv.(.*?)<\\\\\\/span>'\n rs = re.search(pattern, html)\n if rs:\n return rs.group(1)\n else:\n return 0\n\n\ndef _get_header(html):\n soup = BeautifulSoup(html, \"html.parser\")\n scripts = soup.find_all('script')\n pattern = re.compile(r'FM.view\\((.*)\\)')\n cont = ''\n for script in scripts:\n m = pattern.search(script.string)\n if m and 'pl.header.head.index' in script.string:\n all_info = m.group(1)\n cont = json.loads(all_info)['html']\n return cont\n\n\ndef get_headimg(html):\n \"\"\"\n Get the head img url of current user\n :param html: page source\n :return: head img url\n \"\"\"\n soup = BeautifulSoup(_get_header(html), 'html.parser')\n try:\n headimg = utils.url_filter(soup.find(attrs={'class': 'photo_wrap'}).find(attrs={'class': 'photo'})['src'])\n except AttributeError:\n headimg = ''\n return headimg\n\n\ndef get_downimg(url):\n ir = session.get(url)\n path = os.path.join('head_img.jpg') #图片存储位置\n with open(path, 'wb') as f:\n sz = f.write(ir.content)\n if sz <= 0:\n raise('headimg download fail')\n return path\n\n\ndef get_data(user_id):\n html = get_userinfo_html(user_id)\n data = get_userinfo(html)\n img_url = get_headimg(html)\n path = get_downimg(img_url)\n data['level'] = get_level(html)\n data['uid'] = user_id\n data['follows_num'] = get_follows_num(html)\n data['follows'] = get_follows(user_id)\n data['fans_num'] = get_fans_num(html)\n data['fans'] = get_fans(user_id)\n data['head_img'] = path\n if data['current'] != '':\n data['current'] = data['current'].split()\n if data['birth'] != '':\n print(data['birth'])\n reg = r'([0-9]{4})年([0-9]{1,2})月([0-9]{1,2})日'\n b = re.compile(reg)\n birth = re.findall(b, data['birth'])\n data['birth'] = [birth[0][0], birth[0][1], birth[0][2]]\n return data\n\nif __name__ == \"__main__\":\n uid = '2675641754'\n data = get_data(uid)\n print(data)\n","sub_path":"models/weibo/get_info.py","file_name":"get_info.py","file_ext":"py","file_size_in_byte":13557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"468168194","text":"import numpy as np\nfrom pandas import *\nimport seaborn as sns\nimport ProcessingElement as pe\n\nclass SystolicArray(object):\n \"\"\"SystolicArray.\"\"\"\n def __init__(self, n_rows, n_cols):\n self.n_rows = n_rows\n self.n_cols = n_cols\n\n self.sa = np.empty((self.n_rows, self.n_cols), object)\n for i in xrange(self.n_rows):\n for j in xrange(self.n_cols):\n self.sa[i][j] = pe.ProcessingElement(j)\n\n def step(self, ifmaps_in, weights_in):\n for i in xrange(self.n_rows):\n for j in xrange(self.n_cols):\n ifmap_in = ifmaps_in[i] if j == 0 else self.sa[i][j-1].ifmap_out\n psum_in = '0' if i == 0 else self.sa[i-1][j].psum_out\n weight_in = weights_in[i] if j == 0 else self.sa[i][j-1].weight_out\n self.sa[i][j].step(ifmap_in, weight_in, psum_in)\n\n def show(self, keys=\"\"):\n\n pandas.set_option('display.max_colwidth', 100)\n # psum_mat = [[sa_e.cached_weight['even'].val for sa_e in sa_row] for sa_row in self.sa]\n psum_mat = [[sa_e.psum_out for sa_e in sa_row] for sa_row in self.sa]\n df = DataFrame(psum_mat)\n\n def formatter(v):\n\n cm = sns.hls_palette(len(keys), h=.5, l=.4, s=.4).as_hex()\n cmap = dict(zip(keys, cm))\n\n span = '{}'.format\n return ''.join([span(cmap[s],s) if s in cmap\n else span(\"white\",s) for s in v.split()])\n\n def bgcolor(v, color = \"black\"):\n return ['background-color: '+color for s in v]\n\n s = df.style.format(formatter).set_table_attributes(\"border=1\")\\\n .apply(bgcolor)\n\n open('some_file.html', 'a').write(s.render())\n","sub_path":"SystolicArray.py","file_name":"SystolicArray.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"211709295","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom src import define\ndef main():\n image1 = cv2.imread(define.IMG_STITCH1)\n image2 = cv2.imread(define.IMG_STITCH2)\n\n image1Gray = cv2.cvtColor(image1, cv2.COLOR_RGB2GRAY)\n image2Gray = cv2.cvtColor(image2, cv2.COLOR_RGB2GRAY)\n\n edges_1 = cv2.Canny(image1Gray, 0, 300,10)\n edges_2 = cv2.Canny(image2Gray, 0, 300,10)\n\n plt.subplot(121), plt.imshow(edges_1, cmap='gray')\n plt.title('Original Image'), plt.xticks([]), plt.yticks([])\n plt.subplot(122), plt.imshow(edges_2, cmap='gray')\n plt.title('Edge Image'), plt.xticks([]), plt.yticks([])\n plt.show()\n\nif __name__ == '__main__':\n main()","sub_path":"src/canny.py","file_name":"canny.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"73067457","text":"import sys\nfrom heapq import heappop, heappush\nfrom operator import itemgetter\nfrom collections import deque, defaultdict, Counter\nfrom bisect import bisect_left, bisect_right\ninput = sys.stdin.readline\nsys.setrecursionlimit(10 ** 7)\nMOD = 10**9 + 7\nINF = float('inf')\n\ndef sol():\n N = int(input())\n S = input().rstrip()\n\n ans = 0\n prev = -1\n\n for s in S:\n if prev != s:\n ans += 1\n prev = s\n\n print(ans)\n\nsol()","sub_path":"AtCoder/abc/143c.py","file_name":"143c.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"351407541","text":"# Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface.\r\n\r\nfrom tkinter import *\r\n\r\nroot = Tk()\r\ntheLabel = Label(root, text=\"hello world\");\r\ntheLabel.pack()\r\nroot.mainloop()\r\n\r\n\r\n# Q2. Write a python program to in the same interface as above and create a action when the button is click it will display some text.\r\n\r\nroot = Tk()\r\ndef PrintName():\r\n print(\"Hi my name is Raja\")\r\nButton1 = Button(root,text=\"ClickHere\",command = PrintName)\r\nButton1.pack()\r\ntheLabel = Label(root, text=\"hello world\");\r\ntheLabel.pack()\r\nroot.mainloop()\r\n\r\n\r\n# Q3. Create a frame using tkinter with any label text and two buttons.One to exit and other to change the label to some other text.\r\nfrom tkinter import *\r\nroot = Tk()\r\n\r\ndef ToChange():\r\n frame2 = Frame(root, width=300, height=300)\r\n label2 = Label(root, text=\"hello once again\")\r\n button3 = Button(root, text=\"ToExit\", command=root.quit)\r\n\r\n label2.pack()\r\n frame2.pack()\r\n button3.pack()\r\n\r\ndef Main():\r\n frame1= Frame(root, width=300,height=300)\r\n labell = Label(root, text=\"hello\")\r\n\r\n button1=Button(root,text=\"ToExit\",command=root.quit)\r\n button2=Button(root,text=\"toChanngeLabel\" , command =ToChange )\r\n\r\n labell.pack()\r\n button1.pack()\r\n button2.pack()\r\n frame1.pack()\r\n\r\nprint(Main())\r\nroot.mainloop()\r\n\r\n\r\n# Q4. Write a python program using tkinter interface to take an input in the GUI program and print it.\r\n\r\nroot = Tk()\r\n\r\nroot.title(\"to take input\")\r\nlabel9=Label(root,text=\"enter your name\")\r\nlabel9.grid(row=0,column=0)\r\n\r\nlabel8=Label(root,text=\"hello unknown\")\r\nlabel8.grid(row=1,column=1)\r\n\r\nusername= StringVar()\r\n\r\nuserEntry = Entry(root,width=26,textvariable=username)\r\nuserEntry.grid(row=0,column=1)\r\n\r\ndef action():\r\n label8.configure(text=\"hello\" + username.get())\r\n\r\nbtn = Button(root,text = \"submit\", command=action)\r\nbtn.grid(row=0,column=2)\r\n\r\nroot.mainloop()\r\n\r\n\r\n","sub_path":"Assignment 15.py","file_name":"Assignment 15.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"554961870","text":"from scheduling import get_schedule as greedy_get_schedule\nfrom bruteforce_scheduling import get_schedule as bruteforce_get_schedule\nfrom pseudo_accurate import get_schedule as accurate_get_schedule\nfrom pseudo_approx import get_schedule as approx_get_schedule\nimport os\nimport time\n\ndef get_time_of_schedule(sch, list_of_weights):\n\ttimes = [0] * count_of_machines\n\tfor i in xrange(count_of_jobs):\n\t\ttimes[sch[i]] += list_of_weights[i]\n\treturn max(times)\n\ni = 1\nwhile True:\n\ttry:\n\t\tftest = open(os.path.join(\"tests\", str(i) + \".txt\"), 'r')\n\t\tlines = ftest.readline()\n\t\tcount_of_machines = int(lines.split(\" \")[0])\n\t\tcount_of_jobs = int(lines.split(\" \")[1])\n\t\tlist_of_weights = map(lambda x: int(x), ftest.readline().split(\" \"))\n\t\tgr_start = time.time()\n\t\tgr = greedy_get_schedule(count_of_machines, count_of_jobs, list_of_weights)\n\t\tgr_end = time.time()\n\t\tapp_start = time.time()\n\t\tapp = approx_get_schedule(count_of_machines, count_of_jobs, list_of_weights, 1.2)\n\t\tapp_end = time.time()\n\t\tacc_start = time.time()\n\t\tacc = accurate_get_schedule(count_of_machines, count_of_jobs, list_of_weights)\n\t\tacc_end = time.time()\n\t\tprint(\"Test \" + str(i) + \\\n\t\t\t\". Greedy: \" + str(get_time_of_schedule(gr, list_of_weights)) + \" (\" + str(gr_end - gr_start) + \"s)\" + \\\n\t\t\t\". Pseudo (approx, epsilon=1.2): \" + str(get_time_of_schedule(app, list_of_weights)) + \" (\" + str(app_end - app_start) + \"s)\" + \\\n\t\t\t\". Pseudo (accurate): \" + str(get_time_of_schedule(acc, list_of_weights)) + \" (\" + str(acc_end - acc_start) + \"s)\" + \".\")\n\t\ti += 1\n\texcept IOError:\n\t\tbreak\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"217221731","text":"import pandas as pd\n\nx_list = [1,2,3,4,5,6,7,8,9,10]\ny_list = [10,20,30,40,50,60,70,80,90,100]\n\ndf = pd.DataFrame()\ndf['x'] = x_list\ndf['y'] = y_list\n\n#LOC\n# print(df.loc[:,'x'])\n#\n# #FILTER\n# df1 = df[df['x'] > 5]['y']\n# print(df1)\n\n#SET WITHOUT LOC\n# df2 = df[df.x> 5]['y']\n# df2['y'] = 100\n# print(df2)\n\n#SET WITH LOC AFTER FILTER\ndf.loc[df.x> 5,y] = 5\n# df3['y'] = 100\ndf.reset_index(drop=True,inplace=True)\nprint(df)\n\n# #CONCAT\n# df4 = pd.concat([df3,df3],axis=1)\n# df4.columns=['x','y']\n# print(df4)\n#\n# df5 = pd.concat([df,df4],axis=0).reset_index()\n# print(df5)\n\n#ITERATE\n# for index, row in df.iterrows():\n# if row.x == 5:\n# df.at[index,'new'] = \"amazing,stunning\"\n# print(df)\n\n","sub_path":"Application/pandascheatsheet.py","file_name":"pandascheatsheet.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"576451672","text":"from django.conf.urls import url\nfrom hotel.Proxy import views\n\nurlpatterns = [\n url(r'^proxy_mapping/$', views.index, name='proxy_mapping'),\n url(r'^upload/$', views.upload, name='upload_proxies'),\n url(r'^proxy/$', views.get_proxy, name='get_proxies'),\n url(r'^proxy/download/$', views.download_proxy, name='proxy-download'),\n url(r'^delete_proxies_by_vendor/$', views.delete_proxies_by_vendor, name='delete_proxies_by_vendor'),\n url(r'^unmapped_proxies/$', views.unmapped_proxies, name='unmapped_proxies'),\n url(r'^mapped_proxies/$', views.mapped_proxies, name='mapped_proxies'),\n url(r'^allMappedProxy/$', views.allMappedProxy, name='allMappedProxy'),\n url(r'^unmapped_proxies_by_vendor/$', views.unmapped_proxies_by_vendor, name='unmapped_proxies_by_vendor'),\n]","sub_path":"eCube_Hotel_2/eCube_UI_2/hotel/Proxy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"163670734","text":"#! usr/bin/python\n'''\nCoded by luke on 30th June 2017\nAiming to get familiar with classification in tensorflow\n'''\n\nfrom __future__ import print_function\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n# number 1 to 10\n#from add_layer_ import add_layer\n\nmnist = input_data.read_data_sets('MNIST_data',one_hot = True)\n\n\ndef add_layer(inputs,input_size,output_size,activation_function=None):\n\t# Add one more layer and return the output of this layer\n\tWeights = tf.Variable(tf.random_normal([input_size,output_size]),name='W')\n\tBiases = tf.Variable(tf.zeros([1,output_size]) + 0.1)\n\tWx_plus_b = tf.matmul(inputs,Weights) + Biases\n\tif activation_function is None:\n\t\toutputs = Wx_plus_b\n\telse:\n\t\toutputs = activation_function(Wx_plus_b)\n\n\treturn outputs\n\n# Define the placeholder for inputs to network\nxs = tf.placeholder(tf.float32,[None,784])\nys = tf.placeholder(tf.float32,[None,10])\n\n# Add output layer\nprediction = add_layer(xs,784,10,activation_function=tf.nn.softmax)\n\n# The error between prediction and real data\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),reduction_indices=[1]))\n\n# Train step\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n\ndef compute_accuracy(v_xs,v_ys):\n\tglobal prediction\n\ty_pre = sess.run(prediction,feed_dict={xs:v_xs})\n\tcorrect_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))\n\taccuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n\tresult = sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})\n\treturn result\n\n\nsess = tf.Session()\n\nsess.run(tf.global_variables_initializer())\n\nfor i in range(1000):\n\tbatch_x,batch_y = mnist.train.next_batch(100)\n\tsess.run(train_step,feed_dict={xs:batch_x,ys:batch_y})\n\tif i%50 ==0:\n\t\tprint(compute_accuracy(mnist.test.images,mnist.test.labels))\n\t\n","sub_path":"classification_.py","file_name":"classification_.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"124677977","text":"#representation of complex numbers with j\n2j\n\ncomp = 3 + 2j #(3+2j)\nprint(type(comp)) #\n\ncomplex(3) #(3+0j)\n\ncomplex(-3, 2) # (-3+2j)\n\nmy_comp = 3 + 2j\nmy_comp.real #3.0\nmy_comp.imag #2.0\n\n#math module for complex numbers\nimport cmath\ncmath.sqrt(-1) #1j\n\n\n\n\n\n\n\n","sub_path":"main/15-numeric-scalar-types/03-complex-numbers.py","file_name":"03-complex-numbers.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"301133840","text":"\"\"\"\nFunctions relating to robust statistical methods for normalizing data.\n\"\"\"\nimport numpy as np\nimport ubelt as ub\nimport math # NOQA\n\ntry:\n from math import isclose\nexcept Exception:\n from numpy import isclose\n\n\ndef find_robust_normalizers(data, params='auto'):\n \"\"\"\n Finds robust normalization statistics a set of scalar observations.\n\n The idea is to estimate \"fense\" parameters: minimum and maximum values\n where anything under / above these values are likely outliers. For\n non-linear normalizaiton schemes we can also estimate an likely middle and\n extent of the data.\n\n Args:\n data (ndarray): a 1D numpy array where invalid data has already been removed\n\n params (str | dict): normalization params.\n\n When passed as a dictionary valid params are:\n\n scaling (str):\n This is the \"mode\" that will be used in the final\n normalization. Currently has no impact on the\n Defaults to 'linear'. Can also be 'sigmoid'.\n\n extrema (str):\n The method for determening what the extrama are.\n Can be \"quantile\" for strict quantile clipping\n Can be \"adaptive-quantile\" for an IQR-like adjusted quantile method.\n Can be \"tukey\" or \"IQR\" for an exact IQR method.\n\n low (float): This is the low quantile for likely inliers.\n\n mid (float): This is the middle quantlie for likely inliers.\n\n high (float): This is the high quantile for likely inliers.\n\n Can be specified as a concise string.\n\n The string \"auto\" defaults to:\n ``dict(extrema='adaptive-quantile', scaling='linear', low=0.01, mid=0.5, high=0.9)``.\n\n The string \"tukey\" defaults to:\n ``dict(extrema='tukey', scaling='linear')``.\n\n Returns:\n Dict[str, str | float]:\n normalization parameters that can be passed to\n :func:`kwarray.normalize` containing the keys:\n\n type (str): which is always 'normalize'\n\n mode (str): the value of ``params['scaling']``\n\n min_val (float): the determined \"robust\" minimum inlier value.\n\n max_val (float): the determined \"robust\" maximum inlier value.\n\n beta (float): the determined \"robust\" middle value for use in\n non-linear normalizers.\n\n alpha (float): the determined \"robust\" extent value for use in\n non-linear normalizers.\n\n Note:\n The defaults and methods of this function are subject to change.\n\n TODO:\n - [ ] No (or minimal) Magic Numbers! Use first principles to deterimine defaults.\n - [ ] Probably a lot of literature on the subject.\n - [ ] https://arxiv.org/pdf/1707.09752.pdf\n - [ ] https://www.tandfonline.com/doi/full/10.1080/02664763.2019.1671961\n - [ ] https://www.rips-irsp.com/articles/10.5334/irsp.289/\n\n - [ ] This function is not possible to get right in every case\n (probably can prove this with a NFL theroem), might be useful\n to allow the user to specify a \"model\" which is specific to some\n domain.\n\n Example:\n >>> from kwarray.util_robust import * # NOQA\n >>> data = np.random.rand(100)\n >>> norm_params1 = find_robust_normalizers(data, params='auto')\n >>> norm_params2 = find_robust_normalizers(data, params={'low': 0, 'high': 1.0})\n >>> norm_params3 = find_robust_normalizers(np.empty(0), params='auto')\n >>> print('norm_params1 = {}'.format(ub.urepr(norm_params1, nl=1)))\n >>> print('norm_params2 = {}'.format(ub.urepr(norm_params2, nl=1)))\n >>> print('norm_params3 = {}'.format(ub.urepr(norm_params3, nl=1)))\n\n Example:\n >>> # xdoctest: +REQUIRES(module:scipy)\n >>> from kwarray.util_robust import * # NOQA\n >>> from kwarray.distributions import Mixture\n >>> import ubelt as ub\n >>> # A random mixture distribution for testing\n >>> data = Mixture.random(6).sample(3000)\n \"\"\"\n if data.size == 0:\n normalizer = {\n 'type': None,\n 'min_val': np.nan,\n 'max_val': np.nan,\n }\n else:\n # should center the desired distribution to visualize on zero\n # beta = np.median(imdata)\n default_params = {\n 'extrema': 'adaptive-quantile',\n 'scaling': 'linear',\n 'low': 0.01,\n 'mid': 0.5,\n 'high': 0.9,\n }\n fense_extremes = None\n if isinstance(params, str):\n if params == 'auto':\n params = {}\n elif params == 'sigmoid':\n params = {'scaling': 'sigmoid'}\n elif params == 'linear':\n params = {'scaling': 'linear'}\n elif params in {'tukey', 'iqr'}:\n params = {\n 'extrema': 'tukey',\n }\n elif params == 'std':\n pass\n else:\n raise KeyError(params)\n\n # hack\n params = ub.dict_union(default_params, params)\n\n # TODO:\n # https://github.com/derekbeaton/OuRS\n # https://en.wikipedia.org/wiki/Feature_scaling\n if params['extrema'] in {'tukey', 'iqr'}:\n fense_extremes = _tukey_quantile_fence(data, clip=False)\n elif params['extrema'] in {'tukey-clip', 'iqr-clip'}:\n fense_extremes = _tukey_quantile_fence(data, clip=True)\n elif params['extrema'] == 'quantile':\n fense_extremes = _quantile_extreme_estimator(data, params)\n elif params['extrema'] in {'custom-quantile', 'adaptive-quantile'}:\n fense_extremes = _custom_quantile_extreme_estimator(data, params)\n else:\n raise KeyError(params['extrema'])\n min_val, mid_val, max_val = fense_extremes\n\n beta = mid_val\n # division factor\n # from scipy.special import logit\n # alpha = max(abs(old_min - beta), abs(old_max - beta)) / logit(0.998)\n # This chooses alpha such the original min/max value will be pushed\n # towards -1 / +1.\n logit_998 = 6.212606095751518 # value of logit(0.998)\n alpha = max(abs(min_val - beta), abs(max_val - beta)) / logit_998\n\n normalizer = {\n 'type': 'normalize',\n 'mode': params['scaling'],\n 'min_val': min_val,\n 'max_val': max_val,\n 'mid_val': mid_val,\n 'beta': beta,\n 'alpha': alpha,\n }\n return normalizer\n\n\ndef _tukey_quantile_fence(data, clip=False):\n \"\"\"\n One might wonder where the 1.5 in the above interval comes from -- Paul\n Velleman, a statistician at Cornell University, was a student of John\n Tukey, who invented this test for outliers. He wondered the same thing.\n When he asked Tukey, \"Why 1.5?\", Tukey answered, \"Because 1 is too small\n and 2 is too large.\" [OxfordShapeSpread]_.\n\n References:\n .. [OxfordShapeSpread] http://mathcenter.oxford.emory.edu/site/math117/shapeCenterAndSpread/\n .. [YTFindOutliers] https://www.youtube.com/watch?v=zY1WFMAA-ec\n \"\"\"\n # Tukey method for outliers\n q1, q2, q3 = np.quantile(data, [0.25, 0.5, 0.75])\n iqr = q3 - q1\n fence_lower = q1 - 1.5 * iqr\n fence_upper = q1 + 1.5 * iqr\n if clip:\n # ensure fences are clipped to max/min values.\n min_ = data.min()\n max_ = data.max()\n fence_lower = max(fence_lower, min_)\n fence_upper = min(fence_upper, max_)\n return fence_lower, q2, fence_upper\n\n\ndef _quantile_extreme_estimator(data, params):\n # Simple quantile\n quant_low = params['low']\n quant_mid = params['mid']\n quant_high = params['high']\n qvals = [quant_low, quant_mid, quant_high]\n quantile_vals = np.quantile(data, qvals)\n (quant_low_val, quant_mid_val, quant_high_val) = quantile_vals\n min_val = quant_low_val\n max_val = quant_high_val\n mid_val = quant_mid_val\n return (min_val, mid_val, max_val)\n\n\ndef _custom_quantile_extreme_estimator(data, params):\n # Quantile with postprocessing\n quant_low = params['low']\n quant_mid = params['mid']\n quant_high = params['high']\n qvals = [0, quant_low, quant_mid, quant_high, 1]\n quantile_vals = np.quantile(data, qvals)\n\n (quant_low_abs, quant_low_val, quant_mid_val, quant_high_val,\n quant_high_abs) = quantile_vals\n\n # TODO: we could implement a hueristic where we do a numerical inspection\n # of the intensity distribution. We could apply a normalization that is\n # known to work for data with that sort of histogram distribution.\n # This might involve fitting several parametarized distributions to the\n # data and choosing the one with the best fit. (check how many modes there\n # are).\n\n # inner_range = quant_high_val - quant_low_val\n # upper_inner_range = quant_high_val - quant_mid_val\n # upper_lower_range = quant_mid_val - quant_low_val\n\n # Compute amount of weight in each quantile\n quant_mid_amount = (quant_high_val - quant_low_val)\n quant_low_amount = (quant_mid_val - quant_low_val)\n quant_high_amount = (quant_high_val - quant_mid_val)\n\n if isclose(quant_mid_amount, 0):\n high_weight = 0.5\n low_weight = 0.5\n else:\n high_weight = quant_high_amount / quant_mid_amount\n low_weight = quant_low_amount / quant_mid_amount\n\n quant_high_residual = (1.0 - quant_high)\n quant_low_residual = (quant_low - 0.0)\n # todo: verify, having slight head fog, not 100% sure\n low_pad_val = quant_low_residual * (low_weight * quant_mid_amount)\n high_pad_val = quant_high_residual * (high_weight * quant_mid_amount)\n min_val = max(quant_low_abs, quant_low_val - low_pad_val)\n max_val = max(quant_high_abs, quant_high_val - high_pad_val)\n mid_val = quant_mid_val\n return (min_val, mid_val, max_val)\n\n\ndef robust_normalize(imdata, return_info=False, nodata=None, axis=None,\n dtype=np.float32, params='auto', mask=None):\n \"\"\"\n Normalize data intensities using heuristics to help put sensor data with\n extremely high or low contrast into a visible range.\n\n This function is designed with an emphasis on getting something that is\n reasonable for visualization.\n\n TODO:\n - [x] Move to kwarray and renamed to robust_normalize?\n - [ ] Support for M-estimators?\n\n Args:\n imdata (ndarray): raw intensity data\n\n return_info (bool):\n if True, return information about the chosen normalization\n heuristic.\n\n params (str | dict):\n Can contain keys, low, high, or mid, scaling, extrema\n e.g. {'low': 0.1, 'mid': 0.8, 'high': 0.9, 'scaling': 'sigmoid'}\n See documentation in :func:`find_robust_normalizers`.\n\n axis (None | int):\n The axis to normalize over, if unspecified, normalize jointly\n\n nodata (None | int):\n A value representing nodata to leave unchanged during\n normalization, for example 0\n\n dtype (type) : can be float32 or float64\n\n mask (ndarray | None):\n A mask indicating what pixels are valid and what pixels should be\n considered nodata. Mutually exclusive with ``nodata`` argument.\n A mask value of 1 indicates a VALID pixel. A mask value of 0\n indicates an INVALID pixel.\n Note this is the opposite of a masked array.\n\n Returns:\n ndarray | Tuple[ndarray, Any]:\n a floating point array with values between 0 and 1.\n if return_info is specified, also returns extra data\n\n Note:\n This is effectively a combination of :func:`find_robust_normalizers`\n and :func:`normalize`.\n\n Example:\n >>> # xdoctest: +REQUIRES(module:scipy)\n >>> from kwarray.util_robust import * # NOQA\n >>> from kwarray.distributions import Mixture\n >>> import ubelt as ub\n >>> # A random mixture distribution for testing\n >>> data = Mixture.random(6).sample(3000)\n >>> param_basis = {\n >>> 'scaling': ['linear', 'sigmoid'],\n >>> 'high': [0.6, 0.8, 0.9, 1.0],\n >>> }\n >>> param_grid = list(ub.named_product(param_basis))\n >>> param_grid += ['auto']\n >>> param_grid += ['tukey']\n >>> rows = []\n >>> rows.append({'key': 'orig', 'result': data})\n >>> for params in param_grid:\n >>> key = ub.urepr(params, compact=1)\n >>> result, info = robust_normalize(data, return_info=True, params=params)\n >>> print('key = {}'.format(key))\n >>> print('info = {}'.format(ub.urepr(info, nl=1)))\n >>> rows.append({'key': key, 'info': info, 'result': result})\n >>> # xdoctest: +REQUIRES(--show)\n >>> import seaborn as sns\n >>> import kwplot\n >>> kwplot.autompl()\n >>> pnum_ = kwplot.PlotNums(nSubplots=len(rows))\n >>> for row in rows:\n >>> ax = kwplot.figure(fnum=1, pnum=pnum_()).gca()\n >>> sns.histplot(data=row['result'], kde=True, bins=128, ax=ax, stat='density')\n >>> ax.set_title(row['key'])\n\n Example:\n >>> # xdoctest: +REQUIRES(module:kwimage)\n >>> from kwarray.util_robust import * # NOQA\n >>> import ubelt as ub\n >>> import kwimage\n >>> import kwarray\n >>> s = 512\n >>> bit_depth = 11\n >>> dtype = np.uint16\n >>> max_val = int(2 ** bit_depth)\n >>> min_val = int(0)\n >>> rng = kwarray.ensure_rng(0)\n >>> background = np.random.randint(min_val, max_val, size=(s, s), dtype=dtype)\n >>> poly1 = kwimage.Polygon.random(rng=rng).scale(s / 2)\n >>> poly2 = kwimage.Polygon.random(rng=rng).scale(s / 2).translate(s / 2)\n >>> forground = np.zeros_like(background, dtype=np.uint8)\n >>> forground = poly1.fill(forground, value=255)\n >>> forground = poly2.fill(forground, value=122)\n >>> forground = (kwimage.ensure_float01(forground) * max_val).astype(dtype)\n >>> imdata = background + forground\n >>> normed, info = kwarray.robust_normalize(imdata, return_info=True)\n >>> print('info = {}'.format(ub.urepr(info, nl=1)))\n >>> # xdoctest: +REQUIRES(--show)\n >>> import kwplot\n >>> kwplot.autompl()\n >>> kwplot.imshow(imdata, pnum=(1, 2, 1), fnum=1)\n >>> kwplot.imshow(normed, pnum=(1, 2, 2), fnum=1)\n \"\"\"\n if axis is not None:\n # Hack, normalize each channel individually. This could\n # be implementd more effciently.\n reorg = imdata.swapaxes(0, axis)\n if return_info:\n infos_to_return = []\n ...\n if mask is None:\n parts = []\n for item in reorg:\n part = robust_normalize(item, nodata=nodata, params=params,\n dtype=dtype, axis=None,\n return_info=return_info)\n if return_info:\n infos_to_return.append(part[1])\n part = part[0]\n parts.append(part[None, :])\n else:\n reorg_mask = mask.swapaxes(0, axis)\n parts = []\n for item, item_mask in zip(reorg, reorg_mask):\n part = robust_normalize(item, nodata=nodata, params=params,\n dtype=dtype, axis=None, mask=item_mask,\n return_info=return_info)\n if return_info:\n infos_to_return.append(part[1])\n part = part[0]\n parts.append(part[None, :])\n recomb = np.concatenate(parts, axis=0)\n final = recomb.swapaxes(0, axis)\n if return_info:\n return final, infos_to_return\n\n is_masked = isinstance(imdata, np.ma.MaskedArray)\n if is_masked:\n if mask is None:\n mask = ~imdata.mask\n imdata = imdata.data\n\n if imdata.dtype.kind == 'f':\n if mask is None:\n mask = ~np.isnan(imdata)\n\n if mask is None:\n if nodata is not None:\n mask = imdata != nodata\n\n if mask is None:\n imdata_valid = imdata\n else:\n imdata_valid = imdata[mask]\n\n assert not np.any(np.isnan(imdata_valid))\n normalizer = find_robust_normalizers(imdata_valid, params=params)\n imdata_normalized = _apply_robust_normalizer(normalizer, imdata,\n imdata_valid, mask, dtype)\n\n if mask is not None:\n result = np.where(mask, imdata_normalized, imdata)\n else:\n result = imdata_normalized\n\n if is_masked:\n result = np.ma.MaskedArray(result, ~mask)\n\n if return_info:\n return result, normalizer\n else:\n return result\n\n\ndef _apply_robust_normalizer(normalizer, imdata, imdata_valid, mask, dtype, copy=True):\n \"\"\"\n TODO:\n abstract into a scikit-learn-style Normalizer class which can\n fit/predict different types of normalizers.\n \"\"\"\n import kwarray\n if normalizer['type'] is None:\n imdata_normalized = imdata.astype(dtype, copy=copy)\n elif normalizer['type'] == 'normalize':\n # Note: we are using kwarray normalize, the one in kwimage is deprecated\n imdata_valid_normalized = kwarray.normalize(\n imdata_valid.astype(dtype, copy=copy), mode=normalizer['mode'],\n beta=normalizer['beta'], alpha=normalizer['alpha'],\n min_val=normalizer.get('min_val', None),\n max_val=normalizer.get('max_val', None),\n )\n if mask is None:\n imdata_normalized = imdata_valid_normalized\n else:\n imdata_normalized = imdata.copy() if copy else imdata\n imdata_normalized[mask] = imdata_valid_normalized\n else:\n raise KeyError(normalizer['type'])\n return imdata_normalized\n\n\ndef normalize(arr, mode='linear', alpha=None, beta=None, out=None,\n min_val=None, max_val=None):\n \"\"\"\n Normalizes input values based on a specified scheme.\n\n The default behavior is a linear normalization between 0.0 and 1.0 based on\n the min/max values of the input. Parameters can be specified to achieve\n more general constrat stretching or signal rebalancing. Implements the\n linear and sigmoid normalization methods described in [WikiNorm]_.\n\n Args:\n arr (NDArray): array to normalize, usually an image\n\n out (NDArray | None): output array. Note, that we will create an\n internal floating point copy for integer computations.\n\n mode (str): either linear or sigmoid.\n\n alpha (float): Only used if mode=sigmoid. Division factor\n (pre-sigmoid). If unspecified computed as:\n ``max(abs(old_min - beta), abs(old_max - beta)) / 6.212606``.\n Note this parameter is sensitive to if the input is a float or\n uint8 image.\n\n beta (float): subtractive factor (pre-sigmoid). This should be the\n intensity of the most interesting bits of the image, i.e. bring\n them to the center (0) of the distribution.\n Defaults to ``(max - min) / 2``. Note this parameter is sensitive\n to if the input is a float or uint8 image.\n\n min_val: inputs lower than this minimum value are clipped\n\n max_val: inputs higher than this maximum value are clipped.\n\n SeeAlso:\n :func:`find_robust_normalizers` - determine robust parameters for\n normalize to mitigate the effect of outliers.\n\n :func:`robust_normalize` - finds and applies robust normalization\n parameters\n\n References:\n .. [WikiNorm] https://en.wikipedia.org/wiki/Normalization_(image_processing)\n\n Example:\n >>> raw_f = np.random.rand(8, 8)\n >>> norm_f = normalize(raw_f)\n\n >>> raw_f = np.random.rand(8, 8) * 100\n >>> norm_f = normalize(raw_f)\n >>> assert isclose(norm_f.min(), 0)\n >>> assert isclose(norm_f.max(), 1)\n\n >>> raw_u = (np.random.rand(8, 8) * 255).astype(np.uint8)\n >>> norm_u = normalize(raw_u)\n\n Example:\n >>> # xdoctest: +REQUIRES(module:kwimage)\n >>> import kwimage\n >>> arr = kwimage.grab_test_image('lowcontrast')\n >>> arr = kwimage.ensure_float01(arr)\n >>> norms = {}\n >>> norms['arr'] = arr.copy()\n >>> norms['linear'] = normalize(arr, mode='linear')\n >>> # xdoctest: +REQUIRES(module:scipy)\n >>> norms['sigmoid'] = normalize(arr, mode='sigmoid')\n >>> # xdoctest: +REQUIRES(--show)\n >>> import kwplot\n >>> kwplot.autompl()\n >>> kwplot.figure(fnum=1, doclf=True)\n >>> pnum_ = kwplot.PlotNums(nSubplots=len(norms))\n >>> for key, img in norms.items():\n >>> kwplot.imshow(img, pnum=pnum_(), title=key)\n\n Example:\n >>> # xdoctest: +REQUIRES(module:kwimage)\n >>> arr = np.array([np.inf])\n >>> normalize(arr, mode='linear')\n >>> # xdoctest: +REQUIRES(module:scipy)\n >>> normalize(arr, mode='sigmoid')\n >>> # xdoctest: +REQUIRES(--show)\n >>> import kwplot\n >>> kwplot.autompl()\n >>> kwplot.figure(fnum=1, doclf=True)\n >>> pnum_ = kwplot.PlotNums(nSubplots=len(norms))\n >>> for key, img in norms.items():\n >>> kwplot.imshow(img, pnum=pnum_(), title=key)\n\n Benchmark:\n >>> # Our method is faster than standard in-line implementations for\n >>> # uint8 and competative with in-line float32, in addition to being\n >>> # more concise and configurable. In 3.11 all inplace variants are\n >>> # faster.\n >>> # xdoctest: +REQUIRES(module:kwimage)\n >>> import timerit\n >>> import kwimage\n >>> import kwarray\n >>> ti = timerit.Timerit(1000, bestof=10, verbose=2, unit='ms')\n >>> arr = kwimage.grab_test_image('lowcontrast', dsize=(512, 512))\n >>> #\n >>> arr = kwimage.ensure_float01(arr)\n >>> out = arr.copy()\n >>> for timer in ti.reset('inline_naive(float)'):\n >>> with timer:\n >>> (arr - arr.min()) / (arr.max() - arr.min())\n >>> #\n >>> for timer in ti.reset('inline_faster(float)'):\n >>> with timer:\n >>> max_ = arr.max()\n >>> min_ = arr.min()\n >>> result = (arr - min_) / (max_ - min_)\n >>> #\n >>> for timer in ti.reset('kwarray.normalize(float)'):\n >>> with timer:\n >>> kwarray.normalize(arr)\n >>> #\n >>> for timer in ti.reset('kwarray.normalize(float, inplace)'):\n >>> with timer:\n >>> kwarray.normalize(arr, out=out)\n >>> #\n >>> arr = kwimage.ensure_uint255(arr)\n >>> out = arr.copy()\n >>> for timer in ti.reset('inline_naive(uint8)'):\n >>> with timer:\n >>> (arr - arr.min()) / (arr.max() - arr.min())\n >>> #\n >>> for timer in ti.reset('inline_faster(uint8)'):\n >>> with timer:\n >>> max_ = arr.max()\n >>> min_ = arr.min()\n >>> result = (arr - min_) / (max_ - min_)\n >>> #\n >>> for timer in ti.reset('kwarray.normalize(uint8)'):\n >>> with timer:\n >>> kwarray.normalize(arr)\n >>> #\n >>> for timer in ti.reset('kwarray.normalize(uint8, inplace)'):\n >>> with timer:\n >>> kwarray.normalize(arr, out=out)\n >>> print('ti.rankings = {}'.format(ub.urepr(\n >>> ti.rankings, nl=2, align=':', precision=5)))\n\n Ignore:\n globals().update(xdev.get_func_kwargs(normalize))\n \"\"\"\n if out is None:\n out = arr.copy()\n\n # TODO:\n # - [ ] Parametarize new_min / new_max values\n # - [ ] infer from datatype\n # - [ ] explicitly given\n new_min = 0.0\n if arr.dtype.kind in ('i', 'u'):\n # Need a floating point workspace\n float_out = out.astype(np.float32)\n new_max = float(np.iinfo(arr.dtype).max)\n elif arr.dtype.kind == 'f':\n float_out = out\n new_max = 1.0\n else:\n raise TypeError(f'Normalize not implemented for {arr.dtype}')\n\n # TODO:\n # - [ ] Parametarize old_min / old_max strategies\n # - [X] explicitly given min and max\n # - [ ] raw-naive min and max inference\n # - [ ] outlier-aware min and max inference (see util_robust)\n if min_val is not None:\n old_min = min_val\n np.maximum(float_out, min_val, out=float_out)\n # float_out[float_out < min_val] = min_val\n else:\n try:\n old_min = np.nanmin(float_out)\n except ValueError:\n old_min = 0\n\n if max_val is not None:\n old_max = max_val\n np.minimum(float_out, max_val, out=float_out)\n # float_out[float_out > max_val] = max_val\n else:\n try:\n old_max = np.nanmax(float_out)\n except ValueError:\n old_max = max(0, old_min)\n\n old_span = old_max - old_min\n new_span = new_max - new_min\n\n if mode == 'linear':\n # linear case\n # out = (arr - old_min) * (new_span / old_span) + new_min\n factor = 1.0 if old_span == 0 else (new_span / old_span)\n if old_min != 0:\n float_out -= old_min\n elif mode == 'sigmoid':\n # nonlinear case\n # out = new_span * sigmoid((arr - beta) / alpha) + new_min\n from scipy.special import expit as sigmoid\n if beta is None:\n # should center the desired distribution to visualize on zero\n beta = old_max - old_min\n\n if alpha is None:\n # division factor\n # from scipy.special import logit\n # alpha = max(abs(old_min - beta), abs(old_max - beta)) / logit(0.998)\n # This chooses alpha such the original min/max value will be pushed\n # towards -1 / +1.\n alpha = max(abs(old_min - beta), abs(old_max - beta)) / 6.212606\n\n try:\n if isclose(alpha, 0):\n alpha = 1\n except TypeError:\n alpha = alpha + np.isclose(alpha, 0)\n\n energy = float_out\n energy -= beta\n energy /= alpha\n # Ideally the data of interest is roughly in the range (-6, +6)\n float_out = sigmoid(energy, out=float_out)\n factor = new_span\n else:\n raise KeyError(mode)\n\n # Stretch / shift to the desired output range\n if factor != 1:\n float_out *= factor\n\n if new_min != 0:\n float_out += new_min\n\n if float_out is not out:\n final_out = float_out.astype(out.dtype)\n out.ravel()[:] = final_out.ravel()[:]\n return out\n","sub_path":"kwarray/util_robust.py","file_name":"util_robust.py","file_ext":"py","file_size_in_byte":26837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"539946380","text":"from string import punctuation\n\n\ndef pig_latin_punctuation(word):\n\n if word[-1] in punctuation:\n word, end_symbol = word[:-1], word[-1]\n else:\n word, end_symbol = word, \"\"\n\n if word[0] in \"aeiou\":\n output = word + \"way\"\n else:\n output = word[1:] + word[0] + \"ay\"\n\n return output + end_symbol\n\n\nprint(pig_latin_punctuation(\"tarun!\"))\n","sub_path":"ch02-strings/e05b2_punctuation.py","file_name":"e05b2_punctuation.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"524454094","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"The Fermionic-particle Operator.\"\"\"\n\nimport re\nimport warnings\nfrom dataclasses import dataclass\nfrom itertools import product\nfrom typing import List, Optional, Tuple, Union\n\nimport numpy as np\nfrom scipy.sparse import csc_matrix\n\nfrom qiskit_nature.operators.second_quantization.second_quantized_op import SecondQuantizedOp\n\n_ZERO_LABELS = {\n (\"+\", \"+\"),\n (\"+\", \"N\"),\n (\"-\", \"-\"),\n (\"-\", \"E\"),\n (\"N\", \"E\"),\n (\"E\", \"+\"),\n (\"N\", \"-\"),\n (\"E\", \"N\"),\n}\n_MAPPING = {\n (\"I\", \"I\"): \"I\",\n (\"I\", \"+\"): \"+\",\n (\"I\", \"-\"): \"-\",\n (\"I\", \"N\"): \"N\",\n (\"I\", \"E\"): \"E\",\n (\"+\", \"I\"): \"+\",\n (\"+\", \"-\"): \"N\",\n (\"+\", \"E\"): \"+\",\n (\"-\", \"I\"): \"-\",\n (\"-\", \"+\"): \"E\",\n (\"-\", \"N\"): \"-\",\n (\"N\", \"I\"): \"N\",\n (\"N\", \"+\"): \"+\",\n (\"N\", \"N\"): \"N\",\n (\"E\", \"I\"): \"E\",\n (\"E\", \"-\"): \"-\",\n (\"E\", \"E\"): \"E\",\n}\n\n\n@dataclass(frozen=True)\nclass _FermionLabelPrimitive:\n \"\"\"Represent Label for Fermion +_{n} or -_{n}\"\"\"\n\n is_creation: bool # if True creation operator, otherwise annihilation operator\n index: int\n\n def __str__(self):\n if self.is_creation:\n return f\"+_{self.index}\"\n return f\"-_{self.index}\"\n\n def adjoint(self) -> \"_FermionLabelPrimitive\":\n \"\"\"Calculate adjoint\n\n Returns:\n The adjoint label\n \"\"\"\n return _FermionLabelPrimitive(not self.is_creation, self.index)\n\n\n_FermionLabel = List[_FermionLabelPrimitive]\n\n\nclass FermionicOp(SecondQuantizedOp):\n r\"\"\"\n N-mode Fermionic operator.\n\n **Label**\n\n Allowed characters for the label are `I`, `-`, `+`, `N`, and, `E`.\n\n .. list-table::\n :header-rows: 1\n\n * - Label\n - Mathematical Representation\n - Meaning\n * - `I`\n - :math:`I`\n - Identity operator\n * - `-`\n - :math:`c`\n - Annihilation operator\n * - `+`\n - :math:`c^\\dagger`\n - Creation operator\n * - `N`\n - :math:`n = c^\\dagger c`\n - Number operator\n * - `E`\n - :math:`I - n = c c^\\dagger`\n - Hole number\n\n There are two types of label modes for this class.\n The label mode is automatically detected by the presence of underscore `_`.\n\n 1. Dense Label\n\n Dense labels are strings with allowed characters above.\n This is similar to Qiskit's string-based representation of qubit operators.\n For example,\n\n .. code-block:: python\n\n \"+\"\n \"II++N-IE\"\n\n are possible labels.\n\n 2. Sparse Label\n\n When the parameter `register_length` is passed to :meth:`~FermionicOp.__init__`,\n label is assumed to be a sparse label.\n A sparse label is a string consisting of a space-separated list of words.\n Each word must look like :code:`[+-INE]_`, where the :code:``\n is a non-negative integer representing the index of the fermionic mode.\n For example,\n\n .. code-block:: python\n\n \"+_0\"\n \"-_2\"\n \"+_0 -_1 +_4 +_10\"\n\n are possible labels.\n\n **Initialization**\n\n The FermionicOp can be initialized in several ways:\n\n `FermionicOp(label)`\n A label consists of the permitted characters listed above.\n\n `FermionicOp(tuple)`\n Valid tuples are of the form `(label, coeff)`. `coeff` can be either `int`, `float`,\n or `complex`.\n\n `FermionicOp(list)`\n The list must be a list of valid tuples as explained above.\n\n **Output of str and repr**\n\n By default, the output of str and repr is truncated.\n You can change the number of characters with `set_truncation`.\n If you pass 0 to `set_truncation`, truncation is disabled and the full output will be printed.\n\n Example:\n\n .. jupyter-execute::\n\n from qiskit_nature.operators.second_quantization import FermionicOp\n\n print(\"truncated str output\")\n print(sum(FermionicOp(\"I\", display_format=\"sparse\") for _ in range(25)))\n\n FermionicOp.set_truncation(0)\n print(\"not truncated str output\")\n print(sum(FermionicOp(\"I\", display_format=\"sparse\") for _ in range(25)))\n\n\n **Algebra**\n\n This class supports the following basic arithmetic operations: addition, subtraction, scalar\n multiplication, operator multiplication, and adjoint.\n For example,\n\n Addition\n\n .. jupyter-execute::\n\n 0.5 * FermionicOp(\"I+\", display_format=\"dense\") + FermionicOp(\"+I\", display_format=\"dense\")\n\n Sum\n\n .. jupyter-execute::\n\n 0.25 * sum(FermionicOp(label, display_format=\"sparse\") for label in ['+_0', '-_1', 'N_2'])\n\n Operator multiplication\n\n .. jupyter-execute::\n\n print(FermionicOp(\"+-\", display_format=\"dense\") @ FermionicOp(\"E+\", display_format=\"dense\"))\n\n Dagger\n\n .. jupyter-execute::\n\n ~FermionicOp(\"+\", display_format=\"dense\")\n\n In principle, you can also add :class:`FermionicOp` and integers, but the only valid case is the\n addition of `0 + FermionicOp`. This makes the `sum` operation from the example above possible\n and it is useful in the following scenario:\n\n .. code-block:: python\n\n fermion = 0\n for i in some_iterable:\n some processing\n fermion += FermionicOp(somedata)\n\n \"\"\"\n # Warn only once\n _display_format_warn = True\n\n _truncate = 200\n\n def __init__(\n self,\n data: Union[\n str,\n Tuple[str, complex],\n List[Tuple[str, complex]],\n List[Tuple[str, float]],\n List[Tuple[_FermionLabel, complex]],\n ],\n register_length: Optional[int] = None,\n display_format: Optional[str] = None,\n ):\n \"\"\"\n Args:\n data: Input data for FermionicOp. The allowed data is label str,\n tuple (label, coeff), or list [(label, coeff)].\n register_length: positive integer that represents the length of registers.\n display_format: If sparse, the label is represented sparsely during output.\n if dense, the label is represented densely during output. (default: dense)\n\n Raises:\n ValueError: given data is invalid value.\n TypeError: given data has invalid type.\n \"\"\"\n if display_format is None:\n display_format = \"dense\"\n if FermionicOp._display_format_warn:\n FermionicOp._display_format_warn = False\n warnings.warn(\n \"The default value for `display_format` will be changed from 'dense' \"\n \"to 'sparse' in version 0.3.0. Once that happens, you must specify \"\n \"display_format='dense' directly.\",\n stacklevel=2,\n )\n\n self.display_format = display_format\n\n self._data: List[Tuple[_FermionLabel, complex]]\n\n if isinstance(data, list) and isinstance(data[0][0], list) and register_length is not None:\n self._data = data # type: ignore\n self._register_length = register_length\n else:\n if not isinstance(data, (tuple, list, str)):\n raise TypeError(f\"Type of data must be str, tuple, or list, not {type(data)}.\")\n\n if isinstance(data, str):\n data = [(data, complex(1))]\n\n elif isinstance(data, tuple):\n if not isinstance(data[0], str) or not isinstance(data[1], (int, float, complex)):\n raise TypeError(\n f\"Data tuple must be (str, number), not ({type(data[0])}, {type(data[1])}).\"\n )\n data = [data]\n\n else:\n if not isinstance(data[0][0], str) or not isinstance(\n data[0][1], (int, float, complex)\n ):\n raise TypeError(\"Data list must be [(str, number)].\")\n\n if all(\"_\" not in label for label, _ in data):\n self._data = [\n (\n self._substituted_label([(c, int(i)) for i, c in enumerate(label)]),\n complex(coeff), # type: ignore\n )\n for label, coeff in data\n ]\n else:\n self._data = [\n (\n self._substituted_label(\n [(c[0], int(c[2:])) for c in label.split()] # type: ignore\n ),\n complex(coeff), # type: ignore\n )\n for label, coeff in data\n ]\n\n if register_length is not None:\n self._register_length = register_length\n\n def _substituted_label(self, label):\n max_index = 0\n new_label = []\n for c, index in label:\n max_index = max(max_index, index)\n if c == \"+\":\n new_label.append(_FermionLabelPrimitive(True, index))\n elif c == \"-\":\n new_label.append(_FermionLabelPrimitive(False, index))\n elif c == \"N\":\n new_label.append(_FermionLabelPrimitive(True, index))\n new_label.append(_FermionLabelPrimitive(False, index))\n elif c == \"E\":\n new_label.append(_FermionLabelPrimitive(False, index))\n new_label.append(_FermionLabelPrimitive(True, index))\n elif c == \"I\":\n continue\n else:\n raise ValueError(f\"Invalid label {c}_{index} is given.\")\n\n self._register_length = max_index + 1\n return new_label\n\n def __repr__(self) -> str:\n data = self.to_list()\n if len(self) == 1:\n if data[0][1] == 1:\n data_str = f\"'{data[0][0]}'\"\n data_str = f\"'{data[0]}'\"\n data_str = f\"{data}\"\n\n if FermionicOp._truncate and len(data_str) > FermionicOp._truncate:\n data_str = data_str[0 : FermionicOp._truncate - 5] + \"...\" + data_str[-2:]\n return (\n \"FermionicOp(\"\n f\"{data_str}, \"\n f\"register_length={self.register_length}, \"\n f\"display_format='{self.display_format}'\"\n \")\"\n )\n\n @classmethod\n def set_truncation(cls, val: int) -> None:\n \"\"\"Set the max number of characters to display before truncation.\n Args:\n val: the number of characters.\n\n .. note::\n Truncation will be disabled if the truncation value is set to 0.\n \"\"\"\n cls._truncate = int(val)\n\n def __str__(self) -> str:\n \"\"\"Sets the representation of `self` in the console.\"\"\"\n\n if len(self) == 1:\n label, coeff = self.to_list()[0]\n return f\"{coeff} * ({label})\"\n pre = (\n \"Fermionic Operator\\n\"\n f\"register length={self.register_length}, number terms={len(self)}\\n\"\n )\n ret = \" \" + \"\\n+ \".join(\n [f\"{coeff} * ( {label} )\" if label else f\"{coeff}\" for label, coeff in self.to_list()]\n )\n if FermionicOp._truncate and len(ret) > FermionicOp._truncate:\n ret = ret[0 : FermionicOp._truncate - 4] + \" ...\"\n return pre + ret\n\n def __len__(self):\n return len(self._data)\n\n @property\n def register_length(self) -> int:\n \"\"\"Gets the register length.\"\"\"\n return self._register_length\n\n def mul(self, other: complex) -> \"FermionicOp\":\n if not isinstance(other, (int, float, complex)):\n raise TypeError(\n f\"Unsupported operand type(s) for *: 'FermionicOp' and '{type(other).__name__}'\"\n )\n return FermionicOp(\n [(label, coeff * other) for label, coeff in self._data],\n register_length=self.register_length,\n display_format=self.display_format,\n )\n\n def compose(self, other: \"FermionicOp\") -> \"FermionicOp\":\n if not isinstance(other, FermionicOp):\n raise TypeError(\n f\"Unsupported operand type(s) for *: 'FermionicOp' and '{type(other).__name__}'\"\n )\n\n new_data = list(\n filter(\n lambda x: x[1] != 0,\n (\n (label1 + label2, cf1 * cf2)\n for label2, cf2 in other._data\n for label1, cf1 in self._data\n ),\n )\n )\n register_length = max(self.register_length, other.register_length)\n display_format = (\n \"sparse\"\n if self.display_format == \"sparse\" or other.display_format == \"sparse\"\n else \"dense\"\n )\n if not new_data:\n return FermionicOp((\"\", 0), register_length, display_format)\n return FermionicOp(new_data, register_length, display_format)\n\n def add(self, other: \"FermionicOp\") -> \"FermionicOp\":\n if not isinstance(other, FermionicOp):\n raise TypeError(\n f\"Unsupported operand type(s) for +: 'FermionicOp' and '{type(other).__name__}'\"\n )\n\n return FermionicOp(\n self._data + other._data,\n max(self.register_length, other.register_length),\n self.display_format or other.display_format,\n )\n\n # pylint: disable=arguments-differ\n def to_list(\n self,\n display_format: Optional[str] = None,\n ) -> List[Tuple[str, complex]]: # type: ignore\n \"\"\"Returns the operators internal contents in list-format.\n\n Args:\n display_format: when specified this will overwrite ``self.display_format``. Can\n be either 'dense' or 'sparse'. See the class documentation for more details.\n\n Returns:\n A list of tuples consisting of the dense label and corresponding coefficient.\n\n Raises:\n ValueError: if the given format is invalid.\n \"\"\"\n if display_format is not None:\n display_format = display_format.lower()\n if display_format not in {\"sparse\", \"dense\"}:\n raise ValueError(\n f\"Invalid `display_format` {display_format} is given.\"\n \"`display_format` must be 'dense' or 'sparse'.\"\n )\n else:\n display_format = self.display_format\n if display_format == \"sparse\":\n return [\n (\" \".join(str(label) for label in label_data), coeff)\n for label_data, coeff in self._data\n ]\n return self._to_dense_label_data()\n\n def to_matrix(self, sparse: Optional[bool] = True) -> Union[csc_matrix, np.ndarray]:\n \"\"\"Convert to a matrix representation over the full fermionic Fock space in occupation number\n basis. The basis states are ordered in increasing bitstring order as 0000, 0001, ..., 1111.\n\n Args:\n sparse: If true, the matrix is returned as a sparse csc_matrix, else it is returned as a\n dense numpy array.\n\n Returns:\n The matrix of the operator in the Fock basis (scipy.sparse.csc_matrix or numpy.ndarray\n with dtype=numpy.complex128)\n \"\"\"\n\n csc_data, csc_col, csc_row = [], [], []\n\n dimension = 1 << self.register_length\n\n # loop over all columns of the matrix\n for col_idx in range(dimension):\n initial_occupations = [occ == \"1\" for occ in f\"{col_idx:0{self.register_length}b}\"]\n # loop over the terms in the operator data\n for opstring, prefactor in self.reduce()._data:\n # check if op string is the identity\n if not opstring:\n csc_data.append(prefactor)\n csc_row.append(col_idx)\n csc_col.append(col_idx)\n else:\n occupations = initial_occupations.copy()\n sign = 1\n mapped_to_zero = False\n\n # apply terms sequentially to the current basis state\n for label_primitive in reversed(opstring):\n occ = occupations[label_primitive.index]\n if label_primitive.is_creation == occ:\n # Applying the creation operator on an occupied state maps to zero. So\n # does applying the annihilation operator on an unoccupied state.\n mapped_to_zero = True\n break\n sign *= (-1) ** sum(occupations[: label_primitive.index])\n occupations[label_primitive.index] = not occ\n\n # add data point to matrix in the correct row\n if not mapped_to_zero:\n row_idx = sum(int(occ) << idx for idx, occ in enumerate(occupations[::-1]))\n csc_data.append(sign * prefactor)\n csc_row.append(row_idx)\n csc_col.append(col_idx)\n\n sparse_mat = csc_matrix(\n (csc_data, (csc_row, csc_col)),\n shape=(dimension, dimension),\n dtype=complex,\n )\n\n if sparse:\n return sparse_mat\n else:\n return sparse_mat.toarray()\n\n def adjoint(self) -> \"FermionicOp\":\n data = []\n for label, coeff in self._data:\n conjugated_coeff = coeff.conjugate()\n adjoint_label = [fer_label.adjoint() for fer_label in reversed(label)]\n data.append((adjoint_label, conjugated_coeff))\n\n return FermionicOp(\n data, register_length=self.register_length, display_format=self.display_format\n )\n\n def reduce(self, atol: Optional[float] = None, rtol: Optional[float] = None) -> \"FermionicOp\":\n if atol is None:\n atol = self.atol\n if rtol is None:\n rtol = self.rtol\n\n labels, coeffs = zip(*self.to_normal_order()._to_dense_label_data())\n label_list, indices = np.unique(labels, return_inverse=True, axis=0)\n coeff_list = np.zeros(len(coeffs), dtype=np.complex128)\n for i, val in zip(indices, coeffs):\n coeff_list[i] += val\n non_zero = [\n i for i, v in enumerate(coeff_list) if not np.isclose(v, 0, atol=atol, rtol=rtol)\n ]\n if not non_zero:\n return FermionicOp((\"\", 0), self.register_length, display_format=self.display_format)\n return FermionicOp(\n list(zip(label_list[non_zero].tolist(), coeff_list[non_zero])),\n display_format=self.display_format,\n )\n\n @property\n def display_format(self):\n \"\"\"Return the display format\"\"\"\n return self._display_format\n\n @display_format.setter\n def display_format(self, display_format: str):\n \"\"\"Set the display format of labels.\n\n Args:\n display_format: display format for labels. \"sparse\" or \"dense\" is available.\n\n Raises:\n ValueError: invalid mode is given\n \"\"\"\n display_format = display_format.lower()\n if display_format not in {\"sparse\", \"dense\"}:\n raise ValueError(\n f\"Invalid `display_format` {display_format} is given.\"\n \"`display_format` must be 'dense' or 'sparse'.\"\n )\n self._display_format = display_format\n\n def _to_dense_label_data(self) -> List[Tuple[str, complex]]:\n dense_label_data = []\n for label, coeff in self._data:\n label_list = [\"I\"] * self.register_length\n for fer_label in label:\n char = \"+\" if fer_label.is_creation else \"-\"\n index = fer_label.index\n if (label_list[index], char) in _ZERO_LABELS:\n break\n label_list[index] = _MAPPING[(label_list[index], char)]\n if index != self.register_length and char in {\"+\", \"-\"}:\n exchange_label = label_list[index + 1 :]\n num_exchange = exchange_label.count(\"+\") + exchange_label.count(\"-\")\n coeff *= -1 if num_exchange % 2 else 1\n else:\n dense_label_data.append((\"\".join(label_list), coeff))\n if not dense_label_data:\n return [(\"I\" * self.register_length, 0j)]\n return dense_label_data\n\n def to_normal_order(self) -> \"FermionicOp\":\n \"\"\"Convert to the equivalent operator with normal order.\n The returned operator is a sparse label mode.\n\n .. note::\n\n This method implements the transformation of an operator to the normal ordered operator.\n The transformation is calculated by considering all commutation relations between the\n operators. For example, for the case :math:`\\\\colon c_0 c_0^\\\\dagger\\\\colon`\n where :math:`c_0` is an annihilation operator,\n this method returns :math:`1 - c_0^\\\\dagger c_0` due to commutation relations.\n See the reference: https://en.wikipedia.org/wiki/Normal_order#Multiple_fermions.\n\n \"\"\"\n temp_display_label = self.display_format\n self.display_format = \"dense\"\n ret = 0\n\n for label, coeff in self.to_list():\n splits = label.split(\"E\")\n\n for inter_ops in product(\"IN\", repeat=len(splits) - 1):\n label = splits[0]\n label += \"\".join(link + next_base for link, next_base in zip(inter_ops, splits[1:]))\n\n pluses = [it.start() for it in re.finditer(r\"\\+|N\", label)]\n minuses = [it.start() for it in re.finditer(r\"-|N\", label)]\n\n count = sum(1 for plus in pluses for minus in minuses if plus > minus)\n sign_swap = (-1) ** count\n sign_n = (-1) ** inter_ops.count(\"N\")\n new_coeff = coeff * sign_n * sign_swap\n\n ret += new_coeff * FermionicOp(\n \" \".join([f\"+_{i}\" for i in pluses] + [f\"-_{i}\" for i in minuses]),\n self.register_length,\n \"sparse\",\n )\n\n self.display_format = temp_display_label\n\n if isinstance(ret, FermionicOp):\n return ret\n return FermionicOp((\"\", 0), self.register_length, \"sparse\")\n\n @classmethod\n def zero(cls, register_length: int) -> \"FermionicOp\":\n \"\"\"Constructs a zero-operator.\n\n Args:\n register_length: the length of the operator.\n\n Returns:\n The zero-operator of the given length.\n \"\"\"\n return FermionicOp((\"I_0\", 0.0), register_length=register_length, display_format=\"sparse\")\n\n @classmethod\n def one(cls, register_length: int) -> \"FermionicOp\":\n \"\"\"Constructs a unity-operator.\n\n Args:\n register_length: the length of the operator.\n\n Returns:\n The unity-operator of the given length.\n \"\"\"\n return FermionicOp((\"I_0\", 1.0), register_length=register_length, display_format=\"sparse\")\n","sub_path":"qiskit_nature/operators/second_quantization/fermionic_op.py","file_name":"fermionic_op.py","file_ext":"py","file_size_in_byte":23353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"397699200","text":"class Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n # check whether can find word, start at (i,j) position \n def findChar(board, i, j, word):\n if len(word) == 0:# all the characters are checked\n return True;\n if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or word[0] != board[i][j]:\n return False;\n curLoc = board[i][j];# first character is found, check the remaining part\n board[i][j] = '#';# avoid visit agian \n # check whether can find \"word\" along one direction\n result = findChar(board, i + 1, j, word[1:]) or findChar(board, i, j + 1, word[1:]) or findChar(board, i - 1, j, word[1:]) or findChar(board, i, j - 1, word[1:]);\n #if cannot find the match charter, deleter # to make it visitalbe again.\n board[i][j] = curLoc;\n return result;\n \n for i in range(len(board)):\n for j in range(len(board[0])):\n if findChar(board, i, j, word):\n return True;\n return False;\n\n#class Solution:\n# def exist(self, b, w):\n# if not b or not b[0]: return False\n# bc = Counter(chain(*b))\n# wc = Counter(w)\n# if any(c > bc[s] for s, c in wc.items()): return False\n# m, n, wl = len(b), len(b[0]), len(w) - 1\n# def dfs(d: int, x: int, y: int) -> bool:\n# if w[d] != b[y][x]: return False\n# if d == wl: return True\n# c, b[y][x] = b[y][x], ''\n# if x > 0 and dfs(d + 1, x - 1, y): return True\n# if x < n-1 and dfs(d + 1, x + 1, y): return True\n# if y > 0 and dfs(d + 1, x, y - 1): return True\n# if y < m-1 and dfs(d + 1, x, y + 1): return True\n# b[y][x] = c\n# return False\n# return any(dfs(0, j, i) for i in range(m) for j in range(n) if w[0] == b[i][j])","sub_path":"Array/79. Word Search(Med).py","file_name":"79. Word Search(Med).py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"352236527","text":"from flask import Blueprint, jsonify, request, make_response\nfrom data.database.video import Video, video_schema, videos_schema\nfrom data.api.auth import permission_needed\nfrom werkzeug import secure_filename\nimport os\nfrom data.config import upload_path\nfrom fnmatch import fnmatch\nfrom datetime import datetime\nimport pafy\nfrom flask_jwt_extended import decode_token\n\n\nbp = Blueprint('video_api', __name__, url_prefix='/api')\n\n\n@bp.route('/video/add_from_file', methods=['POST'])\n@permission_needed\ndef create_video():\n \"\"\"\n example: POST: host/api/video/add_from_file\n \"\"\"\n\n file = request.files.get('file')\n\n access_token = request.headers.get('Authorization')\n\n decoded_token = decode_token(access_token)\n\n author_id = decoded_token['identity']\n\n title = ''\n text = ''\n\n if not file:\n return make_response(jsonify(message='no file found.')), 400\n\n filename = secure_filename(file.filename)\n\n if not fnmatch(filename, '*.mp4'):\n return make_response(jsonify(message='the video format should be mp4.')), 400\n\n path = '{}{}/{}'.format(upload_path, 'videos', author_id)\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n new_filename = secure_filename(str(datetime.now()) + '.mp4')\n file.save('{}{}{}'.format(path, '/', new_filename))\n\n new_video = Video(author_id, title, text, root=path, filename=new_filename)\n new_video.save()\n return make_response(video_schema.jsonify(new_video)), 201\n\n\n@bp.route('/video/add_from_url', methods=['GET'])\n@permission_needed\ndef add_video_from_url():\n \"\"\"\n example: GET: host/api/video?url=nickipedia\n \"\"\"\n\n url = request.args.get('url', default='', type=str)\n\n access_token = request.headers.get('Authorization')\n\n decoded_token = decode_token(access_token)\n\n author_id = decoded_token['identity']\n\n path = '{}{}/{}'.format(upload_path, 'videos', author_id)\n\n new_filename = secure_filename(str(datetime.now()) + '.mp4')\n\n try:\n video = pafy.new(url)\n\n title = video.title\n text = video.description\n original_author = video.author\n views = video.viewcount\n duration = video.duration\n best = video.getbest(preftype='mp4')\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n best.download(filepath='{}{}{}'.format(path, '/', new_filename), quiet=True)\n\n new_video = Video(author_id, title, text, root=path, filename=new_filename)\n new_video.original_author = original_author\n new_video.original_views = views\n new_video.duration = duration\n new_video.save()\n return make_response(video_schema.jsonify(new_video)), 201\n\n except ValueError:\n return make_response(jsonify(message='video url not correct.')), 400\n\n\n@bp.route('/video', methods=['GET'])\ndef get_videos():\n \"\"\"\n example: GET: host/api/video?video_id=1\n \"\"\"\n\n video_id = request.args.get('video_id', default=0, type=int)\n all = request.args.get('all', default=False, type=bool)\n\n if all:\n\n all_videos_public = Video.get_all_public()\n\n if not all_videos_public:\n return make_response(jsonify(message='no video was found.')), 404\n\n result = videos_schema.dump(all_videos_public)\n\n return make_response(jsonify(result.data)), 200\n\n if not all:\n\n video = Video.query.get(video_id)\n if not video:\n return make_response(jsonify(message='video not found.')), 404\n\n return make_response(video_schema.jsonify(video)), 200\n\n\n@bp.route('/video', methods=['PUT'])\n#@permission_needed\ndef update_video():\n \"\"\"\n example: PUT: host/api/video/?video_id=1\n \"\"\"\n\n if not request.is_json:\n return make_response(jsonify(message='missing json.')), 400\n\n video_id = request.args.get('video_id', default=0, type=int)\n\n video = Video.query.get(video_id)\n if not video:\n return make_response(jsonify(message='video not found.')), 404\n\n data = request.get_json()\n data.pop('id', None)\n data.pop('author_id', None)\n\n errors = video_schema.validate(data, partial=True)\n\n if errors:\n return make_response(jsonify(errors)), 400\n\n video.update(**data)\n\n return make_response(jsonify(message='video updated.')), 201\n\n\n@bp.route('/video/thumbnail', methods=['PUT'])\n@permission_needed\ndef video_thumbnail():\n \"\"\"\n example: PUT: host/api/video/thumbnail?id=0\n \"\"\"\n\n video_id = request.args.get('id', default=0, type=int)\n\n access_token = request.headers.get('Authorization')\n\n decoded_token = decode_token(access_token)\n\n author_id = decoded_token['identity']\n\n video = Video.query.get(video_id)\n\n if not video:\n return make_response(jsonify(message='video not found')), 400\n\n pic = request.files.get('file')\n\n if not pic:\n return make_response(jsonify(message='no file found.')), 400\n\n filename = secure_filename(pic.filename)\n\n if not fnmatch(filename, '*.jpg'):\n return make_response(jsonify(message='the file format should be jpg.')), 400\n\n path = '{}{}/{}'.format(upload_path, 'photos', author_id)\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n new_filename = secure_filename(str(datetime.now()) + '.jpg')\n path = '{}{}{}'.format(path, '/', new_filename)\n pic.save(path)\n\n video.thumbnail = new_filename\n video.save()\n return make_response(jsonify(message='video thumbnail updated.')), 201\n\n\n@bp.route('/video', methods=['DELETE'])\n#@permission_needed\ndef delete_video():\n \"\"\"\n example: DELETE: host/api/video/?video_id=1\n \"\"\"\n\n video_id = request.args.get('video_id', default=0, type=int)\n\n video = Video.query.get(video_id)\n if not video:\n return make_response(jsonify(message='video not found.')), 404\n\n video.delete()\n\n return make_response(jsonify(message='video deleted.')), 200\n","sub_path":"flask/data/api/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":5869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"393497787","text":"import requests as rq\nfrom bs4 import BeautifulSoup as bs\n\nurl = \"http://www.uia.no\"\nr = rq.get(url)\ndata = r.text\nsoup = bs(data, \"html.parser\")\n\nfor link in soup.find_all('a'):\n innerurl = link.get('href')\n s = rq.get(innerurl)\n innerdata = s.text\n innersoup = bs(innerdata, \"html.parser\")\n","sub_path":"Scripting/webDev/findLinks.py","file_name":"findLinks.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"277550918","text":"# import time module, Observer, FileSystemEventHandler \nimport time \nfrom watchdog.observers import Observer \nfrom watchdog.events import FileSystemEventHandler \nimport ntpath\nimport os\nimport shutil\n\n\nwatchDirectory = input(\"the full path to the file that you wanna arrange: \")\ndestination=input(\"the destination where the files should be arranged: \")\nvideo=destination+'/video'\nos.mkdir(video)\npdf=destination+'/pdf'\nos.mkdir(pdf)\nimages=destination+'/images'\nos.mkdir(images)\napp=destination+'/app'\nos.mkdir(app)\nzipfile=destination+'/zip'\nos.mkdir(zipfile)\n\nclass OnMyWatch: \n\twatchDirectory=watchDirectory\n\t\n\n\tdef __init__(self): \n\t\tself.observer = Observer() \n\n\tdef run(self): \n\t\tevent_handler = Handler() \n\t\tself.observer.schedule(event_handler, self.watchDirectory, recursive = True) \n\t\tself.observer.start() \n\t\ttry: \n\t\t\twhile True: \n\t\t\t\ttime.sleep(5) \n\t\texcept: \n\t\t\tself.observer.stop() \n\t\t\tprint(\"Observer Stopped\") \n\n\t\tself.observer.join() \n\nclass Handler(FileSystemEventHandler):\n\tdef on_any_event(self,event):\n\t\tif event.is_directory:\n\t\t\treturn None\n\t\telif event.event_type == 'created':\n\t\t\tfile_path=event.src_path\n\t\t\tfile_name=ntpath.basename(file_path)\n\t\t\tsplit=os.path.splitext(file_name)\n\t\t\tif split[1]=='.pdf':\n \t\t\t\tshutil.move(file_path,pdf)\n\t\t\tif split[1]=='.mp4' or split[1]=='.avi' or split[1]=='.mov' or split[1]=='.flv' or split[1]=='.mkv' or split[1]=='.ts':\n \t\t\t\tshutil.move(file_path,video)\n\t\t\tif split[1]=='.zip':\n \t\t\t\tshutil.move(file_path,zipfile)\n\t\t\tif split[1]=='.jpeg' or split[1]=='.gif' or split[1]=='.png' or split[1]=='.svg':\n \t\t\t\tshutil.move(file_path,images)\n\t\t\tif split[1]=='.exe':\n \t\t\t\tshutil.move(file_path,app)\n\n\n\n \t\t\t\t\n \t\t\t\t\n\t\t\n\t\t\t\n\t\t\n \t\t\t\n\nif __name__=='__main__':\n\twatch=OnMyWatch()\n\twatch.run()\n\n\n\t\t\t\t\t\t \n\n\t\t\t\t\n\n","sub_path":"automate.py","file_name":"automate.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"466558963","text":"import manager\nfrom consts import Consts\nfrom medical_state import (\n INFECTABLE_MEDICAL_STATES,\n INFECTIONS_MEDICAL_STATES,\n MedicalState,\n)\n\n\nclass Agent:\n \"\"\"\n This class represents a person in our doomed world.\n \"\"\"\n\n __slots__ = (\n \"ssn\",\n \"ID\",\n \"home\",\n \"work\",\n \"medical_state\",\n \"infection_date\",\n \"is_home_quarantined\",\n \"is_full_quarantined\",\n \"next_medical_state_transmition_date\",\n \"next_medical_state\",\n )\n\n def __init__(self, ssn):\n self.ssn = ssn\n self.ID = ssn\n self.home = None\n self.work = None\n self.infection_date = None\n self.medical_state = MedicalState.Healthy\n self.is_home_quarantined = False\n self.is_full_quarantined = False\n self.next_medical_state_transmition_date = -1\n self.next_medical_state = MedicalState.Latent\n\n def __str__(self):\n return \"\".format(self.ssn, self.medical_state)\n\n def is_infectious(self):\n \"\"\"\n Check if this agent is infectious.\n\n :return: bool, True if this agent can infect others.\n \"\"\"\n\n # pay attantion, doesn't have to be only in this stage. in the future this could be multiple stages check\n return self.medical_state in INFECTIONS_MEDICAL_STATES\n\n def is_infectable(self):\n return self.medical_state in INFECTABLE_MEDICAL_STATES\n\n def infect(self, date=0, manager=None):\n \"\"\"\n Will try to infect this agent with given probability\n \"\"\"\n if self.is_infectable():\n self.change_medical_state(current_date=date, manager=manager)\n self.infection_date = date\n return True\n\n def get_infection_ratio(self, consts: Consts):\n if self.medical_state == MedicalState.Symptomatic:\n return consts.Symptomatic_infection_ratio\n elif self.medical_state == MedicalState.Asymptomatic:\n return consts.ASymptomatic_infection_ratio\n elif self.medical_state == MedicalState.Silent:\n return consts.Silent_infection_ratio\n # right now you are not infecting when in hospital\n # elif self.medical_state == MedicalState.Hospitalized:\n # return consts.Symptomatic_infection_ratio # todo find out the real number\n # elif self.medical_state == MedicalState.Icu:\n # return consts.Symptomatic_infection_ratio # todo find out the real number\n return 0\n\n def add_home(self, home):\n self.home = home\n\n def add_work(self, work):\n self.work = work\n\n def change_medical_state(self, current_date: int, roll=-1, manager=None):\n # todo now doesnt roll for next transition date\n if current_date < self.next_medical_state_transmition_date:\n return \"nothing new\"\n else:\n if manager is not None:\n if self.medical_state != MedicalState.Healthy:\n manager.counters[self.medical_state] = (\n manager.counters[self.medical_state] - 1\n )\n manager.counters[self.next_medical_state] = (\n manager.counters[self.next_medical_state] + 1\n )\n if self.next_medical_state == MedicalState.Latent:\n self.medical_state = MedicalState.Latent\n self.next_medical_state = MedicalState.Silent\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_latent_to_silent_days\n )\n return \"new latent\"\n elif self.next_medical_state == MedicalState.Silent:\n self.medical_state = MedicalState.Silent\n if (\n roll < Consts.silent_to_asymptomatic_probability\n ): # next is asymptomatic\n self.next_medical_state = MedicalState.Asymptomatic\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_silent_to_asymptomatic_days\n )\n else:\n self.next_medical_state = MedicalState.Symptomatic\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_silent_to_symptomatic_days\n )\n return \"new_infecting\"\n elif self.next_medical_state == MedicalState.Asymptomatic:\n self.medical_state = MedicalState.Asymptomatic\n self.next_medical_state = MedicalState.Immune\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_asymptomatic_to_recovered_days\n )\n return \"new asymptomatic\"\n elif self.next_medical_state == MedicalState.Immune:\n self.medical_state = MedicalState.Immune\n self.next_medical_state_transmition_date = -1\n return \"new_not_infecting\"\n elif self.next_medical_state == MedicalState.Symptomatic:\n self.medical_state = MedicalState.Symptomatic\n if roll < Consts.symptomatic_to_asymptomatic_probability:\n self.next_medical_state = MedicalState.Asymptomatic\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_symptomatic_to_asymptomatic_days\n )\n else:\n self.next_medical_state = MedicalState.Hospitalized\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_symptomatic_to_hospitalized_days\n )\n return \"new symptomatic\"\n elif self.next_medical_state == MedicalState.Hospitalized:\n self.medical_state = MedicalState.Hospitalized\n if roll < Consts.hospitalized_to_asymptomatic_probability:\n self.next_medical_state = MedicalState.Asymptomatic\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_hospitalized_to_asymptomatic_days\n )\n else:\n self.next_medical_state = MedicalState.Icu\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_hospitalized_to_icu_days\n )\n return \"new hospitalized\"\n elif self.next_medical_state == MedicalState.Icu:\n self.medical_state = MedicalState.Icu\n if roll < Consts.icu_to_hospitalized_probability:\n self.next_medical_state = MedicalState.Hospitalized\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_icu_to_hospitalized_days\n )\n else:\n self.next_medical_state = MedicalState.Deceased\n self.next_medical_state_transmition_date = (\n current_date + Consts.average_icu_to_dead_days\n )\n return \"new icu\"\n elif self.next_medical_state == MedicalState.Deceased:\n self.medical_state = MedicalState.Deceased\n return \"new_not_infecting\"\n\n return \"nothing new\"\n\n def __cmp__(self, other):\n return self.ID == other.ID\n\n\nclass Circle:\n __slots__ = \"type\", \"agents\"\n\n def __init__(self, type):\n self.type = type\n self.agents = []\n\n def add_agent(self, agent):\n self.agents.append(agent)\n\n def get_indexes_of_my_circle(self, my_index):\n rest_of_circle = {o.ID for o in self.agents}\n rest_of_circle.remove(my_index)\n return rest_of_circle\n","sub_path":"src/corona_hakab_model/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":7912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"126598648","text":"import unittest\nfrom Heap import Heap\n\n# Returns a heap containing 100 integers in the range 1 through 100.\ndef test_Heap():\n from random import choice, randint\n\n A = [randint(1,100) for _ in range(50)]\n \n heap = Heap()\n for num in A:\n heap.insert(num)\n\n return heap\n\n\nclass TestHeap(unittest.TestCase):\n\n def test_Heap_init(self):\n heap = Heap()\n self.assertEqual(len(heap), 0)\n\n\n def test_access(self):\n heap = test_Heap()\n result = heap.access()\n self.assertEqual(result, max(heap.heap))\n\n heap = test_Heap()\n result = heap.access()\n self.assertEqual(result, max(heap.heap))\n\n\n def test_search(self):\n from random import choice\n\n heap = test_Heap()\n \n search_key = choice(heap.heap)\n result = heap.search( search_key )\n self.assertEqual( result, heap.heap.index(search_key) )\n\n result = heap.search(1000)\n self.assertEqual(result, -1)\n\n\n def test_insert(self):\n from random import choice, randint\n\n A = [randint(1,100) for _ in range(50)]\n \n heap = Heap()\n for num in A:\n heap.insert(num)\n self.assertEqual( heap.is_valid_heap() , True)\n\n\n def test_delete(self):\n from random import choice\n heap = test_Heap()\n\n for i in range(50):\n currMax = max(heap.heap)\n result = heap.delete()\n self.assertEqual(result, currMax)\n self.assertEqual( heap.is_valid_heap() , True)\n\n # Test deletion when heap is empty\n heap.delete()\n self.assertEqual(heap.heap, [])","sub_path":"InterviewPrep/datastructures/test_Heap.py","file_name":"test_Heap.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"325414565","text":"class Solution(object):\n def letterCombinations(self, digits):\n dic = [\" \", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"]\n result = []\n if not digits:\n return result\n result.append(\"\")\n for i in range(0, len(digits)):\n letters = dic[ord(digits[i]) - ord('0')]\n newRes = []\n for j in range(0, len(result)):\n for k in range(0, len(letters)):\n newRes.append(result[j] + letters[k])\n result = newRes\n return result\n","sub_path":"17/17.letter-combinations-of-a-phone-number.744898942.Accepted.leetcode.python3.py","file_name":"17.letter-combinations-of-a-phone-number.744898942.Accepted.leetcode.python3.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"498648802","text":"import argparse\nimport h5py\nimport numpy as np\nimport random\nimport math\nimport os\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Udacity SDC Challenge-2 Video viewer')\n parser.add_argument('--dataset', type=str, default=\"dataset.h5\", help='Dataset/ROS Bag name')\n\n args = parser.parse_args()\n\n dataset = args.dataset\n\n hdf5_file = h5py.File(dataset, 'r+')\n\n ys_dataset = hdf5_file['y_dataset']\n\n ys = ys_dataset[()]\n\n ys /= np.max(np.abs(ys)) # normalize to [-1, 1] interval\n signs = np.sign(ys)\n\n scale_value = 5\n\n ys = np.log((np.abs(ys) * scale_value) + 1) # log-transform with scale before so more effective\n ys *= signs\n ys /= np.max(np.abs(ys)) # re-normalize\n\n for i in range(len(ys)):\n ys_dataset[i] = ys[i]","sub_path":"normalize_hdf5.py","file_name":"normalize_hdf5.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"349442727","text":"\n\nfrom xai.brain.wordbase.nouns._typeface import _TYPEFACE\n\n#calss header\nclass _TYPEFACES(_TYPEFACE, ):\n\tdef __init__(self,): \n\t\t_TYPEFACE.__init__(self)\n\t\tself.name = \"TYPEFACES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"typeface\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_typefaces.py","file_name":"_typefaces.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"112910160","text":"import os\nimport logging\n\nimport redis\n\n\ndef get_env() -> dict:\n if not os.environ.get('ENV'):\n a = os.path.join(os.path.dirname(__file__), '../environment/test')\n with open(a) as f:\n defaults = dict(tuple(x.strip().split('=')) for x in f.readlines() if x != '\\n')\n return defaults\n else:\n return os.environ\n\n\nenv = get_env()\n\nlogging.basicConfig(level=getattr(logging, env.get('LOG_LEVEL').upper()))\n\nredis_db = redis.Redis(env.get('REDIS_HOST'), port=int(env.get('REDIS_PORT')))\n\ntwitter_access_token = env.get('TWITTER_ACCESS_TOKEN')\ntwitter_access_secret = env.get('TWITTER_ACCESS_SECRET')\ntwitter_consumer_key = env.get('TWITTER_CONSUMER_KEY')\ntwitter_consumer_secret = env.get('TWITTER_CONSUMER_SECRET')\n","sub_path":"python/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"122509103","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport importlib\nimport os\nimport sys\n\nimport compas_rhino\n\nfrom compas._os import create_symlink\n\n__all__ = []\n\nINSTALLABLE_PACKAGES = ('compas', 'compas_ghpython', 'compas_rhino')\n\n\ndef _get_package_path(package):\n return os.path.abspath(os.path.join(os.path.dirname(package.__file__), '..'))\n\n\ndef install(version='6.0', packages=None):\n \"\"\"Install COMPAS for Rhino.\n\n Parameters\n ----------\n version : {'5.0', '6.0'}\n The version number of Rhino.\n packages : list of str\n List of packages to install or None to use default package list.\n\n Examples\n --------\n .. code-block:: python\n\n >>> import compas_rhino\n >>> compas_rhino.install('6.0')\n\n .. code-block:: python\n\n $ python -m compas_rhino.install 6.0\n\n \"\"\"\n\n print('Installing COMPAS packages to Rhino {0} IronPython lib:'.format(version))\n\n ipylib_path = compas_rhino._get_ironpython_lib_path(version)\n\n results = []\n exit_code = 0\n\n for package in packages:\n base_path = _get_package_path(importlib.import_module(package))\n package_path = os.path.join(base_path, package)\n symlink_path = os.path.join(ipylib_path, package)\n\n if os.path.exists(symlink_path):\n results.append(\n (package, 'ERROR: Package \"{}\" already found in Rhino lib, try uninstalling first'.format(package)))\n continue\n\n try:\n create_symlink(package_path, symlink_path)\n results.append((package, 'OK'))\n except OSError:\n results.append(\n (package, 'Cannot create symlink, try to run as administrator.'))\n\n for _, status in results:\n if status is not 'OK':\n exit_code = -1\n\n # Installing the bootstrapper rarely fails, so, only do it if no other package failed\n if exit_code == -1:\n results.append(('compas_bootstrapper', 'ERROR: One or more packages failed, will not install bootstrapper, try uninstalling first'))\n else:\n conda_prefix = os.environ.get('CONDA_PREFIX', None)\n try:\n with open(os.path.join(ipylib_path, 'compas_bootstrapper.py'), 'w') as f:\n f.write('CONDA_PREFIX = r\"{0}\"'.format(conda_prefix))\n results.append(('compas_bootstrapper', 'OK'))\n except:\n results.append(\n ('compas_bootstrapper', 'Could not create compas_bootstrapper to auto-determine Python environment'))\n\n for package, status in results:\n print(' {} {}'.format(package.ljust(20), status))\n\n # Re-check just in case bootstrapper failed\n if status is not 'OK':\n exit_code = -1\n\n print('\\nCompleted.')\n sys.exit(exit_code)\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == \"__main__\":\n\n import sys\n\n print('\\nusage: python -m compas_rhino.install [version]\\n')\n print(' version Rhino version (5.0 or 6.0)\\n')\n\n try:\n version = sys.argv[1]\n except IndexError:\n version = '6.0'\n else:\n try:\n version = str(version)\n except Exception:\n version = '6.0'\n\n install(version=version, packages=INSTALLABLE_PACKAGES)\n","sub_path":"src/compas_rhino/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":3418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"431293083","text":"#!/usr/bin/env python\n\nimport functools\nimport markdown\nimport os.path\nimport re\nimport tornado.web\nimport tornado.wsgi\nimport unicodedata\nimport wsgiref.handlers\nimport logging\n\nfrom tornado import escape\nfrom imdb import Person\nfrom imdb import IMDb\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\nfrom google.appengine.api import urlfetch\nfrom google.appengine.api import images\n\nclass Movie(db.Model):\n imdbID = db.StringProperty()\n title = db.StringProperty()\n year = db.StringProperty()\n plotOutline = db.StringProperty()\n plot = db.TextProperty()\n picture = db.BlobProperty(default=None)\n director = db.StringListProperty()\n writer = db.StringListProperty()\n cast = db.StringListProperty()\n certificates = db.StringListProperty()\n category = db.CategoryProperty()\n runtimes = db.StringListProperty()\n\n def cert(self, country):\n for cert in self.certificates:\n i = cert.find('::')\n if i != -1:\n cert = cert[:i]\n i = cert.find(country)\n if i != -1:\n j = cert.find(':')\n return cert[j+1:]\n return \"Unknown\"\n\n def get_cast(self, limit=5, joiner=u', '):\n if len(self.cast) == 0 : return \"Not Available\"\n cast = self.cast[:limit]\n return joiner.join(cast)\n\n def get_director(self, limit=5, joiner=u', '):\n if len(self.director) == 0 : return \"Not Available\"\n director = self.director[:limit]\n return joiner.join(director)\n\n def get_writer(self, limit=5, joiner=u', '):\n if len(self.writer) == 0 : return \"Not Available\"\n writer = self.writer[:limit]\n return joiner.join(writer)\n\n def get_runtime(self):\n return self.runtimes[0]\n\ndef administrator(method):\n \"\"\"Decorate with this method to restrict to site admins.\"\"\"\n @functools.wraps(method)\n def wrapper(self, *args, **kwargs):\n if not self.current_user:\n if self.request.method == \"GET\":\n self.redirect(self.get_login_url())\n return\n raise tornado.web.HTTPError(403)\n elif not self.current_user.administrator:\n if self.request.method == \"GET\":\n self.redirect(\"/\")\n return\n raise tornado.web.HTTPError(403)\n else:\n return method(self, *args, **kwargs)\n return wrapper\n\nclass BaseHandler(tornado.web.RequestHandler):\n \"\"\"Implements Google Accounts authentication methods.\"\"\"\n def get_current_user(self):\n user = users.get_current_user()\n if user: user.administrator = users.is_current_user_admin()\n return user\n\n def get_login_url(self):\n return users.create_login_url(self.request.uri)\n\n def render_string(self, template_name, **kwargs):\n # Let the templates access the users module to generate login URLs\n return tornado.web.RequestHandler.render_string(\n self, template_name, users=users, **kwargs)\n\nclass HomeHandler(BaseHandler):\n def get(self):\n self.redirect(\"cms/index.html\")\n\nclass ImdbHandler(BaseHandler):\n \"\"\" Manages Showing now films http://127.0.0.1:8000/showingNow?action=store&id=1504320 \"\"\"\n def _findPlot(self, movie):\n \"\"\" Find and return the most suitable plot information from a movie \"\"\"\n plot = movie.get('plot')\n if not plot:\n plot = movie.get('plot outline')\n if plot:\n plot = [plot]\n if plot:\n plot = plot[0]\n i = plot.find('::')\n if i != -1:\n plot = plot[:i]\n return plot\n\n def _moviePoster(self, movie):\n \"\"\" Find the best poster for a movie \"\"\"\n pictureFile = urlfetch.Fetch(movie.get('full-size cover url')).content\n\n # If we can't fina a poster then use the not avaiable image\n if not pictureFile:\n pictureFile = urlfetch.Fetch('/image/notavailable.jpg').content\n\n # Make all our images 500 pixels wide to avoid storing giant image blobs\n image = images.Image(pictureFile)\n image.resize(500)\n return image.execute_transforms(output_encoding=images.JPEG)\n\n def _personToString(self, personList):\n nl = []\n for person in personList:\n n = person.get('name', u'')\n if person.currentRole: n += u' (%s)' % person.currentRole\n nl.append(n)\n return nl\n\n def get(self):\n action = self.get_argument(\"action\")\n\n if action == \"store\":\n ia = IMDb('http')\n imdbKey = self.get_argument(\"id\")\n category = self.get_argument(\"cat\", \"SN\")\n imdbMovie = ia.get_movie(imdbKey)\n\n movie = Movie(key_name = imdbMovie.movieID,\n imdbID = imdbMovie.movieID,\n title = imdbMovie.get('title', u'Not Available'),\n year = str(imdbMovie.get('year')),\n plotOutline = imdbMovie.get('plot outline'),\n plot = self._findPlot(imdbMovie),\n picture = db.Blob(self._moviePoster(imdbMovie)),\n director = self._personToString(imdbMovie.get('director')),\n writer = self._personToString(imdbMovie.get('writer')),\n cast = self._personToString(imdbMovie.get('cast')),\n certificates = imdbMovie.get('certificates'),\n category = db.Category(category),\n runtimes = imdbMovie.get('runtimes')\n )\n movie.put()\n\n filmJson = escape.json_encode({\n 'id': movie.imdbID,\n 'title':movie.title,\n 'year':movie.year,\n 'plotOutline':movie.plotOutline,\n 'plot':movie.plot,\n 'director':movie.director,\n 'writer':movie.writer,\n 'cast':movie.cast,\n 'runtimes':movie.runtimes\n })\n\n logging.info(filmJson)\n self.write(filmJson)\n\n if action == \"search\":\n ia = IMDb('http')\n movies = []\n\n for movie in ia.search_movie(self.get_argument(\"title\")):\n movies.append({'id': movie.movieID,'title':movie.get('long imdb canonical title')})\n\n self.write(escape.json_encode(movies))\n\n if action == \"display\":\n ia = IMDb('http')\n imdbMovie = ia.get_movie(self.get_argument(\"id\"))\n self.set_header(\"Content-Type\", \"text/xml\")\n self.write(imdbMovie.asXML())\n\nclass ImageHandler(BaseHandler):\n\n def get(self):\n id = self.get_argument('id')\n newWidth = self.get_argument('width', 0)\n\n result = db.GqlQuery(\"SELECT * FROM Movie WHERE imdbID = :1 LIMIT 1\",id).fetch(1)\n movie = result[0]\n picture = movie.picture\n\n if newWidth > 0:\n image = images.Image(picture)\n image.resize(int(newWidth))\n picture = image.execute_transforms(output_encoding=images.JPEG)\n\n self.set_header(\"Content-Type\", \"image/jpeg\")\n self.write(str(picture))\n\nclass PurgeHandler(BaseHandler):\n \"\"\"Remove all movies\"\"\"\n def get(self):\n movies = db.GqlQuery(\"SELECT * FROM Movie\")\n for movie in movies:\n movie.delete()\n\nclass CmsHandler(BaseHandler):\n \"\"\"Fire up the CMS application\"\"\"\n def get(self):\n self.redirect(\"/static/cinemaCMS.html\")\n\nclass rcfHomeHandler(BaseHandler):\n def get(self):\n movies = db.GqlQuery(\"SELECT * FROM Movie WHERE category='SN' LIMIT 3\")\n self.render(\"rcfHome.html\", movies=movies)\n\nclass rcfShowingNowHandler(BaseHandler):\n \"\"\"Display the Showing Now page for the Royal Cinema\"\"\"\n def get(self):\n movies = db.GqlQuery(\"SELECT * FROM Movie WHERE category='SN'\")\n self.render(\"rcfShowingNow.html\", movies=movies)\n\nclass rcfComingSoonHandler(BaseHandler):\n \"\"\"Display the Coming Soon page for the Royal Cinema\"\"\"\n def get(self):\n movies = db.GqlQuery(\"SELECT * FROM Movie WHERE category='CS'\")\n self.render(\"rcfComingSoon.html\", movies=movies)\n\nclass rcfAboutUsHandler(BaseHandler):\n \"\"\"Display the About Us page for the Royal Cinema\"\"\"\n def get(self):\n self.render(\"rcfAboutUs.html\")\n\nclass rcfContactUsHandler(BaseHandler):\n \"\"\"Display the About Us page for the Royal Cinema\"\"\"\n def get(self):\n self.render(\"rcfContactUs.html\")\n\nclass FilmModule(tornado.web.UIModule):\n def render(self, movies):\n return self.render_string(\"modules/film.html\", movies=movies)\n\nclass FilmDetailModule(tornado.web.UIModule):\n\n def render(self, movie):\n return self.render_string(\"modules/filmDetail.html\", movie=movie)\n\nclass AdScraperModule(tornado.web.UIModule):\n \"\"\"Google Adsense Scraper Ad\"\"\"\n def render(self):\n return self.render_string(\"modules/scraper.html\")\n\nclass FilmComingModule(tornado.web.UIModule):\n \"\"\"Module for Coming Soon film details\"\"\"\n def render(self, movie):\n return self.render_string(\"modules/filmComing.html\", movie=movie)\n\nsettings = {\n \"cinema_name\": u\"The Royal Cinema\",\n \"cinema_location\": u\"Faversham\",\n \"cinema_title\": u\"The Royal Cinema Faversham\",\n \"template_path\": os.path.join(os.path.dirname(__file__), \"templates\"),\n \"static_path\": os.path.join(os.path.dirname(__file__), \"static\"),\n \"ui_modules\": {\n \"Film\": FilmModule,\n \"FilmDetail\": FilmDetailModule,\n \"AdScraper\": AdScraperModule,\n \"FilmComing\": FilmComingModule\n },\n \"xsrf_cookies\": True,\n}\n\napplication = tornado.wsgi.WSGIApplication([\n (r\"/\", HomeHandler),\n (r\"/purge\", PurgeHandler),\n (r\"/cms\", CmsHandler),\n (r\"/imdb\", ImdbHandler),\n (r\"/image\", ImageHandler),\n], **settings)\n\napplication.add_handlers(r\"royalcinema\\.independent-cinemas\\.com\", [\n (r\"/\", rcfHomeHandler),\n (r\"/home\", rcfHomeHandler),\n (r\"/index.html\", rcfHomeHandler),\n (r\"/showingNow\", rcfShowingNowHandler),\n (r\"/comingSoon\", rcfComingSoonHandler),\n (r\"/aboutUs\", rcfAboutUsHandler),\n (r\"/contactUs\", rcfContactUsHandler),\n (r\"/image\", ImageHandler),\n ])\n\ndef main():\n wsgiref.handlers.CGIHandler().run(application)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cinema.py","file_name":"cinema.py","file_ext":"py","file_size_in_byte":10376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"318932736","text":"\"\"\"Rule for checking content of jinja template strings.\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport re\nimport sys\nfrom collections import namedtuple\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any\n\nimport black\nimport jinja2\nfrom ansible.errors import AnsibleError, AnsibleParserError\nfrom ansible.parsing.yaml.objects import AnsibleUnicode\nfrom jinja2.exceptions import TemplateSyntaxError\n\nfrom ansiblelint.constants import LINE_NUMBER_KEY\nfrom ansiblelint.file_utils import Lintable\nfrom ansiblelint.rules import AnsibleLintRule\nfrom ansiblelint.skip_utils import get_rule_skips_from_line\nfrom ansiblelint.text import has_jinja\nfrom ansiblelint.utils import parse_yaml_from_file, template\nfrom ansiblelint.yaml_utils import deannotate, nested_items_path\n\nif TYPE_CHECKING:\n from ansiblelint.errors import MatchError\n from ansiblelint.utils import Task\n\n\n_logger = logging.getLogger(__package__)\nKEYWORDS_WITH_IMPLICIT_TEMPLATE = (\"changed_when\", \"failed_when\", \"until\", \"when\")\n\nToken = namedtuple(\"Token\", \"lineno token_type value\")\n\nignored_re = re.compile(\n \"|\".join( # noqa: FLY002\n [\n r\"^Object of type method is not JSON serializable\",\n r\"^Unexpected templating type error occurred on\",\n r\"^obj must be a list of dicts or a nested dict$\",\n r\"^the template file (.*) could not be found for the lookup$\",\n r\"could not locate file in lookup\",\n r\"unable to locate collection\",\n r\"^Error in (.*)is undefined$\",\n r\"^Mandatory variable (.*) not defined.$\",\n r\"is undefined\",\n r\"Unrecognized type <> for (.*) filter $\",\n # https://github.com/ansible/ansible-lint/issues/3155\n r\"^The '(.*)' test expects a dictionary$\",\n ],\n ),\n flags=re.MULTILINE | re.DOTALL,\n)\n\n\nclass JinjaRule(AnsibleLintRule):\n \"\"\"Rule that looks inside jinja2 templates.\"\"\"\n\n id = \"jinja\"\n severity = \"LOW\"\n tags = [\"formatting\"]\n version_added = \"v6.5.0\"\n _ansible_error_re = re.compile(\n r\"^(?P.*): (?P.*)\\. String: (?P.*)$\",\n flags=re.MULTILINE,\n )\n\n env = jinja2.Environment(trim_blocks=False)\n _tag2msg = {\n \"invalid\": \"Syntax error in jinja2 template: {value}\",\n \"spacing\": \"Jinja2 spacing could be improved: {value} -> {reformatted}\",\n }\n _ids = {\n \"jinja[invalid]\": \"Invalid jinja2 syntax\",\n \"jinja[spacing]\": \"Jinja2 spacing could be improved\",\n }\n\n def _msg(self, tag: str, value: str, reformatted: str) -> str:\n \"\"\"Generate error message.\"\"\"\n return self._tag2msg[tag].format(value=value, reformatted=reformatted)\n\n # pylint: disable=too-many-locals\n def matchtask(\n self,\n task: Task,\n file: Lintable | None = None,\n ) -> list[MatchError]:\n result = []\n try:\n for key, v, path in nested_items_path(\n task,\n ignored_keys=(\"block\", \"ansible.builtin.block\", \"ansible.legacy.block\"),\n ):\n if isinstance(v, str):\n try:\n template(\n basedir=file.path.parent if file else Path(\".\"),\n value=v,\n variables=deannotate(task.get(\"vars\", {})),\n fail_on_error=True, # we later decide which ones to ignore or not\n )\n # ValueError RepresenterError\n except AnsibleError as exc:\n bypass = False\n orig_exc = (\n exc.orig_exc if getattr(exc, \"orig_exc\", None) else exc\n )\n orig_exc_message = getattr(orig_exc, \"message\", str(orig_exc))\n match = self._ansible_error_re.match(\n getattr(orig_exc, \"message\", str(orig_exc)),\n )\n if ignored_re.search(orig_exc_message) or isinstance(\n orig_exc,\n AnsibleParserError,\n ):\n # An unhandled exception occurred while running the lookup plugin 'template'. Error was a , original message: the template file ... could not be found for the lookup. the template file ... could not be found for the lookup\n\n # ansible@devel (2.14) new behavior:\n # AnsibleError(TemplateSyntaxError): template error while templating string: Could not load \"ipwrap\": 'Invalid plugin FQCN (ansible.netcommon.ipwrap): unable to locate collection ansible.netcommon'. String: Foo {{ buildset_registry.host | ipwrap }}. Could not load \"ipwrap\": 'Invalid plugin FQCN (ansible.netcommon.ipwrap): unable to locate collection ansible.netcommon'\n bypass = True\n elif (\n isinstance(orig_exc, (AnsibleError, TemplateSyntaxError))\n and match\n ):\n error = match.group(\"error\")\n detail = match.group(\"detail\")\n if error.startswith(\n \"template error while templating string\",\n ):\n bypass = False\n elif detail.startswith(\"unable to locate collection\"):\n _logger.debug(\"Ignored AnsibleError: %s\", exc)\n bypass = True\n else:\n bypass = False\n elif re.match(r\"^lookup plugin (.*) not found$\", exc.message):\n # lookup plugin 'template' not found\n bypass = True\n\n # AnsibleError: template error while templating string: expected token ':', got '}'. String: {{ {{ '1' }} }}\n # AnsibleError: template error while templating string: unable to locate collection ansible.netcommon. String: Foo {{ buildset_registry.host | ipwrap }}\n if not bypass:\n result.append(\n self.create_matcherror(\n message=str(exc),\n lineno=_get_error_line(task, path),\n filename=file,\n tag=f\"{self.id}[invalid]\",\n ),\n )\n continue\n reformatted, details, tag = self.check_whitespace(\n v,\n key=key,\n lintable=file,\n )\n if reformatted != v:\n result.append(\n self.create_matcherror(\n message=self._msg(\n tag=tag,\n value=v,\n reformatted=reformatted,\n ),\n lineno=_get_error_line(task, path),\n details=details,\n filename=file,\n tag=f\"{self.id}[{tag}]\",\n ),\n )\n except Exception as exc:\n _logger.info(\"Exception in JinjaRule.matchtask: %s\", exc)\n raise\n return result\n\n def matchyaml(self, file: Lintable) -> list[MatchError]:\n \"\"\"Return matches for variables defined in vars files.\"\"\"\n data: dict[str, Any] = {}\n raw_results: list[MatchError] = []\n results: list[MatchError] = []\n\n if str(file.kind) == \"vars\":\n data = parse_yaml_from_file(str(file.path))\n # pylint: disable=unused-variable\n for key, v, _path in nested_items_path(data):\n if isinstance(v, AnsibleUnicode):\n reformatted, details, tag = self.check_whitespace(\n v,\n key=key,\n lintable=file,\n )\n if reformatted != v:\n results.append(\n self.create_matcherror(\n message=self._msg(\n tag=tag,\n value=v,\n reformatted=reformatted,\n ),\n lineno=v.ansible_pos[1],\n details=details,\n filename=file,\n tag=f\"{self.id}[{tag}]\",\n ),\n )\n if raw_results:\n lines = file.content.splitlines()\n for match in raw_results:\n # lineno starts with 1, not zero\n skip_list = get_rule_skips_from_line(\n line=lines[match.lineno - 1],\n lintable=file,\n )\n if match.rule.id not in skip_list and match.tag not in skip_list:\n results.append(match)\n else:\n results.extend(super().matchyaml(file))\n return results\n\n def lex(self, text: str) -> list[Token]:\n \"\"\"Parse jinja template.\"\"\"\n # https://github.com/pallets/jinja/issues/1711\n self.env.keep_trailing_newline = True\n\n self.env.lstrip_blocks = False\n self.env.trim_blocks = False\n self.env.autoescape = True\n self.env.newline_sequence = \"\\n\"\n tokens = [\n Token(lineno=t[0], token_type=t[1], value=t[2]) for t in self.env.lex(text)\n ]\n new_text = self.unlex(tokens)\n if text != new_text:\n _logger.debug(\n \"Unable to perform full roundtrip lex-unlex on jinja template (expected when '-' modifier is used): {text} -> {new_text}\",\n )\n return tokens\n\n def unlex(self, tokens: list[Token]) -> str:\n \"\"\"Return original text by compiling the lex output.\"\"\"\n result = \"\"\n last_lineno = 1\n last_value = \"\"\n for lineno, _, value in tokens:\n if lineno > last_lineno and \"\\n\" not in last_value:\n result += \"\\n\"\n result += value\n last_lineno = lineno\n last_value = value\n return result\n\n # pylint: disable=too-many-statements,too-many-locals\n def check_whitespace(\n self,\n text: str,\n key: str,\n lintable: Lintable | None = None,\n ) -> tuple[str, str, str]:\n \"\"\"Check spacing inside given jinja2 template string.\n\n We aim to match Python Black formatting rules.\n :raises NotImplementedError: On few cases where valid jinja is not valid Python.\n\n :returns: (string, string, string) reformatted text, detailed error, error tag\n \"\"\"\n\n def cook(value: str, *, implicit: bool = False) -> str:\n \"\"\"Prepare an implicit string for jinja parsing when needed.\"\"\"\n if not implicit:\n return value\n if value.startswith(\"{{\") and value.endswith(\"}}\"):\n # maybe we should make this an error?\n return value\n return f\"{{{{ {value} }}}}\"\n\n def uncook(value: str, *, implicit: bool = False) -> str:\n \"\"\"Restore an string to original form when it was an implicit one.\"\"\"\n if not implicit:\n return value\n return value[3:-3]\n\n tokens = []\n details = \"\"\n begin_types = (\"variable_begin\", \"comment_begin\", \"block_begin\")\n end_types = (\"variable_end\", \"comment_end\", \"block_end\")\n implicit = False\n\n # implicit templates do not have the {{ }} wrapping\n if (\n key in KEYWORDS_WITH_IMPLICIT_TEMPLATE\n and lintable\n and lintable.kind\n in (\n \"playbook\",\n \"task\",\n )\n ):\n implicit = True\n text = cook(text, implicit=implicit)\n\n # don't try to lex strings that have no jinja inside them\n if not has_jinja(text):\n return text, \"\", \"spacing\"\n\n expr_str = None\n expr_type = None\n verb_skipped = True\n lineno = 1\n try:\n for token in self.lex(text):\n if (\n expr_type\n and expr_type.startswith(\"{%\")\n and token.token_type in (\"name\", \"whitespace\")\n and not verb_skipped\n ):\n # on {% blocks we do not take first word as part of the expression\n tokens.append(token)\n if token.token_type != \"whitespace\":\n verb_skipped = True\n elif token.token_type in begin_types:\n tokens.append(token)\n expr_type = token.value # such {#, {{, {%\n expr_str = \"\"\n verb_skipped = False\n elif token.token_type in end_types and expr_str is not None:\n # process expression\n # pylint: disable=unsupported-membership-test\n if isinstance(expr_str, str) and \"\\n\" in expr_str:\n raise NotImplementedError\n leading_spaces = \" \" * (len(expr_str) - len(expr_str.lstrip()))\n expr_str = leading_spaces + blacken(expr_str.lstrip())\n if tokens[\n -1\n ].token_type != \"whitespace\" and not expr_str.startswith(\" \"):\n expr_str = \" \" + expr_str\n if not expr_str.endswith(\" \"):\n expr_str += \" \"\n tokens.append(Token(lineno, \"data\", expr_str))\n tokens.append(token)\n expr_str = None\n expr_type = None\n elif expr_str is not None:\n expr_str += token.value\n else:\n tokens.append(token)\n lineno = token.lineno\n\n except jinja2.exceptions.TemplateSyntaxError as exc:\n return \"\", str(exc.message), \"invalid\"\n # https://github.com/PyCQA/pylint/issues/7433 - py311 only\n # pylint: disable=c-extension-no-member\n except (NotImplementedError, black.parsing.InvalidInput) as exc:\n # black is not able to recognize all valid jinja2 templates, so we\n # just ignore InvalidInput errors.\n # NotImplementedError is raised internally for expressions with\n # newlines, as we decided to not touch them yet.\n # These both are documented as known limitations.\n _logger.debug(\"Ignored jinja internal error %s\", exc)\n return uncook(text, implicit=implicit), \"\", \"spacing\"\n\n # finalize\n reformatted = self.unlex(tokens)\n failed = reformatted != text\n reformatted = uncook(reformatted, implicit=implicit)\n details = (\n f\"Jinja2 template rewrite recommendation: `{reformatted}`.\"\n if failed\n else \"\"\n )\n return reformatted, details, \"spacing\"\n\n\ndef blacken(text: str) -> str:\n \"\"\"Format Jinja2 template using black.\"\"\"\n return black.format_str(\n text,\n mode=black.FileMode(line_length=sys.maxsize, string_normalization=False),\n ).rstrip(\"\\n\")\n\n\nif \"pytest\" in sys.modules:\n import pytest\n\n from ansiblelint.rules import RulesCollection # pylint: disable=ungrouped-imports\n from ansiblelint.runner import Runner # pylint: disable=ungrouped-imports\n\n @pytest.fixture(name=\"error_expected_lines\")\n def fixture_error_expected_lines() -> list[int]:\n \"\"\"Return list of expected error lines.\"\"\"\n return [33, 36, 39, 42, 45, 48, 74]\n\n # 21 68\n @pytest.fixture(name=\"lint_error_lines\")\n def fixture_lint_error_lines() -> list[int]:\n \"\"\"Get VarHasSpacesRules linting results on test_playbook.\"\"\"\n collection = RulesCollection()\n collection.register(JinjaRule())\n lintable = Lintable(\"examples/playbooks/jinja-spacing.yml\")\n results = Runner(lintable, rules=collection).run()\n return [item.lineno for item in results]\n\n def test_jinja_spacing_playbook(\n error_expected_lines: list[int],\n lint_error_lines: list[int],\n ) -> None:\n \"\"\"Ensure that expected error lines are matching found linting error lines.\"\"\"\n # list unexpected error lines or non-matching error lines\n error_lines_difference = list(\n set(error_expected_lines).symmetric_difference(set(lint_error_lines)),\n )\n assert len(error_lines_difference) == 0\n\n def test_jinja_spacing_vars() -> None:\n \"\"\"Ensure that expected error details are matching found linting error details.\"\"\"\n collection = RulesCollection()\n collection.register(JinjaRule())\n lintable = Lintable(\"examples/playbooks/vars/jinja-spacing.yml\")\n results = Runner(lintable, rules=collection).run()\n\n error_expected_lineno = [14, 15, 16, 17, 18, 19, 32]\n assert len(results) == len(error_expected_lineno)\n for idx, err in enumerate(results):\n assert err.lineno == error_expected_lineno[idx]\n\n @pytest.mark.parametrize(\n (\"text\", \"expected\", \"tag\"),\n (\n pytest.param(\n \"{{-x}}{#a#}{%1%}\",\n \"{{- x }}{# a #}{% 1 %}\",\n \"spacing\",\n id=\"add-missing-space\",\n ),\n pytest.param(\"\", \"\", \"spacing\", id=\"1\"),\n pytest.param(\"foo\", \"foo\", \"spacing\", id=\"2\"),\n pytest.param(\"{##}\", \"{# #}\", \"spacing\", id=\"3\"),\n # we want to keep leading spaces as they might be needed for complex multiline jinja files\n pytest.param(\"{# #}\", \"{# #}\", \"spacing\", id=\"4\"),\n pytest.param(\n \"{{-aaa|xx }}foo\\nbar{#some#}\\n{%%}\",\n \"{{- aaa | xx }}foo\\nbar{# some #}\\n{% %}\",\n \"spacing\",\n id=\"5\",\n ),\n pytest.param(\n \"Shell with jinja filter\",\n \"Shell with jinja filter\",\n \"spacing\",\n id=\"6\",\n ),\n pytest.param(\n \"{{{'dummy_2':1}|true}}\",\n \"{{ {'dummy_2': 1} | true }}\",\n \"spacing\",\n id=\"7\",\n ),\n pytest.param(\"{{{foo:{}}}}\", \"{{ {foo: {}} }}\", \"spacing\", id=\"8\"),\n pytest.param(\n \"{{ {'test': {'subtest': variable}} }}\",\n \"{{ {'test': {'subtest': variable}} }}\",\n \"spacing\",\n id=\"9\",\n ),\n pytest.param(\n \"http://foo.com/{{\\n case1 }}\",\n \"http://foo.com/{{\\n case1 }}\",\n \"spacing\",\n id=\"10\",\n ),\n pytest.param(\"{{foo(123)}}\", \"{{ foo(123) }}\", \"spacing\", id=\"11\"),\n pytest.param(\"{{ foo(a.b.c) }}\", \"{{ foo(a.b.c) }}\", \"spacing\", id=\"12\"),\n # pytest.param(\n # \"spacing\",\n # ),\n pytest.param(\n \"{{foo(x =['server_options'])}}\",\n \"{{ foo(x=['server_options']) }}\",\n \"spacing\",\n id=\"14\",\n ),\n pytest.param(\n '{{ [ \"host\", \"NA\"] }}',\n '{{ [\"host\", \"NA\"] }}',\n \"spacing\",\n id=\"15\",\n ),\n pytest.param(\n \"{{ {'dummy_2': {'nested_dummy_1': value_1,\\n 'nested_dummy_2': value_2}} |\\ncombine(dummy_1) }}\",\n \"{{ {'dummy_2': {'nested_dummy_1': value_1,\\n 'nested_dummy_2': value_2}} |\\ncombine(dummy_1) }}\",\n \"spacing\",\n id=\"17\",\n ),\n pytest.param(\"{{ & }}\", \"\", \"invalid\", id=\"18\"),\n pytest.param(\n \"{{ good_format }}/\\n{{- good_format }}\\n{{- good_format -}}\\n\",\n \"{{ good_format }}/\\n{{- good_format }}\\n{{- good_format -}}\\n\",\n \"spacing\",\n id=\"19\",\n ),\n pytest.param(\n \"{{ {'a': {'b': 'x', 'c': y}} }}\",\n \"{{ {'a': {'b': 'x', 'c': y}} }}\",\n \"spacing\",\n id=\"20\",\n ),\n pytest.param(\n \"2*(1+(3-1)) is {{ 2 * {{ 1 + {{ 3 - 1 }}}} }}\",\n \"2*(1+(3-1)) is {{ 2 * {{1 + {{3 - 1}}}} }}\",\n \"spacing\",\n id=\"21\",\n ),\n pytest.param(\n '{{ \"absent\"\\nif (v is version(\"2.8.0\", \">=\")\\nelse \"present\" }}',\n \"\",\n \"invalid\",\n id=\"22\",\n ),\n pytest.param(\n '{{lookup(\"x\",y+\"/foo/\"+z+\".txt\")}}',\n '{{ lookup(\"x\", y + \"/foo/\" + z + \".txt\") }}',\n \"spacing\",\n id=\"23\",\n ),\n pytest.param(\n \"{{ x | map(attribute='value') }}\",\n \"{{ x | map(attribute='value') }}\",\n \"spacing\",\n id=\"24\",\n ),\n pytest.param(\n \"{{ r(a= 1,b= True,c= 0.0,d= '') }}\",\n \"{{ r(a=1, b=True, c=0.0, d='') }}\",\n \"spacing\",\n id=\"25\",\n ),\n pytest.param(\"{{ r(1,[]) }}\", \"{{ r(1, []) }}\", \"spacing\", id=\"26\"),\n pytest.param(\n \"{{ lookup([ddd ]) }}\",\n \"{{ lookup([ddd]) }}\",\n \"spacing\",\n id=\"27\",\n ),\n pytest.param(\n \"{{ [ x ] if x is string else x }}\",\n \"{{ [x] if x is string else x }}\",\n \"spacing\",\n id=\"28\",\n ),\n pytest.param(\n \"{% if a|int <= 8 -%} iptables {%- else -%} iptables-nft {%- endif %}\",\n \"{% if a | int <= 8 -%} iptables{%- else -%} iptables-nft{%- endif %}\",\n \"spacing\",\n id=\"29\",\n ),\n pytest.param(\n # \"- 2\" -> \"-2\", minus does not get separated when there is no left side\n \"{{ - 2 }}\",\n \"{{ -2 }}\",\n \"spacing\",\n id=\"30\",\n ),\n pytest.param(\n # \"-2\" -> \"-2\", minus does get an undesired spacing\n \"{{ -2 }}\",\n \"{{ -2 }}\",\n \"spacing\",\n id=\"31\",\n ),\n pytest.param(\n # array ranges do not have space added\n \"{{ foo[2:4] }}\",\n \"{{ foo[2:4] }}\",\n \"spacing\",\n id=\"32\",\n ),\n pytest.param(\n # array ranges have the extra space removed\n \"{{ foo[2: 4] }}\",\n \"{{ foo[2:4] }}\",\n \"spacing\",\n id=\"33\",\n ),\n pytest.param(\n # negative array index\n \"{{ foo[-1] }}\",\n \"{{ foo[-1] }}\",\n \"spacing\",\n id=\"34\",\n ),\n pytest.param(\n # negative array index, repair\n \"{{ foo[- 1] }}\",\n \"{{ foo[-1] }}\",\n \"spacing\",\n id=\"35\",\n ),\n pytest.param(\"{{ a +~'b' }}\", \"{{ a + ~'b' }}\", \"spacing\", id=\"36\"),\n pytest.param(\n \"{{ (a[: -4] *~ b) }}\",\n \"{{ (a[:-4] * ~b) }}\",\n \"spacing\",\n id=\"37\",\n ),\n pytest.param(\"{{ [a,~ b] }}\", \"{{ [a, ~b] }}\", \"spacing\", id=\"38\"),\n # Not supported yet due to being accepted by black:\n pytest.param(\"{{ item.0.user }}\", \"{{ item.0.user }}\", \"spacing\", id=\"39\"),\n # Not supported by back, while jinja allows ~ to be binary operator:\n pytest.param(\"{{ a ~ b }}\", \"{{ a ~ b }}\", \"spacing\", id=\"40\"),\n pytest.param(\n \"--format='{{'{{'}}.Size{{'}}'}}'\",\n \"--format='{{ '{{' }}.Size{{ '}}' }}'\",\n \"spacing\",\n id=\"41\",\n ),\n pytest.param(\n \"{{ list_one + {{ list_two | max }} }}\",\n \"{{ list_one + {{list_two | max}} }}\",\n \"spacing\",\n id=\"42\",\n ),\n pytest.param(\n \"{{ lookup('file' , '/tmp/non-existent', errors='ignore') }}\",\n \"{{ lookup('file', '/tmp/non-existent', errors='ignore') }}\",\n \"spacing\",\n id=\"43\",\n ),\n # https://github.com/ansible/ansible-lint/pull/3057\n # since jinja 3.0.0, \\r is converted to \\n if the string has jinja in it\n pytest.param(\n \"{{ 'foo' }}\\r{{ 'bar' }}\",\n \"{{ 'foo' }}\\n{{ 'bar' }}\",\n \"spacing\",\n id=\"44\",\n ),\n # if we do not have any jinja constructs, we should keep original \\r\n # to match ansible behavior\n pytest.param(\n \"foo\\rbar\",\n \"foo\\rbar\",\n \"spacing\",\n id=\"45\",\n ),\n ),\n )\n def test_jinja(text: str, expected: str, tag: str) -> None:\n \"\"\"Tests our ability to spot spacing errors inside jinja2 templates.\"\"\"\n rule = JinjaRule()\n\n reformatted, details, returned_tag = rule.check_whitespace(\n text,\n key=\"name\",\n lintable=Lintable(\"playbook.yml\"),\n )\n assert tag == returned_tag, details\n assert expected == reformatted\n\n @pytest.mark.parametrize(\n (\"text\", \"expected\", \"tag\"),\n (\n pytest.param(\n \"1+2\",\n \"1 + 2\",\n \"spacing\",\n id=\"0\",\n ),\n pytest.param(\n \"- 1\",\n \"-1\",\n \"spacing\",\n id=\"1\",\n ),\n # Ensure that we do not choke with double templating on implicit\n # and instead we remove them braces.\n pytest.param(\"{{ o | bool }}\", \"o | bool\", \"spacing\", id=\"2\"),\n ),\n )\n def test_jinja_implicit(text: str, expected: str, tag: str) -> None:\n \"\"\"Tests our ability to spot spacing errors implicit jinja2 templates.\"\"\"\n rule = JinjaRule()\n # implicit jinja2 are working only inside playbooks and tasks\n lintable = Lintable(name=\"playbook.yml\", kind=\"playbook\")\n reformatted, details, returned_tag = rule.check_whitespace(\n text,\n key=\"when\",\n lintable=lintable,\n )\n assert tag == returned_tag, details\n assert expected == reformatted\n\n @pytest.mark.parametrize(\n (\"lintable\", \"matches\"),\n (pytest.param(\"examples/playbooks/vars/rule_jinja_vars.yml\", 0, id=\"0\"),),\n )\n def test_jinja_file(lintable: str, matches: int) -> None:\n \"\"\"Tests our ability to process var filesspot spacing errors.\"\"\"\n collection = RulesCollection()\n collection.register(JinjaRule())\n errs = Runner(lintable, rules=collection).run()\n assert len(errs) == matches\n for err in errs:\n assert isinstance(err, JinjaRule)\n assert errs[0].tag == \"jinja[invalid]\"\n assert errs[0].rule.id == \"jinja\"\n\n def test_jinja_invalid() -> None:\n \"\"\"Tests our ability to spot spacing errors inside jinja2 templates.\"\"\"\n collection = RulesCollection()\n collection.register(JinjaRule())\n success = \"examples/playbooks/rule-jinja-fail.yml\"\n errs = Runner(success, rules=collection).run()\n assert len(errs) == 2\n assert errs[0].tag == \"jinja[spacing]\"\n assert errs[0].rule.id == \"jinja\"\n assert errs[0].lineno == 9\n assert errs[1].tag == \"jinja[invalid]\"\n assert errs[1].rule.id == \"jinja\"\n assert errs[1].lineno == 9\n\n def test_jinja_valid() -> None:\n \"\"\"Tests our ability to parse jinja, even when variables may not be defined.\"\"\"\n collection = RulesCollection()\n collection.register(JinjaRule())\n success = \"examples/playbooks/rule-jinja-pass.yml\"\n errs = Runner(success, rules=collection).run()\n assert len(errs) == 0\n\n\ndef _get_error_line(task: dict[str, Any], path: list[str | int]) -> int:\n \"\"\"Return error line number.\"\"\"\n line = task[LINE_NUMBER_KEY]\n ctx = task\n for _ in path:\n ctx = ctx[_]\n if LINE_NUMBER_KEY in ctx:\n line = ctx[LINE_NUMBER_KEY]\n if not isinstance(line, int):\n msg = \"Line number is not an integer\"\n raise RuntimeError(msg)\n return line\n","sub_path":"src/ansiblelint/rules/jinja.py","file_name":"jinja.py","file_ext":"py","file_size_in_byte":29425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"512427491","text":"import argparse\nimport torch\nfrom torchvision import models\n\nfrom timm.models import create_model\n\n\nparser = argparse.ArgumentParser(description='pytorch CNN visualization by Grad-CAM')\nparser.add_argument('--model_backbone', type=str, default='mnasnet_small', help='the type of model chosen.') # mnasnet_small semnasnet_100 # mobilenetv2_100\nparser.add_argument('--classes_num', type=int, default=2, help='the number of classification class.')\nparser.add_argument('--input_channel', type=int, default=3, help='the number of input channel.')\nparser.add_argument('--input_size', type=int, default=224, help='the size of input.')\nparser.add_argument('--torch_model', default='/home/night/PycharmProjects/Picture_Classification/pytorch-image-models/checkpoints/face_mask/MNASNet_small/checkpoint-51.pth.tar') # '/home/night/PycharmProjects/Picture_Classification/pytorch-image-models/checkpoints/face_mask/mobilenetv2_100_no_prefetcher/checkpoint-42.pth.tar' # \"/home/night/PycharmProjects/Picture_Classification/pytorch-image-models/checkpoints/Live_Detection/model_best.pth.tar\" # # './checkpoints/train/20200319-182337-mobilenetv2_100-224/checkpoint-14.pth.tar'\n\nargs = parser.parse_args()\n\nprint(\"=====> load pytorch checkpoint...\")\nmymodel = create_model(\n model_name=args.model_backbone,\n pretrained=False,\n num_classes=args.classes_num,\n in_chans=args.input_channel,\n global_pool='avg') # , checkpoint_path=args.torch_model\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # PyTorch v0.4.0\nmymodel = mymodel.to(device)\n\n# mymodel = models.resnet50(pretrained=False)\n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # PyTorch v0.4.0\n# mymodel = mymodel.to(device)\n\nfor name, module in mymodel._modules.items():\n print(name)\n print(module)\n print('=============================>')","sub_path":"Visualization/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"202733059","text":"# print(dir(list))\n# tuple hashable\n# list dict set 可变 unhashable\nclass Solution(object):\n def threeSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n # def twoSum(num, tar):\n # ans = []\n # old = []\n # for i in range(len(num)):\n # if num[i] in old: continue\n # else: old.append(num[i])\n # if tar-num[i] in num[i+1:]:\n # ans.append([num[i],tar-num[i]])\n # return ans\n\n # nums.sort()\n # old = []\n # an = []\n # for i in range(len(nums)):\n # if nums[i] in old: continue\n # else: old.append(nums[i])\n # temp = twoSum(nums[i+1:], -nums[i])\n # for j in range(len(temp)):\n # temp[j] = [nums[i]] + temp[j]\n # an+=temp\n # return an\n \n # nums.sort()\n # old = []\n # res = []\n # for i in range(len(nums)-2):# n\n # if nums[i] in old: continue# hash\n # old.append(nums[i])\n # temp = {}\n # oldd = []\n # for j in range(i+1,len(nums)):# n\n # if nums[j] in oldd: continue# hash\n # if nums[j] not in temp: temp[-nums[i]-nums[j]] = j# hash\n # else:\n # res.append([nums[i],-nums[i]-nums[j],nums[j]])\n # oldd.append(nums[j])\n # return res\n\n nums.sort()\n ans = set()\n for i in range(len(nums)-2):\n x, y = i+1, len(nums)-1\n while x < y:\n temp = nums[x]+nums[y]+nums[i]\n if temp == 0:\n ans.add((nums[i],nums[x],nums[y]))\n x+=1\n if temp < 0: x+=1\n if temp > 0: y-=1\n return [list(_) for _ in ans]\n\n # res = []\n # nums.sort()\n # for i in range(len(nums)-2):\n # if i and nums[i] == nums[i-1]: continue\n # l, r = i+1, len(nums)-1\n # while l < r:\n # s = nums[i] + nums[l] + nums[r]\n # if s < 0: l +=1 \n # if s > 0: r -= 1\n # if s == 0:\n # res.append([nums[i], nums[l], nums[r]])\n # while l < r and nums[l] == nums[l+1]:\n # l += 1\n # while l < r and nums[r] == nums[r-1]:\n # r -= 1\n # l += 1\n # r -= 1\n # return res\n\nif __name__ == '__main__':\n s = [-1, 0, 1, 2, -1, -4]\n b = [0,0,0,0,0,0,0,0]\n sol = Solution()\n print(sol.threeSum(b))\n print(sol.threeSum(s))","sub_path":"Algorithms/15 3Sum/3Sum.py","file_name":"3Sum.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"374177734","text":"# -*- coding: utf-8 -*- \n\"\"\"\nMaster Plugin\nCopyright (C) 2010 Olaf Lüke \n\nmaster.py: Master Plugin implementation\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License \nas published by the Free Software Foundation; either version 2 \nof the License, or (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 GNU\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU General Public\nLicense along with this program; if not, write to the\nFree Software Foundation, Inc., 59 Temple Place - Suite 330,\nBoston, MA 02111-1307, USA.\n\"\"\"\n\n#import logging\n\nfrom plugin_system.plugin_base import PluginBase\nfrom bindings import ip_connection\n\nfrom PyQt4.QtGui import QWidget, QFrame, QMessageBox\nfrom PyQt4.QtCore import QTimer, Qt\n\nfrom ui_master import Ui_Master\nfrom ui_chibi import Ui_Chibi\nfrom ui_rs485 import Ui_RS485\nfrom ui_extension_type import Ui_extension_type\n\nfrom bindings import brick_master\n\nclass ExtensionTypeWindow(QFrame, Ui_extension_type):\n def __init__(self, parent):\n QFrame.__init__(self, parent, Qt.Popup | Qt.Window | Qt.Tool)\n self.setupUi(self)\n \n self.setWindowTitle(\"Configure Extension Type\")\n \n self.master = parent.master\n self.button_type_save.pressed.connect(self.save_pressed)\n self.combo_extension.currentIndexChanged.connect(self.index_changed)\n \n self.index_changed(0)\n \n \n def popup_ok(self):\n QMessageBox.information(self, \"Upload\", \"Check OK\", QMessageBox.Ok)\n \n def popup_fail(self):\n QMessageBox.critical(self, \"Upload\", \"Check Failed\", QMessageBox.Ok)\n \n def index_changed(self, index):\n ext = self.master.get_extension_type(index)\n if ext < 0 or ext > 2:\n ext = 0\n self.type_box.setCurrentIndex(ext)\n \n def save_pressed(self):\n extension = self.combo_extension.currentIndex()\n type = self.type_box.currentIndex()\n try:\n self.master.set_extension_type(extension, type)\n except:\n self.popup_fail()\n return\n \n try:\n new_type = self.master.get_extension_type(extension)\n except:\n self.popup_fail()\n return\n \n if type == new_type:\n self.popup_ok()\n else:\n self.popup_fail()\n \nclass Chibi(QWidget, Ui_Chibi):\n def __init__(self, parent):\n QWidget.__init__(self)\n self.setupUi(self)\n \n self.master = parent.master\n \n if parent.version_minor > 0:\n address = self.master.get_chibi_address()\n address_slave = []\n for i in range(32):\n x = self.master.get_chibi_slave_address(i)\n if x == 0:\n break\n else:\n address_slave.append(str(x))\n \n address_slave_text = ', '.join(address_slave)\n address_master = self.master.get_chibi_master_address()\n frequency = self.master.get_chibi_frequency()\n channel = self.master.get_chibi_channel()\n \n type = 0\n if address == address_master:\n type = 1\n \n self.lineedit_slave_address.setText(address_slave_text)\n self.address_spinbox.setValue(address)\n self.master_address_spinbox.setValue(address_master)\n self.chibi_frequency.setCurrentIndex(frequency)\n self.chibi_channel.setCurrentIndex(channel)\n \n self.save_button.pressed.connect(self.save_pressed)\n self.chibi_type.currentIndexChanged.connect(self.chibi_type_changed)\n self.chibi_frequency.currentIndexChanged.connect(self.chibi_frequency_changed)\n self.chibi_channel.currentIndexChanged.connect(self.chibi_channel_changed)\n \n self.chibi_type.setCurrentIndex(type)\n self.chibi_type_changed(type)\n self.new_max_count()\n \n def popup_ok(self):\n QMessageBox.information(self, \"Save\", \"Check OK\", QMessageBox.Ok)\n \n def popup_fail(self):\n QMessageBox.critical(self, \"Save\", \"Check Failed\", QMessageBox.Ok)\n \n def new_max_count(self):\n channel = int(self.chibi_channel.currentText())\n self.chibi_channel.currentIndexChanged.disconnect(self.chibi_channel_changed)\n \n for i in range(12):\n self.chibi_channel.removeItem(0)\n \n index = self.chibi_frequency.currentIndex()\n \n if index == 0:\n self.chibi_channel.addItem(\"0\")\n if channel != 0:\n channel = 0\n elif index in (1, 3):\n channel -= 1\n self.chibi_channel.addItem(\"1\")\n self.chibi_channel.addItem(\"2\")\n self.chibi_channel.addItem(\"3\")\n self.chibi_channel.addItem(\"4\")\n self.chibi_channel.addItem(\"5\")\n self.chibi_channel.addItem(\"6\")\n self.chibi_channel.addItem(\"7\")\n self.chibi_channel.addItem(\"8\")\n self.chibi_channel.addItem(\"9\")\n self.chibi_channel.addItem(\"10\")\n if not channel in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10):\n channel = 0\n elif index == 2:\n self.chibi_channel.addItem(\"0\")\n self.chibi_channel.addItem(\"1\")\n self.chibi_channel.addItem(\"2\")\n self.chibi_channel.addItem(\"3\")\n if not channel in (0, 1, 2, 3):\n channel = 0\n \n \n self.chibi_channel.setCurrentIndex(channel)\n self.chibi_channel.currentIndexChanged.connect(self.chibi_channel_changed)\n \n def save_pressed(self):\n type = self.chibi_type.currentIndex()\n frequency = self.chibi_frequency.currentIndex()\n channel = self.chibi_channel.currentIndex()\n if frequency in (1, 3):\n channel += 1\n address = self.address_spinbox.value()\n address_master = self.master_address_spinbox.value()\n address_slave_text = str(self.lineedit_slave_address.text().replace(' ', ''))\n if address_slave_text == '':\n address_slave = []\n else:\n address_slave = map(int, address_slave_text.split(','))\n address_slave.append(0)\n \n self.master.set_chibi_frequency(frequency)\n self.master.set_chibi_channel(channel)\n self.master.set_chibi_address(address)\n if type == 0:\n self.master.set_chibi_master_address(address_master)\n else:\n self.master.set_chibi_master_address(address)\n for i in range(len(address_slave)):\n self.master.set_chibi_slave_address(i, address_slave[i])\n \n new_frequency = self.master.get_chibi_frequency()\n new_channel = self.master.get_chibi_channel()\n new_address = self.master.get_chibi_address()\n if type == 0:\n new_address_master = self.master.get_chibi_master_address()\n if new_frequency == frequency and \\\n new_channel == channel and \\\n new_address == address and \\\n new_address_master == address_master:\n self.popup_ok()\n else:\n self.popup_fail()\n else:\n new_address_master = self.master.get_chibi_master_address()\n new_address_slave = []\n for i in range(len(address_slave)):\n new_address_slave.append(self.master.get_chibi_slave_address(i))\n if new_frequency == frequency and \\\n new_channel == channel and \\\n new_address == address and \\\n new_address_master == address and \\\n new_address_slave == address_slave:\n self.popup_ok()\n else:\n self.popup_fail()\n \n def index_changed(self, index):\n addr = self.master.get_chibi_slave_address(index)\n self.slave_address_spinbox.setValue(addr)\n \n def chibi_frequency_changed(self, index):\n self.new_max_count()\n\n def chibi_channel_changed(self, index):\n channel = int(self.chibi_channel.itemText(index))\n \n def chibi_type_changed(self, index):\n if index == 0:\n self.label_slave_address.hide()\n self.lineedit_slave_address.hide()\n self.label_master_address.show()\n self.master_address_spinbox.show()\n else:\n self.label_master_address.hide()\n self.master_address_spinbox.hide()\n self.label_slave_address.show()\n self.lineedit_slave_address.show()\n \n def signal_strength_update(self, ss):\n ss_str = \"%g dBm\" % (ss,)\n self.signal_strength_label.setText(ss_str)\n \n def update_data(self):\n try:\n ss = self.master.get_chibi_signal_strength()\n self.signal_strength_update(ss)\n except ip_connection.Error:\n return\n \nclass RS485(QWidget, Ui_RS485):\n def __init__(self, parent):\n QWidget.__init__(self)\n self.setupUi(self)\n \n self.master = parent.master\n \n if parent.version_minor > 1:\n speed, parity, stopbits = self.master.get_rs485_configuration()\n self.speed_spinbox.setValue(speed)\n if parity == 'e':\n self.parity_combobox.setCurrentIndex(1)\n elif parity == 'o':\n self.parity_combobox.setCurrentIndex(2)\n else:\n self.parity_combobox.setCurrentIndex(0)\n self.stopbits_spinbox.setValue(stopbits)\n \n address = self.master.get_rs485_address()\n address_slave = []\n for i in range(32):\n x = self.master.get_rs485_slave_address(i)\n if x == 0:\n break\n else:\n address_slave.append(str(x))\n \n address_slave_text = ', '.join(address_slave)\n \n type = 0\n if address == 0:\n type = 1\n \n self.lineedit_slave_address.setText(address_slave_text)\n self.address_spinbox.setValue(address)\n \n self.save_button.pressed.connect(self.save_pressed)\n self.rs485_type.currentIndexChanged.connect(self.rs485_type_changed)\n \n self.rs485_type.setCurrentIndex(type)\n self.rs485_type_changed(type)\n \n def popup_ok(self):\n QMessageBox.information(self, \"Save\", \"Check OK\", QMessageBox.Ok)\n \n def popup_fail(self):\n QMessageBox.critical(self, \"Save\", \"Check Failed\", QMessageBox.Ok)\n \n def save_pressed(self):\n speed = self.speed_spinbox.value()\n parity_index = self.parity_combobox.currentIndex()\n parity = 'n'\n if parity_index == 1:\n parity = 'e'\n elif parity_index == 2:\n parity = 'o'\n stopbits = self.stopbits_spinbox.value()\n \n self.master.set_rs485_configuration(speed, parity, stopbits)\n \n type = self.rs485_type.currentIndex()\n if type == 0:\n address = self.address_spinbox.value()\n else:\n address = 0\n \n address_slave_text = str(self.lineedit_slave_address.text().replace(' ', ''))\n if address_slave_text == '':\n address_slave = []\n else:\n address_slave = map(int, address_slave_text.split(','))\n address_slave.append(0)\n \n self.master.set_rs485_address(address)\n if type == 1:\n for i in range(len(address_slave)):\n self.master.set_rs485_slave_address(i, address_slave[i])\n \n new_address = self.master.get_rs485_address()\n if type == 0:\n if new_address == address:\n self.popup_ok()\n else:\n self.popup_fail()\n else:\n new_address_slave = []\n for i in range(len(address_slave)):\n new_address_slave.append(self.master.get_rs485_slave_address(i))\n if new_address == 0 and new_address_slave == address_slave:\n self.popup_ok()\n else:\n self.popup_fail()\n \n def rs485_type_changed(self, index):\n if index == 0:\n self.label_slave_address.hide()\n self.lineedit_slave_address.hide()\n self.label.show()\n self.address_spinbox.show()\n else:\n self.label_slave_address.show()\n self.lineedit_slave_address.show()\n self.label.hide()\n self.address_spinbox.hide()\n \n def update_data(self):\n pass\n \nclass Master(PluginBase, Ui_Master):\n def __init__ (self, ipcon, uid):\n PluginBase.__init__(self, ipcon, uid)\n self.setupUi(self)\n\n self.master = brick_master.Master(self.uid)\n self.device = self.master\n self.ipcon.add_device(self.master)\n\n version = self.master.get_version()\n self.version = '.'.join(map(str, version[1]))\n self.version_minor = version[1][1]\n self.version_release = version[1][2]\n \n self.update_timer = QTimer()\n self.update_timer.timeout.connect(self.update_data)\n \n self.extensions = []\n num_extensions = 0\n # construct chibi widget\n if self.version_minor > 0:\n self.extension_type_button.pressed.connect(self.extension_pressed)\n if self.master.is_chibi_present():\n num_extensions += 1\n chibi = Chibi(self)\n self.extensions.append(chibi)\n self.extension_layout.addWidget(chibi)\n else:\n self.extension_type_button.setEnabled(False)\n \n # RS485 widget\n if self.version_minor > 1:\n if self.master.is_rs485_present():\n num_extensions += 1\n rs485 = RS485(self)\n self.extensions.append(rs485)\n self.extension_layout.addWidget(rs485)\n \n if num_extensions == 0:\n self.extension_label.setText(\"None Present\")\n else:\n self.extension_label.setText(\"\" + str(num_extensions) + \" Present\")\n\n def start(self):\n self.update_timer.start(100)\n\n def stop(self):\n self.update_timer.stop()\n\n def has_reset_device(self):\n return self.version_minor > 2 or (self.version_minor == 2 and self.version_release > 0)\n\n def reset_device(self):\n if self.has_reset_device():\n self.master.reset()\n\n def get_chip_temperature(self):\n if self.version_minor > 2 or (self.version_minor == 2 and self.version_release > 0):\n return u'{0} °C'.format(self.master.get_chip_temperature()/10.0)\n else:\n return '(> 1.2.0 needed)'\n\n @staticmethod\n def has_name(name):\n return 'Master Brick' in name\n \n def update_data(self):\n try:\n sv = self.master.get_stack_voltage()\n sc = self.master.get_stack_current()\n self.stack_voltage_update(sv)\n self.stack_current_update(sc)\n except ip_connection.Error:\n return\n for extension in self.extensions:\n extension.update_data()\n \n def stack_voltage_update(self, sv):\n sv_str = \"%gV\" % round(sv/1000.0, 1)\n self.stack_voltage_label.setText(sv_str)\n \n def stack_current_update(self, sc):\n if sc < 999:\n sc_str = \"%gmA\" % sc\n else:\n sc_str = \"%gA\" % round(sc/1000.0, 1) \n self.stack_current_label.setText(sc_str)\n \n def extension_pressed(self):\n etw = ExtensionTypeWindow(self)\n etw.setAttribute(Qt.WA_QuitOnClose)\n etw.show()\n","sub_path":"src/brickv/plugin_system/plugins/master/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":16225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"627234031","text":"from django import forms\nfrom django.forms import formset_factory, ModelMultipleChoiceField\n\nfrom django.contrib.auth.forms import UserCreationForm\n\nfrom django.core.exceptions import ValidationError\n\nfrom .models import Source, Category, User\n\nimport pytz\n\n# Setting some default lists and variables for use in the forms\n\nstockoptions = [(\"AAPL\", \"Apple, Inc. (APPL)\"),(\"TSLA\", \"Tesla, Inc. (TSLA)\"),(\"NKE\",\"Nike, Inc. (NKE)\"),(\"JCP\",\"JC Penney, Inc. (JCP)\")] #total stock list\n\ncityoptions = [(\"New York, NY\",\"New York, NY\"),(\"Austin, TX\",\"Austin, TX\"),(\"Portland, OR\",\"Portland, OR\"),(\"Chicago, IL\",\"Chicago, IL\")]\n\ntimeoptions = [('',''),(\"01:00:00\",\"1 a.m.\"),(\"02:00:00\",\"2 a.m.\"),(\"03:00:00\",\"3 a.m.\"),(\"04:00:00\",\"4 a.m.\"),(\"05:00:00\",\"5 a.m.\"),(\"06:00:00\",\"6 a.m.\"),(\"07:00:00\",\"7 a.m.\"),(\"08:00:00\",\"8 a.m.\"),(\"09:00:00\",\"9 a.m.\"),(\"10:00:00\",\"10 a.m.\"), (\"11:00:00\",\"11 a.m.\"), (\"12:00:00\",\"Noon\"),(\"13:00:00\",\"1 p.m.\"),(\"14:00:00\",\"2 p.m.\"),(\"15:00:00\",\"3 p.m.\"), (\"16:00:00\",\"4 p.m.\"), (\"17:00:00\",\"5 p.m.\"), (\"18:00:00\",\"6 p.m.\"), (\"19:00:00\",\"7 p.m.\"), (\"20:00:00\",\"8 p.m.\"), (\"21:00:00\",\"9 p.m.\"), (\"22:00:00\",\"10 p.m.\"), (\"23:00:00\",\"11 p.m.\"), (\"00:00:00\",\"Midnight\")]\n\ncategoryoptions = []\n\nfor cat in Category.objects.all():\n selection = (cat.category,cat.category)\n categoryoptions.append(selection)\n\ncategoryoptions.append((\"Custom alerts\",\"Custom alerts\"))\n\nTIMEZONES = []\n\ntzlist = pytz.common_timezones\n\nfor timezone in tzlist:\n newtuple = (timezone, timezone)\n TIMEZONES.append(newtuple)\n\n# TIMEZONES = pytz.common_timezones\n# (\n# ('US/Eastern','US/Eastern'),\n# ('US/Central','US/Central'),\n# ('US/Mountain','US/Mountain'),\n# ('US/Pacific','US/Pacific')\n# )\n\n\n# Old form for setting categories and sources with checklists - not used anymore\n\n# Field and form for setting sources\n\nclass SourceMultipleChoiceField(ModelMultipleChoiceField):\n def label_from_instance(self,obj):\n return obj.source # So that we can have multiple of the source preference form on the same page\n\nclass SourcePreferenceForm(forms.Form):\n\n def __init__(self, cat, *args, **kwargs):\n super(SourcePreferenceForm, self).__init__(*args, **kwargs)\n self.fields['sources'] = SourceMultipleChoiceField(\n widget=forms.CheckboxSelectMultiple,\n queryset=Source.objects.filter(category=cat).order_by('source'),\n label=''\n )\n\n# Form to use for processing results\n\nclass AllSourceForm(forms.Form):\n sources = forms.ModelMultipleChoiceField(\n widget=forms.CheckboxSelectMultiple,\n queryset=Source.objects.all(),\n label=''\n )\n\n# Form for users to pick stocks and weather\n\nclass StockPreferenceForm(forms.Form):\n stocks = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'id':'stock_select'}), choices=stockoptions, label='')\n\nclass WeatherForm(forms.Form):\n cities = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'id':'city_select'}), choices=cityoptions, label='')\n\nclass WidgetForm(forms.Form):\n def __init__(self, wname, choicelist, *args, **kwargs):\n super(WidgetForm, self).__init__(*args, **kwargs)\n self.fields[wname] = forms.MultipleChoiceField(\n widget=forms.SelectMultiple(attrs={'id':'' + wname + '_select'}),\n choices=choicelist,\n label=''\n )\n\n# Form for users to create new topics - also used for them to edit old topics\n\nclass NewTopicForm(forms.Form):\n title = forms.CharField(label='Name for your custom alert:')\n keywords = forms.CharField(label='Keywords to search for:')\n categories = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Category.objects.all().order_by('category'), label='Select categories to search in:')\n\n\nclass TopicForm(forms.Form):\n title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Your Alert Name'}), label='Name for your custom alert:')\n categories = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Category.objects.all().order_by('category'), label='Select categories to search in:')\n\nclass KeywordForm(forms.Form):\n keyword = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Your Alert Keyword'}),label='')\n\nKeywordFormset = formset_factory(KeywordForm, extra = 0, can_delete=True)\n\n# Form to order categories - not used because I couldn't order Model fields with Django\n\nclass CategoryOrderForm(forms.Form):\n categories = forms.ModelMultipleChoiceField(widget=forms.SelectMultiple(attrs={'id':'cat_order'}), queryset=Category.objects.all().order_by('category'), label=\"Select the order in which you'd like to see news categories appear:\")\n\n# Form to order categories - used because it allows for more flexibility\n\nclass SelectForm(forms.Form):\n def __init__(self, choicelist, *args, **kwargs):\n super(SelectForm, self).__init__(*args, **kwargs)\n self.fields['categories'] = forms.MultipleChoiceField(\n widget=forms.CheckboxSelectMultiple,\n choices=choicelist,\n label=''\n )\n\n# Simple form for users to pick what timezone they are in\n\nclass TimezoneForm(forms.Form):\n timezone = forms.ChoiceField(choices=TIMEZONES, label='Timezone:', help_text='This will determine what timezone your custom news bulletins are sent in.', widget=forms.Select(attrs={\n 'class': 'form-control prefs-dropdown'}))\n\n\n# Simple form to set email address\n\nclass SetAddressForm(forms.Form):\n email = forms.EmailField(label = 'Email address:', help_text='This is the email address where you will receive your custom news bulletins.', widget=forms.EmailInput(attrs={'class': 'form-control'}))\n\n\n# Forms to set email time preferences\n\nclass EmailTimeForm(forms.Form):\n mailtimes = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'id':'mailtime_select'}), choices=timeoptions, label='')\n\nclass EmailForm(forms.Form):\n day = forms.ChoiceField(\n widget=forms.Select(\n attrs={'class': 'form-control prefs-dropdown'}),\n choices = [('',''),('Every day', 'Every day'),('Weekdays', 'Weekdays'),('Monday', 'Mondays'),('Tuesday', 'Tuesdays'),('Wednesday', 'Wednesdays'),('Thursday', 'Thursdays'),('Friday', 'Fridays'),('Saturday', 'Saturdays'),('Sunday', 'Sundays')],\n label = 'Send me an email')\n time = forms.ChoiceField(widget=forms.Select(attrs={\n 'class': 'form-control prefs-dropdown'}), choices = timeoptions, label = 'at')\n\nEmailFormset = formset_factory(EmailForm, extra = 0, can_delete = True)\n\n\n# Feedback form\n\nclass ContactForm(forms.Form):\n email = forms.EmailField(max_length=254, help_text='Please enter a contact email, so we can follow up if necessary.', label='Your email')\n message = forms.CharField(\n max_length=5000,\n widget=forms.Textarea(),\n )\n\n\n# Signup form with email\n\nclass SignupForm(UserCreationForm):\n email = forms.EmailField(max_length=254,label='Email address')\n\n def clean(self):\n email = self.cleaned_data.get('email')\n if User.objects.filter(email=email).exists():\n raise ValidationError(\"There is already an account associated with this email address.\")\n return self.cleaned_data\n\n class Meta:\n model = User\n fields = ('username', 'email', 'password1', 'password2')\n","sub_path":"news/bulletin/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":7402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"286119819","text":"import os\nimport re\nos.chdir('./Desktop/DSI_Religion/Megan_Capstone/')\n\n\n\nimport getSingleDirs as gsd \n\nos.chdir('./DSI-Religion-2017/')\nfilepath = 'Interns Scoring.xlsx'\nolddir = './data_dsicap_FULL/'\nnewdir = 'data_dsicap_testagain'\nnewcopy = './data_dsicap_FULL_2/'\nworkingdir = '/Users/meganstiles/Desktop/DSI_Religion/Megan_Capstone/DSI-Religion-2017/'\n\ngsd.getSingleDocDirs(filepath, olddir, newdir, newcopy, workingdir)\n\ndf = pd.read_csv('./refData/docRanks.csv')\n\nfor i in range(0,len(df)):\n file = re.sub('.txt', '', df['Filename'][i])\n df['Filename'][i] = file\n\ndf.to_csv('docRanks.csv')","sub_path":"Directory Maintence/singledirscript.py","file_name":"singledirscript.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"369181437","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n# 根据机器上py版本,自动选择调用py2还是py3\n\n\nimport sys\nimport os\ncurrentFilePath = os.path.dirname(os.path.abspath(__file__))\nprint(\"currentFilePath===\" + currentFilePath)\n\nargvs=sys.argv[1:]\nparams = \" \".join(argvs)\nprint(\"params===\" + params)\n\nif sys.version > '3':\n pyPath = \"py3\"\nelse:\n pyPath = \"py2\"\n\nexecPy = \"python \" + currentFilePath +os.sep +\"py\" +os.sep + pyPath + os.sep + \"datax.py \" + params\nprint(\"execPy===\" + execPy)\nos.system(execPy)","sub_path":"core/src/main/bin/py/datax.py","file_name":"datax.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"83707498","text":"import os\n\nfrom glob import glob\n\nfile_path = '/Users/psehgal/dev/PythonFundamentals.Exercises.Part8'\n\n\npath = input('Enter a directory name - ')\ndirectory_name = os.walk(path)\nfor path_name, subdirc_name, file_name in directory_name:\n print(path_name, subdirc_name,file_name)\n for var_file in file_name:\n print(os.path.join(path_name, var_file))\n\n\ndef walk(dirname, file_handler):\n items = os.listdir","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"402630225","text":"from django.conf.urls.static import static\nfrom django.conf import settings\nfrom django.views.generic import TemplateView\nfrom django.contrib import admin\nfrom django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('',\n #url(r'^$', TemplateView.as_view(template_name='base.html')),\n\n # Examples:\n # url(r'^$', 'Factura.views.home', name='home'),\n # url(r'^Factura/', include('Factura.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\n url(r'^admin/', include(admin.site.urls)),\n url(r'^grappelli/', include('grappelli.urls')), # grappelli URLS\n url(r'^$','facturaciones.views.ingresar'),\n url(r'^privado/$','facturaciones.views.privado'),\n# url(r'^factura/$','facturaciones.views.privado'),\n url(r'^clientes$','facturaciones.views.clientes'),\n url(r'^clienteAdd/$','facturaciones.views.clienteAdd'),\n url(r'^clienteEdit/(?P\\d+)$','facturaciones.views.clienteEdit'),\n url(r'^clienteDelete/(?P\\d+)$','facturaciones.views.clienteDelete'),\n url(r'^productos/$','facturaciones.views.productos'),\n url(r'^productoAdd/$','facturaciones.views.productoAdd'),\n url(r'^productoEdit/(?P\\d+)$','facturaciones.views.productoEdit'),\n url(r'^productoDelete/(?P\\d+)$','facturaciones.views.productoDelete'),\n url(r'^factura/$','facturaciones.views.factura'),\n url(r'^detalle/$','facturaciones.views.detalle'),\n url(r'^imprimir/$', TemplateView.as_view(template_name='facturaciones/imprimir.html')),\n url(r'^cerrar/$','facturaciones.views.cerrar'),\n)\n\n# Uncomment the next line to serve media files in dev.\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += patterns('',\n url(r'^__debug__/', include(debug_toolbar.urls)),\n )\n","sub_path":"Factura/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"617881284","text":"from flask import render_template\n\n\nfrom . import app\nfrom .database import session, Entry\n\nfrom flask import request, redirect, url_for\n\n\nPAGINATE_BY = 10\n\n@app.route(\"/\")\n@app.route(\"/page//?limit=10\")\ndef entries(page=1):\n # Zero-indexed page\n page_index = page - 1\n \n count = session.query(Entry).count()\n \n \n try:\n PAGINATE_BY = int(request.args.get('limit', 10))\n except:\n PAGINATE_BY = 10\n \n start = page_index * PAGINATE_BY\n end = start + PAGINATE_BY\n \n total_pages = (count - 1) // PAGINATE_BY + 1\n has_next = page_index < total_pages - 1\n has_prev = page_index > 0\n \n entries = session.query(Entry)\n entries = entries.order_by(Entry.datetime.desc())\n entries = entries[start:end]\n \n return render_template(\"entries.html\",\n entries=entries, \n has_next=has_next,\n has_prev=has_prev,\n page=page,\n total_pages=total_pages, \n limit=PAGINATE_BY\n )\n\nfrom flask_login import login_required, current_user\n\n@app.route(\"/entry/add\", methods=[\"GET\"])\n@login_required\ndef add_entry_get():\n return render_template(\"add_entry.html\")\n\n\n@app.route(\"/entry/add\", methods=[\"POST\"])\n@login_required\ndef add_entry_post():\n entry = Entry(\n title=request.form[\"title\"],\n content=request.form[\"content\"],\n author=current_user\n )\n session.add(entry)\n session.commit()\n return redirect(url_for(\"entries\"))\n\n@app.route(\"/entry/\")\n#click to get to this route\n# query the single entry\ndef entry(id):\n entry = session.query(Entry).filter(Entry.id == id).first()\n return render_template(\"view_entry.html\", entry=entry)\n\n@app.route(\"/entry//edit\", methods=[\"GET\", \"POST\"])\ndef edit_entry_get(id):\n \n if request.method==\"GET\":\n entry = session.query(Entry).filter(Entry.id == id).one()\n return render_template(\"edit_entry.html\", entry=entry)\n \n elif request.method==\"POST\":\n #edit_entry_post(id)\n entry = session.query(Entry).filter(Entry.id==id).one()\n entry.title = request.form.get(\"title\", entry.title)\n entry.content = request.form.get(\"content\", entry.content)\n session.add(entry)\n session.commit()\n return redirect(url_for('entries'))\n \n@app.route(\"/entry//delete\", methods=[\"GET\", \"POST\"])\ndef open_options(id):\n \n if request.method==\"GET\":\n entry = session.query(Entry).filter(Entry.id==id).one()\n return render_template(\"delete_entry.html\", entry=entry)\n \n elif request.method==\"POST\":\n entry = session.query(Entry).filter(Entry.id==id).one()\n session.delete(entry)\n session.commit()\n return redirect(url_for(\"entries\"))\n\n@app.route(\"/login\", methods=[\"GET\"])\ndef login_get():\n return render_template(\"login.html\")\n\nfrom flask import flash\nfrom flask_login import login_user\nfrom werkzeug.security import check_password_hash\nfrom .database import User\n\n@app.route(\"/login\", methods=[\"POST\"])\ndef login_post():\n email = request.form[\"email\"]\n password = request.form[\"password\"]\n user = session.query(User).filter_by(email=email).first()\n if not user or not check_password_hash(user.password, password):\n flash(\"Incorrect username or password\", \"danger\")\n return redirect(url_for(\"login_get\"))\n\n login_user(user)\n return redirect(request.args.get('next') or url_for(\"entries\"))\n\n# style=\"color:black; color:hover:black;\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"426637627","text":"#experiment with different setting and save in different epochs\nfrom __future__ import print_function\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.datasets import cifar100\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization, AveragePooling2D\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.callbacks import ModelCheckpoint\nfrom extra_models.resnet import lr_schedule, resnet_v1, resnet_v2\nimport extra_models.densenet as densenet\nimport argparse\nimport h5py\nimport json\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom keras.models import model_from_config\n\n\ndef lr_schedule_densenet(epoch):\n lr = 1e-3\n if epoch > 180:\n lr *= 0.5e-3\n elif epoch > 160:\n lr *= 1e-3\n elif epoch > 120:\n lr *= 1e-2\n elif epoch > 80:\n lr *= 1e-1\n print('Learning rate: ', lr)\n return lr\n\n\nparser = argparse.ArgumentParser(description='Train a target model.')\nparser.add_argument('-d', '--dataset', type=str, default='cifar_10', choices=['mnist', 'cifar_10', 'cifar_100', 'cifar_100_resnet', 'cifar_100_densenet', 'imagenet_inceptionv3', 'imagenet_xception'], help='Indicate dataset and target model archtecture.')\nparser.add_argument('-c', '--conv_blocks', type=int, default=0, help='The number of conv blocks for CIFAR10 and CIFAR100.')\nparser.add_argument('-b', '--batch_size', type=int, default=64, help='Batch size')\nparser.add_argument('-e', '--epochs', type=int, help='Number of training epochs')\nparser.add_argument('-l', '--learning_rate', type=float, default=0.001, help='learning rate.')\nparser.add_argument('-P', '--periodical_save', default=False, help='Save the model periodically during training.', action='store_true')\nparser.add_argument('-p', '--save_period', type=int, default=10, help='Save the model each p epoch.')\nparser.add_argument('-R', '--lr_reducer', default=False, help='Use learning reducer.', action='store_true')\nparser.add_argument('-S', '--lr_scheduler', default=False, help='Use learning scheduler.', action='store_true')\nargs = parser.parse_args()\n\n\nif __name__ == '__main__':\n dataset = args.dataset\n batch_size = args.batch_size\n use_lr_reducer = args.lr_reducer\n use_lr_scheduler = args.lr_scheduler\n periodic_save = args.periodical_save\n saving_period = args.save_period\n num_epochs = 200\n learning_rate = args.learning_rate\n\n save_dir = os.path.join(os.getcwd(), 'saved_models')\n save_dir_intermediate = os.path.join(save_dir, 'intermediate')\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n if not os.path.isdir(save_dir_intermediate):\n os.makedirs(save_dir_intermediate)\n sub_model_name = dataset + '_weights_'\n model_name = sub_model_name + 'final.h5'\n\n if dataset == \"mnist\":\n num_epochs = 30\n num_classes = 10\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)\n x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)\n elif dataset == \"cifar_10\":\n num_epochs = 30\n num_classes = 10\n if args.conv_blocks <= 0:\n conv_blocks = 2\n elif args.conv_blocks < 4:\n conv_blocks = args.conv_blocks\n else:\n print(\"Error: The number of convolutional blocks shoud be 0, 1, 2, 3 or 4! (0 indicates default value for the model)\")\n exit()\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n elif dataset == \"cifar_100\":\n num_classes = 100\n if args.conv_blocks <= 0:\n conv_blocks = 3\n elif args.conv_blocks < 4:\n conv_blocks = args.conv_blocks\n else:\n print(\"Error: The number of convolutional blocks shoud be 0, 1, 2, 3 or 4! (0 indicates default value for the model)\")\n exit()\n (x_train, y_train), (x_test, y_test) = cifar100.load_data()\n elif dataset == \"cifar_100\":\n num_classes = 100\n (x_train, y_train), (x_test, y_test) = cifar100.load_data()\n elif dataset == \"cifar_100_resnet\":\n num_classes = 100\n (x_train, y_train), (x_test, y_test) = cifar100.load_data()\n elif dataset == \"cifar_100_densenet\":\n num_classes = 100\n (x_train, y_train), (x_test, y_test) = cifar100.load_data()\n elif dataset == \"cifar_100_inceptionv3\":\n num_classes = 100\n (x_train, y_train), (x_test, y_test) = cifar100.load_data()\n elif dataset == \"imagenet_inceptionv3\":\n model = keras.applications.inception_v3.InceptionV3(include_top=True, weights='imagenet', input_shape=(299, 299, 3), input_tensor=None, pooling=None)\n model_name_v1 = 'imagenet_inceptionV3_v1.hdf5'\n model_name_v2 = 'imagenet_inceptionV3_v2.hdf5'\n model_path = os.path.join(save_dir, model_name_v1)\n model.save(model_path)\n with h5py.File(model_path) as h5:\n config = json.loads(h5.attrs.get(\"model_config\").decode('utf-8').replace('input_dtype', 'dtype'))\n with tf.Session('') as sess:\n model = model_from_config(config)\n model.load_weights(model_path)\n model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(lr=1e-4), metrics=['accuracy'])\n model_path = os.path.join(save_dir, model_name_v2)\n model.save(model_path)\n del model\n del sess\n print(\"InceptionV3 Model has been successfully downloaded and saved.\")\n exit()\n elif dataset == \"imagenet_xception\":\n model = keras.applications.xception.Xception(include_top=True, weights='imagenet', input_shape=(299, 299, 3), input_tensor=None, pooling=None)\n model_name_v1 = 'imagenet_xception_v1.hdf5'\n model_name_v2 = 'imagenet_xception_v2.hdf5'\n model_path = os.path.join(save_dir, model_name_v1)\n model.save(model_path)\n with h5py.File(model_path) as h5:\n config = json.loads(h5.attrs.get(\"model_config\").decode('utf-8').replace('input_dtype', 'dtype'))\n with tf.Session('') as sess:\n model = model_from_config(config)\n model.load_weights(model_path)\n model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(lr=1e-4), metrics=['accuracy'])\n model_path = os.path.join(save_dir, model_name_v2)\n model.save(model_path)\n del model\n del sess\n print(\"Xception Model has been successfully downloaded and saved.\")\n exit()\n else:\n print(\"Unknown dataset/Model!\")\n exit()\n\n if args.epochs is not None:\n num_epochs = args.epochs\n \n # Convert class vectors to binary class matrices.\n y_train = keras.utils.to_categorical(y_train, num_classes)\n y_test = keras.utils.to_categorical(y_test, num_classes)\n\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n x_train /= 255\n x_test /= 255\n\n print('x_train shape:', x_train.shape)\n print('y_train shape:', y_train.shape)\n print(x_train.shape[0], 'train samples')\n print(x_test.shape[0], 'test samples')\n\n if dataset == \"mnist\":\n #LeNet Architecture\n model = keras.Sequential()\n model.add(Conv2D(filters=6, kernel_size=(3, 3), activation='relu', input_shape=x_train.shape[1:]))\n model.add(AveragePooling2D())\n model.add(Conv2D(filters=16, kernel_size=(3, 3), activation='relu'))\n model.add(AveragePooling2D())\n\n model.add(Flatten())\n model.add(Dense(units=120, activation='relu'))\n model.add(Dense(units=84, activation='relu'))\n model.add(Dense(units=num_classes, activation='softmax'))\n elif dataset == \"cifar_10\" or dataset == \"cifar_100\":\n model = Sequential()\n model.add(Conv2D(32, (3, 3), padding='same',\n input_shape=x_train.shape[1:]))\n model.add(Activation('relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(32, (3, 3)))\n model.add(Activation('relu'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.2))\n\n if conv_blocks >= 2:\n model.add(Conv2D(64, (3, 3), padding='same'))\n model.add(Activation('relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(64, (3, 3)))\n model.add(Activation('relu'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.2))\n\n if conv_blocks >= 3:\n model.add(Conv2D(128, (3, 3), padding='same'))\n model.add(Activation('relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(128, (3, 3)))\n model.add(Activation('relu'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.2))\n\n if conv_blocks >= 4:\n model.add(Conv2D(256, (3, 3), padding='same'))\n model.add(Activation('relu'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.2))\n\n if dataset == \"cifar_10\":\n model.add(Flatten())\n model.add(Dense(128))\n elif dataset == \"cifar_100\":\n model.add(Flatten())\n model.add(Dense(1024))\n\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(num_classes))\n model.add(Activation('softmax'))\n elif dataset == \"cifar_100_resnet\":\n # model = keras.applications.resnet.ResNet101(include_top=True, weights=None, input_tensor=None, input_shape=(32, 32, 3), pooling=None, classes=num_classes)\n #model = keras.applications.resnet50.ResNet50(include_top=True, weights=None, input_tensor=None, input_shape=(32, 32, 3), pooling=None, classes=num_classes)\n model = resnet_v2(input_shape=x_train.shape[1:], depth=101, num_classes=num_classes)\n elif dataset == \"cifar_100_densenet\":\n #model = keras.applications.densenet.DenseNet121(include_top=True, weights=None, input_tensor=None, input_shape=(32, 32, 3), pooling=None, classes=num_classes)\n depth = 100\n nb_dense_block = 3\n growth_rate = 12\n nb_filter = 12\n bottleneck = False\n reduction = 0.0\n dropout_rate = 0.2 # 0.0 for data augmentation\n model = densenet.DenseNet((32, 32, 3), classes=num_classes, depth=70, nb_dense_block=nb_dense_block,\n growth_rate=growth_rate, nb_filter=nb_filter, dropout_rate=dropout_rate,\n bottleneck=bottleneck, reduction=reduction, weights=None)\n\n # initiate Adam optimizer\n opt = keras.optimizers.Adam(lr=learning_rate, beta_1=0.5, beta_2=0.99, epsilon=1e-08)\n\n callbacks = []\n if periodic_save:\n filepath = save_dir_intermediate + \"/\" + sub_model_name + \"_{epoch:02d}.hdf5\"\n checkpoint = ModelCheckpoint(filepath, monitor=['val_accuracy'], verbose=1, save_best_only=False,\n mode='max', save_weights_only=False, period=saving_period)\n callbacks.append(checkpoint)\n\n if use_lr_reducer:\n lr_reducer = keras.callbacks.ReduceLROnPlateau(factor=np.sqrt(0.1), cooldown=0, patience=5, min_lr=0.5e-6)\n callbacks.append(lr_reducer)\n\n if use_lr_scheduler:\n lr_scheduler = LearningRateScheduler(lr_schedule)\n callbacks.append(lr_scheduler)\n\n model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\n model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=num_epochs, shuffle=True, batch_size=batch_size,\n callbacks=callbacks)\n\n # Save model and weights\n model_path = os.path.join(save_dir, model_name)\n model.save(model_path)\n print('Saved trained model at %s ' % model_path)\n\n # Score trained model on train set.\n scores = model.evaluate(x_train, y_train, verbose=1)\n print('Train loss:', scores[0])\n print('Train accuracy:', scores[1])\n\n # Score trained model on test set.\n scores = model.evaluate(x_test, y_test, verbose=1)\n print('Test loss:', scores[0])\n print('Test accuracy:', scores[1])\n","sub_path":"train_target_model.py","file_name":"train_target_model.py","file_ext":"py","file_size_in_byte":12371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"228207227","text":"from theano import shared\nimport numpy\nimport theano.tensor as T\n\n\nclass Adam(object):\n def __init__(self, alpha=0.001, b1=0.9, b2=0.999):\n self.alpha = alpha\n self.b1 = b1\n self.b2 = b2\n\n def get_updates(self, loss, weights):\n # mi servono due memorie\n grads = [shared(weight.get_value() * 0, broadcastable=weight.broadcastable) for weight in weights]\n deltas = [shared(weight.get_value() * 0, broadcastable=weight.broadcastable) for weight in weights]\n # e il timestep\n timestep = shared(numpy.ones(1, dtype=\"float32\"), name=\"timestep\")\n updates = []\n # fuori dal ciclo.eseguto solo una volta\n updates.append((timestep, timestep + 1))\n\n lr_t = self.alpha * (numpy.sqrt(1. - numpy.power(self.b2, timestep[0])) /\n (1. - numpy.power(self.b1, timestep[0])))\n\n for i, weight in enumerate(weights):\n grad = T.grad(loss, weight)\n\n m_t = (self.b1* grads[i]) + (1. - self.b1) * grad\n v_t = (self.b2 * deltas[i]) + (1. - self.b2) * numpy.square(grad)\n weight_t = weight - lr_t * m_t / (numpy.sqrt(v_t) + 1e-08)\n\n updates.append((weight, weight_t))\n updates.append((grads[i], m_t))\n updates.append((deltas[i], v_t))\n\n\n\n return updates\n\n\nclass Adadelta(object):\n def __init__(self, alpha = 1.0,b=0.95):\n self.alpha = alpha\n self.b = b\n\n def get_updates(self, loss, weights):\n # mi servono due memorie\n grads = [shared(weight.get_value() * 0, broadcastable=weight.broadcastable) for weight in weights]\n deltas = [shared(weight.get_value() * 0, broadcastable=weight.broadcastable) for weight in weights]\n # e il timestep\n updates = []\n\n for i, weight in enumerate(weights):\n grad = T.grad(loss, weight)\n #update accumulator\n acc= self.b * grads[i] + (1. - self.b) * numpy.square(grad)\n updates.append((grads[i],acc))\n #update\n update = grad * numpy.sqrt(deltas[i] + 1e-08) / numpy.sqrt(acc + 1e-08)\n\n updates.append((weights[i], weights[i] - self.alpha*update))\n delta = self.b * deltas[i] + (1 - self.b) * numpy.square(update)\n updates.append((deltas[i],delta))\n\n\n return updates\n\n\nclass Sgd(object):\n def __init__(self, alpha):\n self.alpha = alpha\n\n def get_updates(self, loss, weights):\n updates = []\n\n for i, weight in enumerate(weights):\n grad = T.grad(loss, weight)\n\n updates.append((weights[i], weights[i] - self.alpha * grad))\n\n return updates\n\n\nclass Momentum(object):\n def __init__(self, alpha, momentum):\n self.alpha = alpha\n self.momentum = momentum\n\n def get_updates(self, loss, weights):\n # mi servono due memorie\n grads = [shared(weight.get_value() * 0, broadcastable=weight.broadcastable) for weight in weights]\n updates = []\n\n for i, weight in enumerate(weights):\n grad = T.grad(loss, weight)\n # peso aggiornato con peso-(sqrt(somma deltas quadrati+epsilon)*grad)/sqrt(somma grads quadrati+epsilon)*grad\n\n updates.append((weights[i], weights[i] - self.alpha * grad - self.momentum * grads[i]))\n updates.append((grads[i], grad))\n\n return updates\n","sub_path":"NN/sequential/optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"329504427","text":"\nfrom selenium import webdriver\nfrom os import environ\n \npath = environ.get('PATH')\nenviron.putenv('PATH', path + ';C:/Program Files (x86)/Firefox')\n\nb = webdriver.Firefox()\nb.get('https://www.cnblogs.com/')\n\n# 引入 ActionChains 模拟鼠标操作\nfrom selenium.webdriver import ActionChains\n# 选中目标元素\nele = b.find_element_by_partial_link_text('编程语言')\n# 将鼠标移动到目标元素上\nActionChains(b).move_to_element(ele).perform()\n\n# 选中弹出层元素\nele = b.find_element_by_partial_link_text('Java(')\nele.click()\n\nfrom selenium.webdriver.common.keys import Keys\n\nele = b.find_element_by_id('zzk_q');\nele.send_keys('python')\n# 模拟在目标元素上按下退格键 \nele.send_keys(Keys.BACKSPACE)\n# 模拟在目标元素上按下组合键 ctrl+a,实现全选\nele.send_keys(Keys.CONTROL, 'a')\n# 模拟在目标元素上按下组合键 ctrl+x,实现剪切\nele.send_keys(Keys.CONTROL, 'x')\n# 模拟在目标元素上按下组合键 ctrl+v,实现黏贴\nele.send_keys(Keys.CONTROL, 'v')\n\nb.quit()\n","sub_path":"org/zxd/selenium/mousekeyboard/mouse_keyboard.py","file_name":"mouse_keyboard.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"561825040","text":"import json\nimport os\nfrom .dict import ToolConfDict\n\n\nclass ToolConfJsonFile(ToolConfDict):\n _configs_dir = None\n\n def __init__(self, config_file):\n if not os.path.isfile(config_file):\n raise Exception(\"LTI tool config file not found: \" + config_file)\n self._configs_dir = os.path.dirname(config_file)\n\n cfg = open(config_file, 'r')\n iss_conf = json.loads(cfg.read())\n super(ToolConfJsonFile, self).__init__(iss_conf)\n cfg.close()\n\n for iss in iss_conf:\n private_key_file = iss_conf[iss]['private_key_file']\n if not private_key_file.startswith('/'):\n private_key_file = self._configs_dir + '/' + private_key_file\n\n prf = open(private_key_file, 'r')\n self.set_private_key(iss, prf.read())\n prf.close()\n","sub_path":"pylti1p3/tool_config/json_file.py","file_name":"json_file.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"109635566","text":"import math\n\n\ndef main():\n x = 0\n y = 0\n lastX = 0\n lastY = 0\n\n roundCircle = 0.0\n padding = 80\n steps = 200\n\n for i in range(steps):\n sinVal = math.sin(i / float(steps) * 2 * math.pi)\n cosVal = math.cos(i / float(steps) * 2 * math.pi)\n\n x = padding + int((sinVal + 1) / 2 * (200 - padding))\n y = padding + int((cosVal + 1) / 2 * (200 - padding))\n\n if(lastX != x or lastY != y):\n print(F\"Motion_moveTo({x}, {y}, 0);\")\n\n lastX = x\n lastY = y\n\n\nif __name__ == '__main__':\n main()","sub_path":"project/src/trace_circle.py","file_name":"trace_circle.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"386597986","text":"## creator tools for \nimport numpy as np\nimport cupy as cp\n\n# from model.utils.bbox_tools import bbox2loc, bbox_iou, loc2bbox\nfrom model.utils.bbox_pts_tools import bbox_score_intense_event\nfrom model.utils.nms import non_maximum_suppression\n\nclass ProposalPointTargetCreator(object):\n \"\"\" Assign ground truth points to given RoIs.\n \"\"\"\n def __init__(self,\n n_sample=128,\n pos_ratio=0.4, \n pos_score_thresh=1,\n neg_score_thresh_hi=3,\n neg_score_thresh_lo=0.3\n ):\n self.n_sample = n_sample\n self.pos_ratio = pos_ratio\n\n ## assign pre-defined threshold\n self.pos_score_thresh = pos_score_thresh\n self.neg_score_thresh_hi = neg_score_thresh_hi\n self.neg_score_thresh_lo = neg_score_thresh_lo\n \n\n def __call__(self, img, roi, points, label,\n loc_normalize_mean=(0., 0., 0., 0.),\n loc_normalize_std=(0.1, 0.1, 0.2, 0.2),\n method='intensity_event_per_pixel'):\n \"\"\" assign the ground-truth to the sampled proposals\n\n The function samples total of n_samples RoIs from total RoIs.\n for each RoI we compute a score that weights the relationships between \n storm events, pixels, and reflection intensity.\n\n Losses includes:\n `intensity_event_per_pixel`: n_event * Relu(avg_intensity) / n_pixel\n\n TBD: find the best loss function\n\n Args:\n img (array): intensity after normalization. with approx. \n range [-1,1] for pytorch.\n roi (array): Region of Interests (RoIs) from which we sample.\n Its shape is :math:`(R, 4)`\n bbox (array): The coordinates of ground truth bounding boxes.\n Its shape is :math:`(R', 4)`.\n label (array): Ground truth bounding box labels. Its shape\n is :math:`(R',)`. Its range is :math:`[0, L - 1]`, where\n :math:`L` is the number of foreground classes.\n loc_normalize_mean (tuple of four floats): Mean values to normalize\n coordinates of bouding boxes.\n loc_normalize_std (tupler of four floats): Standard deviation of\n the coordinates of bounding boxes.\n \"\"\"\n pos_roi_per_image = np.round(self.n_sample * self.pos_ratio)\n\n ## manually create some bboxes\n _, H, W = img.shape\n\n if method == 'intensity_event_per_pixel':\n score_perpix, intensity_perpix, cnt_exten = bbox_score_intense_event(\n img, roi, points)\n ## other methods TBD\n\n # select positive objects\n pos_index = np.where(score_perpix >= self.pos_score_thresh)[0]\n pos_roi_per_this_image = int(min(pos_roi_per_image, pos_index.size))\n if pos_index.size > 0:\n pos_index = np.random.choice(\n pos_index, size=pos_roi_per_this_image, replace=False)\n\n # Select background RoIs as whose intensity within\n neg_index = np.where((cnt_exten == 0) & \n (intensity_perpix > self.neg_score_thresh_lo) &\n (intensity_perpix < self.neg_score_thresh_hi))[0]\n\n # add more negative examples\n neg_index_candidate = np.where((cnt_exten == 0) &\n (intensity_perpix <= self.neg_score_thresh_lo))[0]\n\n neg_roi_per_this_image = self.n_sample - pos_roi_per_this_image\n if neg_index.size < neg_roi_per_this_image:\n neg_index_candidate = np.random.choice(\n neg_index_candidate, \n size=min(neg_index_candidate.size, neg_roi_per_this_image - neg_index.size),\n replace=False)\n neg_index = np.append(neg_index, neg_index_candidate)\n elif neg_index.size > 0:\n neg_index = np.random.choice(\n neg_index, size=neg_roi_per_this_image, replace=False)\n \n neg_roi_per_this_image = neg_index.size\n\n # The indices that we're selecting (both positive and negative).\n keep_index = np.append(pos_index, neg_index)\n\n # for 2 classes cases, just make labels to be 1 and 0\n gt_roi_label = np.ones((pos_roi_per_this_image + neg_roi_per_this_image,)).astype(int)\n gt_roi_label[pos_roi_per_this_image:] = 0 # negative labels --> 0\n sample_roi = roi[keep_index]\n\n return sample_roi, gt_roi_label\n\n\nclass AnchorPointTargetCreator(object):\n \"\"\"Assign the ground truth bounding boxes to anchors.\n\n Assigns the ground truth bounding boxes to anchors for training Region\n Proposal Networks introduced in Faster R-CNN [#]_.\n\n Offsets and scales to match anchors to the ground truth are\n calculated using the encoding scheme of\n :func:`model.utils.bbox_tools.bbox2loc`.\n\n .. [#] Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun. \\\n Faster R-CNN: Towards Real-Time Object Detection with \\\n Region Proposal Networks. NIPS 2015.\n\n Args:\n n_sample (int): The number of regions to produce.\n pos_iou_thresh (float): Anchors with IoU above this\n threshold will be assigned as positive.\n neg_iou_thresh (float): Anchors with IoU below this\n threshold will be assigned as negative.\n pos_ratio (float): Ratio of positive regions in the\n sampled regions.\n\n \"\"\"\n\n def __init__(self,\n n_sample=256,\n pos_score_thresh=1, \n neg_score_thresh_hi=3,\n neg_score_thresh_lo=0.3,\n pos_ratio=0.5):\n self.n_sample = n_sample\n self.pos_score_thresh = pos_score_thresh\n self.neg_score_thresh_hi = neg_score_thresh_hi\n self.neg_score_thresh_lo = neg_score_thresh_lo\n self.pos_ratio = pos_ratio\n\n def __call__(self, img, points, anchor, img_size):\n \"\"\"Assign ground truth supervision to sampled subset of anchors.\n\n Types of input arrays and output arrays are same.\n\n Here are notations.\n\n * :math:`S` is the number of anchors.\n * :math:`R` is the number of bounding boxes.\n\n Args:\n bbox (array): Coordinates of bounding boxes. Its shape is\n :math:`(R, 4)`.\n anchor (array): Coordinates of anchors. Its shape is\n :math:`(S, 4)`.\n img_size (tuple of ints): A tuple :obj:`H, W`, which\n is a tuple of height and width of an image.\n\n Returns:\n (array, array):\n\n #NOTE: it's scale not only offset\n * **loc**: Offsets and scales to match the anchors to \\\n the ground truth bounding boxes. Its shape is :math:`(S, 4)`.\n * **label**: Labels of anchors with values \\\n :obj:`(1=positive, 0=negative, -1=ignore)`. Its shape \\\n is :math:`(S,)`.\n\n \"\"\"\n\n img_H, img_W = img_size\n\n n_anchor = len(anchor)\n inside_index = _get_inside_index(anchor, img_H, img_W)\n anchor = anchor[inside_index]\n label = self._create_label(img, inside_index, anchor, points)\n\n # map up to original set of anchors\n label = _unmap(label, n_anchor, inside_index, fill=-1)\n\n return label\n\n\n def _create_label(self, img, inside_index, anchor, points):\n # label: 1 is positive, 0 is negative, -1 is dont care\n label = np.empty((len(inside_index),), dtype=np.int32)\n label.fill(-1)\n\n score_perpix, intensity_perpix, cnt_exten = bbox_score_intense_event(\n img, anchor, points)\n\n # assign positive examples\n label[score_perpix > self.pos_score_thresh] = 1\n\n # assign negative examples\n idx_neg = np.where(\n (cnt_exten == 0) & \n (intensity_perpix > self.neg_score_thresh_lo) &\n (intensity_perpix < self.neg_score_thresh_hi)\n )[0]\n label[idx_neg] = 0\n\n # subsample positive labels if we have too many\n n_pos = int(self.pos_ratio * self.n_sample)\n pos_index = np.where(label == 1)[0]\n if len(pos_index) > n_pos:\n disable_index = np.random.choice(\n pos_index, size=(len(pos_index) - n_pos), replace=False)\n label[disable_index] = -1\n\n # subsample negative labels if we have too many\n n_neg = self.n_sample - np.sum(label == 1)\n neg_index = np.where(label == 0)[0]\n if len(neg_index) > n_neg:\n disable_index = np.random.choice(\n neg_index, size=(len(neg_index) - n_neg), replace=False)\n label[disable_index] = -1\n\n return label\n\n\ndef _unmap(data, count, index, fill=0):\n # Unmap a subset of item (data) back to the original set of items (of\n # size count)\n\n if len(data.shape) == 1:\n ret = np.empty((count,), dtype=data.dtype)\n ret.fill(fill)\n ret[index] = data\n else:\n ret = np.empty((count,) + data.shape[1:], dtype=data.dtype)\n ret.fill(fill)\n ret[index, :] = data\n return ret\n\n\ndef _get_inside_index(anchor, H, W):\n # Calc indicies of anchors which are located completely inside of the image\n # whose size is speficied.\n index_inside = np.where(\n (anchor[:, 0] >= 0) &\n (anchor[:, 1] >= 0) &\n (anchor[:, 2] < H) &\n (anchor[:, 3] < W)\n )[0]\n return index_inside","sub_path":"model/utils/creator_tool_pts.py","file_name":"creator_tool_pts.py","file_ext":"py","file_size_in_byte":9347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"178038017","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # 1. Factorial\n\n# In[ ]:\n\n\ndef fact (n):\n if n==1 or n==0: return 1\n return n*fact(n-1)\n\ndef factorial (n):\n try:\n # check if input has non-numeric value:\n if isinstance(n, str) is True:\n msg = \"input must have numberic value\"\n raise Exception (msg)\n \n # check if input is non-integer:\n if isinstance(n, int) is False:\n msg = \"input number must be integer\"\n raise Exception (msg)\n \n # check if input is negative:\n if n < 0:\n msg = \"input number must be positive \"\n raise Exception (msg) \n \n return fact(n)\n \n except Exception:\n print(msg)\n\n\n# # 2. Combination\n\n# In[ ]:\n\n\n# n is the total number of objects in a set\n# k is the number of objects selected from the set. \n# Use function \"factorial\" from question 1 to calculate combinations\n\ndef combination ():\n n = int(input(\"total number of objects in a set is \"))\n k = int(input(\"number of objects selected from the set is \"))\n return factorial(n)/(factorial(k)*factorial(n-k))\n\n\n# # 3. Permutation\n\n# In[ ]:\n\n\n# n is the total number of objects in a set\n# k is the number of objects selected from the set. \n# Use function \"factorial\" from question 1 to calculate permutation\ndef permutation ():\n n = int(input(\"total number of objects in a set is \"))\n k = int(input(\"number of objects selected from the set is \"))\n return factorial(n)/factorial(n-k)\n\n\n# # 4. Percentile\n\n# In[ ]:\n\n\nimport math\ndef percentile (seqOfRealNum, aRealNum):\n try:\n if 0 < aRealNum < 100: \n seqOfRealNum.sort() \n iniIndex = (aRealNum/100)*len(seqOfRealNum) \n roundIndex = math.ceil(iniIndex)\n if roundIndex == iniIndex:\n print(\"rounded index is equal to initial index\")\n return (seqOfRealNum[roundIndex-1] + seqOfRealNum[roundIndex])/2 \n else:\n return seqOfRealNum[roundIndex-1]\n else:\n raise Exception\n except Exception:\n print(\"Exception: percentile value is out of range\")\n\n\n# # 5. Coefficient Correlation\n\n# In[ ]:\n\n\nimport math\n# this function returns an average of all elements in a list\ndef mean(list):\n try:\n return sum(list)/len(list)\n except:\n print(\"a list cannot be empty and must be numeric\")\n\n# this function returns the standard deviation of all elements in a list\n# if sample, divide by (n-1)\n# if population, divide by n\ndef std(list, sample=True):\n if sample == True:\n length = len(list) -1\n else:\n length = len(list)\n \n # calculating average and stdev\n ave = mean(list)\n sse = sum([(x-ave)**2 for x in list])\n return math.sqrt(sse/length)\n\n# this function return the correlation between 2 lists\n# if 2 lists have same lengths, calculate Sx, Sx, Sxy \n# and return Sxy / (Sx * Sy)\n# else:raise an exception\ndef Pearson_correl(list1, list2, sample=True):\n try:\n if len(list1) == len(list2):\n if sample == True:\n length = len(list1) - 1\n else:\n length = len(list1)\n #calculate average of list1, list2: Xave. Yave\n Xave = mean(list1)\n Yave = mean(list2)\n #calculate Sxy\n Sxy = 0\n for x,y in zip(list1, list2):\n Sxy += (x - Xave)*(y - Yave)\n \n Sxy /= length\n print(\"sample covariance is\", Sxy) \n # calculate standard deviation of list1 and list2: Sx and Sy\n Sx = std(list1, True)\n Sy = std(list2, True)\n # return the correlation coefficient between 2 lists\n return Sxy/(Sx * Sy) \n else:\n raise Exception\n except Exception:\n print(\"Exception: the length of two lists is not equal\")\n\n\n# # 6. Z_score\n\n# In[ ]:\n\n\nfrom math import sqrt\n#this function returns z_score for an element in a list\ndef z_score (list,x):\n m = mean(list)\n s = std(list)\n return (x-m)/s\n\n\n# # 7. Sample Variance\n\n# In[ ]:\n\n\ndef sample_variance(s):\n m = sum(s)/len(s)\n sse = sum([(x-m)**2 for x in s])\n return sse/(len(s)-1) \n\n\n# # 8. Testing Central Limit Theorem\n\n# In[ ]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import sqrt\n\n# Testing Central Limit Theorem with Uniform distribution\n\n# simulating the experiment\nn=125 # sample size\nt=10000 # the number of repetition or iteration\nsample = np.random.uniform(low=0, high=1, size=(t,n))\n\n# theoretical results from central limit theorem\nmean_pop = (1+0)/2\nsigma = (1/4)**0.5\nse_pop = sigma/(n**0.5)\nprint(mean_pop, se_pop)\n\n# experimental results \nsample_mean = np.mean(sample, axis=1)\ngrand_mean = np.mean(sample_mean)\nse_sam = np.std(sample_mean, ddof=1)\nprint(grand_mean, se_sam)\n\n# Histogram for testing Central Limit Theorem\nb = 100\nget_ipython().run_line_magic('matplotlib', 'inline')\nplt.hist(sample_mean, b, normed=1, color='m')\nplt.title('Histogram for Testing Central Limit Theorem')\nplt.xlabel('Sample Mean')\nplt.ylabel('Probability')\nplt.show()\n\n\n# # 9. Power of the hypothesis test\n\n# In[ ]:\n\n\nfrom scipy.stats import norm, t\nfrom math import sqrt\n\ndef power_in_hypo_test_for_mean(mu_b, mu_h, n, alpha, sd, pop=True, tail=-1):\n try:\n if (tail not in (-1,0,1)):\n raise ValueError(\"Error: tail must be -1, 0 or 1\")\n if (n <= 0):\n raise ValueError(\"Error: size n must be positive\")\n if (sd <= 0):\n raise ValueError (\"Error:standard deviation must be positive\")\n if alpha <= 0 or alpha >= 1:\n raise ValueError (\"Error: alpha must be between 0 and 1\")\n \n except (ValueError) as E:\n print(E)\n \n else: \n if pop==True:\n if tail==-1:\n print(\"Lower tail test\")\n if mu_bmu_h:\n crit_z = norm.ppf(1-alpha,0,1)\n crit_sample_mean = mu_h + crit_z*sd/sqrt(n)\n z_score = (crit_sample_mean - mu_b)/(sd/sqrt(n))\n power = 1- norm.cdf(z_score,0,1)\n print(\"Power of the hypothesis test is\", power)\n else:\n print(\"Type II error cannot be made\")\n \n if tail==0:\n print(\"Two tailed test\")\n if mu_b != mu_h:\n # z_lower_tail:\n cz_lower = norm.ppf(alpha/2,0,1)\n crit_sample_mean_lower = mu_h + cz_lower*sd/sqrt(n)\n z_lower = (crit_sample_mean_lower - mu_b)/(sd/sqrt(n))\n power_lower = norm.cdf(z_lower,0,1)\n \n #z_upper tail:\n cz_upper = norm.ppf(1-alpha/2,0,1)\n crit_sample_mean_upper = mu_h + cz_upper*sd/sqrt(n)\n z_upper = (crit_sample_mean_upper - mu_b)/(sd/sqrt(n))\n power_upper = 1- norm.cdf(z_upper,0,1)\n power = power_lower + power_upper\n print(\"Power of the hypothesis test is\", power)\n else:\n print(\"Type II error cannot be made\")\n \n else:\n if tail==-1:\n print(\"Lower tail test\")\n if mu_bmu_h:\n crit_t = t.ppf(1-alpha,n-1)\n crit_sample_mean = mu_h + crit_t*sd/sqrt(n)\n t_score = (crit_sample_mean - mu_b)/(sd/sqrt(n))\n beta = t.cdf(t_score, n-1)\n power = 1 - beta\n print(\"Power of the hypothesis test is\", power)\n else:\n print(\"Type II error cannot be made\")\n \n if tail==0:\n print(\"Two tailed test\")\n if mu_b != mu_h:\n #t_lower_tail: \n ct_lower = t.ppf(alpha/2, n-1)\n crit_sample_mean_lower = mu_h + ct_lower*sd/sqrt(n)\n t_lower = (crit_sample_mean_lower - mu_b)/(sd/sqrt(n))\n power_lower = t.cdf(t_lower, n-1)\n \n #t_upper_tail: \n ct_upper = t.ppf(1-alpha/2, n-1)\n crit_sample_mean_upper = mu_h + ct_upper*sd/sqrt(n)\n t_upper = (crit_sample_mean_upper - mu_b)/(sd/sqrt(n))\n power_upper = 1- t.cdf(t_upper, n-1)\n \n power = power_lower + power_upper\n print(\"Power of the hypothesis test is\", power)\n else:\n print(\"Type II error cannot be made\") \n\n","sub_path":"Statistical Functions using Python.py","file_name":"Statistical Functions using Python.py","file_ext":"py","file_size_in_byte":9756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"111008518","text":"import cv2\nimport time\nfrom scratch.flask_VS_like.base_camera import *\n\n\nclass CameraRTSP(BaseCamera):\n video_source = 0\n\n def __init__(self, src):\n self.set_video_source(src)\n # if os.environ.get('OPENCV_CAMERA_SOURCE'):\n # Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))\n super(CameraRTSP, self).__init__()\n\n @staticmethod\n def set_video_source(source):\n CameraRTSP.video_source = source\n\n @staticmethod\n def frames():\n camera = cv2.VideoCapture(CameraRTSP.video_source)\n if not camera.isOpened():\n raise RuntimeError('Could not start camera.')\n\n while True:\n # read current frame\n grabbed, img = camera.read()\n\n # encode as a jpeg image and return it\n # yield cv2.imencode('.jpg', img)[1].tobytes()\n yield img\n\n\ndef gen(camera):\n \"\"\"Video streaming generator function.\"\"\"\n while True:\n frame = camera.get_frame()\n yield (frame)\n\n\nif __name__ == '__main__':\n\n frames1 = gen(CameraRTSP(\"rtsp://192.168.183.242:554\"))\n cv2.namedWindow('VIDEO1')\n # frames2 = gen(CameraRTSP(\"rtsp://192.168.183.242:554\"))\n # cv2.namedWindow('VIDEO2')\n\n count = 0\n while True:\n count += 1\n if count < 10:\n\n frame = next(frames1, None)\n if frame is not None:\n cv2.imshow('VIDEO1', frame)\n\n # frame = next(frames2, None)\n # if frame is not None:\n # cv2.imshow('VIDEO2', frame)\n else:\n time.sleep(0.1)\n\n k = cv2.waitKey(10)\n txt = None\n if k == 27 or k == 3:\n break # esc to quit\n elif k == ord('s'):\n count = 0\n\n # print(count)\n\n cv2.destroyAllWindows()\n","sub_path":"scratch/flask_VS_like/camera_opencv.py","file_name":"camera_opencv.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"506966447","text":"from app.trader.strategy_base import MarketData, StrategyBase, TradeManagerBase\n\n\nkMinIntervals = 300 * 1000\nkMeanDuration = 90 * 1000\nkThreshold = 0.01\nkOrderTimeout = 10 * 60 * 1000\n\n\nclass MediumStrategy(StrategyBase):\n def __init__(self, strategy_id: int, manager: TradeManagerBase) -> None:\n StrategyBase.__init__(self, strategy_id, manager)\n self._amount = 1000\n self._pending = False\n self._buy_order_id = 0\n self._sell_order_id = 0\n self._data_list = []\n self._last_data_ts = 0\n self._last_order_ts = 0\n\n def on_market_data(self, data: MarketData) -> None:\n self._data_list.append(\n [data.ts, data.bids_price[0], data.asks_price[0],\n (data.bids_price[0] + data.asks_price[0]) / 2])\n if self._pending:\n return\n if data.ts < self._data_list[0][0] + kMinIntervals:\n return\n if data.asks_amount[0] < self._amount \\\n or data.bids_amount[0] < self._amount:\n return\n price = self._data_list[-1][3]\n max_value = price\n min_value = price\n for item in self._data_list[-2::-1]:\n if max_value < item[3]:\n max_value = item[3]\n if min_value > item[3]:\n min_value = item[3]\n if item[0] + kMeanDuration < data.ts:\n break\n if price + kThreshold > max_value \\\n or price - kThreshold < min_value:\n return\n sell_price = (max_value + price) / 2\n buy_price = (price + min_value) / 2\n self._pending = True\n self._last_order_ts = data.ts\n self._buy_order_id = self._manager.place_order(\n self._sid, 'buy', buy_price, self._amount)\n self._sell_order_id = self._manager.place_order(\n self._sid, 'sell', sell_price, self._amount)\n print(f'place order buy: {buy_price}, sell: {sell_price}')\n\n def on_commission(self, order_id: int, value: float) -> None:\n if self._buy_order_id != order_id \\\n and self._sell_order_id != order_id:\n return\n if self._buy_order_id == order_id:\n self._buy_order_id = -1\n if self._sell_order_id == order_id:\n self._sell_order_id = -1\n if self._sell_order_id == -1 and self._buy_order_id == -1:\n self._pending = False\n\n def on_partial_filled(self, order_id: int,\n filled_amount: int, filled_value: float) -> None:\n pass\n\n def on_canceled(self, order_id: int) -> None:\n if self._buy_order_id != order_id \\\n and self._sell_order_id != order_id:\n return\n if self._buy_order_id == order_id:\n self._buy_order_id = -1\n if self._sell_order_id == order_id:\n self._sell_order_id = -1\n if self._sell_order_id == -1 and self._buy_order_id == -1:\n self._pending = False\n\n def on_reset(self) -> None:\n self._data_list = []\n self._pending = False\n self._sell_order_id = -1\n self._buy_order_id = -1\n","sub_path":"app/trader/medium_strategy.py","file_name":"medium_strategy.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"468944230","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n===============================================================\nauthor:sjyttkl\nemail:695492835@qq.com\ndate:2018\nintroduction:\n===============================================================\n\"\"\"\n__author__ = \"sjyttkl\"\n\nimport tensorflow as tf\nimport numpy as np\n# 1. 假设我们输入矩阵\nM = np.array([\n [[1],[-1],[0]],\n [[-1],[2],[1]],\n [[0],[2],[-2]]\n ])\nprint(M.shape)\n#定义卷积过滤器深度为1\nfilter_weight = tf.get_variable(name=\"weigths\",shape=[2,2,1,1],initializer=tf.constant_initializer([[1,-1],[0,2]]))\nbiases = tf.get_variable(name=\"biases\",shape=[1],initializer=tf.constant_initializer(1))\n# 3.调整输入的格式符合TensorFlow的要求。\nM = np.array(p_object=M,dtype=\"float32\")\nM = M.reshape(1,3,3,1)\n#4, 计算矩阵通过卷积层过滤器和池化层过滤器计算后的结果。\n\n# x 的 形式为[batch, in_height, in_width, in_channels]`\nx= tf.placeholder(dtype=\"float32\",shape=[1,None,None,1])\n# x input tensor of shape `[batch, in_height, in_width, in_channels]`\n# W filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels]\n# `strides[0] = strides[3] = 1`. strides[1]代表x方向的步长,strides[2]代表y方向的步长\n# padding: A `string` from: `\"SAME\", \"VALID\"`\nconv = tf.nn.conv2d(x,filter_weight,strides=[1,2,2,1],padding=\"SAME\")\nbias = tf.nn.bias_add(conv,biases)\npool =tf.nn.avg_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding=\"SAME\")\nwith tf.Session() as sess:\n tf.global_variables_initializer().run()\n convoluted_M = sess.run(bias,feed_dict={x:M})\n pooled_M = sess.run(pool,feed_dict={x:M})\n\n print(\"convoluted_M: \\n\", convoluted_M)\n print(\"pooled_M: \\n\", pooled_M)\n\n","sub_path":"codes/Chapter06/1.卷积层、池化层样.py","file_name":"1.卷积层、池化层样.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"637736868","text":"'''\nTopic-based Text embedding class for Round 10 Yelp Dataset Challenge\n'''\n\nimport pandas as pd\nimport gensim\nfrom gensim.utils import simple_preprocess\nfrom gensim import corpora, models, similarities\nfrom gensim.parsing.preprocessing import STOPWORDS\nimport nltk\nimport numpy as np\nimport pickle\n\nclass TextEmbedder(object):\n def __init__(self, **kwargs):\n self.trained = True\n self.business_idf = False\n self.user_idf = False\n if kwargs != None:\n # load dictionary if exists\n if 'dictionary' not in kwargs.keys():\n self.dictionary = None\n self.trained = False\n else:\n self.dictionary = kwargs['dictionary']\n\n # load topic model if exists\n if 'model' not in kwargs.keys():\n self.model = None\n self.trained = False\n else:\n self.model = kwargs['model']\n\n # load user_idf if exists\n if 'user_idf' not in kwargs.keys():\n self.user_idf_dict = None\n else:\n self.user_idf_dict = kwargs['user_idf']\n self.user_idf = True\n\n # load user_idf if exists\n if 'business_idf' not in kwargs.keys():\n self.business_idf_dict = None\n else:\n self.business_idf_dict = kwargs['business_idf']\n self.business_idf = True\n\n\n def tokenize_(self, text):\n '''\n tokenize the text using the utils from Gensim\n\n Input:\n text(str) : text that you want to tokenize\n Output\n (list): tokenized text\n '''\n return [token for token in simple_preprocess(text) if token not in STOPWORDS]\n\n def embed(self, text, minimum_probability = None):\n '''\n embed the raw text into the vector with the length of topic number\n\n Input:\n text(str) : text that you want to embed\n Output:\n (list): embedded text\n '''\n if self.trained:\n model = self.model\n dictionary = self.dictionary\n text = self.tokenize_(text)\n bow = self.dictionary.doc2bow(text)\n kindex = self.model.get_document_topics(bow, minimum_probability)\n out = [0.] * self.model.num_topics\n for i, p in kindex:\n out[i] = p\n return np.array(out)\n else:\n print ('Load LDA model and dictionary')\n return None\n\n\n def embed_sent(self, text, minimum_probability = None):\n '''\n tokenize the text by sentences first, then\n embed the raw text into the vector with the length of topic number\n\n Input:\n text(str) : text that you want to embed\n minimum_probability(float) : the lowest threshold to be counted as one of topics.\n None otherwise\n Output:\n (list): embedded text\n '''\n if self.trained:\n model = self.model\n dictionary = self.dictionary\n out = np.array([0.] * self.model.num_topics)\n sentences = len(nltk.sent_tokenize(text))\n for text in nltk.sent_tokenize(text):\n out += self.embed(text, minimum_probability)\n return (out/sentences)\n else:\n print ('Load LDA model and dictionary')\n return None\n\n\n def embed_bow(self, text):\n '''\n return a sparse matrix of bag of words model\n\n Input:\n text(str) : text that you want to embed\n Output:\n (list): embedded text\n '''\n if self.trained:\n model = self.model\n text = self.tokenize_(text)\n bow = self.dictionary.doc2bow(text)\n return bow\n else:\n print ('Load LDA model and dictionary')\n return None\n\n\n def augmented_embed_text(self, text, alpha = 0.5, minimum_probability = 0.0):\n '''\n add scaling to normalize documents with large sentence counts\n smooth the result by alpha value, rescale the result so that the\n sum of embedding becomes 1.0\n\n Input:\n text(str) : text that you want to embed\n minimum_probability(float) : the lowest threshold to be counted as one of topics.\n None otherwise\n Output:\n (list): embedded text\n '''\n if self.trained:\n\n out = np.array([0.]*128)\n sentences = len(nltk.sent_tokenize(text))\n for text in nltk.sent_tokenize(text):\n out += self.embed(text,minimum_probability)\n\n out = alpha + alpha * out/max(out)\n\n return out/sum(out)\n else:\n print ('Load LDA model and dictionary')\n return None\n\n def user_tfidf_embed(self, text, user_id, alpha = 0.5, minimum_probability = 0.0):\n '''\n embed the text with tf-idf of the topic values for each user\n This will scale the embedding by penalizing frequently mentioned\n topic for one user\n '''\n # for now not allowing this function without loading idf\n if self.trained and self.user_idf:\n tf = self.augmented_embed_text(text, alpha, minimum_probability)\n idf = self.user_idf_dict[user_id]\n out = np.multiply(tf, idf)\n if sum(out) == 0.0:\n print ('User has too low idf')\n return np.array([0.]*128)\n return out/sum(out)\n else:\n print ('Load LDA model and dictionary and user idf')\n return None\n\n def user_tf_business_idf(self, text, business_id, alpha = 0.5, minimum_probability = 0.0):\n '''\n embed the text with tf-idf of the topic values for each business\n This will scale the embedding by penalizing frequently mentioned\n topic for each business\n '''\n # for now not allowing this function without loading idf\n if self.trained and self.business_idf:\n tf = self.augmented_embed_text(text, alpha, minimum_probability)\n idf = self.business_idf_dict[business_id]\n out = np.multiply(tf, idf)\n if sum(out) == 0.0:\n print ('Business has too low idf')\n return np.array([0.]*128)\n return out/sum(out)\n else:\n print ('Load LDA model and dictionary and user idf')\n return None\n\n def user_tfidf_business_idf(self, text, user_id, business_id, alpha = 0.5, minimum_probability = 0.0):\n '''\n embed the text with tf-idf of the topic values for each user, then\n multiply this value by topic idf for each business\n\n Give high value of the review that by the user who doesn't usually\n talk about topicA and topicA is importnant characteristic of the particular\n business\n '''\n # for now not allowing this function without loading idf\n if self.trained and self.business_idf and self.user_idf:\n tf = self.augmented_embed_text(text, alpha, minimum_probability)\n bidf = self.business_idf_dict[business_id]\n uidf = self.user_idf_dict[user_id]\n out = np.multiply(np.multiply(tf, uidf), bidf)\n if sum(out) == 0.0:\n print ('Business has too low idf')\n return np.array([0.]*128)\n return out/sum(out)\n else:\n print ('Load LDA model and dictionary and user idf')\n return None\n\n\nif __name__ == '__main__':\n dictionary = corpora.Dictionary.load('../workspace/gensim/chinsese_dict.dict')\n model = models.LdaModel.load('../workspace/gensim/lda.model')\n\n with open('u_idf.pickle', 'rb') as f:\n uidf_data = pickle.load(f)\n\n with open('b_idf.pickle', 'rb') as f:\n bidf_data = pickle.load(f)\n\n\n model = TextEmbedder(model = model, dictionary = dictionary, user_idf = uidf_data, business_idf = bidf_data)\n\n user1 = 'CxDOIDnH8gp9KXzpBHJYXw'\n business = 'gtcsOodbmk4E0TulYHnlHA'\n\n sample = \"Bar Crawl #1: Beau's Kissmeyer Nordic Pale Ale & St Bernardus Abt 12\\\n \\n\\nHappy Hour Everyday till 7 pm! $2 off drafts and bottles/cans. Sweet!\\\n \\n\\nOf course I have to start off with a pint: Beau's Kissmeyer Nordic Pale Ale ($5.50 with HH specials!) \\\n and my Yelp friend with a can of Howe Sound Lager ($4.5 with HH Special). \\\n And of course if you prefer some exquisite import: A bottle of St Bernardus Abt 12 ($28).\\\n \\n\\nThe interior is dark, dim and cozy. I like how Northwood is a coffee/beer/cocktail drinking \\\n place as that means I can hang out here the whole day. \\\n \\n\\nToo bad they were out of the 8oz Cold Brew to go. \\\n I guess I have to come back soon to try out their cocktails and coffee! And free WIFI!! \\\n Oh that means I can even yelp a bit!\"\n\n print (model.augmented_embed_text(sample))\n print (model.user_tfidf_embed(sample, user1))\n print (model.user_tf_business_idf(sample, business))\n print (model.user_tfidf_business_idf(sample, user1, business))\n","sub_path":"topic_over_time/workspace/text_embedder.py","file_name":"text_embedder.py","file_ext":"py","file_size_in_byte":9109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"173359409","text":"from shutil import copyfile\nfrom os import listdir\nfrom os.path import join\n\nSRC_DIR = 'images'\nTRAIN_DIR = '10k_images'\nTEST_DIR = '500_images'\n\nNUM_TEST = 500\nNUM_TRAIN = 10000\n\n# curr_num_train = 0\n# for filename in listdir(SRC_DIR):\n# if curr_num_train == NUM_TRAIN: break\n#\n# source = join(SRC_DIR, filename)\n# destination = join(TRAIN_DIR, filename)\n# copyfile(source, destination)\n# curr_num_train += 1\n\ntrain_filenames = set()\nfor train_filename in listdir(TRAIN_DIR):\n train_filenames.add(train_filename)\n\ncurr_num_test = 0\nfor filename in listdir(SRC_DIR):\n if curr_num_test == NUM_TEST: break\n if filename not in train_filenames:\n source = join(SRC_DIR, filename)\n destination = join(TEST_DIR, filename)\n copyfile(source, destination)\n curr_num_test += 1\n","sub_path":"dataset/split_dataset.py","file_name":"split_dataset.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"261163319","text":"from gremlin_python import statics\nfrom gremlin_python.process.anonymous_traversal import traversal\nfrom gremlin_python.process.graph_traversal import __\nfrom gremlin_python.process.strategies import *\nfrom gremlin_python.driver.driver_remote_connection import DriverRemoteConnection\nfrom gremlin_python.structure.graph import Graph, Vertex\nfrom gremlin_python.process.traversal import T\n\nfrom nltk.corpus import wordnet\nfrom bs4 import BeautifulSoup as soup\nfrom urllib.request import urlopen as uReq\nfrom urllib.error import HTTPError\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport collections\n\n\nclass Vertex:\n\n g = None\n def __init__(self,graph):\n self.g = graph\n \n def list_all(self):\n return self.g.nodes\n\n def properties(self,vid):\n return self.g.nodes[vid]\n\n def add_vertex(self,label,prop):\n vertex = tuple([label,prop])\n vertex = [vertex]\n self.g.add_nodes_from(vertex)\n\n def add_multiple_vertex(self,nodes):\n self.g.add_nodes_from(nodes)\n\n def delete_vertex(self,vid):\n self.g.remove_node(vid)\n\n\nclass Edge:\n\n g = None\n\n def __init__(self,graph):\n self.g = graph\n\n def add_edge(self,id1,id2,prop):\n edge = tuple([id1,id2,prop])\n edge = [edge]\n self.g.add_edges_from(edge)\n \n def add_multiple_edges(self,edges):\n self.g.add_edges_from(edges)\n\n def delete_edge(self,id1,id2):\n self.g.remove_edge(id1,id2)\n\nclass Import:\n\n def __init__(self):\n self.graph = None\n\n def import_graphml(self, file_name):\n G1 = nx.read_graphml(file_name)\n G1 = G1.to_undirected()\n self.graph = G1\n return G1\n\n def create_graph(self, nodes, edges):\n G2 = nx.Graph()\n G2.add_nodes_from(nodes)\n G2.add_edges_from(edges)\n return G2\n\n def generate_subg(self, node_name, depth=3):\n\n ego_graph = nx.ego_graph(self.graph, node_name, radius=depth)\n \n # plot graph \n nx.draw(ego_graph,with_labels=True)\n plt.show()\n\n return ego_graph\n\n\nclass Algo:\n def __init__(self):\n self.graph = None\n\n def join_graphs(self, graph1, graph2):\n\n ''' \n Converting two graph object to single object\n Adding vertex and edges can be done easily\n ''' \n G = nx.compose(graph1,graph2)\n l = len(G.nodes)+1\n # List of all nodes in a graph\n g1 = [node for node in graph1.nodes(data=True)]\n g2 = [node for node in graph2.nodes(data=True)]\n \n '''\n Iterate over each node and find similarity between the nodes\n If similarity is more than 50% add bridge node to connect both the nodes\n '''\n for s in g1:\n if 'labelV' in s[1]:\n cb = wordnet.synsets(s[1]['labelV'])\n else:\n continue\n if len(cb)==0:\n continue\n cb = cb[0]\n\n for e in g2:\n if 'labelV' in e[1]:\n ib = wordnet.synsets(e[1]['labelV'])\n else:\n continue\n if len(ib)==0:\n continue\n ib = ib[0]\n if s[1]['labelV'].lower() == e[1]['labelV'].lower():\n for i in e[1]:\n if i not in s[1]:\n s[1][i] = e[1][i]\n edg = list(G.edges(e[0]))\n for i in range(len(edg)):\n #print([s[0],edg[i][1],{'labelE': 'has'}])\n G.add_edges_from([(s[0],edg[i][1],{'labelE': 'has'})])\n G.remove_node(e[0])\n continue\n # Condition if similarity is more than 50% \n if ib.wup_similarity(cb)>=0.5:\n\n # Lowest hypernym will be bridge node\n bridgess = cb.lowest_common_hypernyms(ib)\n lemma = bridgess[0].lemmas()\n\n # If that node is already there add only new edge, else add vertex and edges\n\n if G.has_node(lemma[0].name()):\n G.add_edge(e[0],lemma[0].name())\n else:\n G.add_nodes_from([(str(l),{\"labelB\":lemma[0].name()}),])\n G.add_edges_from([(s[0],str(l),{'labelE': 'has'})])\n G.add_edges_from([(e[0],str(l),{'labelE': 'has'})])\n l+=1\n\n print(s[1]['labelV'],e[1]['labelV'],end=\"...............\")\n print(ib.wup_similarity(cb), lemma[0].name())\n\n return G\n\nclass Synonym:\n def find_synonyms(self,string):\n synonym_words = []\n synonym_words.append(string)\n try:\n # Remove whitespace before and after word and use underscore between words\n stripped_string = string.strip()\n fixed_string = stripped_string.replace(\" \", \"_\")\n #print(f\"{fixed_string}:\")\n\n # Set the url using the amended string\n my_url = f'https://thesaurus.plus/thesaurus/{fixed_string}'\n # Open and read the HTMLz\n uClient = uReq(my_url)\n page_html = uClient.read()\n uClient.close()\n\n # Parse the html into text\n page_soup = soup(page_html, \"html.parser\")\n word_boxes = page_soup.find(\"ul\", {\"class\": \"list paper\"})\n results = word_boxes.find_all(\"div\", \"list_item\")\n\n # Iterate over results and print\n for result in results:\n synonym_words.append(result.text.strip())\n\n except HTTPError:\n pass\n\n return synonym_words\n\n def add_synonyms(self,nodes):\n for node in nodes:\n synonyms = self.find_synonyms(node[1]['labelV'])\n for syn in synonyms:\n node[1]['$'+syn] = 'Synonym'\n\n return nodes\n\n\nclass Query:\n def findNode(self,g,name):\n nodes1 = set(g.V().has('labelV',name).toList())\n nodes2 = set(g.V().has('labelB',name).toList())\n nodes = nodes1.union(nodes2)\n if len(nodes)==0:\n return \"No such node\"\n \n final_node = '0'\n for node in nodes:\n node_name = g.V(node).valueMap(True).toList()[0]['labelV'][0]\n if name == node_name:\n final_node = node\n if final_node == '0':\n final_node = list(nodes)[0]\n \n return final_node\n\n def extractVertex(self,g,graph):\n tem_vertex = graph['@value']['vertices']\n l = []\n for v in tem_vertex:\n for p in g.V(v).properties():\n if p.label=='labelV':\n l.append(p.value)\n break\n return tuple(l)\n\n def extractEdges(self,g,graph):\n tem_edge = graph['@value']['edges']\n edges = []\n for edg in tem_edge:\n tem = str(edg).split('[')[2].replace('-edge-','').replace(']','')\n tem = tem.split('>')\n try: \n start = g.V(tem[0]).valueMap(True).toList()[0]['labelV'][0]\n except:\n start = g.V(tem[0]).valueMap(True).toList()[0]['labelB'][0]\n try:\n end = g.V(tem[1]).valueMap(True).toList()[0]['labelV'][0]\n except:\n end = g.V(tem[1]).valueMap(True).toList()[0]['labelB'][0]\n edges.append((start,end))\n return tuple(edges)\n\n\n def findTrees(self,g,name,depth):\n node = self.findNode(g,name)\n if node == \"No such node\":\n return\n subGraph = g.V(node).repeat(__.bothE().subgraph('subGraph').V()).times(depth).cap('subGraph').next()\n vertex = self.extractVertex(g,subGraph)\n edges = self.extractEdges(g,subGraph)\n return (vertex,edges)\n \n\n def findDescendants(self,g,name,depth):\n node = self.findNode(g,name)\n if node == \"No such node\":\n return\n\n subGraph = g.V(node).repeat(__.bothE().subgraph('subGraph').V()).times(depth).cap('subGraph').next()\n\n tem_vertex = subGraph['@value']['vertices']\n\n nodes = []\n\n for ver in tem_vertex:\n for p in g.V(ver).properties():\n if p.label=='labelV':\n nodes.append((p.value,ver))\n break\n return tuple(nodes)\n\n def bfs(self,graph,root,g):\n visited, queue = set(), collections.deque([(root,root)])\n removed = set()\n visited.add(root)\n\n while queue:\n\n # Dequeue a vertex from queue\n vertex = queue.popleft()\n if vertex[0] in removed or vertex[1] in removed:\n continue\n flag = 0\n for p in g.V(vertex[0]).properties():\n if p.label=='labelV':\n flag=1\n break\n if flag:\n print(maping[vertex[0]],end=' ')\n visited.add(vertex[0])\n for neighbour in graph[vertex[0]]:\n if neighbour not in visited:\n queue.append((neighbour,vertex[0]))\n else:\n print(\"...\",maping[vertex[0]],maping[vertex[1]])\n visited.add(vertex[0])\n removed.add(vertex[0])\n for neighbour in graph[vertex[0]]:\n if neighbour not in visited:\n print(maping[neighbour],neighbour)\n response = input()\n if response == 'y' or response=='Y':\n graph[vertex[1]].append(neighbour)\n graph[neighbour].remove(vertex[0])\n graph[neighbour].append(vertex[1])\n\n queue.append((neighbour,vertex[1]))\n else:\n graph[neighbour].remove(vertex[0])\n graph.pop(vertex[0])\n return graph\n\nclass pathtraversal:\n q = Query()\n\n def countbirdge(self, path):\n #Counts the number of bridge nodes, but noticed that bridge nodes always have an out degree of 0\n #So they will not lie on a path, need to check if this is always true\n\n count = 0\n for j in path:\n if(len(g.V(j.id).properties('labelB').toList())== 0):\n continue\n else:\n count+=1\n return count\n \n def priortizePaths(self, paths):\n\n #TODO Incomplete function just finds number of bridge nodes and length of paths and creates a list of tuples\n #Need to check criteria for prioritzation\n\n temp = list()\n for i in paths:\n temp.append(self.countbridge(i), len(i)-2)\n \n\n def allpaths(self, g, node1_label, node2_label):\n #Returns all paths between two labels\n\n if(type(q.findNode(g, node1_label)) is str or type(q.findNode(g, node2_label)) is str ):\n return \"One or both nodes don't exist\"\n return g.V(q.findNode(g, node1_label).id).repeat(__.out().simplePath()).until(__.hasId(q.findNode(g, node2_label).id)).path().toList()\n \n def npaths(self, g, node1_label, node2_label, numberofpaths):\n #Returns at most n paths between two labels\n if(type(q.findNode(g, node1_label)) is str or type(q.findNode(g, node2_label)) is str ):\n return \"One or both nodes don't exist\"\n return g.V(q.findNode(g, node1_label).id).repeat(__.out().simplePath()).until(__.hasId(q.findNode(g, node2_label).id)).path().limit(numberofpaths).toList()\n \n def shortestpath(self, g, node1_label, node2_label):\n #Returns shortest path between two labels\n if(type(q.findNode(g, node1_label)) is str or type(q.findNode(g, node2_label)) is str ):\n return \"One or both nodes don't exist\"\n return g.V(q.findNode(g, node1_label).id).repeat(__.out().simplePath()).until(__.hasId(q.findNode(g, node1_label).id)).path().limit(1).toList()\n \n def pathToGraph(self, g, path_obj, G):\n # Converts path object to graph object\n nx.add_path(G,path_obj)\n attrs = dict()\n for vertex in path_obj:\n temp = dict()\n for property in g.V(vertex.id).properties().valueMap(True).toList():\n temp[property[T.key]] = property[T.value]\n attrs[vertex]=temp\n \n nx.set_node_attributes(G, attrs)\n\n return G\n \n \nif __name__==\"__main__\":\n\n ''' \n Import graphml file\n '''\n #gra = Import()\n # G3 = gra.import_graphml('g3.graphml')\n # G2 = gra.import_graphml('g2.graphml')\n \n # algo = Algo()\n # G = algo.join_graphs(G2,G3)\n # nx.write_graphml(G, \"gf.graphml\")\n\n #G = gra.import_graphml('D:/Python/Knowledge Graph/KG-main-priyank_1/apache-tinkerpop-gremlin-server-3.4.10/data/g.graphml')\n\n\n ''' Graph traversal '''\n g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g'))\n \n \n\n ''' Get all the nodes '''\n #l = g.with_('evaluationTimeout', 500).V().toList()\n #print(g.V().has('labelV', 'grade').toList())\n \n # name = input(\"Enter the word: \")\n name = 'grade'\n q = Query()\n # print(q.findNode(g, name).id)\n # subGraph = q.findTrees(g, name, 1)\n # print(subGraph)\n # print(\"Descendants\")\n # print(q.findDescendants(g, name, 2))\n \n ''' Path traversal between two nodes'''\n #Area and GradeParalelo have 2 paths between them\n G = nx.Graph()\n p = pathtraversal()\n for path in p.allpaths(g, \"Area\", \"GradeParalelo\"):\n G=p.pathToGraph(g,path,G)\n nx.write_graphml(G, \"g_paths.graphml\")\n \n \n\n # graph = {}\n # edge = []\n # tem_edge = subGraph['@value']['edges']\n \n # for edg in tem_edge:\n # tem = str(edg).split('[')[2].replace('-edge-','').replace(']','')\n # tem = tem.split('>')\n # if tem[0] not in maping or tem[1] not in maping:\n # continue\n # if tem[0] not in graph:\n # graph[tem[0]] = []\n # graph[tem[0]].append(tem[1])\n\n # if tem[1] not in graph:\n # graph[tem[1]] = []\n # graph[tem[1]].append(tem[0])\n\n # edge.append(tuple(tem))\n # # print(graph)\n\n # print(\"output\")\n # graph = bfs(graph,maping[name],g)\n # for node in graph:\n # print(maping[node],end=\" -> \")\n # for i in set(graph[node]):\n # print(maping[i],end = \" \")\n # print()\n # data = dict()\n # for p in g.E(e).properties():\n # print(p.value)\n # for p in g.V(v).properties():\n # data[p.label] = p.value\n # print(data)\n\n\n\n\n\n ''' Add vertex '''\n # nodes = [(1, {'labelV': 'grade', 'grade_id': 'INT', 'name': 'VARCHAR'}), (2, {'labelV': 'course', 'course_id': 'INT', 'name': 'VARCHAR', 'grade_id': 'INT'}),\n # (3, {'labelV': 'classroom', 'classroom_id': 'INT', 'grade_id': 'INT', 'section': 'VARCHAR', 'teacher_id': 'INT'}),\n # (4, {'labelV': 'classroom_student', 'classroom_id': 'INT', 'studen_id': 'INT'}), (5, {'labelV': 'attendance', 'date': 'Date', 'student_id': 'INT', 'status': 'INT'}),\n # (6, {'exam_type': 'INT', 'name': 'VARCHAR', 'labelV': 'exam_type'}), (7, {'exam_id': 'INT', 'exam_type': 'INT', 'name': 'VARCHAR', 'labelV': 'exam'}), \n # (8, {'labelV': 'exam_result', 'exam_id': 'INT', 'student_id': 'INT', 'course_id': 'INT'}), \n # (9, {'labelV': 'student', 'student_id': 'INT', 'email': 'VARCHAR', 'name': 'VARCHAR', 'dob': 'Date', 'parent_id': 'INT'}), \n # (10, {'labelV': 'parent', 'parent_id': 'INT', 'email': 'VARCHAR', 'password': 'VARCHAR', 'mobile': 'VARCHAR'}), \n # (11, {'teacher_id': 'INT', 'name': 'VARCHAR', 'email': 'VARCHAR', 'dob': 'Date', 'labelV': 'teacher'}) ]\n \n # print(nodes)\n # edges = [(1, 2, {'labelE': 'has'}), (1, 3, {'labelE': 'has'}), (3, 4, {'labelE': 'has'}), (3, 11, {'labelE': 'has'}),\n # (6, 7, {'labelE': 'has'}), (7, 8, {'labelE': 'has'}), (5, 9, {'labelE': 'has'}), (4, 9, {'labelE': 'has'}), \n # (2, 8, {'labelE': 'has'}), (9, 8, {'labelE': 'has'}), (9, 10, {'labelE': 'has'})]\n\n \n # nodes = [(12, {'labelV': 'Area', 'Area_id': 'INT', 'Name': 'VARCHAR', 'Subjects_id': 'INT'}), (13, {'labelV': 'Subject', 'Subject_id': 'INT', 'Abbreviation': 'VARCHAR', 'Area_id': 'INT', 'ScoreRecords_id': 'INT', 'SubjectGrades_id': 'INT'}), \n # (14, {'labelV': 'SubjectGrade', 'SubjectGrade_id': 'INT', 'Grade_id': 'INT', 'Subject_id': 'INT'}), (15, {'labelV': 'Level', 'Level_id': 'INT', 'Name': 'VARCHAR', 'Principle': 'VARCHAR', 'Garde_id': 'INT'}), \n # (16, {'labelV': 'Grade', 'Garde_id': 'INT', 'Name': 'VARCHAR', 'Level_id': 'INT', 'Observation': 'VARCHAR', 'Grade_paraleloes_id': 'INT', 'Subject_grades_id': 'INT'}), \n # (17, {'labelV': 'ScoreRecord', 'ScoreRecord_id': 'INT', 'Subject_id': 'INT', 'Student_id': 'INT', 'FirstTrimester': 'VARCHAR', 'SecondTrimester': 'VARCHAR', 'ThirdTrimester': 'VARCHAR', 'FinalGrade': 'INT', 'Year': 'DATE'}), \n # (18, {'labelV': 'Attendance', 'Attendance_id': 'INT', 'Student_id': 'INT', 'Attended': 'VARCHAR', 'Date': 'DATE'}), \n # (19, {'labelV': 'Student', 'Student_id': 'INT', 'Garde_paralelo_id': 'INT', 'Rude': 'VARCHAR', 'Attendance_id': 'INT', 'ScoreRecords_id': 'INT', 'Name': 'VARCHAR', 'Father_name': 'VARCHAR', 'Mother_name': 'VARCHAR', 'Sex': 'VARCHAR', 'Date_of_Birth': 'DATE', 'Mobile_phone': 'VARCHAR', 'Address': 'VARCHAR'}), \n # (20, {'labelV': 'GradeParalelo', 'Garde_paralelo_id': 'INT', 'Grade_id': 'INT', 'Staff_id': 'INT', 'Name': 'VARCHAR', 'Student_id': 'INT'}), \n # (21, {'labelV': 'Staff', 'Staff_id': 'INT', 'Name': 'VARCHAR', 'Date_of_birth': 'DATE', 'Place_of_birth': 'VARCHAR', 'Sex': 'VARCHAR', 'Mobile_phone': 'INT', 'Address': 'VARCHAR', 'Father_name': 'VARCHAR', 'Mother_name': 'VARCHAR', 'Salary': 'VARCHAR', 'StaffType_id': 'INT', 'Garde_paralelos_id': 'INT'}), \n # (22, {'labelV': 'User', 'Username': 'VARCHAR', 'Password': 'VARCHAR'}), (23, {'labelV': 'StaffType', 'Name': 'VARCHAR', 'Staff_id': 'INT'})]\n \n # edges = [(13, 12, {'labelE': 'Area_info'}), (14, 13, {'labelE': 'of_Subject'}), (17, 13, {'labelE': 'subject_info'}), \n # (16, 14, {'labelE': 'level_info'}), (16, 15, {'labelE': 'has'}), (16, 20, {'labelE': 'has'}), \n # (20, 19, {'labelE': 'has'}), (19, 17, {'labelE': 'has'}), (19, 18, {'labelE': 'has'}), \n # (20, 21, {'labelE': 'has'}), (21, 23)]\n\n\n '''\n Create grahml file from node and edge list\n '''\n # syn = Synonym()\n # nodes = syn.add_synonyms(nodes)\n \n # G = gra.create_graph(nodes,edges)\n # nx.write_graphml(G, \"g2.graphml\")\n\n\n '''\n Add single data\n '''\n # vet.add_vertex('course',data) \n #vet.delete_vertex('grade')\n # data = {'grade_id':'INT', 'name':'VARCHAR'}\n #vet.add_vertex('grade',data)\n # print(vet.list_all())\n #vet.add_vertex('4',data)\n #ed.add_edge('grade','course','')\n\n #nx.draw(G,with_labels=True)\n #plt.show()\n #nx.write_graphml(G1, \"graph1.graphml\")\n #print(vet.properties('142'))\n","sub_path":"kgn_pathfinding.py","file_name":"kgn_pathfinding.py","file_ext":"py","file_size_in_byte":19229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"513032863","text":"import tensorflow as tf\nimport numpy as np\nfrom meta_policy_search.policies.distributions.base import Distribution\n\nTINY = 1e-8\n\n\ndef log_softmax(x):\n x -= x.max(-1, keepdim=True)\n return x - np.log(np.exp(x).sum(-1, keepdim=True) + TINY)\n\n\ndef softmax(x):\n x -= x.max(-1, keepdim=True)\n expx = np.exp(x)\n return expx / expx.sum(-1, keepdim=True)\n\n\nclass Categorical(Distribution):\n def __init__(self, dim):\n self._dim = dim\n\n @property\n def dim(self):\n return self._dim\n\n def kl_sym(self, old_dist_info_vars, new_dist_info_vars):\n \"\"\"\n Computes the symbolic representation of the KL divergence\n\n Args:\n old_dist_info_vars (dict) : dict of old distribution parameters as tf.Tensor\n new_dist_info_vars (dict) : dict of new distribution parameters as tf.Tensor\n\n Returns:\n (tf.Tensor) : Symbolic representation of kl divergence (tensorflow op)\n \"\"\"\n old_prob = old_dist_info_vars[\"prob\"]\n new_prob = new_dist_info_vars[\"prob\"]\n old_logprob = tf.log(old_prob + TINY)\n new_logprob = tf.log(new_prob + TINY)\n\n # assert ranks\n tf.assert_rank(old_prob, 2)\n tf.assert_rank(new_prob, 2)\n\n return tf.reduce_sum(\n old_prob * (old_logprob - new_logprob), reduction_indices=-1)\n\n def kl(self, old_dist_info, new_dist_info):\n \"\"\"\n Compute the KL divergence of two multivariate Gaussian distribution with\n diagonal covariance matrices\n\n Args:\n old_dist_info (dict): dict of old distribution parameters as numpy array\n new_dist_info (dict): dict of new distribution parameters as numpy array\n\n Returns:\n (numpy array): kl divergence of distributions\n \"\"\"\n\n old_prob = old_dist_info[\"prob\"]\n new_prob = new_dist_info[\"prob\"]\n old_logprob = np.log(old_prob + TINY)\n new_logprob = np.log(old_prob + TINY)\n\n\n # assert ranks\n assert old_prob.ndim == 2\n assert new_prob.ndim == 2\n\n return np.sum(\n old_prob * (old_logprob - new_logprob), axis=-1)\n\n def likelihood_ratio_sym(self, x_var, old_dist_info_vars, new_dist_info_vars):\n \"\"\"\n Symbolic likelihood ratio p_new(x)/p_old(x) of two distributions\n\n Args:\n x_var (tf.Tensor): variable where to evaluate the likelihood ratio p_new(x)/p_old(x)\n old_dist_info_vars (dict) : dict of old distribution parameters as tf.Tensor\n new_dist_info_vars (dict) : dict of new distribution parameters as tf.Tensor\n\n Returns:\n (tf.Tensor): likelihood ratio\n \"\"\"\n with tf.variable_scope(\"log_li_new\"):\n logli_new = self.log_likelihood_sym(x_var, new_dist_info_vars)\n with tf.variable_scope(\"log_li_old\"):\n logli_old = self.log_likelihood_sym(x_var, old_dist_info_vars)\n return tf.exp(logli_new - logli_old)\n\n def log_likelihood_sym(self, x_var, dist_info_vars):\n probs = dist_info_vars[\"prob\"]\n log_probs = tf.log(probs + TINY)\n\n # assert ranks\n tf.assert_rank(probs, 2)\n tf.assert_rank(x_var, 2)\n\n return tf.batch_gather(log_probs, x_var)\n\n def log_likelihood(self, xs, dist_info):\n assert xs.ndim == 1\n probs = dist_info[\"prob\"]\n\n return np.log(probs + TINY)[np.arange(len(xs)), xs]\n\n def entropy_sym(self, dist_info_vars):\n probs = dist_info_vars[\"prob\"]\n log_probs = tf.log(probs + TINY)\n return -tf.reduce_sum(probs * log_probs, reduction_indices=-1)\n\n def entropy(self, dist_info):\n probs = dist_info[\"prob\"]\n log_probs = np.log(probs + TINY)\n return -np.sum(probs * log_probs, axis=-1)\n\n def sample(self, dist_info):\n probs = dist_info[\"prob\"]\n return np.asarray([np.random.choice(prob.shape[1], p=prob) for prob in probs])\n\n @property\n def dist_info_specs(self):\n return [(\"prob\", (self.dim,))]\n","sub_path":"meta_policy_search/policies/distributions/categorical.py","file_name":"categorical.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"105403273","text":"# -*- coding: utf-8 -*-\n# Royal HaskoningDHV\n\nfrom radar_calibrate.tests import testconfig\nfrom radar_calibrate.tests import testutils\nfrom radar_calibrate import gridtools\nfrom radar_calibrate import calibration\nfrom radar_calibrate import kriging_r\nfrom radar_calibrate import plot\nfrom radar_calibrate import utils\n\nimport numpy as np\n\nimport logging\nimport os\n\n@utils.timethis\ndef krige_r(x, y, z, radar, xi, yi, zi):\n return kriging_r.ked_r(x, y, z, radar, xi, yi, zi)\n\n\n@utils.timethis\ndef krige_py(x, y, z, radar, xi, yi, zi):\n return calibration.ked(x, y, z, radar, xi, yi, zi)\n\n\ndef test_compare_ked(plot_comparison=False, timestamp='20170305080000'):\n # test data from files\n aggregatefile = r'data\\24uur_{}.h5'.format(timestamp)\n calibratefile = r'data\\RAD_TF2400_U_{}.h5'.format(timestamp)\n calibrate_kwargs, aggregate, calibrate = testutils.get_testdata(\n aggregatefile,\n calibratefile,\n )\n # NaN mask\n nan_mask = numpy.isnan(aggregate)\n\n # ked using R\n timedresult_r = krige_r(**calibrate_kwargs)\n logging.info('ked in R took {dt:.2f} seconds'.format(dt=timedresult_r.dt))\n rain_est_r = timedresult_r.result\n calibrate_r = utils.apply_countrymask(\n rain_est_r.reshape(calibrate.shape), aggregate)\n calibrate_r[nan_mask] = numpy.nan\n\n # ked using Python\n timedresult_py = krige_py(**calibrate_kwargs)\n logging.info('ked in python took {dt:.2f} seconds'.format(\n dt=timedresult_py.dt))\n rain_est_py, sigma = timedresult_py.result\n calibrate_py = utils.apply_countrymask(\n rain_est_py.reshape(calibrate.shape), aggregate)\n calibrate_py[nan_mask] = numpy.nan\n\n # plot\n if plot_comparison:\n imagefile = os.path.join(testconfig.PLOTDIR,\n 'compare_ked_{}.png'.format(timestamp))\n plot.compare_ked(aggregate,\n calibrate, calibrate_r, calibrate_py,\n imagefile=imagefile,\n )\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n test_compare_ked(plot_comparison=True)\n","sub_path":"radar_calibrate/examples/example_kriging.py","file_name":"example_kriging.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"571593862","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nimport sqlalchemy\nfrom flask import current_app\n\nfrom polylogyx.models import ResultLogScan, ThreatIntelCredentials\nfrom polylogyx.utils import check_and_save_intel_alert\nfrom .base import AbstractIntelPlugin\nfrom polylogyx.database import db\nfrom OTXv2 import OTXv2\nfrom polylogyx.util.otx.is_malicious import *\n\n\nclass OTXIntel(AbstractIntelPlugin):\n LEVEL_MAPPINGS = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warn': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL,\n }\n\n def __init__(self, config):\n self.name = 'alienvault'\n levelname = config.get('level', 'debug')\n self.otx = None\n\n def update_credentials(self):\n try:\n credentials = db.session.query(ThreatIntelCredentials).filter(\n ThreatIntelCredentials.intel_name == 'alienvault').first()\n if credentials and 'key' in credentials.credentials:\n self.otx = OTXv2(credentials.credentials['key'])\n current_app.logger.info('AlienVault OTX api configured')\n else:\n self.otx = None\n current_app.logger.warn('AlienVault OTX api not configured')\n except Exception as e:\n current_app.logger.error(e)\n\n def analyse_hash(self, value, type, node):\n if self.otx:\n result_log_scan_elem = db.session.query(ResultLogScan).filter(ResultLogScan.scan_value == value).first()\n response = {}\n if result_log_scan_elem:\n if self.name not in result_log_scan_elem.reputations:\n response = is_hash_malicious(value, self.otx)\n newReputations = dict(result_log_scan_elem.reputations)\n newReputations[self.name] = response\n result_log_scan_elem.reputations = newReputations\n db.session.add(result_log_scan_elem)\n db.session.commit()\n else:\n response = result_log_scan_elem.reputations[self.name]\n if 'alerts' in response and len(response['alerts']) > 0:\n check_and_save_intel_alert(scan_type=type, scan_value=value, data=response['result'], source=self.name,\n severity=\"LOW\")\n\n\n def analyse_pending_hashes(self):\n if self.otx:\n result_log_scans = ResultLogScan.query.filter(\n sqlalchemy.not_(ResultLogScan.reputations.has_key(self.name))).filter(\n ResultLogScan.scan_type.in_(['md5', 'sha1', 'sha256'])).limit(4).all()\n for result_log_scan_elem in result_log_scans:\n\n try:\n response = is_hash_malicious(result_log_scan_elem.scan_value, self.otx)\n newReputations = dict(result_log_scan_elem.reputations)\n newReputations[self.name] = response\n if 'alerts' in response and len(response['alerts']) > 0:\n newReputations[self.name + \"_detected\"] = True\n else:\n newReputations[self.name + \"_detected\"] = False\n result_log_scan_elem.reputations = newReputations\n db.session.add(result_log_scan_elem)\n except Exception as e:\n newReputations = dict(result_log_scan_elem.reputations)\n newReputations[self.name]={}\n result_log_scan_elem.reputations = newReputations\n db.session.add(result_log_scan_elem)\n current_app.logger.error(e)\n db.session.commit()\n\n def generate_alerts(self):\n try:\n source = self.name\n from polylogyx.database import db\n from polylogyx.models import ResultLogScan\n from polylogyx.utils import check_and_save_intel_alert\n\n result_log_scans = db.session.query(ResultLogScan).filter(\n ResultLogScan.reputations[source + \"_detected\"].astext.cast(sqlalchemy.Boolean).is_(True)).all()\n for result_log_scan in result_log_scans:\n check_and_save_intel_alert(scan_type=result_log_scan.scan_type, scan_value=result_log_scan.scan_value,\n data=result_log_scan.reputations[source],\n\n source=source,\n severity=\"LOW\")\n except Exception as e:\n current_app.logger.error(e)\n\n\n def analyse_domain(self, value, type, node):\n # TODO(andrew-d): better message?\n\n current_app.logger.log(self.level, 'Triggered alert: ')\n","sub_path":"plgx-esp/polylogyx/plugins/intel/otx.py","file_name":"otx.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"565508476","text":"from time import sleep\nfrom threading import Semaphore, Thread\n\n\nclass Customer:\n\n num = None\n comein_time = None\n start_time = None\n service_time = None\n end_time = None\n service_counter_number = None\n\n def __init__(self, num, comein_time, service_time):\n self.num = num\n self.comein_time = comein_time\n self.service_time = service_time\n\n# test case file name\ntest_file_name = 'test.txt'\n\n# real time and program time ratio\ninterval = 1\n\n# global time\ntime_now = 0\n\n# the number of the counter\ncounter_number = 10\n\n# mutex semaphore\nmutex = Semaphore(1)\n\n# synchronizing semaphore\nsync = Semaphore(counter_number)\n\n# customer_list is used to store the information of customer\ncustomer_list = []\n\n# customer_service is used as the queue of customers after they get a number\ncustomer_in_queue = []\n\n# counter_service is used to store the number of the customer after service\ncounter_service = []\n\n\ndef get_number():\n\n # declare the global value\n global customer_list\n global mutex\n global customer_in_queue\n global time_now\n\n # to keep the number of the customers that came in\n num_now = 1\n\n while True:\n\n # if num_now is greater than the size of customer_list, pass\n if num_now > len(customer_list):\n continue\n\n # When a customer is coming in\n if customer_list[num_now - 1].comein_time == time_now:\n if mutex.acquire(blocking=False):\n customer_in_queue.append(customer_list[num_now - 1])\n num_now += 1\n\n # Release the resource\n mutex.release()\n\n\n# when the customer is called\ndef called():\n\n # declare the global value\n global counter_service\n global mutex\n global customer_in_queue\n global time_now\n\n while True:\n\n # if there is no customer in the blockinging queue\n if len(customer_in_queue) == 0:\n continue\n if sync.acquire(blocking=False):\n if mutex.acquire(blocking=False):\n customer_in_queue[0].service_counter_number = counter_service[0]\n customer_in_queue[0].start_time = time_now\n customer_in_queue[0].end_time = customer_in_queue[0].start_time + customer_in_queue[0].service_time\n # Create a new thread to handle\n Thread(target=bank_service,\n name=str(customer_in_queue[0].num),\n kwargs={'customer': customer_in_queue[0]}).start()\n customer_in_queue.remove(customer_in_queue[0])\n counter_service.remove(counter_service[0])\n mutex.release()\n\n\n# bank service function\ndef bank_service(customer):\n\n sleep(customer.service_time * interval)\n\n if mutex.acquire(blocking=False):\n counter_service.append(customer.service_counter_number)\n\n # print customer number,\n # come in time,\n # service start time,\n # service end time,\n # service bank counter number\n print(\"{} {} {} {} {}\".format(customer.num,\n customer.comein_time,\n customer.start_time,\n customer.end_time,\n customer.service_counter_number))\n\n sync.release()\n mutex.release()\n\n\nif __name__ == '__main__':\n\n with open(test_file_name, 'r') as f:\n for line in f:\n line = line.strip().split(' ')\n if line != ['']:\n customer_list.append(Customer(int(line[0]), int(line[1]), int(line[2])))\n\n for i in range(counter_number):\n counter_service.append(i)\n\n Thread(target=get_number, name='get_number').start()\n Thread(target=called, name='called').start()\n\n while True:\n sleep(interval)\n time_now += 1\n\n","sub_path":"bank_service_problem.py","file_name":"bank_service_problem.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"385814232","text":"import pandas as pd\n\nfrom vax.utils.files import export_metadata\n\n\ndef main(paths):\n\n vaccine_mapping = {\n 1: \"Pfizer/BioNTech\",\n 2: \"Moderna\",\n 3: \"Oxford/AstraZeneca\",\n 4: \"Johnson&Johnson\",\n }\n one_dose_vaccines = [\"Johnson&Johnson\"]\n\n source = (\n \"https://www.data.gouv.fr/fr/datasets/r/fa4ad329-14ec-4394-85a4-c5df33769dff\"\n )\n\n df = pd.read_csv(\n source, usecols=[\"jour\", \"n_cum_dose1\", \"n_cum_complet\"], sep=\";\"\n )\n\n df = df.rename(\n columns={\n \"jour\": \"date\",\n \"n_cum_dose1\": \"people_vaccinated\",\n \"n_cum_complet\": \"people_fully_vaccinated\",\n }\n )\n\n # Add total doses\n df[\"total_vaccinations\"] = df.people_vaccinated + df.people_fully_vaccinated\n\n df = df.assign(\n location=\"France\",\n source_url=(\n \"https://www.data.gouv.fr/fr/datasets/donnees-relatives-aux-personnes-vaccinees-contre-la-covid-19-1/\"\n ),\n )\n\n df.to_csv(paths.tmp_vax_out(\"France\"), index=False)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"patch/batch/france.py","file_name":"france.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"469129371","text":"\nfrom __future__ import print_function\n\nimport inro_byd.byd as _byd\nimport inro_byd.util as _util\nimport inro_byd.source_control as _sc\n\nfrom inro_byd.shorthand import *\n\nclass DesktopStep(_byd.Step):\n def __init__(self, byd):\n super(DesktopStep, self).__init__(byd)\n self.repo = self.byd.repo('desktop')\n self.workspace = jpath(self.byd.workspace_dir, 'desktop')\n \n \nclass TagDesktop(DesktopStep):\n def run(self):\n print('tag desktop')\n _sc.tag(self.repo, self.byd.tag)\n\n \nclass CheckoutDesktop(DesktopStep):\n def run(self):\n print('checkout desktop')\n _sc.checkout(self.repo, self.workspace)\n \n \nclass StampDesktop(DesktopStep):\n def run(self):\n print('stamp desktop')\n \n template_1 = ''' QString const DEFAULT_WORKSPACE(\"lastworkspace_Trial\") ;\n#else\n QString const PARENT_REGISTRY_KEY(\"$(parentkey)\") ;\n QString const VERSION_REGISTRY_KEY(\"$(versionkey)\") ;\n\n #if defined(_WIN64)\n QString const DEFAULT_WORKSPACE(\"lastworkspace_$(workspace)-64bit\") ;\n #else\n QString const DEFAULT_WORKSPACE(\"lastworkspace_$(workspace)\") ;\n #endif\n#endif\n'''\n\n template_2 = '''::QUrl const TRIAL_HOST_URL(\"http://trial.inrosoftware.com\") ;\n\n::QString const GR_VERSION(\"$(fullversion)\") ;\n\n} // namespace distro\n'''\n\n env = { \n 'parentkey': 'Emme ' + str(self.byd.version.major),\n 'versionkey': str(self.byd.version),\n 'workspace':str(self.byd.version),\n 'fullversion': self.byd.version.full }\n \n distro_fn = jpath(self.workspace, 'other', 'distro.hpp')\n self.byd.logger.debug('desktop distro file at {}'.format(distro_fn))\n \n templates = [template_1, template_2]\n nbr_subs = _util.patch_file(distro_fn, templates, env)\n\n if nbr_subs != len(templates): \n raise RuntimeError('stamping desktop failed')\n \n \nclass CommitDesktop(DesktopStep):\n def run(self):\n print('commit desktop')\n msg = 'Commit stamping code to tag {}.'.format(self.byd.tag)\n _sc.commit(msg, self.workspace)\n \n \nclass CompileDesktop(DesktopStep): \n def run(self):\n print('compile desktop')\n","sub_path":"inro_byd/steps/desktop.py","file_name":"desktop.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"608798229","text":"from random import randint\n\nmetre = 0\nano = 1\nwhile 0<=metre<=100:\n fet = randint(0, 1) \n print(fet, end=' ')\n if fet == 1:\n ano *= -1\n print(ano, end=' ')\n metre += ano*10\n else:\n metre += ano*10\n print(metre)\nprint(metre)","sub_path":"school/simple/47.py","file_name":"47.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"393062692","text":"#Amber Roberson\r\n#09/24/2019\r\n#CIS 115 01H - Error Code\r\n\r\n\r\n#Receive the amount\r\namount = float(input(\"Enter the amount: \")) #NonType logic error - Replaced 'print'\r\n\r\n#Convert to cents\r\nchangedAmount = int(amount*100)\r\n\r\n#Dollars\r\nnumDollars = changedAmount//100 #Out of order\r\nchangedAmount = changedAmount%100 \r\n\r\n#Quarters\r\nnumQuarters = changedAmount//25 #Out of order / MATH Error - 'changedAmount/25'\r\nchangedAmount = changedAmount%25 # Syntax - lower case error in 'changedAmount' / MATH Error - 'changedAmount*25'\r\n\r\n#Dimes\r\nnumDimes = changedAmount//10 #Out of order / NameType 'angedAmount'\r\nchangedAmount = changedAmount%10\r\n\r\n#Nickels\r\nnumNickels = changedAmount//5 #Out of order / NameType 'angedAmount'\r\nChangedAmount = changedAmount%5 #Syntax error - cases error 'ChangedAmount'\r\n\r\n#Pennies\r\nnumPennies = changedAmount\r\n\r\n#Output\r\nprint(\"For $\", amount, \"consists of: \\n\\t\", numDollars, \"dollars \\n\\t\", numQuarters, \"quarters \\n\\t\", numDimes, \"dimes \\n\\t\", numNickels, \"nickels \\n\\t\", numPennies, \"pennies\") # Syntax error\r\n\r\n'''\r\n^\r\nline 32 column 83-100\r\nSyntax error - missing comma after 'numDimes'\r\nSyntax error - spacing between '\\n\\ t\" '\r\nSyntax error - NameType errors for 'chnumDimes' & 'chnumNickles\r\n'''\r\n","sub_path":"CIS_115_01H_ASP5.py","file_name":"CIS_115_01H_ASP5.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"297371210","text":"import os\n\nfrom plugins.base.base_factory import Factory\nfrom core.logger import info\nfrom utils.system_printer import SystemPrinter\n\n\nclass Plugin:\n def __init__(self, config):\n self.config = config\n self.factory = self.create_factory()\n self.model = None\n self.criterion = None\n self.loader = None\n self.extension = None\n\n @info\n def create_factory(self):\n\n plugin_name = self.config.plugin\n plugin = os.path.join(\"plugins/\", plugin_name)\n\n file = os.path.join(os.curdir, plugin, plugin_name + \"_factory.py\")\n\n import importlib.util\n\n spec = importlib.util.spec_from_file_location(plugin_name, file)\n foo = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(foo)\n\n for cls in Factory.__subclasses__():\n f = cls(self.config)\n SystemPrinter.sys_print(\n \"\\t LOADED PLUGIN FACTORY - {}\".format(f.__class__.__name__)\n )\n return f\n\n def load_plugin(self):\n self.model = self.factory.create_network(\n self.config.model_name, self.config.model_param\n )\n SystemPrinter.sys_print(\n \"\\t LOADED MODEL - {}\".format(self.model.__class__.__name__)\n )\n\n self.criterion = self.factory.create_criterion(\n self.config.loss_name, self.config.loss_param\n )\n SystemPrinter.sys_print(\n \"\\t LOADED CRITERION - {}\".format(self.criterion.__class__.__name__)\n )\n\n self.loader = self.factory.create_data_set()\n self.extension = self.factory.create_extension()\n","sub_path":"core/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"553206767","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/coils/logic/workflow/actions/format/simple_filter.py\n# Compiled at: 2012-10-12 07:02:39\nimport string\nfrom StringIO import StringIO\nfrom lxml import etree\nfrom coils.core import *\nfrom coils.core.logic import ActionCommand\n\nclass SimpleFilter(ActionCommand):\n __domain__ = 'action'\n __operation__ = 'simple-filter'\n __aliases__ = ['simpleFilter', 'simpleFilterAction']\n\n def __init__(self):\n ActionCommand.__init__(self)\n\n def do_action(self):\n summary = StringIO('')\n self._row_in = 0\n self._row_out = 0\n try:\n StandardXML.Filter_Rows(self._rfile, self._wfile, callback=self.callback)\n finally:\n summary.write(('\\n Rows input = {0}, Rows output = {1}').format(self._row_in, self._row_out))\n self.log_message(summary.getvalue(), category='info')\n\n def callback(self, row):\n self._row_in += 1\n (keys, fields) = StandardXML.Parse_Row(row)\n if self._field_name in keys:\n x = keys[self._field_name]\n elif self._field_name in fields:\n x = fields[self._field_name]\n else:\n raise CoilsException(('Field {0} not found in input record.').format(self._field_name))\n if self._expression == 'EQUALS':\n if x == self._compare_value:\n self._row_out += 1\n return True\n return False\n if self._expression == 'NOT-EQUALS':\n if x != self._compare_value:\n self._row_out += 1\n return True\n return False\n raise CoilsException(('Unknown comparision expression: {0}').format(self._compare_value))\n\n def parse_action_parameters(self):\n self._field_name = self._params.get('fieldName', None)\n self._expression = self._params.get('expression', 'EQUALS').upper()\n self._cast_as = self._params.get('castAs', 'STRING').upper()\n self._compare_value = self._params.get('compareValue', None)\n if self._field_name is None:\n raise CoilsException('No field name specified for comparison.')\n if self._compare_value is None:\n raise CoilsException('No comparison expression specified')\n if self._cast_as == 'INTEGER':\n self._compare_value = int(self._compare_value)\n elif self._cast_as == 'FLOAT':\n self._compare_value = float(self._compare_value)\n elif self._cast_as == 'UNICODE':\n self._compare_value = unicode(self._compare_value)\n return","sub_path":"pycfiles/OpenGroupware-0.1.48-py2.6/simple_filter.py","file_name":"simple_filter.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"542050224","text":"from numpy import zeros, array\n\ndef produit(P,Q,n):\n \"\"\"Produit PQ tronqué à l'ordre n\"\"\"\n L = [0.]*(n+1)\n for k in range(n+1):\n for i in range(k+1):\n if k-len(Q) < i < len(P) :\n L[k] = L[k] + P[i]*Q[k-i]\n return L\n\ndef matrice(P):\n \"\"\"Matrice du systeme donnant les coefficients du DL de la réciproque de f\n P : coefficients du DL de f\"\"\"\n n = len(P)-1\n B = zeros((n,n))\n Q = P.copy()\n for j in range(n):\n for i in range(j,n):\n B[i,j] = Q[i+1]\n Q = produit(P,Q,n)\n return B\n\ndef resoutTI(T,Y):\n \"\"\"Donne X solution de TX = Y, avec T triangulaire inférieure\"\"\"\n n,_ = T.shape\n X = zeros((n,1))\n for i in range(n):\n X[i,0] = Y[i,0]\n for j in range(i):\n X[i,0] = X[i,0] - T[i,j]*X[j,0]\n X[i,0] = X[i,0] / T[i,i]\n return X\n\ndef DLreciproque(P):\n \"\"\"Donne le DL de la reciproque de f(x)+o(x n)\n Précondition : f(0)=0\"\"\"\n T = matrice(P)\n n = len(P)-1\n Y =zeros((n,1))\n Y[0,0] = 1.\n X = resoutTI(T,Y)\n Q = [0.]*(n+1)\n for i in range(1,n+1):\n Q[i] = X[i-1,0]\n return Q\n\ndef DLtan(n):\n \"\"\"Donne la partie principale du DL de la tangente à l'ordre n\"\"\"\n atan = [0.]*(n+1)\n i = -1\n s = -1\n while i+2 <= n :\n i = i+2\n s = -s\n atan[i] = s / i\n return DLreciproque(atan)\n","sub_path":"Exercices/33_systemes/SYS-001/SYS-001.py","file_name":"SYS-001.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"51546120","text":"# -*- coding: UTF-8 -*-\n\"\"\"Week 3.\n\nModify each function until the tests pass.\n\"\"\"\n# 3 steps a while loop needs:\n\n# i = 0 variable initialization\n# while(i < 5) loop condition on that variable\n# print(i)\n# i = i+1 or i +=1 Variable change value\n\n\n\ndef loop_ranger(start, stop=None, step=1):\n \"\"\"Return a list of numbers between start and stop in steps of step.\n\n Do this using any method apart from just using range()\n \"\"\"\n counter = start #while loops are foer when you dont know how long somthing is going to go for, for loop you know the range\n a_list = []\n while counter < stop:\n a_list.append(counter)\n counter += step #this saves the value of step, updates counter\n return a_list\n \n\n\ndef lone_ranger(start, stop, step):\n \"\"\"Duplicate the functionality of range.\n\n Look up the docs for range() and wrap it in a 1:1 way\n \"\"\"\n x = range(start,stop,step)\n f = list(x)\n return f \n \n\n\ndef two_step_ranger(start, stop):\n \"\"\"Make a range that steps by 2.\n\n Sometimes you want to hide complexity.\n Make a range function that always has a step size of 2\n \"\"\"\n a_list = []\n counter_a = start\n counter_b = stop\n step_2 = 2 # giving step_2 a value\n while counter_a < counter_b: # sets the loop conditions\n a_list.append(counter_a)\n counter_a += step_2 #this saves the value of step and updates counter\n return a_list\n\n\ndef gene_krupa_range(start, stop, even_step, odd_step):\n \"\"\"Make a range that has two step sizes.\n\n make a list that instead of having evenly spaced steps\n has odd steps be one size and even steps be another.\n \"\"\"\n step = 0\n counter = start\n a_list = []\n while counter < stop:\n a_list.append(counter)\n if step % 2 == 1: \n counter += even_step\n else:\n counter += odd_step\n step += 1\n return a_list\n \n\ndef stubborn_asker(low, high):\n \"\"\"Ask for a number between low and high until actually given one.\n\n Ask for a number, and if the response is outside the bounds keep asking\n until you get a number that you think is OK\n \"\"\"\n message = \"Give me a number between {low} and {high}:\".format(low=low,high=high)\n while True:\n guessed_number = int(input(message)) \n \n if low < guessed_number < high: #sets the condition \n print(\"{} is a correct number\".format(guessed_number))\n return guessed_number\n else: \n print (\"{} not in range, try again\".format(guessed_number))\n\n\n\n\ndef not_number_rejector(message):\n \"\"\"Ask for a number repeatedly until actually given one.\n\n Ask for a number, and if the response is actually NOT a number (e.g. \"cow\",\n \"six\", \"8!\") then throw it out and ask for an actual number.\n When you do get a number, return it.\n \"\"\"\n \n while True: \n try:\n guessed_Number = int(input(\"Enter a number:\"))\n a_number = int(guessed_Number) # makes it an integer\n return a_number \n except Exception: #if the guesser uses a non integer it will be an error and process to print next line\n print(\"Sorry, that is not an integer, please try again\")\n\n\n\n\n\nimport random\ndef super_asker(low, high):\n \"\"\"Robust asking function.\n\n Combine stubborn_asker and not_number_rejector to make a function\n that does it all!\n \"\"\"\n\n message = \"Give me a number between {low} and {high}:\".format(low=low,high=high)\n while True:\n try:\n guessed_number = int(input(message))\n print(\"you guessed {},\".format(guessed_number))\n if low < guessed_number < high: #sets the condition \n print(\"{} is a number within the range\".format(guessed_number))\n return guessed_number\n else: \n print (\"{} not in range, try again\".format(guessed_number))\n except Exception as e: \n print(\"Sorry, {} is not an integer, please try again\".format(e))\n\n\n return \"You got it\"\n\n\n\n\n \n\nif __name__ == \"__main__\":\n # this section does a quick test on your results and prints them nicely.\n # It's NOT the official tests, they are in tests.py as usual.\n # Add to these tests, give them arguments etc. to make sure that your\n # code is robust to the situations that you'll see in action.\n # NOTE: because some of these take user input you can't run them from\n \n\n print(\"\\nloop_ranger\", loop_ranger(1, 10, 2))\n print(\"\\nlone_ranger\", lone_ranger(1, 10, 3))\n print(\"\\ntwo_step_ranger\", two_step_ranger(1, 10))\n print(\"\\nstubborn_asker\")\n stubborn_asker(30, 45)\n print(\"\\nnot_number_rejector\")\n not_number_rejector(\"Enter a number: \")\n print(\"\\nsuper_asker\")\n super_asker(33, 42)\n","sub_path":"week3/exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":4787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"553983657","text":"################################################################\n# _ _ _____ __ _ #\n# | | | | / ____| / _| | #\n# _ __ _ _| |_| |__ ___ _ __ | | _ __ __ _| |_| |_ #\n# | '_ \\| | | | __| '_ \\ / _ \\| '_ \\| | | '__/ _` | _| __| #\n# | |_) | |_| | |_| | | | (_) | | | | |____| | | (_| | | | |_ #\n# | .__/ \\__, |\\__|_| |_|\\___/|_| |_|\\_____|_| \\__,_|_| \\__| #\n# | | __/ | #\n# |_| |___/ SpecialEffectz #\n################################################################\n################################################################\n# Looking through the code, I see? ;) ##########################\n################################################################\n\nimport random,re,math\n\ndef output_contents(path):\n # outputs ALL the contents of a file\n try:\n with open(str(path), 'r') as f:\n print(f.read())\n except FileNotFoundError or FileExistsError:\n print(\"Error reading file, that path does not exist.\")\n\n\ndef output_lines(path, first, last):\n # outputs specific line(s) of a file\n with open(str(path), 'r') as f:\n lines = f.readlines()\n for i in range(first, last):\n print(lines[i], end='')\n\n\ndef menu():\n # prints the menu text\n with open('resources/menu.txt', 'r') as f:\n print(f.read())\n\n\n# change this to \"False\" if you would not like the menu to\n# load when the game starts.\ndo_menu = True\n\nif do_menu:\n menu()\n\n# variables\naction_msg = '~ Action: '\ndo_debug = False\nitems = {\n 'apple': 0,\n 'torch': 0,\n 'meat': 0,\n 'wood': 0,\n 'ore': 0,\n 'pie': 0\n}\nmineables = ['wood', 'ore']\ncraftables = ['pick', 'sword', 'torch']\nrecipes = {\n 'pick': {\n 'wood': 1\n },\n 'sword': {\n 'wood': 1,\n 'ore': 1\n },\n 'torch': {\n 'wood': 1,\n 'ore': 2\n }\n}\nstats = {\n 'health': 20.0,\n 'hunger': 20.0\n}\ntool_stats = {\n 'sword': 0,\n 'pick': 0\n}\nhas_tools = {\n 'sword': False,\n 'pick': False\n}\nfoods = {\n 'apple': 1.0,\n 'meat': 2.0\n}\nbreak_msg = '--'\n\n\n# inventory function\ndef inventory():\n global break_msg, items, has_tools\n print(str(break_msg))\n print('==== Inventory ====')\n for item in items:\n print('{0} {1}'.format(item,str(items[item])))\n for tool in has_tools:\n print('Has {0} - {1}'.format(tool.title(),has_tools[tool]))\n print(str(break_msg))\n\n\n# eat function\ndef eat(e):\n if e in foods:\n if items[e] < 1:\n print(\"You can't eat any {0}! You don't have any!\".format(e))\n else:\n print('You ate 1 {0}.'.format(str(e)))\n items[e] -= 1\n stats['hunger'] += foods[e]\n\n # stats function\n\n\n# print stats\ndef print_stats():\n global break_msg, stats, has_tools\n print(str(break_msg))\n print('==== Stats ====')\n for stat in stats:\n print('{0}: {1}/20'.format(stat.title(),stats[stat]))\n for tool in has_tools:\n print('Has {0} - {1}'.format(tool.title(),has_tools[tool]))\n print(str(break_msg))\n\n\n# mine function\ndef mine(increment, material):\n global mineables\n if material in mineables:\n print(str(break_msg))\n print('You mined a(n) {0}! + {1} {2}'.format(material.title(),str(increment),material.title()))\n items[material] += increment\n print(str(break_msg))\n else:\n print('You cannot mine a(n) {0}!'.format(material.title()))\n stats['hunger'] -= 1.0\n print('hunger: {0} (-1)'.format(str(stats['hunger'])))\n\n\n# craft function\ndef craft(what_crafted):\n global craftables, recipes, break_msg\n if what_crafted in craftables:\n recipe = recipes[what_crafted]\n for material in recipe:\n material -= recipe[material]\n print(str(break_msg))\n print('You crafted a(n) {0}.'.format(what_crafted))\n print('Type \"inventory\" to open your inventory.')\n print(str(break_msg))\n if what_crafted == 'pick' or what_crafted == 'sword':\n tool_stats[what_crafted] = 100\n else:\n print(str(break_msg))\n print('You cannot craft a(n) {0}, you do not have enough ingredients!'.format(what_crafted.title()))\n print('Type \"recipes\" to see recipes.')\n print(str(break_msg))\n\n\ndef get_recipes():\n global break_msg\n print(str(break_msg))\n print('==== Recipes ====')\n print('pie - Free! :)')\n print('pick - 3 Wood')\n print('torch - 1 Wood, 1 Ore')\n print(str(break_msg))\n\n\n# help function\ndef get_help(mini, maxi):\n print(str(break_msg))\n output_lines('resources/help.txt', mini, maxi)\n print(str(break_msg))\n\n\n# restart function\ndef restart():\n for stat in stats:\n stats[stat] = 20.0\n for tool in tool_stats:\n tool_stats[tool] = 0\n for tool in has_tools:\n has_tools[tool] = False\n for item in items:\n items[item] = 0\n print('\\n' * 300)\n print('Successfully restarted game.')\n\n\ndef get_food(fmax):\n chance = random.randint(0, fmax)\n if not has_tools['sword']:\n if chance <= 1:\n items['apple'] += 1\n print('You found an apple on a(n) nearby tree. You now have {0} apples.'.format(str(items['apple'])))\n elif 2 <= chance <= 5:\n items['meat'] += 1\n print('You found some nearby animals. You killed them for food. You now have {0} meat.'.format(str(\n items['meat'])))\n else:\n print('You couldn\\'t find any food. :(')\n if has_tools['sword']:\n if chance <= 2:\n items['apple'] += 1\n print('You found an apple on a(n) nearby tree. You now have {0} apples.'.format(str(items['apple'])))\n elif 5 >= chance >= 3:\n items['meat'] += 1\n print('You found some nearby animals. You killed them with your sword for food. You now have {0} + meat.'.format(str(items['meat'])))\n else:\n print('You couldn\\'t find any food. :(')\n\n\n# the core of the program, all the good stuff happens here!\nwhile True:\n # checks pickaxe\n if tool_stats['pick'] == 0 and has_tools['pick']:\n print('Oh no! Your pickaxe broke!')\n has_tools['pick'] = False\n continue\n # checks sword\n if tool_stats['sword'] == 0 and has_tools['sword']:\n print('Oh no! Your sword broke!')\n has_tools['sword'] = False\n continue\n if stats['hunger'] < 14.0:\n print(str(break_msg))\n print('Your hunger has gone down! Make sure to eat food soon!')\n print('hunger: {0}/20'.format(str(stats['hunger'])))\n print(str(break_msg))\n continue\n\n action = str(input(action_msg)).split(' ')\n\n noun = ''\n verb = ''\n\n if len(action) >= 1:\n noun = action[0]\n if len(action) >= 2:\n verb = action[1]\n\n if re.search(r'\\bdebug\\b', noun.lower(), re.I):\n print('Debug activated.')\n do_debug = True\n continue\n\n ########################################################################\n\n ##############\n # DEBUG ONLY #\n ##############\n\n # get pick\n if re.search(r'\\bgetPick\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n print('Debug: You got a(n) pick.')\n has_tools['pick'] = True\n tool_stats['pick'] = 10\n continue\n # heal pick\n elif re.search(r'\\bhealPick\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n if not has_tools['pick']:\n print('Debug: You cannot heal a pick! You don\\'t have one!')\n continue\n else:\n print('Debug: You healed your pick.')\n tool_stats['pick'] += 5\n continue\n # delete pick\n elif re.search(r'\\bdelPick\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n if not has_tools['pick']:\n print('Debug: You cannot delete a pick! You don\\'t have one!')\n continue\n else:\n print('Debug: You deleted your pick.')\n has_tools['pick'] = False\n tool_stats['pick'] = 0\n # get sword\n elif re.search(r'\\bgetSword\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n print('Debug: You got a sword.')\n has_tools['sword'] = True\n tool_stats['sword'] = 10\n continue\n # heal sword\n elif re.search(r'\\bhealSword\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n if not has_tools['sword']:\n print('Debug: You cannot heal a sword! You don\\'t have one!')\n continue\n else:\n print('Debug: You healed your sword.')\n tool_stats['sword'] += 5\n continue\n # delete sword\n elif re.search(r'\\bdelSword\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n if not has_tools['sword']:\n print('Debug: You cannot delete a sword! You don\\'t have one!')\n continue\n else:\n print('Debug: You deleted your sword.')\n has_tools['sword'] = False\n tool_stats['sword'] = 0\n continue\n elif re.search(r'\\bsetHealth\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n else:\n what_to_set = input('Number: ')\n try:\n what_to_set = (math.floor(float(what_to_set) * 10)) / 10\n stats['hunger'] = what_to_set\n continue\n except TypeError:\n print('Error: {0} is not a float!'.format(str(what_to_set)))\n continue\n elif re.search(r'\\baddHealth\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n else:\n what_to_add = input('Number: ')\n try:\n what_to_add = (math.floor(float(what_to_add) * 10)) / 10\n except TypeError:\n print('Error: {0} is not a float!'.format(str(what_to_add)))\n continue\n elif re.search(r'\\bsetHunger\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n else:\n what_toset = input('Number: ')\n try:\n what_to_set = (math.floor(float(what_to_set) * 10)) / 10\n stats['hunger'] = what_to_set\n if float(stats['hunger']) > 20.0:\n stats['hunger'] = 20.0\n continue\n except TypeError:\n print('Error: {0} is not a float!'.format(str(what_to_set)))\n continue\n elif re.search(r'\\baddHunger\\b', noun.lower(), re.I):\n if not do_debug:\n print('Debug is not enabled! Enable it with \"debug\".')\n continue\n else:\n what_to_add = input('Number: ')\n try:\n what_to_add = (math.floor(float(what_to_set) * 10)) / 10\n stats['hunger'] += what_to_add\n if float(stats['hunger']) > 20.0:\n stats['hunger'] = 20.0\n continue\n except TypeError:\n print('Error: {0} is not a float!'.format(str(what_to_set)))\n continue\n\n ########################################################################\n\n # opens 'menu'\n if re.search(r'\\bmenu\\b', noun.lower(), re.I):\n menu()\n continue\n # opens inventory\n elif re.search(r'\\binventory|items\\b', noun.lower(), re.I):\n inventory()\n continue\n # shows help usage\n elif re.search(r'\\b^help$\\b', noun.lower(), re.I):\n if verb == '':\n print(str(break_msg))\n print('help ')\n print('E.g. \"help 1\"')\n print(str(break_msg))\n elif verb != '':\n if verb == '1' or verb == '2' or verb == '3' or verb == 'debug':\n if verb == '1':\n get_help(1, 6)\n continue\n elif verb == '2':\n get_help(7, 12)\n continue\n elif verb == '3':\n get_help(13, 15)\n continue\n elif verb == 'debug':\n try:\n which_page = int(input('Which page? '))\n except:\n print('Error: {0} is not a valid debug help page!'.format(str(verb)))\n if which_page == 1:\n get_help(16, 21)\n elif which_page == 2:\n get_help(22, 27)\n\n else:\n print('Error: {0} is not a valid help page!')\n continue\n # opens recipe menu\n elif re.search(r'\\brecipes\\b', noun.lower(), re.I):\n get_recipes()\n continue\n # clears console\n elif re.search(r'\\bclear\\b', noun.lower(), re.I):\n print('\\n' * 300)\n print('Cleared the console.')\n continue\n # restarts game\n elif re.search(r'\\brestart\\b', noun.lower(), re.I):\n print('Are you sure you want to reset the game? All your info will be lost!')\n confirmation = str(input('Type \"yes\" or \"no\": '))\n if re.search(r'\\byes\\b', confirmation, re.I):\n restart()\n menu()\n continue\n elif re.search(r'\\bno\\b', confirmation, re.I):\n print('Restart cancelled.')\n continue\n else:\n print('Restart cancelled.')\n continue\n # mines\n elif re.search(r'\\bmines?\\b', noun.lower(), re.I):\n what_to_mine = str(input('What would you like to mine? '))\n if what_to_mine in mineables:\n # mine wood\n if re.search(r'\\bwoods?\\b', what_to_mine, re.I):\n mine(1, 'wood')\n continue\n # mine ore\n elif re.search(r'\\bores?\\b', what_to_mine, re.I):\n if not has_tools['pick']:\n # if you dont have a pick, dont mine the ore\n print('You cannot mine ore! You need a pickaxe first!')\n continue\n else:\n # if you have a pick, mine the ore\n mine(1, 'ore')\n tool_stats['pick'] -= 1\n print('Pickaxe health: {0} (-1)'.format(str(tool_stats['pick'])))\n continue\n # error message\n else:\n print('You cannot mine a(n) \"' + what_to_mine + '\"!')\n print(str(break_msg))\n print('You can mine:')\n print('Wood - No tool required')\n print('Ore - Pickaxe required')\n print(str(break_msg))\n continue\n # gets food\n elif re.search(r'\\bget food\\b', noun.lower(), re.I):\n get_food(10)\n continue\n # eat\n elif re.search(r'\\beat\\b', noun.lower(), re.I):\n if stats['hunger'] >= 20.0:\n print(str(break_msg))\n print(\"You cannot eat; you are not hungry!\")\n print(str(break_msg))\n print(str(break_msg))\n print('You have: {0} apple(s) and {1} meat'.format(items['apple'], items['meat']))\n what_to_eat = str(input('What would you like to eat? '))\n print(str(break_msg))\n eat(what_to_eat)\n\n # craft item\n elif action == 'craft':\n what_to_craft = str(input('Type \"out\" to stop crafting. \\nWhat would you like to craft? '))\n # craft pick\n if re.search(r'\\bpick|pickaxe\\b', what_to_craft, re.I):\n craft('pick')\n continue\n # craft torch\n elif re.search(r'\\btorch\\b', what_to_craft, re.I):\n craft('torch')\n continue\n # craft sword\n elif re.search(r'\\bswords?\\b', what_to_craft, re.I):\n craft('wood')\n continue\n elif re.search(r'\\bout\\b', what_to_craft, re.I):\n # get out of crafting menu\n print('You are no longer crafting.')\n continue\n else:\n # error message\n print(str(break_msg))\n print('\"{0}\" is not an item you can craft!'.format(str(what_to_craft)))\n print('Type \"recipes\" to view all recipes.')\n print(str(break_msg))\n continue\n elif re.search(r'\\bstats?\\b', noun.lower(), re.I):\n print_stats()\n continue\n elif re.search(r'\\bexit\\b', noun.lower(), re.I) or re.search(r'\\bquit\\b', noun.lower(), re.I):\n print('Are you sure you wish to exit the game? All data will be lost!')\n exit_confirmation = str(input('Type \"yes\" or \"no\". '))\n\n if re.search(r'\\byes\\b', exit_confirmation, re.I):\n print(str(break_msg))\n print('Exiting the game.')\n print('Thanks for playing! :)')\n print(str(break_msg))\n break\n elif re.search(r'\\bno\\b', exit_confirmation, re.I):\n print(str(break_msg))\n print('Exit cancelled.')\n print(str(break_msg))\n continue\n else:\n print(str(break_msg))\n print('Exit cancelled.')\n print(str(break_msg))\n continue\n else:\n # error message\n print('\"{0}\" is not an action!'.format(noun))\n continue\n","sub_path":"pythonCraft.py","file_name":"pythonCraft.py","file_ext":"py","file_size_in_byte":17804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"27497882","text":"import os\nfrom flask import (Flask, request, abort, jsonify, render_template)\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom models import setup_db, Actor, Movie, rollback\nfrom auth import requires_auth, AuthError\n\n\ndef create_app(test_config=None):\n\n # create and configure the app\n\n app = Flask(__name__)\n setup_db(app)\n CORS(app)\n\n# create the actors action here \n @app.route('/', methods=['GET'])\n\n def start():\n return \"

    welcome

    \"\n\n\n @app.route('/actors', methods=['GET']) # set a get request for actors\n @requires_auth('get:actors')\n def get_actors(payload):\n actor = Actor.query.all() # get all actors detail \n return jsonify({\n \"success\": True,\n \"actors\": [actors.format() for actors in actor]\n }), 200\n\n @app.route('/actors/', methods=['GET']) # get the actorst by_id\n @requires_auth('get:actors')\n def get_actor(payload ,actor_id):\n actor = Actor.query.get(actor_id) # I get the code here by id \n if actor is None: # if there is no actor I will abort 404 or (not found)\n abort(404)\n return jsonify({\n \"success\": True,\n \"actor\": actor.format()\n }), 200\n\n @app.route('/actors', methods=['POST']) # post an actor\n @requires_auth('post:actors')\n def post_actors(payload):\n body = request.get_json()\n name = body.get('name') # I get the name\n age = body.get('age') # I get the age \n gender = body.get('gender') # I get the gender \n if (name is None) or (age is None) or (gender is None): # if there is no age-name-gender I want to give 422 error \n abort(422)\n try:\n new_actor = Actor(\n name = name,\n gender = gender,\n age = age\n )\n\n new_actor.insert() # I insert the data to the database \n except Exception:\n abort(500)\n return jsonify({\n \"success\": True,\n \"created_actor\": new_actor.format()\n }), 201\n\n @app.route('/actors/', methods=['PATCH']) # patch the data or (update it)\n @requires_auth('patch:actors')\n def edit_actors(payload, actor_id):\n body = request.get_json() \n \n actor = Actor.query.get(actor_id)\n\n if actor is None: # if there is no actor I want to raise 404 error (not found)\n abort(404)\n\n new_name = body.get('name')\n new_age = body.get('age') # get the age and the name as will as the gender \n new_gender = body.get('gender')\n\n if (new_name is None) or (new_age is None) or (new_gender is None):\n abort(422)\n\n try:\n if new_name is not None:\n actor.name = new_name\n if new_age is not None:\n actor.age = new_age # if the data i exist => I will add it to thhe database\n if new_gender is not None:\n actor.gender = new_gender\n\n actor.update()\n except:\n rollback() #d if there is something wrong I want to rollback I set this func in the models.py \n abort(422)\n\n return jsonify({\n \"success\": True,\n \"patched_actor\": actor.format()\n }), 200\n\n @app.route('/actors/', methods=['DELETE'])\n @requires_auth('delete:actors')\n def delete_actors(payload, actor_id):\n actor = Actor.query.get(actor_id) # get the actor by id \n if actor is None:\n abort(404)\n\n try:\n actor.delete() # if there is nothing wrong I will delete it \n except Exception:\n rollback() # but if there is an error I want to rollback and raise 500 error\n abort(500)\n\n return jsonify({\n \"success\": True,\n \"deleted_actor\": actor.format()\n }), 200\n\n\n# here I will setup the movie (get , patch , post and delete) requests\n\n\n\n @app.route('/movies', methods=['GET']) # get the movie \n @requires_auth('get:movies')\n def get_movies(payload):\n movies = Movie.query.all()\n\n return jsonify({\n \"success\": True,\n \"movies\": [movie.format() for movie in movies]\n })\n\n @app.route('/movies/', methods=['GET'])\n @requires_auth('get:movies')\n def get_movie(payload, movie_id):\n movie = Movie.query.get(movie_id) # get the movie by id \n if movie is None:\n abort(404) # if the movie does not exist I want to raise 404 error \n return jsonify({\n \"success\": True,\n \"movie\": [movie.format()]\n })\n\n @app.route('/movies', methods=['POST']) # create movie \n @requires_auth('post:movies')\n def post_movies(payload):\n # Fetch request body\n body = request.get_json()\n\n title = body.get('title')\n release_date = body.get('release_date')\n\n if title is None or release_date is None:\n abort(400)\n\n try:\n new_movie = Movie()\n new_movie.title = title\n new_movie.release_date = release_date\n\n new_movie.insert()\n except Exception as e:\n print(e)\n\n return (jsonify({'success': True,\n 'created_movie': new_movie.format()}), 201)\n\n @app.route('/movies/', methods=['PATCH'])\n @requires_auth('patch:moviess')\n def edit_movies(payload, id):\n\n movie = Movie.query.get(id)\n\n if movie is None:\n abort(404)\n\n body = request.get_json()\n\n title = body.get(\"title\")\n release_date = body.get(\"release_date\")\n\n if (title is None) or (release_date is None):\n abort(422)\n\n try:\n if title is not None:\n movie.title = title\n if release_date is not None:\n movie.relaese_date = release_date\n movie.update()\n\n except Exception:\n abort(422)\n\n\n return jsonify({\n \"success\": True,\n \"patched_movie\": movie.format()\n }), 201\n\n @app.route('/movies/', methods=['DELETE', \"GET\"])\n @requires_auth('delete:movie')\n def delete_movie(payload, movie_id):\n try:\n movie = Movie.query.filter(\n Movie.id == movie_id).one_or_none()\n\n if movie is None:\n abort(404)\n\n movie.delete()\n\n return jsonify({\n 'success': True,\n 'deleted_movie': movie.format()\n }), 200\n except:\n rollback()\n abort(422)\n\n\n\n# handle error =====================================================================\n\n\n @app.errorhandler(400)\n def bad_request(error):\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": 'Bad request'\n }), 400\n\n @app.errorhandler(401)\n def unauthorized(error):\n return jsonify({\n \"success\":False,\n \"error\": 401,\n \"message\": \"Unauthorized\"\n }), 401\n\n @app.errorhandler(403)\n def forbidden(error):\n return jsonify({\n \"success\": False,\n \"error\": 403,\n \"message\": \"Forbidden\"\n }), 403\n\n\n @app.errorhandler(404)\n def resource_not_found_error(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"not found\"\n }), 404\n\n @app.errorhandler(422)\n def unprocessable(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": 'unprocessable'\n }), 422\n\n\n @app.errorhandler(500)\n def internal_server_error(error):\n return jsonify({\n \"success\": False,\n \"error\": 500,\n \"message\": \"Internal server error\"\n }), 500\n\n @app.errorhandler(AuthError)\n def error(error):\n return jsonify({\n \"success\": False,\n \"error\": error.status_code,\n \"message\": error.error\n }), error.status_code\n\n return app\n\n\nAPP = create_app()\n\nif __name__ == '__main__':\n APP.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"446884459","text":"from flask import Flask, render_template, g, url_for\n\nclass Item:\n def __init__(self, id, content, content2, completed, planned_date, due_date):\n self.id = id\n self.content = content #assignment title, too lazy to refactor\n self.content2 = content2 #assignment description\n self.completed = completed\n self.planned_date = planned_date\n self.due_date = due_date\n self.due_date_str = date_to_string(due_date)\n # self.img_src = url_for('static', filename='images/check-filled.png') if self.completed else url_for('static', filename='images/check-unfilled.png')\n def compare_to(self, other):\n if(self.id == other.id):\n return True\n else:\n return False\n\nclass ItemCollection:\n def __init__(self, date, items):\n self.date = date\n self.date_str = date_to_string(self.date)\n self.items = items\n # self.img_plus_url = url_for('static', filename='images/plus.png')\n def add_item(self, item):\n self.items.append(item)\n def render(self):\n # g.date = self.date_to_string(self.date)\n # content_html = \"\"\n # for item in self.items: content_html += item.render()\n # g.content = content_html\n # g.img_plus_url = url_for('static', filename='images/plus.png')\n # return render_template('list.html')\n print(\"Deprecated function\")\n\ndef date_to_string(dt):\n return dt.strftime('%A') + \", \" + dt.strftime('%b') + \". \" + str(dt.day)\n\ndef sort_items(item_list):\n item_list.sort(key=get_planned_date)\n print(item_list)\n ics = [ ]\n ics.append(ItemCollection(item_list[0].planned_date, []))\n for item in item_list:\n if item.planned_date != ics[-1].date:\n print(date_to_string(item.planned_date) + \"!=\" + date_to_string(ics[-1].date))\n ics.append(ItemCollection(item.planned_date, [item]))\n else:\n ics[-1].add_item(item)\n return ics\n\n\ndef get_planned_date(i):\n return i.planned_date","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"469625747","text":"# encoding='utf-8'\n\n'''\n author:zhangyu\n description: 按照要求反转一个字符串\n date:2019.8.19\n'''\nimport re\n\n\ndef get_reverse_string(s, k):\n '''\n 字符串反转\n Args:\n arr: 字符串\n Returns:\n 反转后字符串\n\n '''\n list = []\n sb = ''\n number = len(s) // k\n for i in range(number):\n list.append(s[i * k:i * k + k])\n if number * k < len(s):\n list.append(s[number * k:len(s)])\n for i in range(len(list)):\n if i % 2 == 0:\n sb += list[i][::-1]\n else:\n sb += list[i]\n return sb\n\n\ndef get_reverse_string2(s, k):\n '''\n 字符串反转\n Args:\n arr: 字符串\n Returns:\n 反转后字符串\n\n '''\n # 当s字符串长度小于k的值\n if len(s) <= k:\n return s[::-1]\n # 当字符串长度在k和2k之间\n if len(s) > k and len(s) <= 2 * k:\n temp_str = s[0: k]\n return temp_str[::-1] + s[k:len(s)]\n # 当字符串长度大于2*k\n if len(s) > 2 * k:\n list = []\n sb = ''\n number = len(s) // k\n for i in range(number):\n list.append(s[i * k:i * k + k])\n if number * k < len(s):\n list.append(s[number * k:len(s)])\n for i in range(len(list)):\n if i % 2 == 0:\n sb += list[i][::-1]\n else:\n sb += list[i]\n return sb\n return '-1'\n\n\n# 截取固定长度的字符串\ndef cut_text(text, lenth):\n textArr = re.findall('.{' + str(lenth) + '}', text)\n textArr.append(text[(len(textArr) * lenth):])\n return textArr\n\n\ndef get_reverse_str(arr):\n '''\n 字符串反转\n Args:\n arr: 字符串\n Returns:\n 反转后字符串\n\n '''\n s = ''\n for i in range(len(arr)):\n if i % 2 == 0:\n s += arr[i][::-1]\n else:\n s += arr[i]\n return s\n\n\nif __name__ == '__main__':\n s = 'abc'\n revese_s = get_reverse_string(s, 2)\n print(revese_s)\n","sub_path":"src/python/string/reverse_string2_541.py","file_name":"reverse_string2_541.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"135018101","text":"import os\nimport uvloop\nimport asyncio\nimport aiodns\nimport aiohttp\nfrom aiohttp import web\nfrom kubernetes_asyncio import client, config\nimport logging\n\nuvloop.install()\n\ndef make_logger():\n fmt = logging.Formatter(\n # NB: no space after levename because WARNING is so long\n '%(levelname)s\\t| %(asctime)s \\t| %(filename)s \\t| %(funcName)s:%(lineno)d | '\n '%(message)s')\n\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.INFO)\n stream_handler.setFormatter(fmt)\n\n log = logging.getLogger('router-resolver')\n log.setLevel(logging.INFO)\n\n logging.basicConfig(handlers=[stream_handler], level=logging.INFO)\n\n return log\n\nlog = make_logger()\n\napp = web.Application()\nroutes = web.RouteTableDef()\n\n@routes.get('/')\nasync def auth(request):\n app = request.app\n k8s_client = app['k8s_client']\n host = request.headers['Host']\n if not host.endswith('.internal.hail.is'):\n # would prefer 404, but that's not handled by nginx request_auth\n return web.Response(status=403)\n labels = host.split('.')\n namespace = labels[-4]\n try:\n router = await k8s_client.read_namespaced_service('router', namespace)\n except client.rest.ApiException as err:\n if err.status == 404:\n return web.Response(status=403)\n raise\n return web.Response(status=200, headers={'X-Router-IP': router.spec.cluster_ip})\n\napp.add_routes(routes)\n\nasync def on_startup(app):\n if 'BATCH_USE_KUBE_CONFIG' in os.environ:\n await config.load_kube_config()\n else:\n config.load_incluster_config()\n app['k8s_client'] = client.CoreV1Api()\n\napp.on_startup.append(on_startup)\n\nweb.run_app(app, host='0.0.0.0', port=5000)\n","sub_path":"router-resolver/router-resolver/router-resolver.py","file_name":"router-resolver.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"459956607","text":"\"\"\"This script runs all other scripts required for calculating a ranking\n\n@author: St. Elmo Wilken, Simon Streicher\n\n\"\"\"\n\nfrom ranking.controlranking import LoopRanking\nfrom ranking.formatmatrices import FormatMatrix\n\nimport json\n\nfilesloc = json.load(open('config.json'))\n\ndatamatrix = FormatMatrix(filesloc['connections'], filesloc['data'], 0)\ncontrolmatrix = LoopRanking(datamatrix.scaledforwardgain,\n datamatrix.scaledforwardvariablelist,\n datamatrix.scaledforwardconnection,\n datamatrix.scaledbackwardgain,\n datamatrix.scaledbackwardvariablelist,\n datamatrix.scaledbackwardconnection,\n datamatrix.nodummyvariablelist)\n\n#controlmatrix.display_control_importances([], datamatrix.nodummyconnection)\n#controlmatrix.show_all()\n#controlmatrix.exportogml()","sub_path":"looptest.py","file_name":"looptest.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"299075246","text":"# @author: Ryan West (ryan.west@sovrin.org)\n\n# This script requires 4 parameters as follows:\n# pool_name - The name of the pool you created to attach to the\n# Sovrin Network (pool must already exist)\n# wallet_name - The name of the wallet containing the DID used to\n# send ledger requests (wallet must already exist)\n# wallet_key - The secret key of \n# signing_did - The DID with sufficient rights to run\n# get-validator-info (must already be in the wallet )\n\nimport sys\nsys.path.insert(0, '../local_ledger/') # nopep8 # noqa\nimport ledger_query as lq\nfrom local_ledger import LocalLedger\nimport asyncio\nimport argparse\nimport time\nfrom datetime import datetime\nimport urllib.request\n\nnymTxn = '1'\nattribTxn = '100'\nschemaTxn = '101'\ncredDefTxn = '102'\n\n\n# Handles and parses all arguments, returning them\ndef parseArgs():\n helpTxt = 'You may optionally place each argument, line by line, in a\\\n file, then read arguments from that file as so: \\\n \"python3 file.py @argumentFile.txt\"'\n # ch.eck arguments\n parser = argparse.ArgumentParser(fromfile_prefix_chars='@', epilog=helpTxt)\n parser.add_argument(\"pool_name\", help=\"the pool you want to connect to.\")\n parser.add_argument(\"wallet_name\", help=\"wallet name to be used\")\n parser.add_argument(\"wallet_key\", help=\"wallet key for opening the wallet\")\n parser.add_argument(\n \"signing_did\", help=\"did used to sign requests sent to the ledger\")\n parser.add_argument(\n \"start_date\", help=\"mm-dd-yyyy time to start looking at txns\")\n parser.add_argument(\n \"end_date\", help=\"mm-dd-yyyy time to stop looking at txns, inclusive\")\n parser.add_argument(\n \"database_dir\", help=\"optional field to indicate which database dir\",\n default=\"ledger_copy.db\", nargs='?')\n return parser.parse_args()\n\n\n# Converts a POSIX timestamp into a yyyy/mm/dd date\ndef getTimestampStr(date):\n return str(datetime.utcfromtimestamp(date).strftime('%Y-%m-%d'))\n\n\n# Converts a string into a POSIX timestamp\ndef getTimestamp(dateStr):\n try:\n return time.mktime(datetime.strptime(dateStr, \"%m-%d-%Y\").timetuple())\n except ValueError:\n try:\n return time.mktime(\n datetime.strptime(dateStr, \"%m/%d/%Y\").timetuple())\n except ValueError:\n return time.mktime(\n datetime.strptime(dateStr, \"%Y-%m-%d\").timetuple())\n\n\n# Connects to the specified ledger and updates it until the latest txn\n# has been downloaded\nasync def loadTxnsLocally(args, startTimestamp, endTimestamp):\n with LocalLedger(args.database_dir, args.pool_name, args.wallet_name,\n args.wallet_key, args.signing_did) as ll:\n # first updates the local ledger database\n await ll.connect()\n await ll.update()\n await ll.disconnect()\n \n return lq.getTxnRange(ll, startTime=startTimestamp, endTime=endTimestamp)\n\n\n# TODO: fix so this works when using fees that update over time\n# Gets all txns within the specified period (using startTimeStamp and\n# stopTimeStamp), then totals the fees for each txn type and prints them\ndef printFeesInPeriod(txns, txnsByType, fees, startTimestamp, endTimestamp):\n try:\n totalNymCost = fees['1'] * len(txnsByType[nymTxn])\n except Exception:\n totalNymCost = 0\n try:\n totalAttribCost = fees['100'] * len(txnsByType[attribTxn])\n except Exception:\n totalAttribCost = 0\n try:\n totalSchemaCost = fees['101'] * len(txnsByType[schemaTxn])\n except Exception:\n totalSchemaCost = 0\n try:\n totalCDCost = fees['102'] * len(txnsByType[credDefTxn])\n except Exception:\n totalCDCost = 0\n totalCost = totalNymCost + totalAttribCost + totalSchemaCost + totalCDCost\n\n startTimeStr = str(datetime.utcfromtimestamp(\n startTimestamp).strftime('%m-%d-%Y %H:%M:%S'))\n endTimeStr = str(datetime.utcfromtimestamp(\n endTimestamp).strftime('%m-%d-%Y %H:%M:%S'))\n\n # only list amounts if they are > 0\n print('Period: ' + startTimeStr + ' to ' + endTimeStr)\n print('Number of transactions in range:', len(txns),\n '\\tTotal fees to be collected:', totalCost)\n if nymTxn in txnsByType:\n print('\\tNym txns:', str(\n len(txnsByType[nymTxn])),\n '\\t\\t\\tTotal fees to be collected:', str(totalNymCost))\n if attribTxn in txnsByType:\n print('\\tAttribute txns:', str(len(\n txnsByType[attribTxn])),\n '\\t\\tTotal fees to be collected:', str(totalAttribCost))\n if schemaTxn in txnsByType:\n print('\\tSchema txns:', str(len(\n txnsByType[schemaTxn])),\n '\\t\\tTotal fees to be collected:', str(totalSchemaCost))\n if credDefTxn in txnsByType:\n print('\\tCredential def txns:', str(len(\n txnsByType[credDefTxn])),\n '\\tTotal fees to be collected:', str(totalCDCost))\n\n\n# Gets all the txns in the time period starting with startTimestamp and\n# ending with endTimestamp, calculates how much every DID owner owes\n# from that period (based on type and number of txns written), and prints this\n# info to a csv file.\ndef outputBillsFile(startTimestamp, endTimestamp, bills):\n startTimeStr = getTimestampStr(startTimestamp)\n endTimeStr = getTimestampStr(endTimestamp)\n\n filename = 'billing ' + startTimeStr + ' to ' + endTimeStr + '.csv'\n with open(filename, 'w') as f:\n for key, value in sorted(bills.items()):\n f.write(str(key) + ',' + \",\".join(str(x) for x in value) + '\\n')\n\n print('Billing by did written to \\'' + filename + '\\'.')\n\n\n# Looks at the Sovrin fiat fees spreadsheet (in csv format) and converts it\n# into a dict to use when calculating fees over time (where the fees may have\n# changed in the middle of a billing period)\ndef getFiatFees(csvFile='fiatFees.csv'):\n\n feesURL = 'https://docs.google.com/spreadsheets/d/1RFhQ4cOid7h_GoKZKNXudDSlFoyhbyq5U4gsqW4gthE/export?format=csv' # noqa\n\n # downloads the fees.csv file from Google Sheets\n urllib.request.urlretrieve(feesURL, 'fiatFees.csv')\n # opens the file just downloaded (unless another is chosen) to read from\n with open(csvFile, 'r') as file:\n lines = file.readlines()\n\n if len(lines) == 0:\n raise Exception('No fee information found')\n\n # remove header column, if it exists\n if lines[0].startswith('Date'):\n lines.pop(0)\n\n feesByTimePeriod = {}\n\n for line in lines:\n data = line.split(',')\n if len(data) != 8:\n raise Exception('Wrong format for fees csv file')\n\n timestamp = getTimestamp(data[0])\n nymFee = float(data[2])\n attribFee = float(data[3])\n schemaFee = float(data[4])\n credDefFee = float(data[5])\n # Revocation registry is disabled on mainnet for now; ignore these\n # revocRegFee = float(data[6])\n # revogRegUpdateFee = float(data[7])\n\n feesByTimePeriod[timestamp] = {\n nymTxn: nymFee,\n attribTxn: attribFee,\n schemaTxn: schemaFee,\n credDefTxn: credDefFee\n # more will be added when revocation is supported\n }\n\n return feesByTimePeriod\n\n\n# Calculates the bill amount for each did in the time period, checking for\n# fee updates based on the Sovrin fees spreadsheet on Google Sheets\n# TODO: add way to check if txn was token-based or fiat-based\ndef calculateBills(feesByTimePeriod, txns):\n # dict of all DIDs who owe money for the current period\n # in the form key: did, val: list of amounts owed in the following order:\n # [total, nym, attrib, schema, cred_def, revog_reg, revoc_reg update]\n bills = {}\n def _getFeeForTxn(txn, feesByTimePeriod):\n # [total, nym, attrib, schema, cred_def, revoc_reg, revoc_reg update]\n billList = [0, 0, 0, 0, 0, 0, 0]\n\n lastTimestamp = 0\n txnTimestamp = txn.getTime()\n # if there is no timestamp, then it is most likely a genesis txn so\n # do not charge anything\n if txnTimestamp is None:\n return billList\n for timestamp, fees in sorted(feesByTimePeriod.items()):\n if txnTimestamp < timestamp:\n break\n lastTimestamp = timestamp\n\n if lastTimestamp == 0:\n raise Exception('No fees found for transaction timestamp')\n billList[0] = feesByTimePeriod[lastTimestamp][txn.getType()]\n if txn.getType() == nymTxn:\n billList[1] = billList[0]\n elif txn.getType() == attribTxn:\n billList[2] = billList[0]\n elif txn.getType() == schemaTxn:\n billList[3] = billList[0]\n elif txn.getType() == credDefTxn:\n billList[4] = billList[0]\n # TODO: add support for revoc_reg when these are finalized in code\n return billList\n\n for t in txns.values():\n # populate bills dict\n if t.getSenderDid() not in bills:\n bills[t.getSenderDid()] = _getFeeForTxn(t, feesByTimePeriod)\n else:\n bills[t.getSenderDid()] = list(map(lambda x, y: x + y,\n bills[t.getSenderDid()], _getFeeForTxn(t, feesByTimePeriod)))\n\n # If authorless genesis txns are in the range, we don't include these\n bills.pop(None, None)\n\n return bills\n\n\nasync def run(args):\n\n try:\n # convert input args to timestamps\n startTimestamp = getTimestamp(args.start_date)\n endTimestamp = getTimestamp(args.end_date)\n except ValueError:\n raise ValueError('Bad date info')\n\n if startTimestamp > endTimestamp:\n raise ValueError('Start timestamp must be before end timestamp')\n return\n\n # all transactions in the specified range\n txns = await loadTxnsLocally(args, startTimestamp, endTimestamp)\n\n # the commented code below provides additional ledger statistics and can\n # be uncommented if desired\n\n # transactions separated by type in the format key: type, val: list(txns)\n # txnsByType = {}\n #for t in txns.values():\n # # populate txnsByType dict\n # if t.getType() not in txnsByType:\n # txnsByType[t.getType()] = [t]\n # else:\n # txnsByType[t.getType()].append(t)\n\n # retrive fiat fees\n feesByTimePeriod = getFiatFees()\n\n # printFeesInPeriod(txns, txnsByType, feesByTimePeriod,\n # startTimestamp, endTimestamp)\n\n bills = calculateBills(feesByTimePeriod, txns)\n outputBillsFile(startTimestamp, endTimestamp, bills)\n\n # Prints all schema keys\n # for t in txnsByType['101']:\n # print('\\n\\n')\n # t.printKeys()\n\n\nif __name__ == '__main__':\n args = parseArgs()\n try:\n loop = asyncio.get_event_loop()\n loop.run_until_complete(run(args))\n except KeyboardInterrupt:\n pass\n except RuntimeError:\n run(args)\n","sub_path":"fiat_reconciliation/fiatReconciler.py","file_name":"fiatReconciler.py","file_ext":"py","file_size_in_byte":10854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"625297769","text":"\"\"\"\nA unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:\n\n1/2\t= \t0.5\n1/3\t= \t0.(3)\n1/4\t= \t0.25\n1/5\t= \t0.2\n1/6\t= \t0.1(6)\n1/7\t= \t0.(142857)\n1/8\t= \t0.125\n1/9\t= \t0.(1)\n1/10\t= \t0.1\nWhere 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.\n\nFind the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.\n\"\"\"\nfrom decimal import *\n \ndef find_fraction(i):\n getcontext().prec = 1500\n x = Decimal(1) / Decimal(i)\n return x\n \ndef find_period(numb):\n L = (str(numb))\n length = len(L)\n l1, l2, l3 = 0, 0, 0\n if L[2:3] != '0':\n index = L[2:6]\n l1 = 1\n elif L[2:3] == '0' and L[3:4] != '0':\n index = L[3:7]\n l2 = 1\n elif L[2:3] == '0' and L[3:4] == '0':\n index = L[4:8]\n l3 = 1\n max_period = 0\n for v in range(3, length):\n if l1 == 1:\n indexi = L[v:(v + 4)]\n elif l2 == 1:\n indexi = L[(v + 1):(v + 5)]\n elif l3 == 1:\n indexi = L[(v + 2):(v + 6)]\n if index == indexi:\n max_period = v\n break\n return max_period\n\nplace_holder = 0\nfor i in range(1, 1000):\n x = find_fraction(i)\n y = find_period(x)\n if y > place_holder:\n place_holder = y\n result = i\n\nprint(result)\n","sub_path":"answer26.py","file_name":"answer26.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"474738599","text":"# coding=gbk\nimport math\nfrom collections import Counter\nimport matplotlib.pyplot as plt\n\ndef distance(one, other):\n dis = 0\n for k1, k2 in zip(one, other):\n dis += (k1 - k2)**2\n return math.sqrt(dis)\n\n\ndef knn(one, sources, k):\n distances = []\n for source in sources:\n distances.append({\"distance\":distance(one, source[\"vector\"]), \"lable\":source[\"lable\"]})\n distances.sort(key = lambda x:x[\"distance\"])\n res = distances[:k]\n return Counter([distance[\"lable\"] for distance in res]).most_common(1)[0][0]\n\ndef scatter_dots(dots, seconds = 10, xlabel=\"X\", ylabel = \"Y\"):\n fig, axe = plt.subplots(1, 1)\n x = np.array([dot[0] for dot in dots])\n y = np.array([dot[1] for dot in dots])\n axe.scatter(x, y )\n axe.set_title(\"knn matplotlib test\")\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n axe.legend()\n fig.show()\n time.sleep(seconds)\n","sub_path":"language/python/matplot_ml/ml/knn/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"116275390","text":"import time\nimport sys\nfrom psychopy import visual,event,core\n \n# Make the square appear for 1.5 secs, then show a blank screen for 1 sec, then flash the square 3 times for 30 ms each.\n\n\nwin = visual.Window([400,400],color=\"black\", units='pix') # make a window\nsquare = visual.Rect(win,lineColor=\"black\",fillColor=\"red\",size=[100,100]) # make a square!\nsquare.draw() # draw it on the buffer\nwin.flip() # show it!\ncore.wait(1.5) # let it show for 1.5 seconds\nwin.flip() # hide it\ncore.wait(1) # hide for 1 second\n\nfor num in range(3):\n\tsquare.draw() # redraw\n\twin.flip() # show\n\tcore.wait(.3) # flash #1\n\twin.flip() # hide\n\tcore.wait(.3) # hide for a little \n\n\nsys.exit()\n\n","sub_path":"exercise_1_2.py","file_name":"exercise_1_2.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"3244787","text":"import math\nfrom enum import Enum\nfrom typing import List\n\nimport numpy as np\n\nfrom Game import Game\nfrom algorithms.RobotAlgorithm import RobotAlgorithm\n\n\nclass RobotType(Enum):\n circle = 0\n rectangle = 1\n\n\nclass RobotConfig:\n \"\"\"\n everything is in millimeters\n robot has a transmission 36:12 == 3:1\n 160-170 rpm -> 2,75 rps\n wheel diameter is 56 mm\n with transmission we get max speed = 426 mm / s\n \"\"\"\n\n def __init__(self, robotType: RobotType):\n self.maxSpeed = 150.0 # 426.0 # [mm/s]\n self.minSpeed = -50.0 # -426.0 # [m/s]\n # TODO calculate max yaw rate\n self.maxYawRate = 60.0 * math.pi / 180.0 # [rad/s]\n # TODO calculate max acceleration\n self.maxAccel = 50.0 # 100.0 # [mm/ss]\n # TODO calculate max delta yaw rate\n self.maxDeltaYawRate = 60.0 * math.pi / 180.0 # [rad/ss]\n\n self.vResolution = 4.9 # 5.0 # [mm/s]\n self.yawRateResolution = 0.5 * math.pi / 180.0 # [rad/s]\n\n self.dt = 0.25 # 0.2 # [s] Time tick for motion prediction\n self.predictTime = 4.0 # 2.0 # [s]\n\n self.angleCostGain = 0.15 # alpha\n self.speedCostGain = 1.0 # beta\n self.obstacleCostGain = 1.0 # gama\n\n self.robotType = robotType\n\n # if robot_type == RobotType.circle\n # Also used to check if goal is reached in both types\n self.robotRadius = 125.0 # 300.0 # [mm] for collision check\n\n # if robot_type == RobotType.rectangle\n # TODO measure robot width and length\n self.robotWidth = 250 # [mm] for collision check\n self.robotLength = 300 # [mm] for collision check\n\n # @property\n # def robot_type(self):\n # return self._robot_type\n #\n # @robot_type.setter\n # def robot_type(self, value):\n # if not isinstance(value, RobotType):\n # raise TypeError(\"robot_type must be an instance of RobotType\")\n # self._robot_type = value\n\n\nclass DWA(RobotAlgorithm):\n\n def __init__(self, game: Game):\n super().__init__()\n self.game = game\n self.robotConfig = RobotConfig(RobotType.rectangle)\n\n def getControlPoints(self) -> np.array:\n return []\n\n def getMotion(self, currentTrajectoryPoint: np.array) -> np.array:\n\n # start\n # currentTrajectoryPoint: np.array = np.array([0.0, 0.0, math.pi / 8.0, 0.0, 0.0])\n\n # goal\n goal = np.array([2800.0, 1000.0])\n\n # obstacles\n obstacles = np.array([(hive.position[0], hive.position[1]) for hive in self.game.hives])\n\n v, y, predictedTrajectory = self.dwaControl(currentTrajectoryPoint, goal, obstacles)\n\n # simulate robot\n nextTrajectoryPoint = self.motion(currentTrajectoryPoint, v, y)\n\n # check reaching goal\n distToGoal = math.hypot(currentTrajectoryPoint[0] - goal[0], currentTrajectoryPoint[1] - goal[1])\n if distToGoal <= self.robotConfig.robotRadius:\n print(\"Goal!\")\n return np.array([-1, -1, -1, -1, -1])\n # store history\n # trajectory = np.vstack((trajectory, currentTrajectoryPoint))\n\n return nextTrajectoryPoint\n\n def dwaControl(self, trajectoryPoint: np.array, goal, obstacles: np.array) -> (\n float, float, np.vstack):\n\n # get the dynamic window for current position\n dynamicWindow = self.calcDynamicWindow(trajectoryPoint)\n\n # returns v, y, trajectory\n return self.calcControlAndTrajectory(trajectoryPoint, dynamicWindow, goal, obstacles)\n\n def motion(self, trajectoryPoint: np.array, speed, omega) -> np.array:\n \"\"\"\n\n :param trajectoryPoint: reference trajectory point\n :param speed: robot's speed\n :param omega: robot's rotational speed\n \"\"\"\n\n trajectoryPoint[2] += omega * self.robotConfig.dt\n trajectoryPoint[0] += speed * math.cos(trajectoryPoint[2]) * self.robotConfig.dt\n trajectoryPoint[1] += speed * math.sin(trajectoryPoint[2]) * self.robotConfig.dt\n trajectoryPoint[3] = speed\n trajectoryPoint[4] = omega\n\n return trajectoryPoint\n\n def calcDynamicWindow(self, trajectoryPoint: np.array) -> List:\n \"\"\"\n calculate dynamic window based on current state\n \"\"\"\n\n # Dynamic window from robot specification\n # [speed_min, speed_max, yaw_rate_min, yaw_rate_max]\n windowSpecification = [self.robotConfig.minSpeed, self.robotConfig.maxSpeed,\n -self.robotConfig.maxYawRate, self.robotConfig.maxYawRate]\n\n # Dynamic window from motion model\n # [speed_min, speed_max, yaw_rate_min, yaw_rate_max]\n windowModel = [\n trajectoryPoint[3] - self.robotConfig.maxAccel * self.robotConfig.dt,\n trajectoryPoint[3] + self.robotConfig.maxAccel * self.robotConfig.dt,\n trajectoryPoint[4] - self.robotConfig.maxDeltaYawRate * self.robotConfig.dt,\n trajectoryPoint[4] + self.robotConfig.maxDeltaYawRate * self.robotConfig.dt\n ]\n\n # return the best of both\n return [\n max(windowSpecification[0], windowModel[0]), min(windowSpecification[1], windowModel[1]),\n max(windowSpecification[2], windowModel[2]), min(windowSpecification[3], windowModel[3])\n ]\n\n def predictTrajectory(self, initTrajectoryPoint: np.array, v, y) -> np.vstack:\n\n temp = np.array(initTrajectoryPoint)\n trajectory = np.array(initTrajectoryPoint)\n time = 0\n\n while time <= self.robotConfig.predictTime:\n temp = self.motion(temp, v, y)\n trajectory = np.vstack((trajectory, temp))\n time += self.robotConfig.dt\n\n return trajectory\n\n def calcControlAndTrajectory(self, trajectoryPoint: np.array, dynamicWindow: List, goal: List,\n obstacles: np.array) -> (float, float, np.vstack):\n\n initTrajectoryPoint = trajectoryPoint[:]\n minCost = float(\"inf\")\n bestV = 0.0\n bestY = 0.0\n bestTrajectory = np.array([trajectoryPoint])\n\n # evaluate all trajectory with sampled input in dynamic window\n for v in np.arange(dynamicWindow[0], dynamicWindow[1], self.robotConfig.vResolution):\n for y in np.arange(dynamicWindow[2], dynamicWindow[3], self.robotConfig.yawRateResolution):\n\n # Get predicted trajectory with v and y speeds\n trajectory: np.vstack = self.predictTrajectory(initTrajectoryPoint, v, y)\n\n # Target heading - how good is the trajectory based on angle difference to goal\n angleCost = self.robotConfig.angleCostGain * self.calcAngleCost(trajectory, goal)\n\n # Velocity - how good is the trajectory based on the speed\n speedCost = self.robotConfig.speedCostGain * (self.robotConfig.maxSpeed - trajectory[-1, 3])\n\n # Clearance - how good is the trajectory based on the distance to obstacles\n obstacleCost = self.robotConfig.obstacleCostGain * self.calcObstacleCost(trajectory, obstacles)\n\n finalCost = angleCost + speedCost + obstacleCost\n\n # search minimum trajectory\n if minCost >= finalCost:\n minCost = finalCost\n bestV = v\n bestY = y\n bestTrajectory = trajectory\n\n return bestV, bestY, bestTrajectory\n\n def calcObstacleCost(self, trajectory: np.vstack, obstacles: np.array):\n \"\"\"\n calc obstacle cost inf: collision\n \"\"\"\n\n # all obstacles' xs\n obstacleX = obstacles[:, 0]\n\n # all obstacles' ys\n obstacleY = obstacles[:, 1]\n\n dx = trajectory[:, 0] - obstacleX[:, None]\n dy = trajectory[:, 1] - obstacleY[:, None]\n\n # calculate distances to all obstacles for each trajectory point\n r = np.hypot(dx, dy)\n\n if self.robotConfig.robotType == RobotType.rectangle:\n\n yaw = trajectory[:, 2]\n\n # TODO check what this does\n rot = np.array([[np.cos(yaw), -np.sin(yaw)], [np.sin(yaw), np.cos(yaw)]])\n rot = np.transpose(rot, [2, 0, 1])\n\n # TODO check what this does\n localObstacle = obstacles[:, None] - trajectory[:, 0:2]\n localObstacle = localObstacle.reshape(-1, localObstacle.shape[-1])\n localObstacle = np.array([localObstacle @ x for x in rot])\n localObstacle = localObstacle.reshape(-1, localObstacle.shape[-1])\n\n # Check if obstacle is too close\n upperCheck = localObstacle[:, 0] <= self.robotConfig.robotLength / 2\n rightCheck = localObstacle[:, 1] <= self.robotConfig.robotWidth / 2\n bottomCheck = localObstacle[:, 0] >= -self.robotConfig.robotLength / 2\n leftCheck = localObstacle[:, 1] >= -self.robotConfig.robotWidth / 2\n\n # If obstacle is too close return Inf\n if (np.logical_and(np.logical_and(upperCheck, rightCheck), np.logical_and(bottomCheck, leftCheck))).any():\n return float(\"Inf\")\n\n # Just check if any of the obstacles is in the radius\n elif self.robotConfig.robotType == RobotType.circle:\n if np.array(r <= self.robotConfig.robotRadius).any():\n return float(\"Inf\")\n\n # If obstacles are not in the way, take the trajectory that's farthest from obstacles\n minR = np.min(r)\n return 1.0 / minR\n\n @staticmethod\n def calcAngleCost(trajectory: np.vstack, goal):\n\n # trajectory is stack of TrajectoryPoints\n # get the top trajectory point and calc delta\n dx = goal[0] - trajectory[-1, 0]\n dy = goal[1] - trajectory[-1, 1]\n\n errorAngle = math.atan2(dy, dx)\n costAngle = errorAngle - trajectory[-1, 2]\n # the best if the robot moves directly towards the target\n cost = abs(math.atan2(math.sin(costAngle), math.cos(costAngle)))\n\n return cost\n","sub_path":"python/robotSimulator/algorithms/DWA.py","file_name":"DWA.py","file_ext":"py","file_size_in_byte":9967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"628714971","text":"#定义一个二叉路径类,包括当前节点、左节点和右节点\nclass PathSummation():\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n#定义一个函数,返回根节点最后的停值和不停值较大那个\ndef maxPathSum(root):\n print(max(helper(root)))\n\n#定义一个辅助函数,递归算出根节点停值和不停值\ndef helper(root):\n if root == None:\n return [0, 0]\n #得到左子节点的停值与不停值\n leftG, leftS = helper(root.left)\n #得到左子节点的停值与不停值\n rightG, rightS = helper(root.right)\n #不停值\n Go = max(root.value + leftG, root.value +rightG, root.value)\n #停值\n Stop = max(leftS, rightS, leftG, rightG, root.value+leftG+rightG)\n return Go, Stop\n\nnode1 = PathSummation(1)\nnode2 = PathSummation(2)\nnode3 = PathSummation(-2)\nnode4 = PathSummation(10)\nnode5 = PathSummation(12)\nnode6 = PathSummation(2)\nnode7 = PathSummation(1)\nnode1.left = node2\nnode1.right = node3\nnode2.left = node4\nnode2.right = node5\nnode3.left = node6\nnode3.right = node7\nmaxPathSum(node1)\n","sub_path":"static/Mac/play/调用/二分树/最大路径.py","file_name":"最大路径.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"630085095","text":"import pandas as pd \nimport numpy as np\nimport random\n\ndef shuffle(x, y):\n list1 = []\n list2 = []\n indicies = list(range(len(x)))\n random.shuffle(indicies)\n for e in indicies:\n list1.append(x[e])\n list2.append(y[e])\n\n return list1, list2\n\ndef main(split, shuff = True):\n\tdf = pd.read_csv('voice.csv')\n\n\tx = np.array(df.drop('label', 1)).tolist()\n\t \n\ty = np.array(df['label']).tolist()\n\n\tlabels = []\n\n\tfor e in y:\n\t\tif e == 'male':\n\t\t\tlabels.append([0, 1])\n\t\telif e == 'female':\n\t\t\tlabels.append([1, 0])\n\n\ty = labels\n\n\tsplit = int(len(x) * split)\n\n\tif shuff == True:\n\t\tx, y = shuffle(x, y)\n\n\ttrain_x = x[:-split]\n\ttrain_y = y[:-split]\n\ttest_x = x[-split:]\n\ttest_y = y[-split:]\n\n\treturn train_x, train_y, test_x, test_y\n\n\n\n\n","sub_path":"Project 2/Data/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"188716972","text":"import gobject\nimport pygtk\nimport gtk\nimport pango\n\nclass WrapLabel(gtk.Label):\n __gtype_name__ = 'WrapLabel'\n def __init__(self, text = ''):\n gtk.Label.__init__(self)\n self.m_wrap_width = 0\n\n self.get_layout().set_wrap(pango.WRAP_WORD_CHAR)\n self.set_alignment(0.0, 0.0)\n self.set_markup(text)\n self.connect('size-request', self.on_size_request)\n self.connect('size-allocate', self.on_size_allocate)\n\n def set_text(self, text):\n gtk.Label.set_text(self, text)\n self.set_wrap_width(self.m_wrap_width)\n\n def set_markup(self, text):\n gtk.Label.set_markup(self, text)\n self.set_wrap_width(self.m_wrap_width)\n\n def on_size_request(self, widget, requisition):\n width, height = self.get_layout().get_pixel_size()\n requisition.width = 0\n requisition.height = height\n\n def on_size_allocate(self, widget, allocation):\n gtk.Label.size_allocate(self, allocation)\n self.set_wrap_width(allocation.width)\n\n def set_wrap_width(self, width):\n if width == 0:\n return\n\n self.get_layout().set_width(width * pango.SCALE)\n if self.m_wrap_width != width:\n self.m_wrap_width = width\n self.queue_resize()\n\ngobject.type_register(WrapLabel)\n \nif __name__ == '__main__':\n w = gtk.Window(gtk.WINDOW_TOPLEVEL)\n l = WrapLabel(\"This is a very long label that should span many lines. \"\n \"It's a good example of what the WrapLabel can do, and \"\n \"includes formatting, like bold, italic, \"\n \"and underline. The window can be wrapped to any \"\n \"width, unlike the standard Gtk::Label, which is set to \"\n \"a certain wrap width.\")\n w.add(l)\n w.show_all()\n gtk.main()\n","sub_path":"apps/usb-creator/tags/usb-creator-0.1.16guada1/usbcreator/wrap_label.py","file_name":"wrap_label.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"575371308","text":"class Node:\n def __init__(self, value, left, right):\n self.value = value\n self.left = left\n self.right = right\n\nclass BTree:\n def __init__(self):\n self.root = None\n self.nodes = []\n self.visited = []\n\n def getRoot(self):\n return self.root\n\n def add(self, value):\n if self.root == None:\n self.root = Node(value, None, None)\n self.nodes.append(self.root)\n else:\n self._add(self.root, value)\n\n def _add(self, node, value):\n if value < node.value:\n if node.left == None:\n node.left = Node(value, None, None)\n self.nodes.append(node.left)\n else:\n self._add(node.left, value)\n if value > node.value:\n if node.right == None:\n node.right = Node(value, None, None)\n self.nodes.append(node.right)\n else:\n self._add(node.right, value)\n\n def contains(self, node, data):\n if node == None:\n return False\n elif node.value == data:\n return True\n else:\n if data < node.value:\n return self.contains(node.left, data)\n else:\n return self.contains(node.right, data)\n\n def inorder(self, node):\n if node != None:\n self.inorder(node.left)\n print(node.value, end=\" \")\n self.inorder(node.right)\n\n def inorder2(self, node, total):\n if node != None:\n total = self.inorder2(node.left, total)\n total += node.value\n print(node.value, end=\" \")\n total = self.inorder2(node.right, total)\n return total\n\n def preorder(self, node):\n if node != None:\n print(node.value, end=\" \")\n self.preorder(node.left)\n self.preorder(node.right)\n\n def postorder(self, node):\n if node != None:\n self.postorder(node.left)\n self.postorder(node.right)\n print(node.value, end=\" \")\n\n def findLongestRoute(self):\n for node in self.nodes:\n print(self.inorder2(node, 0))\n\n #def remove(self, node):\n\n\ntree2 = Node(1, Node(12, Node(5, None, None), Node(6, None, None)), Node(9, None, None))\ntree1 = BTree()\n\ntree1.add(1)\ntree1.add(12)\ntree1.add(5)\ntree1.add(6)\ntree1.add(9)\n\ntree1.inorder(tree1.getRoot())\nprint(\"\\n\")\ntree1.preorder(tree1.getRoot())\nprint(\"\\n\")\ntree1.postorder(tree1.getRoot())\nprint(\"\\n\")\n#print(tree1.find(5))\n#print(tree1.find(22))\nprint(tree1.contains(tree1.getRoot(), 5))\nprint(tree1.contains(tree1.getRoot(), 22))\n\nprint(tree1.findLongestRoute())\n","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"431792450","text":"import pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpathes\nfrom matplotlib.ticker import MultipleLocator\nimport itertools\n\n\ndata = pickle.load(open(\"/home/yangbang/VideoCaptioning/MSRVTT/info_corpus_2.pkl\", 'rb'))\n#split = data['info']['split']['train']\nsplit = [i for i in range(10000)]\ncaps = data['captions']\n\n\nvocab_size = 10546\ntarget_length = 7\nrec = [[] for _ in range(target_length)]\ncount = 0\n\nfor i in split:\n vid = 'video%d'%i\n cap = caps[vid]\n for item in cap:\n c = item[1:-1]\n if len(c) == target_length:\n count += 1\n for j in range(target_length):\n rec[j].append(c[j])\n\nres = []\nfor i in range(target_length):\n tmp = list(set(rec[i]))\n res.append(len(tmp) / vocab_size)\n\nprint(res)\nprint(count)\n\n\n","sub_path":"analyze_codes/plot_msrvtt_7.py","file_name":"plot_msrvtt_7.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"444213296","text":"# import necessary packages\r\nimport cvlib as cv\r\nimport cv2\r\nimport numpy as np\r\nfrom tensorflow.keras.models import load_model\r\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\r\nfrom tensorflow.keras.preprocessing.image import img_to_array\r\nfrom PIL import ImageFont, ImageDraw, Image\r\n \r\n \r\nmodel = load_model('model.h5')\r\nmodel.summary()\r\n \r\n# open webcam\r\nwebcam = cv2.VideoCapture(0)\r\n \r\n \r\nif not webcam.isOpened():\r\n print(\"Could not open webcam\")\r\n exit()\r\n \r\n \r\n# loop through frames\r\nwhile webcam.isOpened():\r\n \r\n # read frame from webcam \r\n status, frame = webcam.read()\r\n \r\n if not status:\r\n print(\"Could not read frame\")\r\n exit()\r\n \r\n # apply face detection\r\n face, confidence = cv.detect_face(frame)\r\n \r\n # loop through detected faces\r\n for idx, f in enumerate(face):\r\n \r\n (startX, startY) = f[0], f[1]\r\n (endX, endY) = f[2], f[3]\r\n \r\n if 0 <= startX <= frame.shape[1] and 0 <= endX <= frame.shape[1] and 0 <= startY <= frame.shape[0] and 0 <= endY <= frame.shape[0]:\r\n \r\n face_region = frame[startY:endY, startX:endX]\r\n \r\n face_region1 = cv2.resize(face_region, (224, 224), interpolation = cv2.INTER_AREA)\r\n \r\n x = img_to_array(face_region1)\r\n x = np.expand_dims(x, axis=0)\r\n x = preprocess_input(x)\r\n \r\n prediction = model.predict(x)\r\n \r\n if prediction < 0.5: # 마스크 착용으로 판별되면, \r\n cv2.rectangle(frame, (startX,startY), (endX,endY), (0,0,255), 2)\r\n Y = startY - 10 if startY - 10 > 10 else startY + 10\r\n text = \"No Mask ({:.2f}%)\".format((1 - prediction[0][0])*100)\r\n cv2.putText(frame, text, (startX,Y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)\r\n \r\n else: # 마스크 착용으로 판별되면\r\n cv2.rectangle(frame, (startX,startY), (endX,endY), (0,255,0), 2)\r\n Y = startY - 10 if startY - 10 > 10 else startY + 10\r\n text = \"Mask ({:.2f}%)\".format(prediction[0][0]*100)\r\n cv2.putText(frame, text, (startX,Y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,255,0), 2)\r\n \r\n # display output\r\n cv2.imshow(\"mask nomask classify\", frame)\r\n \r\n # press \"Q\" to stop\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n \r\n# release resources\r\nwebcam.release()\r\ncv2.destroyAllWindows() ","sub_path":"test10.py","file_name":"test10.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"624221310","text":"import logging\n\n\n\"\"\"\nLogFile\n\nControls intialization of the \"root\" logger to a file including formatting.\nOther modules will be able to use the following to get a reference to the logger.\n\n\"\"\"\nclass LogFile ():\n\n def __init__(self):\n\n formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n fileHandler = logging.FileHandler('wrx-console.log')\n fileHanlder.setLevel(logging.DEBUG)\n fileHanlder.setFormatter(formatter)\n logger = logging.getLogger(\"root\")\n logger.setLevel(logging.DEBUG)\n logger.addHandler(handler)\n logger.addHanlder(fileHandler)\n return logger\n\n def getLogFile(self):\n return logging.getLogger(\"root\")","sub_path":"Util/LogFile.py","file_name":"LogFile.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"478578404","text":"#definiendo una funcion llamada linedesign \ndef linedesign():\n print(\"#\"*60)\n return \"satisfactorio\"\n\n#entrada : son unas variables que se utilizan en las funciones para realizar procesos\n#salida : es lo que devolvemos al ejecutar una funcion \n\ndef suma(a,b):\n resultado = a+b\n return resultado\n\n#entrada la codigo \n\ndevuelve = linedesign()\nprint(devuelve)\n\n\nresultado = suma(2,4)\nprint(resultado)\n\n\n\n#listas\nclass TortaRedonda():\n def __init__(self,sabor,altura,temperatura,area) :\n self.forma = \"redondas\"\n self.sabor = sabor\n self.altura = altura\n self.temperatura = temperatura\n self.area = area\n\nclass Cocinero():\n def __init__(self,nombre):\n self.nombre = nombre\n def dividir_torta(self,personas,area):\n print(\"voy a dividir la torta\")\n size = area/personas\n return size\n\n #Herencia \nclass Repostero(Cocinero):\n def crear_torta(self,sabor,altura,temperatura,area) :\n print(\"procedo a crear torta\") \n torta = TortaRedonda(sabor,altura,temperatura,area)\n return torta\n\ntorta1 = TortaRedonda(\"chocolate\", 10,42.8,100) \ntorta2 = TortaRedonda(\"vainilla\", 20,52.7,450) \n\nprint (\"el sabor de la primera torta es \", torta1.sabor)\nprint (\"el sabor de la segunda torta es \", torta2.sabor)\nprint (\"la forma de la primera torta es \", torta1.forma)\nprint (\"la forma de la segunda torta es \", torta2.forma)\n#hacer la accion\ncocinero1 = Cocinero(\"Daniel\")\npersonas = 12\nporcion = cocinero1.dividir_torta(personas,torta1.area)\nprint (\"Hola a todos soy\", cocinero1.nombre, \" y dividi la torta para \", personas ,\"personas\")\nprint (\"el tamaño de la porcion para cada uno es \", porcion)\n\ncocinero2 = Repostero(\"Mafer\")\ntorta_creada = cocinero2.crear_torta(\"chocoalmendra\",20,60,200)\nprint(torta_creada.sabor,torta_creada.forma)\n\npersonas_segundo_grupo = 10\nporcion2 = cocinero2.dividir_torta(personas_segundo_grupo,torta_creada.area)\nprint (\"Hola a todos soy\", cocinero2.nombre, \" y dividi la torta para \", personas_segundo_grupo,\"personas\")\nprint (\"el tamaño de la pocion para cada uno es\",porcion2)","sub_path":"clases/clase9/def.py","file_name":"def.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"278835948","text":"import ast\nimport json\nimport os\nimport glob\nimport sys\nimport requests\nimport inspect\nfrom clecode.configs import cfg\nfrom requests_toolbelt import MultipartEncoder\n\n\ndef load_module(file_path, module_name=None):\n \"\"\"\n Load a module by name and search path\n\n This function should work with python 2.7 and 3.x\n\n Returns None if Module could not be loaded.\n \"\"\"\n if module_name is None:\n module_name = os.path.basename(os.path.splitext(file_path)[0])\n if sys.version_info >= (3, 5,):\n import importlib.util\n\n spec = importlib.util.spec_from_file_location(module_name, file_path)\n if not spec:\n return\n\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n\n return module\n else:\n import imp\n mod = imp.load_source(module_name, file_path)\n return mod\n\n\n\ndef auto_module_by_py_dir(py_dir):\n func_dir, func_basename = os.path.split(py_dir)\n import_basename = func_basename.strip().split(\"_v\")[0]\n import_dir = glob.glob(os.path.join(func_dir, \"../../../**\", f\"{import_basename}.py\"), recursive=True)\n assert len(import_dir) == 1\n import_dir = import_dir[0]\n module = load_module(import_dir)\n return module\n\n\n\ndef decorator_default(method_name, class_name=\"Solution\"):\n def decorator(func):\n def decorated(*args, **kwargs):\n\n kws = dict(class_name=class_name, method_name=method_name)\n\n signature = inspect.signature(func)\n for key, value in signature.parameters.items():\n if value.default and (value.default != inspect._empty):\n kws.update({key: value.default})\n\n kws.update(kwargs)\n\n for a, b in zip(args, signature.parameters):\n kws.update({b: a})\n\n new_kws = dict()\n for key, value in kws.items():\n new_kws.update({key: value if isinstance(value, str) else value.__name__})\n\n new_args = list()\n for i, a, b in zip(range(max(len(args), len(signature.parameters))), args, signature.parameters):\n new_args.append(new_kws[b])\n new_kws.pop(b)\n\n if \"_v\" in os.path.basename(func.__code__.co_filename):\n module = auto_module_by_py_dir(func.__code__.co_filename)\n return getattr(module, \"ctest\")(*new_args, **new_kws)\n\n return func(*new_args, **new_kws)\n\n return decorated\n\n return decorator\n\n\ndef login(session, user_agent=None):\n if user_agent is None:\n user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'\n\n url = 'https://leetcode-cn.com'\n\n # cookies = session.get(url, proxies=cfg.LOGINmsg.proxy_dict)\n\n url = \"https://leetcode-cn.com/accounts/login\"\n\n params_data = dict(\n login=cfg.LOGINmsg.email,\n password=cfg.LOGINmsg.password,\n next=\"problems\"\n )\n\n headers = {\n \"User-Agent\": user_agent,\n \"Connection\": 'keep-alive',\n 'Referer': 'https://leetcode-cn.com/accounts/login/',\n \"origin\": \"https://leetcode-cn.com\"\n }\n m = MultipartEncoder(params_data)\n\n headers['Content-Type'] = m.content_type\n\n session.post(url, headers=headers, data=m,\n timeout=10, allow_redirects=False,\n proxies=cfg.LOGINmsg.proxy_dict)\n is_login = session.cookies.get('LEETCODE_SESSION') != None\n return is_login, session\n","sub_path":"clecode/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"242295243","text":"# Method 2: Using the get method\n# We will use the same list for this example:\n\nbook_title = ['great', 'expectations','the',\n 'adventures', 'of', 'sherlock',\n 'holmes','the','great','gasby',\n 'hamlet','adventures','of',\n 'huckleberry','fin']\n# Step 1: Create an empty dictionary.\nword_counter = {}\n\n# Step 2. Iterate through each element, get() its value in the dictionary, and add 1.\n# Recall that the dictionary get method is another way to retrieve the value of a key in a dictionary.\n# Except unlike indexing, this will return a default value if the key is not found.\n# If unspecified, this default value is set to None. We can use get with a default value of 0 to simplify\n# the code from the first method above.\n\nfor word in book_title:\n word_counter[word] = word_counter.get(word, 0) + 1\n\n# What's happening here?\n# The for loop iterates through the list as we saw earlier.\n# The for loop feeds 'great' to the next statement in the body of the for loop.\n\n# In this line: word_counter[word] = word_counter.get(word,0) + 1,\n# since the key 'great' doesn't yet exist in the dictionary,\n# get() will return the value 0 and word_counter[word] will be set to 1.\n\n# Once it encounters a word that already exists in word_counter\n# (e.g. the second appearance of 'the'), the value for that key is incremented by 1.\n# On the second appearance of 'the', the key's value would add 1 again, resulting in 2.\n\n# Once the for loop finishes iterating through the list, the for loop is complete.\n# Printing word_counter shows us we get the same result as we did in method 1.\n\nprint(word_counter)","sub_path":"Introduction_To_Python/3. Control Flow/4. Part 2. Building Dictionaries.py","file_name":"4. Part 2. Building Dictionaries.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"241978988","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nfrom skimage.measure import compare_ssim as ssim\n\nfrom pic.util import mse\n\ndef compare_images(A_path, B_path, title, show=True):\n '''fork from [pyimage](http://www.pyimagesearch.com/2014/09/15/python-compare-two-images/)\n ...compare two imgs' similarity by mse and ssim.\n - mse: higher is less similarity\n - ssim: higher is more similarity\n\n @Params:\n - A/B_path: two images filepath\n - title: if show==true, is the plt's title\n - show: show the result or not\n\n @Returns:\n mse, ssim of two images\n '''\n\t# compute the mean squared error and structural similarity\n\t# index for the images\n imageA = cv2.imread(A_path)\n imageB = cv2.imread(B_path)\n imageA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)\n imageB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)\n m = mse(imageA, imageB)\n s = ssim(imageA, imageB)\n\n\t# setup the figure\n if show:\n fig = plt.figure(title)\n plt.suptitle(\"MSE: %.2f, SSIM: %.2f\" % (m, s))\n\n # show first image\n ax = fig.add_subplot(1, 2, 1)\n plt.imshow(imageA, cmap = plt.cm.gray)\n plt.axis(\"off\")\n\n # show the second image\n ax = fig.add_subplot(1, 2, 2)\n plt.imshow(imageB, cmap = plt.cm.gray)\n plt.axis(\"off\")\n\n # show the images\n plt.show()\n return mse, ssim","sub_path":"pic/measure.py","file_name":"measure.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"471184630","text":"\"\"\"\nModule for breaking vigenere cyphers\n\"\"\"\n\nimport argparse\nimport os\nfrom math import log\nfrom reader import read_ascii_from_file\n\n\nMONOGRAM_FILE = os.path.join(os.path.dirname(\n __file__), '../../frequency_files/english_monograms.txt')\nBIGRAM_FILE = os.path.join(os.path.dirname(\n __file__), '../../frequency_files/english_bigrams.txt')\n\n\nclass VigenereBreaker: # pylint: disable=too-few-public-methods\n \"\"\"\n Vigenere Cipher Breaker class\n \"\"\"\n\n def __init__(self, key_length, monogram_file, bigram_file):\n self.key_length = key_length\n\n # Initialize monograms\n monogram_frequencies = {}\n with open(monogram_file, 'r', encoding='utf-8') as freq_file:\n for line in freq_file:\n key, count = line.split(' ')\n monogram_frequencies[key.lower()] = int(count)\n\n self.monogram_frequencies = VigenereBreaker._map_to_sorted_list(\n monogram_frequencies)\n\n # Initialize bigrams\n self.bigram_map = VigenereBreaker._import_bigram_file(bigram_file)\n\n def break_vigenere(self, text):\n \"\"\"\n Attempts to break vignere cipher using bigram analysis\n Tries out all different key bigrams, rating them based on the resulting\n distribution of decyphered bigrams, then picks the best combination of\n those keys\n \"\"\"\n\n key_guesses = [['' for i in range(self.key_length)], [\n '' for i in range(self.key_length)]]\n key_fitness = [0 for i in range(self.key_length)]\n\n # Split into as many groups as there are letters in the key\n text_fragments = VigenereBreaker._split_text(self.key_length, text)\n\n # Iterate through all positions in the key\n for i in range(self.key_length):\n # Concatenate adjacent text fragments into bigram lists\n bigram_list = [text_fragments[i][c] +\n text_fragments[(i+1) % self.key_length][c +\n int((i+1) / self.key_length)]\n for c in range(min(len(text_fragments[i]),\n len(text_fragments[(i+1) % self.key_length]) -\n int((i+1) / self.key_length)))]\n\n # Iterate through all possible key snippets for the current bigrams\n best_key = 'aa'\n best_fitness = 0\n for j in range(26*26):\n key = chr(int(j / 26) + 97) + chr(int(j % 26) + 97)\n translated_bigram_list = self._tanslate_bigram_list(\n bigram_list, key)\n translated_fitness = self._get_fitness(translated_bigram_list)\n if translated_fitness > best_fitness:\n best_fitness = translated_fitness\n best_key = key\n\n # Insert into appropiate positions in both key guesses to be compared later\n key_guesses[0][i] = best_key[0]\n key_guesses[1][(i + 1) % self.key_length] = best_key[1]\n key_fitness[i] = best_fitness\n\n # Generate final key\n key = ''\n for i in range(self.key_length):\n key += (key_guesses[0][i] if key_fitness[i] > key_fitness[(i-1) % self.key_length]\n else key_guesses[1][i])\n\n # Invert key into correct form\n return self._invert_key(key)\n\n def _get_fitness(self, bigram_list):\n \"\"\"\n Calculate fitness of given bigram list based on the logarithmic frequency table\n \"\"\"\n fitness = 0\n for bigram in bigram_list:\n fitness += self.bigram_map[ord(bigram[0]) -\n 97][ord(bigram[1]) - 97]\n\n return fitness\n\n @staticmethod\n def _invert_key(key):\n \"\"\"\n Inverts the given key a <-> a, b <-> z, etc.\n \"\"\"\n inverted_key = ''\n for char in key:\n inverted_key += chr((26 - (ord(char) - 97)) % 26 + 97)\n\n return inverted_key\n\n @staticmethod\n def _tanslate_bigram_list(bigram_list, key):\n \"\"\"\n Decypher the given bigram list with the given key\n IMPORTANT: Uses inverted key compared to the ones used in vig.py\n \"\"\"\n new_bigrams = []\n shift_a = ord(key[0]) - 97\n shift_b = ord(key[1]) - 97\n\n for bigram in bigram_list:\n new_bigrams.append(chr((ord(bigram[0]) - 97 + shift_a) % 26 + 97) +\n chr((ord(bigram[1]) - 97 + shift_b) % 26 + 97))\n\n return new_bigrams\n\n @staticmethod\n def _import_bigram_file(file_name):\n \"\"\"\n Imports bigrams from file into 2D array using ASCII - 97 indices\n \"\"\"\n bigram_map = [[1 for i in range(26)] for j in range(26)]\n\n with open(file_name, 'r', encoding='utf-8') as file:\n for line in file:\n key, val = line.split(' ')\n key = key.lower()\n bigram_map[ord(key[0]) - 97][ord(key[1]) - 97] = int(val)\n\n # Calculate logarithm\n max_log = 0\n for row, _ in enumerate(bigram_map):\n for col, _ in enumerate(bigram_map[row]):\n bigram_map[row][col] = log(bigram_map[row][col])\n max_log = max(max_log, bigram_map[row][col])\n\n normalize_factor = 1000000 / max_log\n\n # Normalize to integers between 0 and 1 000 000\n for row, _ in enumerate(bigram_map):\n for col, _ in enumerate(bigram_map[row]):\n bigram_map[row][col] = int(\n bigram_map[row][col] * normalize_factor)\n max_log = max(max_log, bigram_map[row][col])\n\n return bigram_map\n\n @staticmethod\n def _split_text(key_len, text):\n \"\"\"\n Splits the text into key_len groups, such that all letters affected by a\n position in the key are in one group\n \"\"\"\n split_text = ['' for i in range(key_len)]\n for c, char in enumerate(text):\n split_text[c % key_len] += char\n return split_text\n\n @staticmethod\n def _map_to_sorted_list(frequency_map):\n \"\"\"\n Returns the elements of a given frequency map, sorted in descending order\n \"\"\"\n return sorted(frequency_map, key=frequency_map.__getitem__, reverse=True)\n\n\nif __name__ == '__main__':\n # Parse arguments\n PARSER = argparse.ArgumentParser()\n PARSER.add_argument('file', metavar='FILE',\n help='The input file.')\n PARSER.add_argument('--keylen', '-k', required=True,\n help='The length of the key used.')\n PARSER.add_argument('--out', '-o',\n help='The output file.')\n\n ARGS = vars(PARSER.parse_args())\n\n BREAKER = VigenereBreaker(int(ARGS['keylen']), MONOGRAM_FILE, BIGRAM_FILE)\n TEXT = BREAKER.break_vigenere(read_ascii_from_file(ARGS['file']))\n\n if ARGS['out']:\n FILE = open(ARGS['out'], 'w')\n FILE.write(TEXT)\n FILE.close()\n else:\n print(TEXT)\n","sub_path":"src/vigenere/break_vig.py","file_name":"break_vig.py","file_ext":"py","file_size_in_byte":7045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"61127003","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport json\nfrom scrapy.exceptions import DropItem\n\nclass CankaoPipeline(object):\n '''\n 保存到文件中\n '''\n def __init__(self):\n self.file = open('./download/papers.json', 'wb')\n\n # def open_spider(self, spider):\n # '''\n # spider是一个Spider对象,代表开启的Spider,当spider被开启时,调用这个方法\n # 数据库/文件的开启可以放在这里\n # :param spider:\n # :return:\n # '''\n # pass\n\n def process_item(self, item, spider):\n '''\n 处理item,进行保存\n :param item:\n :param spider:\n :return:\n '''\n print(item['img'])\n if item['img']:\n line = json.dumps(dict(item)) + '\\n'\n # 要转成字节类型,写入文件\n self.file.write(line.encode())\n # 给下一个pipline处理\n return item\n else:\n # 丢弃,后面的pipline也无法处理了\n raise DropItem('miss img in %s' % item)\n\n def close_spider(self, spider):\n '''\n spider被关闭的时候调用\n 可以放置数据库/文件关闭的代码\n :param spider:\n :return:\n '''\n # pass\n self.file.close()\n print('pipine open file times %s' % 5)\n\n # @classmethod\n # def from_crawler(cls, crawler):\n # '''\n # 类方法,用来创建pipeline实例,可以通过crawler来获取scarpy所有的核心组件,如配置\n # :param crawler:\n # :return:\n # '''\n # pass\n\n\nfrom pymongo import MongoClient\n\nclass CankaoMongoPipeline(object):\n '''\n 以mongo存储为例\n '''\n # 集合名\n collection_name = 'scrapy_items'\n\n def __init__(self, mongo_uri, mongo_port, mongo_db):\n self.mongo_uri = mongo_uri\n self.mongo_port = mongo_port\n self.mongo_db = mongo_db\n\n @classmethod\n def from_crawler(cls, crawler):\n '''\n 类方法,用来创建pipeline实例,可以通过crawler来获取scarpy所有的核心组件,如配置\n :param crawler:\n :return:\n '''\n return cls(\n # 获取mongo连接\n mongo_uri = crawler.settings.get('MONGO_URI'),\n # 获取mongo连接\n mongo_port = crawler.settings.get('MONGO_PORT'),\n # 获取数据库,如果没有则用默认的item\n mongo_db = crawler.settings.get('MONGO_DATABASE', 'fecshop_test')\n )\n\n def open_spider(self, spider):\n '''\n spider是一个Spider对象,代表开启的Spider,当spider被开启时,调用这个方法\n 数据库/文件的开启可以放在这里\n :param spider:\n :return:\n '''\n # 连接mongo\n self.client = MongoClient(self.mongo_uri, self.mongo_port)\n # 选择使用的数据库\n db_auth = self.client[self.mongo_db]\n # 验证登陆\n db_auth.authenticate(\"simpleUser\", \"simplePass\")\n self.db = self.client[self.mongo_db]\n\n def process_item(self, item, spider):\n '''\n 处理item,进行保存\n :param item:\n :param spider:\n :return:\n '''\n # 向集合中添加数据\n self.db[self.collection_name].insert(dict(item))\n return item\n\n def close_spider(self, spider):\n '''\n spider被关闭的时候调用\n 可以放置数据库/文件关闭的代码\n :param spider:\n :return:\n '''\n self.client.close()\n\nimport scrapy\nfrom scrapy.pipelines.files import FilesPipeline\nfrom scrapy.http import Request\nimport os\n\nclass CankaoFilesPipeline(FilesPipeline):\n '''\n 下载文件\n 继承框架自带的FilesPipeline文件下载类\n '''\n\n def get_media_requests(self, item, info):\n '''\n 重写此方法, 用来获取图片url进行下载\n :param item:\n :param info:\n :return:\n '''\n self.item = item\n yield scrapy.Request(item['img'])\n\n # def item_completed(self, results, item, info):\n # '''\n # 下载完成后将会把结果送到这个方法\n # :param results:\n # :param item:\n # :param info:\n # :return:\n # '''\n # # print(results)\n #\n # '''\n # results 为下载��回的数据, 如下\n # [(True, {'url': 'https://img3.doubanio.com/view/subject/m/public/s29816983.jpg', 'path': 'full/fced9acc2ecf23e0f96b9a2d9a442b02234f4388.jpg', 'checksum': 'ce0e7d543b37dbe3d21dd46ef8fcbd1b'})]\n # 图片下载成功时为True\n # url 源图片地址\n # path 下载的文件路径\n # checksum md5 hash\n # '''\n # print(item)\n # print(info)\n\n def file_path(self, request, response=None, info=None):\n '''\n 重写要保存的文件路径,不使用框架自带的hash文件名\n :param request:\n :param response:\n :param info:\n :return:\n '''\n def _warn():\n from scrapy.exceptions import ScrapyDeprecationWarning\n import warnings\n warnings.warn('FilesPipeline.file_key(url) method is deprecated, please use '\n 'file_path(request, response=None, info=None) instead',\n category=ScrapyDeprecationWarning, stacklevel=1)\n\n # check if called from file_key with url as first argument\n if not isinstance(request, Request):\n _warn()\n url = request\n else:\n url = request.url\n\n # 后缀\n media_ext = os.path.splitext(url)[1]\n # 原名带后缀\n media_content = url.split(\"/\")[-1]\n # 使用item中的内容\n # return 'full/%s%s' % (self.item['content'], media_ext)\n return 'full/%s' % (media_content)\n\n\nimport scrapy\nfrom scrapy.pipelines.images import ImagesPipeline\n\nclass CankaoImagesPipeline(ImagesPipeline):\n '''\n 继承框架自带的ImagesPipeline图片下载类,可以下载的同时生成不同尺寸的图片放在配置的目录下\n '''\n\n def get_media_requests(self, item, info):\n '''\n 重写此方法, 用来获取图片url进行下载\n :param item:\n :param info:\n :return:\n '''\n yield scrapy.Request(item['img'])\n\n # def item_completed(self, results, item, info):\n # '''\n # 下载完成后将会把结果送到这个方法\n # :param results:\n # :param item:\n # :param info:\n # :return:\n # '''\n # print(results)\n #\n # '''\n # results 为下载返回的数据, 如下\n # [(True, {'url': 'https://img3.doubanio.com/view/subject/m/public/s29827942.jpg', 'path': 'full/ad6acfdbef4d9df208c0e010ed1efcc287cb6225.jpg', 'checksum': 'c5d853689829ba8731cbb27146d89573'})]\n # 图片下载成功时为True\n # url 源图片地址\n # path 下载的文件路径\n # checksum md5 hash\n # '''\n # print(item)\n # print(info)","sub_path":"cankao/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":7255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"525564987","text":"import numpy as np\n\n\ndef parse_raw_data(path):\n input_sentences = []\n target_sentences = []\n with open(path) as f:\n in_sentence = []\n target_sentence = []\n for line in f:\n if line != \"\\n\":\n in_target = line.split('\\t')\n in_sentence.append(in_target[0])\n target_sentence.append(in_target[1].strip())\n else:\n input_sentences.append(in_sentence)\n target_sentences.append(target_sentence)\n in_sentence = []\n target_sentence = []\n\n data = []\n for sentence_idx in range(len(input_sentences)):\n sentence = input_sentences[sentence_idx]\n sentence_data = np.zeros((70 + 1, 500), dtype=np.float32)\n col_idx = 0\n for word_idx in range(len(sentence)):\n word = sentence[word_idx]\n target_symbol = 0 # 0 PASS\n if (\"company\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 1/10.0\n elif (\"facility\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 2/10.0\n elif (\"geo-loc\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 3/10.0\n elif (\"movie\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 4/10.0\n elif (\"musicartist\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 5/10.0\n elif (\"other\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 6/10.0\n elif (\"person\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 7/10.0\n elif (\"product\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 8/10.0\n elif (\"sportsteam\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 9/10.0\n elif (\"tvshow\" in target_sentences[sentence_idx][word_idx]) is True:\n target_symbol = 10/10.0\n for char in word.upper(): # upper the\n char_dec = ord(char)\n row_idx = 68 # represent other unkonw symbols\n if 96 >= char_dec >= 33:\n row_idx = char_dec - 33\n elif 126 >= char_dec >= 123:\n row_idx = char_dec - 33 - 26\n sentence_data[row_idx, col_idx] = 1\n sentence_data[70, col_idx] = target_symbol\n col_idx += 1\n sentence_data[69, col_idx] = 1\n sentence_data[70, col_idx] = -1\n col_idx += 1\n data.append(sentence_data)\n return np.array(data)\n\n\ndef save_to_disk(train_data, evl_data):\n np.save(train_data + \"_np_v3\", parse_raw_data(train_data))\n np.save(evl_data + \"_np_v3\", parse_raw_data(evl_data))\n\n\nclass DataManager(object):\n def __init__(self, train_data, evl_data, batch_size):\n print (\"Start loading data ...\")\n self._train_data = train_data\n self._evl_data = evl_data\n self._train_data = np.load(self._train_data)\n self._evl_data = np.load(self._evl_data)\n self._batch_size = batch_size\n self._batch_index = 0\n print (\"Data loaded !\")\n\n def get_one_sample(self, index=0, source=\"test\"):\n if source != \"test\":\n return self._train_data[index, 0:70, :], self._train_data[index, 70:, :]\n else:\n return self._evl_data[index, 0:70, :], self._evl_data[index, 70, :]\n\n def get_batch(self):\n epoch_end = False\n self._batch_index += self._batch_size\n if self._batch_index > np.shape(self._train_data)[0]:\n epoch_end = True\n np.random.shuffle(self._train_data) # shuffle the data\n self._batch_index = self._batch_size\n batch_data = self._train_data[self._batch_index - self._batch_size:self._batch_index]\n batch_input = batch_data[:, 0:70, :]\n batch_output = batch_data[:, 70, :]\n return batch_input, batch_output, epoch_end\n","sub_path":"scripts/data_util_v3.py","file_name":"data_util_v3.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"481751893","text":"from time import time\n\n\ndef timef(f, inputs, args_fmt=str, ret_fmt=str):\n vals = []\n\n for args in inputs:\n print(f'{f.__name__}{args_fmt(args)} = ', end='', flush=True)\n\n t1 = time()\n val = f(*args)\n t2 = time()\n total = round((t2 - t1) * 1000, 6)\n\n print(ret_fmt(val))\n print(f'Time: {total} ms\\n')\n\n vals.append(val)\n\n return vals\n","sub_path":"project-euler/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"620083741","text":"def readfile(filename):\n textfile = open(filename, 'r')\n text = ''\n while True:\n read = textfile.readline()\n if not read:\n break\n text += read\n return text\n\ndef writefile(filename, text):\n textfile = open(filename, 'w')\n textfile.write(text)\n textfile.close()\n\ndef flips(string):\n string += \"+\"\n groups = 0\n for char in range(len(string)):\n if char and string[char] != string[char-1]:\n groups += 1\n return groups\n\ncases = [case for case in readfile(\"B-large.in\").split(\"\\n\")[1:] if case != \"\"]\noutput = \"\"\n\nfor case in range(len(cases)):\n output += \"Case #\" + str(case+1) + \": \" + str(flips(cases[case])) + (\"\\n\" if case != len(cases)-1 else \"\")\n\nwritefile(\"output.txt\", output)\n","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_GradyS_codejam_2.py","file_name":"16_0_2_GradyS_codejam_2.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"632666127","text":"from ipaddress import IPv4Address, ip_address \nimport ipaddress\nclass Solution:\n \n def fragmentip(self,ip) -> None:\n self.ip=ip\n \n ip=str(ip)\n cl=\"\"\n des=\"\" #des\n \n co=0 #count to calc len of ip\n br=0 #var to break the loop \n for i in ip:\n if i==\".\" :\n br=1\n for d in range(co,len(ip)):\n if(ip[d]==\".\"):\n continue\n elif (ip[d]==\"/\") :\n break\n else:\n des+=ip[d]\n elif br==1:\n break \n else :\n co+=1\n cl+=i\n return cl\n def find(self,p):\n orginal=p\n obj=Solution()\n self.p=p\n ip=obj.fragmentip(p)\n ipclass=int(ip)\n \n ipdes=orginal\n #class A\n if (ipclass>=1) and (ipclass<=127):\n if(ipdes>=ip_address(\"10.0.0.0\"))and (ipdes<=ip_address(\"10.255.255.255\")):\n print(\"class A , designated private\")\n elif(ipdes>=ip_address(\"1.0.0.0\")and (ipdes<=ip_address(\"127.0.0.0\"))):\n print(\"class A , designated public\") \n \n else:\n print(\"class A , designated Special \")\n #class B\n elif (ipclass>=128) and (ipclass<=191):\n if(ipdes>=ip_address(\"172.16.0.0\"))and (ipdes<=ip_address(\"172.31.255.255\")):\n print(\"class B , designated private\")\n print(ipdes)\n elif(ipdes>=ip_address(\"128.0.0.0\"))and (ipdes<=ip_address(\"191.255.0.0\")):\n print(\"class B , designated public\") \n \n else:\n print(\"class B , designated Special \")\n #class C\n elif (ipclass>=192) and (ipclass<=223):\n \n if(ipdes>=ip_address(\"192.168.0.0\"))and (ipdes<=ip_address(\"192.168.255.255\")):\n print(\"class C , designated private\")\n elif ipdes>=ip_address(\"192.0.0.0\")and ipdes<=ip_address(\"223.255.255.0\"):\n print(\"class C , designated public\") \n \n else:\n print(\"class C , designated Special \") \n \n \n\n\n\nif __name__ == '__main__':\n obj=Solution()\n ip=ip_address(\"192.168.0.0\")\n obj.find(ip)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"471991085","text":"import re\n\nactualhp = re.compile(r\"\\|-damage\\|p(?P1|2)(?Pa|b):\\ (?P.+)\\|(?P[0-9]+)/(?P[0-9]+)\", re.VERBOSE)\npercenthp = re.compile(r\"\\|-damage\\|p(?P1|2)(?Pa|b):\\ (?P.+)\\|p(?P[0-9]+)/100\", re.VERBOSE)\nfnt = re.compile(r\"\\|-damage\\|p(?P1|2)(?Pa|b):\\ (?P.+)\\|0\\ fnt\", re.VERBOSE)\nfaint = re.compile(r\"\\|faint\\|p(?P1|2)(?Pa|b):\\ (?P.+)\", re.VERBOSE)\nanim = re.compile(r\"\\|-anim\\|p(?P1|2)(?Pa|b):\\ (?P[a-zA-Z\\.\\ \\-\\0-9’]+)\\|(?P[a-zA-Z0-9\\ ]+)\\|p(?P1|2)(?Pa|b):\\ (?P[a-zA-Z\\.\\ \\-\\0-9’]+)\", re.VERBOSE)\nmove = re.compile(r\"\\|move\\|p(?P1|2)(?Pa|b):\\ (?P.+)\\|(?P.+)\\|p(?P1|2)(?Pa|b)?:\\ (?P.+)(\\|\\[notarget\\])?\", re.VERBOSE)\npersistmove = re.compile(r\"\\|move\\|p(?P1|2)(?Pa|b):\\ (?P.+)\\|(?P.+)\\|\\|\\[still\\]\", re.VERBOSE)\nsupereffective = re.compile(r\"\\|-supereffective\\|p(?P1|2)(?Pa|b):\\ (?P.+)\", re.VERBOSE)\nresist = re.compile(r\"\\|-resisted\\|p(?P1|2)(?Pa|b):\\ (?P.+)\", re.VERBOSE)\ncrit = re.compile(r\"\\|-crit\\|p(?P1|2)(?Pa|b):\\ (?P.+)\", re.VERBOSE)\nmiss = re.compile(r\"\\|-miss\\|p(?P1|2)(?Pa|b):\\ (?P.+)\\|p(?P1|2)(?Pa|b):\\ (?P.+)\", re.VERBOSE)\nimmune = re.compile(r\"\\|-immune\\|p(?P1|2)(?Pa|b):\\ (?P[a-zA-Z\\.\\ \\-\\0-9’]+)(\\|.+)?\", re.VERBOSE)\nstatus = re.compile(r\"\\|-status\\|p(?P1|2)(?Pa|b):\\ (?P[a-zA-Z\\.\\ \\-\\0-9’]+)\\|(?P[a-zA-Z0-9\\ ]+)(.+)?\", re.VERBOSE)\nprepare = re.compile(r\"\\|-prepare\\|p(?P1|2)(?Pa|b):\\ (?P.+)\\|(?P.+)\", re.VERBOSE)\nhitcount = re.compile(r\"\\|-hitcount\\|p(?P1|2)(?Pa|b)?:\\ (?P.+)\\|(?P[0-9])\", re.VERBOSE)\n\ntime = re.compile(r\"\\|t:\\|(?P