diff --git "a/5890.jsonl" "b/5890.jsonl" new file mode 100644--- /dev/null +++ "b/5890.jsonl" @@ -0,0 +1,783 @@ +{"seq_id":"175018744","text":"from nose.tools import assert_equals\n#-------------------------------------\n\ndef in_array(array1, array2):\n # your code\n L = list()\n for str1 in array1:\n for str2 in array2:\n if str2.find(str1):\n L.append(str1)\n break\n if L == []:\n return []\n\n return L\n\n#--------------------------------------\nif __name__ == '__main__':\n a1 = [\"arp\", \"live\", \"strong\"]\n a2 = [\"lively\", \"alive\", \"harp\", \"sharp\", \"armstrong\"]\n r = ['arp', 'live', 'strong']\n assert_equals(in_array(a1, a2), r)","sub_path":"WhichAreIn.py","file_name":"WhichAreIn.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"529857138","text":"def cut_the_spaces(word):\n if word[0] == ' ':\n word = word[1:]\n if word[-1] == ' ':\n word = word[:-1]\n return word\n\n# make the list of parents for dictionary\ndef make_the_list(parents):\n parents = parents.split()\n for j in range(len(parents)):\n parents[j] = cut_the_spaces(parents[j])\n return parents\n\ndef check_inheritance(parent, ancestor):\n global is_found\n if is_found is False and classes[ancestor] is not None:\n if parent in classes[ancestor]:\n is_found = True\n else:\n for parent in classes[ancestor]:\n check_inheritance(parent, ancestor) \n\nn = int(input())\nclasses = dict()\nfor i in range(n):\n inp = input()\n if ':' in inp:\n class_name, parents = inp.split(':')\n classes[cut_the_spaces(class_name)] = make_the_list(parents)\n else:\n class_name = cut_the_spaces(inp)\n classes[class_name] = list()\n\nq = int(input())\nfor i in range(q):\n parent, ancestor = input().split()\n is_found = False\n check_inheritance(parent, ancestor)\n print('Yes') if is_found else print('No')\n","sub_path":"advanced-python-course/1.6-inheritance/inheritance_simulation.py","file_name":"inheritance_simulation.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"508320648","text":"from tkinter import *\nfrom tkinter import ttk\nfrom datetime import date\nfrom datetime import datetime\nimport sqlite3\nimport time\n\n\nclass Retiro:\n \n bd_name = 'BaseDatos.db'\n\n def Inicio(self):\n self.titulo = \"Retiros\"\n self.icono = \"@../GrupoD-Proyecto/Iconos/Registradora.xbm\"\n self.resizable = False\n self.color = \"#83D6A8\"\n\n # Iniciar ventana\n ventana_retiro = Tk()\n self.ventana_retiro = ventana_retiro\n\n # Titulo\n ventana_retiro.title(self.titulo)\n\n # Tamaño de la ventana\n ox, oy = ventana_retiro.winfo_screenwidth()/5, ventana_retiro.winfo_screenheight()/5\n ventana_retiro.geometry(\"=400x200+%d+%d\" % (ox--220, oy--70))\n\n # Bloquear el tamaño\n if (self.resizable):\n ventana_retiro.resizable(1, 1)\n else:\n ventana_retiro.resizable(0, 0)\n\n # Agregar Icono\n ventana_retiro.iconbitmap(self.icono) \n\n # Configuraciones\n self.ventana_retiro.config(\n bg=self.color\n )\n\n validacion_str = ()\n\n ############################ CONFIGURACIONES DE LA VENTANA #####################################\n # Label Cantidad Retiro\n Label(ventana_retiro, text=\"Cantidad de retiro: \",\n font=(\"Arial\", 14, \"bold\"), bg=\"#83D6A8\").place(x=30, y=4)\n # Entry cantidad retiro\n self.cantidad_retiro = Entry(ventana_retiro)\n self.cantidad_retiro.config(\n font=(\"Arial\", 12),\n width=15,\n bd=2,\n justify=\"center\"\n )\n self.cantidad_retiro.place(x=230, y=6)\n\n # Label Nombre empleado\n Label(ventana_retiro, text=\"Nombre empleado: \",\n font=(\"Arial\", 14, \"bold\"), bg=\"#83D6A8\").place(x=30, y=38)\n # Entry Mombre empleado\n self.nombre_empleado = Entry(ventana_retiro)\n self.nombre_empleado.config(\n font=(\"Arial\", 12),\n width=15,\n bd=2,\n justify=\"center\"\n )\n self.nombre_empleado.place(x=230, y=40)\n\n # Label fecha\n Label(ventana_retiro, text=\"Fecha: \",\n font=(\"Arial\", 14, \"bold\"), bg=\"#83D6A8\").place(x=70, y=72)\n # Entry fecha\n self.fecha_actual = datetime.now()\n formato = self.fecha_actual.strftime('%d / %m / %Y')\n self.fecha = Label(ventana_retiro, text = formato)\n self.fecha.config(\n bg = \"#83D6A8\",\n font = (\"Arial\", 14)\n )\n self.fecha.place(x=240,y=72)\n\n # Label hora\n Label(ventana_retiro, text=\"Hora: \",\n font=(\"Arial\", 14, \"bold\"), bg=\"#83D6A8\").place(x=75, y=105)\n # Entry hora\n def times():\n current_time = time.strftime('Hora: %H:%M')\n hora.config(\n text = current_time,\n bg = \"#83D6A8\",\n font = (\"Arial\", 14)\n )\n hora.after(200,times)\n\n hora = Label(ventana_retiro)\n times()\n hora.place(x=250, y=108)\n\n ################# BOTONES #######################\n #Boton aceptar\n boton_retiro = Button(ventana_retiro, text=\"Aceptar\", command = self.cargar_datos)\n boton_retiro.config(\n width = 40,\n bd = 3,\n relief = RAISED,\n font = (\"Arial\",13, \"bold\"),\n cursor = \"hand2\"\n )\n boton_retiro.place(x= 0, y = 165)\n\n ventana_retiro.mainloop()\n\n # Validacion todos los campos llenos\n def validacion(self):\n if (len(self.nombre_empleado.get()) != 0 and len(self.cantidad_retiro.get()) != 0):\n return TRUE\n else:\n return FALSE\n\n # 'Chekeo' de la tabla\n def ejecuta_consulta(self, consulta, parametros = ()):\n with sqlite3.connect(self.bd_name) as conn:\n cursor = conn.cursor() \n resultado = cursor.execute(consulta, parametros)\n conn.commit()\n return resultado\n raise Exception(' NO SE PUDO CONECTAR A LA BASE DE DATOS. ')\n\n def cargar_datos(self):\n if self.validacion() == TRUE:\n consult = 'INSERT INTO Retiros VALUES(NULL, ?, ?, ?)'\n parametros = (self.nombre_empleado.get(), self.cantidad_retiro.get(), self.fecha_actual)\n self.ejecuta_consulta(consult, parametros)\n self.nombre_empleado.delete(0, END)\n self.cantidad_retiro.delete(0, END)\n self.ventana_retiro.destroy()\n \n # Validacion Str\n @staticmethod\n def lee_str(aux_1):\n if aux_1.isalpha() or aux_1.isspace():\n return True\n else:\n return False\n","sub_path":"Retiros.py","file_name":"Retiros.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"568361045","text":"\n\nfrom xai.brain.wordbase.verbs._remainder import _REMAINDER\n\n#calss header\nclass _REMAINDERED(_REMAINDER, ):\n\tdef __init__(self,): \n\t\t_REMAINDER.__init__(self)\n\t\tself.name = \"REMAINDERED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"remainder\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_remaindered.py","file_name":"_remaindered.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"297072905","text":"import csv\nimport pandas as pd\n\ndef csvsplit(filename, region):\n # init rows list\n rows = []\n\n # open CSV file and append each row to a list\n with open(filename, newline='') as csvfile:\n\n #create CSV reader object and iterate through each row - appending it to the rows list\n csv_obj = csv.reader(csvfile, delimiter=',', quotechar = '|')\n\n for row in csv_obj:\n rows.append(row)\n \n # find where server data ends and comparison between servers begins and shorten list to that length\n end_index = rows.index(['Differences between servers']) - 1\n\n # iterate through each row and create the necessary data frames for each server\n index_list = []\n counter = 0\n for row in rows:\n string_row = str(row)\n\n if ('orldc' in string_row) and counter <= end_index:\n index_list.append(counter)\n\n counter += 1\n \n index_list.append(end_index)\n \n col_names = ['flightid', 'status', 'diversion_time', 'orig_dest', 'asdi_dest', 'origin', 'on_time', 'off_time', 'rowtime']\n default_row = ['NaN', 1, '2019-01-01 00:00:00-00', 'KBOS', 'KBOS', 'KBOS', '2019-01-01 00:00:00-00', '2019-01-01 00:00:00-00', '2019-01-01 00:00:00-00']\n\n\n df_list = []\n servers = []\n names = []\n\n for i in (range(len(index_list) - 1)):\n\n temp_list = rows[index_list[i]:(index_list[i + 1] - 1)]\n\n if len(temp_list) == 1:\n temp_list.append(col_names)\n temp_list.append(default_row)\n else:\n temp_list.pop()\n \n name = temp_list[0][0]\n name = name[(name.index('-') + 1):name.index(':')]\n \n name_list = ['dev-fused02', 'dev-fused03', 'prod-fused04', 'prod-fused06', 'prod-fused07']\n server_list = ['server2', 'server3', 'server4', 'server6', 'server7']\n\n server = server_list[name_list.index(name)]\n\n df = pd.DataFrame(temp_list[2::], columns=col_names)\n\n df_list.append(df)\n servers.append(server)\n names.append(name)\n\n return [df_list, servers, names]\n\n","sub_path":"utl/csvtodf.py","file_name":"csvtodf.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"436615802","text":"import argparse\nimport os\nimport time\n\nimport torch\n\nfrom data import get_dataloader, get_dataloader_ddp\nfrom net import MyNet\nfrom utils import *\n\nfrom pytorch_nndct import get_pruning_runner\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '--local_rank', type=int, default=0, help='node rank for distributed training')\nparser.add_argument(\n '--gpus', type=str, default='0', help='String of available GPU number')\nparser.add_argument(\n '--lr', type=float, default=1e-3, help='Initial learning rate')\nparser.add_argument('--epochs', type=int, default=1, help='Train epoch')\nparser.add_argument(\n '--sparsity', type=float, default=0.5, help='Sparsity ratio')\nparser.add_argument(\n '--pretrained',\n type=str,\n default='mynet.pth',\n help='Pretrained model filepath')\nparser.add_argument(\n '--save_dir',\n type=str,\n default='./',\n help='Where to save retrained model')\nparser.add_argument(\n '--data_dir',\n type=str,\n default='./dataset/cifar10',\n help='Dataset directory')\nparser.add_argument(\n '--num_workers',\n type=int,\n default=48,\n help='Number of workers used in dataloading')\nparser.add_argument('--batch_size', type=int, default=128, help='Batch size')\nparser.add_argument(\n '--weight_decay', type=float, default=1e-4, help='Weight decay')\nparser.add_argument('--momentum', type=float, default=0.9, help='Momentum')\nargs, _ = parser.parse_known_args()\n\ndevice = 'cuda'\ngpus = get_gpus(args.gpus)\n\n\nif __name__ == '__main__':\n assert os.path.exists(args.pretrained), \"No pretrained model!\"\n model_path = os.path.join(args.save_dir, 'mynet_sparse.pth')\n if not os.path.exists(model_path):\n os.system('cp ' + args.pretrained + ' ' + model_path)\n if os.path.exists(args.data_dir):\n download = False\n else:\n download = True\n\n torch.distributed.init_process_group(backend=\"nccl\")\n torch.cuda.set_device(args.local_rank)\n batch_size = args.batch_size * len(gpus)\n train_loader = get_dataloader_ddp(args.data_dir, batch_size, num_workers=args.num_workers, shuffle=True, train=True, download=download)\n val_loader = get_dataloader_ddp(args.data_dir, batch_size, num_workers=args.num_workers, shuffle=False, train=False, download=download)\n\n model = MyNet()\n model = load_weights(model, args.pretrained)\n input_signature = torch.randn([1, 3, 32, 32], dtype=torch.float32)\n input_signature = input_signature.to(device)\n model = model.to(device)\n pruning_runner = get_pruning_runner(model, input_signature, 'iterative')\n\n model = pruning_runner.prune(removal_ratio=args.sparsity, mode='sparse')\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True)\n criterion = torch.nn.CrossEntropyLoss().cuda()\n optimizer = torch.optim.Adam(\n model.parameters(), args.lr, weight_decay=args.weight_decay)\n lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.epochs)\n best_acc1 = 0\n for epoch in range(args.epochs):\n train(train_loader, model, criterion, optimizer, epoch)\n lr_scheduler.step()\n acc1, acc5 = evaluate(val_loader, model, criterion)\n # remember best acc@1 and save checkpoint\n is_best = acc1 > best_acc1\n best_acc1 = max(acc1, best_acc1)\n\n if is_best:\n if hasattr(model, 'module'):\n torch.save(model.state_dict(), model_path)\n else:\n torch.save(model.state_dict(), model_path)\n","sub_path":"examples/vai_optimizer/pytorch/cifar10_ddp/sparse_model_train_ddp.py","file_name":"sparse_model_train_ddp.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"523941693","text":"from loap.obj.base_obj import BaseObj\n\n\nclass Player(BaseObj):\n def __init__(self, x, y):\n super().__init__(x, y, sign='@')\n self.action_points = 3\n self.hit_points = 3\n self.mana = 0\n self.strength = 1\n self.intelligence = 1\n self.dexterity = 1\n self.endurance = 1\n","sub_path":"loap/obj/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"19216096","text":"#!usr/bin/env python\n# -*- coding:utf-8 -*-\n# author: sfhong2020 time:2020/3/31 19:56\n\n\n# 左右根,分治\n# 判断数组是否为二叉搜索树的后序遍历!\nclass Solution:\n def verifyPostorder(self, postorder: List[int]) -> bool:\n\n def helper(sequence):\n n = len(sequence)\n if n <= 1: return True\n root = sequence[-1]\n for i in range(n-1):\n if sequence[i] > root: # 找出大于根的数字,即右子树\n break\n for j in range(i, n-1): # 遍历右子树,如果发现有小于跟的,返回错!\n if sequence[j] > root:\n return False\n return helper(sequence[:i]) and helper(sequence[i:-1]) # 分别进入左右子树判断\n\n if not postorder: return True\n return helper(postorder)\n\n","sub_path":"Leetcode/二叉树/面试题33. 二叉搜索树的后序遍历序列.py","file_name":"面试题33. 二叉搜索树的后序遍历序列.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"477516105","text":"# -*- coding:utf-8 -*-\r\n\r\nimport os, sys\r\nimport framework.app as ModApp\r\nimport entity.login_entity_ as login_entity\r\n\r\ndef main(szServiceName):\r\n szPathEngine = os.path.join(os.getcwd(), \"../login\")\r\n szEngineLib = os.path.join(szPathEngine, \"lib/lib_engine_core.so\")\r\n ModApp.SetService(login_entity.LoginEntity())\r\n ModApp.InitAndLoop(szServiceName, szEngineLib)\r\n\r\nif __name__ == '__main__':\r\n main(sys.argv[1])\r\n","sub_path":"py_project/login/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"214120181","text":"#!/usr/bin/env python3\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sys\nfrom os import path\n\nplt.style.use('default')\nplt.rcParams['errorbar.capsize'] = 2\n\nconfigname_key = 'configname'\np1_key = 'k'\np2_key = 'n'\n\nif len(sys.argv) > 1:\n csv_path = sys.argv[1]\n folder_path = path.split(csv_path)[0]\nelse:\n csv_path = 'results.csv'\n folder_path = './'\n\ndf = pd.read_csv(csv_path)\n\ngrouped = df.groupby([configname_key, p1_key, p2_key])\ndf = pd.concat([\n grouped['ttn', 'mbmean', 'mimean'].mean(),\n grouped['mbmin', 'mimin'].min(),\n grouped['mbmax', 'mimax'].max(),\n ], axis=1, sort=False)\n\n[configname_values, p1_values, p2_values] = df.index.levels\n\nfor configname_value in configname_values:\n\n subdf = df.xs(configname_value)\n\n for p1_value in p1_values:\n\n subsubdf = subdf.xs(p1_value)\n\n if len(subsubdf) < 2:\n print('%s, %s=%d: skipping plot with only one entry (strange error otherwise...).'\n % (configname_value, p1_key, p1_value))\n continue\n\n means = subsubdf[['mbmean', 'mimean', 'ttn']].copy()\n\n # if we only have upper and lower bounds for the minimal intersections, means will be NaN\n means['mimean'] = means['mimean'].fillna(0)\n\n errors = [\n [means['mbmean'] - subsubdf['mbmin'], subsubdf['mbmax'] - means['mbmean']],\n [means['mimean'] - subsubdf['mimin'], subsubdf['mimax'] - means['mimean']],\n [means['ttn'] - means['ttn'], means['ttn'] - means['ttn']],\n ]\n\n means.plot(kind='bar', yerr=errors)\n plt.savefig(path.join(folder_path, 'plot_%s_%s%d.pdf' % (configname_value, p1_key, p1_value)))\n","sub_path":"scripts/csv_to_plots.py","file_name":"csv_to_plots.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"521981640","text":"\"\"\" \nThis program creates a singly linked list \nclass with a nested inner class for nodes.\n@author Chase Fleming\n@date 4/20/16\n\"\"\"\n\nimport sys\n\n__all__ = [\"append\", \"delete\", \"getSize\", \"LLPrint\"]\n\nclass LinkedList(object):\n\n def __init__(self):\n self.head = self.Node()\n self._tail = self.head\n self._size = 0\n \n def append(self, value):\n \"\"\" Appends a value to the end of the linked list. \"\"\"\n add = self.Node(value)\n temp = self._tail\n temp.next = add\n self._tail = temp.next\n self._size = self._size + 1\n return\n \n def delete(self, value=None):\n \"\"\" Deletes the first element of the linked list if value is not passed,\n otherwise attempts to find a node with the value and delete it. \"\"\"\n if self._size == 0:\n return \n elif value == None:\n self.head.next = self.head.next.next\n self._size = self._size - 1\n if self._size == 0:\n self._tail = self.head\n return\n else:\n temp = self.head\n while temp.next != None:\n if temp.next.getValue() == value:\n if self._tail == temp.next:\n self._tail = temp\n temp.next = temp.next.next\n self._size = self._size - 1\n return \n temp = temp.next\n return\n \n def getSize(self):\n \"\"\" Returns the size of the linked list. \"\"\"\n return self._size\n \n def LLPrint(self):\n \"\"\" Prints the linked list in a single line. \"\"\"\n temp = self.head\n while temp.next != None:\n sys.stdout.write(str(temp.next) + \" \")\n temp = temp.next\n print\n return\n \n \n class Node(object):\n \n def __init__(self, value=None, nextnode=None): \n self._val = value\n self.next = nextnode\n \n def getValue(self):\n \"\"\" Returns the value of the Node. \"\"\"\n return self._val\n \n def __str__(self):\n \"\"\" @override returns a string representation of the Node. \"\"\"\n return str(self._val)\n","sub_path":"SLL.py","file_name":"SLL.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"477776491","text":"\n# 伪随机数:采用梅森旋转算法生成的(伪)随机序列中元素\n\nimport random\n# 基本随机数函数\nrandom.seed(10) # 产生种子10对应的序列,若不调用seed函数\nprint(random.random()) # 则默认使用系统时间,可再次调用\nprint(random.random())\n\n# 扩展随机数函数\nrandom.randint(10, 100)\nrandom.randrange(10, 100, 5) # 步长为5\nrandom.uniform(10, 100) # 10-100之间随机小数\nrandom.getrandbits(16) # 16bit长的随机整数\nrandom.choice([1, 3, 5, 8, 9, 20]) # 随机选一个\n# 打乱\ns = [1, 2, 3, 4, 5, 6, 7, 8]\nrandom.shuffle(s)\nprint(s)\n","sub_path":"random库.py","file_name":"random库.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"651318311","text":"from openerp import models, fields, api, _\nfrom openerp.exceptions import except_orm, Warning, RedirectWarning\nfrom openerp.tools import float_compare\nimport openerp.addons.decimal_precision as dp\n \nclass account_invoice_line(models.Model):\n _inherit = \"account.invoice.line\"\n\n shipping_lc = fields.Float(string='Landed Cost Multiplier')\n\n def _anglo_saxon_sale_move_lines(self, cr, uid, i_line, res, context=None):\n if i_line.move_id:\n if not i_line.move_id.picking_id.picking_type_id.is_dropship:\n return super(account_invoice_line, self)._anglo_saxon_sale_move_lines(cr, uid, i_line, res, context=context)\n return []\n\nclass account_invoice(models.Model):\n _inherit = \"account.invoice\"\n\n @api.multi \n def finalize_invoice_move_lines(self, move_lines):\n \n res = super(account_invoice, self).finalize_invoice_move_lines(move_lines)\n \n for line in self.invoice_line:\n flag = False\n # Check Dropship\n if line.move_id and line.move_id.picking_id.picking_type_id.is_dropship:\n # Prepare COGS account\n cogs = line.product_id.property_account_expense and line.product_id.property_account_expense.id\n if not cogs:\n cogs = line.product_id.categ_id.property_account_expense_categ and line.product_id.categ_id.property_account_expense_categ.id\n flag = True\n count = 0\n if self.type == 'in_invoice':\n for item in res:\n if line.product_id and item[2]['product_id'] == line.product_id.id:\n # Update move line with COGS account\n if flag:\n item[2]['account_id'] = cogs\n \n elif self.type == 'out_refund':\n continue\n\n else:\n for item in res:\n\n if count == 0:\n\n count += 1\n continue\n\n if line.product_id and item[2]['product_id'] == line.product_id.id:\n\n if item[2]['credit'] and res[count][2]['credit'] == res[count+1][2]['debit']:\n res[count][2]['credit'] = item[2]['credit']*(1+line.shipping_lc/100)\n\n elif item[2]['debit'] and res[count-1][2]['product_id'] == res[count][2]['product_id'] and res[count-1][2]['quantity'] == res[count][2]['quantity']:\n res[count][2]['debit'] = item[2]['debit']*(1+line.shipping_lc/100)\n\n count += 1\n return res ","sub_path":"ps_landed_cost/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"165773261","text":"import multiprocessing as mp\nimport sys,os,glob\nimport numpy as np\n\ndef runs(x):\n\tprint(x)\n\tos.system('npm start index.html \"%s\"'%x)\n\n\ndata = glob.glob('../*/*_data.csv')\n\nmp.Pool(4).map(runs,data)\n\n\n#make subplots\nwht = 'AE'\nfor f in glob.glob('../%s/*_data.csv'%wht):\n i = f.split('/')[-1]\n j = i.split('_')[0]\n \n sf = '''\\\\begin{subfigure}[b]{0.25\\\\linewidth}\n \\\\centering\n \\\\includegraphics[width=\\\\textwidth]{outputs/DRplots/plots/%s_%s}\n \\\\caption{%s}\n \\\\label{fig:%s_%s}\n\\\\end{subfigure}'''%(wht,i.replace('_data.csv','.png'),j,wht,j)\n print(sf)\n \n \n \n\ndirs = np.array([i.split('/') for i in glob.glob('../*/*/legend.png')])\n \nprint ('\\n\\n\\n\\n')\n \n\nfor f in dirs:\n wht = f[1]\n i = f[2]\n \n sf = '''\\\\begin{subfigure}[b]{0.22\\\\linewidth}\n \\\\centering\n \\\\includegraphics[height =\\textwidth,angle=-90]{outputs/%s/%s/legend.png}\n \\\\caption{%s}\n \\\\label{fig:legend_%s_%s}\n\\\\end{subfigure}'''%(wht,i,i,wht,i)\n print(sf)","sub_path":"dr/outputs/DRplots/automate.py","file_name":"automate.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"426314825","text":"\nimport theano\nimport theano.tensor as T\nfloatX = theano.config.floatX\n\nimport numpy as np\nfrom mozi.utils.theano_utils import sharedX, asfloatX\n\nclass LearningMethod(object):\n\n def update(self, delta, gparam):\n \"\"\"\n Return a list of tuples\n \"\"\"\n raise NotImplementedError(str(type(self))+\" does not implement delta.\")\n\n @property\n def learning_rate(self):\n return float(self.lr.get_value())\n\n @property\n def momentum(self):\n return float(self.mom.get_value())\n\nclass SGD(LearningMethod):\n\n def __init__(self, learning_rate=0.01, momentum=0.9, lr_decay_factor=0.9, decay_batch=10000):\n self.lr = sharedX(learning_rate)\n self.mom = sharedX(momentum)\n self.batch = sharedX(0)\n self.decay_batch = sharedX(decay_batch)\n self.lr_decay_factor = asfloatX(lr_decay_factor)\n\n def update(self, delta, gparam):\n self.batch += 1\n if T.gt(self.batch, self.decay_batch):\n self.lr.set_value(self.lr.get_value() * self.lr_decay_factor)\n self.batch = sharedX(0)\n\n return [(delta, self.mom * delta - self.lr * gparam)]\n\n\nclass AdaGrad(LearningMethod):\n\n def __init__(self, learning_rate=0.9, momentum=0., k=1.0, lr_decay_factor=0.9, decay_batch=10000):\n \"\"\"\n dx = -learning_rate / sqrt(k + sum(gparam^2)) * gparam\n ref : Chris Dyer : Notes on AdaGrad\n \"\"\"\n self.lr = sharedX(learning_rate)\n self.mom = sharedX(momentum)\n self.k = sharedX(k)\n\n def update(self, delta, gparam):\n rlist = []\n eps = theano.shared(self.k.get_value() * np.ones_like(delta.get_value(borrow=True, return_internal_type=True)))\n rlist.append((eps, eps + gparam ** 2))\n rlist.append((delta, self.mom * delta - self.lr * gparam / T.sqrt(eps)))\n return rlist\n\nclass AdaDelta(LearningMethod):\n\n def __init__(self, eps=1e-6, rho=0.95):\n \"\"\"\n dx_t = -rms(dx_{t-1}) / rms(gparam_t) * gparam_t\n rms(dx) = sqrt(E_t(dx^2) + eps)\n E_t(dx^s) = rho E_{t-1}(dx^2) + (1-rho) dx^2\n ref : Matthew D. Zeiler: ADADELTA: AN ADAPTIVE LEARNING RATE METHOD\n \"\"\"\n self.eps = sharedX(eps)\n self.rho = sharedX(rho)\n\n def update(self, delta, gparam):\n rlist = []\n gparam_mean = theano.shared(np.zeros_like(delta.get_value(borrow=True, return_internal_type=True)))\n rlist.append((gparam_mean, self.rho * gparam_mean + (1-self.rho) * gparam**2))\n delta_mean = theano.shared(np.zeros_like(delta.get_value(borrow=True, return_internal_type=True)))\n rlist.append((delta_mean, self.rho * delta_mean + (1-self.rho) * delta**2))\n rlist.append((delta, -T.sqrt(delta_mean+self.eps) / T.sqrt(gparam_mean+self.eps) * gparam))\n return rlist\n","sub_path":"mozi/learning_method.py","file_name":"learning_method.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"306673851","text":"from nvidia.dali.plugin.pytorch import DALIGenericIterator\n\n\ndef get_train_loader(config, Dataset, split_name):\n num_gpus = 1\n if split_name == \"train\":\n pipes = [Dataset(config[\"batch_size\"], 2, device_id, num_gpus, split_name) for device_id in range(num_gpus)]\n else:\n pipes = [Dataset(1, 2, device_id, num_gpus, split_name) for device_id in range(num_gpus)]\n pipes[0].build()\n \n if split_name in [\"train\", \"val\"]:\n dali_iter = DALIGenericIterator(pipelines=pipes, output_map=['data', 'label', 'fn'], reader_name=\"img_Reader\",\n auto_reset=True, fill_last_batch=False, dynamic_shape=False)\n else:\n dali_iter = DALIGenericIterator(pipelines=pipes, output_map=['data', 'fn'], reader_name=\"img_Reader\",\n auto_reset=True, fill_last_batch=False, dynamic_shape=False)\n \n return dali_iter\n\n\n\n\n# import cv2\n# cv2.setNumThreads(0)\n# from torch.utils import data\n\n# from utils.img_utils import random_scale, random_mirror, normalize, generate_random_crop_pos, random_crop_pad_to_shape\n\n\n# class TrainPre(object):\n# def __init__(self, config, img_mean, img_std):\n# self.img_mean = img_mean\n# self.img_std = img_std\n# self.config = config\n\n# def __call__(self, img, gt):\n# img, gt = random_mirror(img, gt)\n# if self.config.train_scale_array is not None:\n# img, gt, scale = random_scale(img, gt, self.config.train_scale_array)\n\n# img = normalize(img, self.img_mean, self.img_std)\n\n# crop_size = (self.config.image_height, self.config.image_width)\n# crop_pos = generate_random_crop_pos(img.shape[:2], crop_size)\n# p_img, _ = random_crop_pad_to_shape(img, crop_pos, crop_size, 0)\n# p_gt, _ = random_crop_pad_to_shape(gt, crop_pos, crop_size, 255)\n# p_gt = cv2.resize(p_gt, (self.config.image_width // self.config.gt_down_sampling, self.config.image_height // self.config.gt_down_sampling), interpolation=cv2.INTER_NEAREST)\n\n# p_img = p_img.transpose(2, 0, 1)\n\n# extra_dict = None\n\n# return p_img, p_gt, extra_dict\n\n\n# def get_train_loader(config, dataset, portion=None, worker=None, test=False):\n# data_setting = {'img_root': config.img_root_folder,\n# 'gt_root': config.gt_root_folder,\n# 'train_source': config.train_source,\n# 'eval_source': config.eval_source,\n# 'down_sampling': config.down_sampling,\n# 'portion': portion}\n# if test:\n# data_setting = {'img_root': config.img_root_folder,\n# 'gt_root': config.gt_root_folder,\n# 'train_source': config.train_eval_source,\n# 'eval_source': config.eval_source,\n# 'down_sampling': config.down_sampling,\n# 'portion': portion}\n# train_preprocess = TrainPre(config, config.image_mean, config.image_std)\n\n# train_dataset = dataset(data_setting, \"train\", train_preprocess, config.batch_size * config.niters_per_epoch)\n\n# is_shuffle = True\n# batch_size = config.batch_size\n\n# train_loader = data.DataLoader(train_dataset,\n# batch_size=batch_size,\n# num_workers=config.num_workers if worker is None else worker,\n# drop_last=True,\n# shuffle=is_shuffle,\n# pin_memory=True)\n\n# return train_loader\n","sub_path":"models/FasterSeg/train/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"525125072","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\nkeyword= 'ring'\n#page_number= '5'\nresults=[]\n\nheaders= {\n 'user-agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0'\n}\n\nfor i in range(1,11):\n #r = requests.get(' https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2334524.m570.l1313&_nkw='+keyword)\n r=requests.get('https://www.ebay.com/sch/i.html?_from=R40&_nkw='+keyword+'_pgn='+str(i), headers=headers)\n print('r.statuscode=', r.status_code) \n\n soup = BeautifulSoup(r.text, 'html.parser')\n\n '''\n\n items = soup.select('.s-item__title')\n for item in items:\n print('item=', item.text) \n\n prices = soup.select('.clearfix.srp-list.srp-results > li.s-item > .clearfix.s-item__wrapper > .clearfix.s-item__info > .clearfix.s-item__details > div.s-item__detail--primary.s-item__detail > .s-item__price')\n for price in prices:\n print('price=', price.text )\n\n statuses = soup.select('.SECONDARY_INFO')\n for status in statuses:\n print('status=', status.text)\n '''\n\n boxes = soup.select('.clearfix.srp-list.srp-results > li.s-item > .clearfix.s-item__wrapper')\n for box in boxes:\n #print('--- ')\n result= {}\n titles = box.select('.s-item__title')\n for title in titles:\n #print('title=', title.text)\n result['title'] =title.text \n prices = box.select('.clearfix.srp-list.srp-results > li.s-item > .clearfix.s-item__wrapper > .clearfix.s-item__info > .clearfix.s-item__details > div.s-item__detail--primary.s-item__detail > .s-item__price')\n for price in prices:\n #print('price=', price.text )\n result['price']= price.text\n statuses = box.select('.SECONDARY_INFO')\n for status in statuses:\n #print('status=', status.text)\n result['status']= status.text\n #print('results=', result)\n results.append(result)\n\n print('len(results)=', len(results))\n\nj= json.dumps(results)\nwith open('items.json', 'w') as f:\n f.write(j)\n#print('j=', j)\n","sub_path":"hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"444766438","text":"from django.test import TestCase\nfrom .models import Session\nfrom django.urls import reverse\nfrom django.utils import timezone\nimport requests\nimport json\n# Create your tests here.\n\n\nclass IndexViewTests(TestCase):\n\n def test_no_sessions(self):\n response = self.client.get(reverse('index'))\n self.assertContains(response, \"No sessions on record\")\n\n def test_one_session(self):\n Session(session_id=5, name=\"Test Session\").save()\n response = self.client.get(reverse('index'))\n self.assertContains(response, \"Test Session\")\n self.assertQuerysetEqual(\n response.context['session_list'],\n ['']\n )\n\nclass SessionModelTests(TestCase):\n def test_is_fixed_no_measurements(self):\n s = Session(session_id=69, name=\"No Measurement\")\n self.assertEqual(s.is_fixed(),False)\n\n def test_is_fixed_unfixed_measurement(self):\n s = Session(session_id=69, name=\"Unfixed\")\n s.save()\n m = s.measurement_set.create(gas_high=100,gas_avg=1)\n self.assertEqual(m.latitude,None)\n self.assertEqual(m.longitude,None)\n self.assertEqual(s.is_fixed(),False)\n\n def test_is_fixed_fixed_measurement(self):\n s = Session(session_id=69, name=\"Fixed\")\n s.save()\n m = s.measurement_set.create(gas_high=100,gas_avg=1, latitude=90, longitude=45)\n\n self.assertEqual(m.latitude,90)\n self.assertEqual(m.longitude,45)\n self.assertEqual(s.is_fixed(),True)\n\n def test_is_fixed_unfixed_fixed(self):\n s = Session(session_id=69, name=\"Unfixed then fixed\")\n s.save()\n unfixed = s.measurement_set.create(gas_high=100,gas_avg=1)\n fixed = s.measurement_set.create(gas_high=100,gas_avg=1, latitude=90, longitude=45)\n\n self.assertEqual(s.is_fixed(),True)\n\n def test_first_fixed_no_measurements(self):\n s = Session(session_id=69, name=\"No Measurement\")\n self.assertEqual(s.get_first_fix(),None)\n\n def test_first_fixed_unfixed_measurement(self):\n s = Session(session_id=69, name=\"Unfixed\")\n s.save()\n m = s.measurement_set.create(gas_high=100,gas_avg=1)\n self.assertEqual(s.get_first_fix(),None)\n self.assertEqual(m.is_fixed(),False)\n\n def test_first_fixed_fixed_measurement(self):\n s = Session(session_id=69, name=\"Fixed\")\n s.save()\n m = s.measurement_set.create(gas_high=100,gas_avg=1, latitude=90, longitude=45)\n\n self.assertEqual(m,s.get_first_fix())\n self.assertEqual(m.is_fixed(),True)\n\n def test_first_fixed_unfixed_fixed(self):\n s = Session(session_id=69, name=\"Unfixed then fixed\")\n s.save()\n unfixed = s.measurement_set.create(gas_high=100,gas_avg=1)\n fixed = s.measurement_set.create(gas_high=100,gas_avg=1, latitude=90, longitude=45)\n\n self.assertEqual(s.get_first_fix(),fixed)\n self.assertEqual(unfixed.is_fixed(),False)\n self.assertEqual(fixed.is_fixed(),True)\n\n def test_first_fixed_two_fixed(self):\n s = Session(session_id=69, name=\"Unfixed then fixed\")\n s.save()\n fixed1 = s.measurement_set.create(gas_high=100,gas_avg=1, latitude=90, longitude=45)\n fixed2 = s.measurement_set.create(gas_high=100,gas_avg=1, latitude=90, longitude=45)\n\n self.assertEqual(fixed1,s.get_first_fix())\n\nclass PostViewTests(TestCase):\n def test_post_into_database(self):\n data = {\n 'session_id': 69,\n 'gas_avg':100,\n 'gas_high': 420,\n 'latitude': 4.13,\n 'longitude': 80.08,\n 'date_time': '2020-07-13 20:30:00'\n }\n headers = {'content-type':'application/json'}\n self.client.post(reverse('readings:post'), content_type='application/json',data=data)\n\n\n session=Session.objects.get(session_id=69)\n measurement=session.measurement_set.last()\n local_date_time = timezone.localtime(measurement.date_time)\n self.assertEqual(session.session_id, 69)\n self.assertEqual(measurement.gas_avg, 100)\n self.assertEqual(measurement.gas_high,420)\n self.assertEqual(measurement.latitude,4.13)\n self.assertEqual(measurement.longitude,80.08)\n self.assertEqual(measurement.date_time.day,13)\n self.assertEqual(measurement.date_time.month,7)\n self.assertEqual(measurement.date_time.year,2020)\n self.assertEqual(measurement.date_time.hour,20)\n self.assertEqual(measurement.date_time.minute,30)\n self.assertEqual(measurement.date_time.second,00)\n","sub_path":"Web Application/gasmon/readings/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"384095646","text":"import pendulum\nfrom dateutil.relativedelta import relativedelta\nfrom flask import current_app as app\n\nimport tests.factories as factories\nfrom atat.forms.task_order import CLINForm, TaskOrderForm\nfrom atat.models import JEDICLINType\nfrom atat.utils.localization import translate\n\n\ndef test_clin_form_jedi_clin_type():\n jedi_type = JEDICLINType.JEDI_CLIN_2\n clin = factories.CLINFactory.create(jedi_clin_type=jedi_type)\n clin_form = CLINForm(obj=clin)\n assert clin_form.jedi_clin_type.data == jedi_type.value\n\n\ndef test_clin_form_start_date_before_end_date():\n invalid_start = pendulum.date(2020, 12, 12)\n invalid_end = pendulum.date(2020, 1, 1)\n invalid_clin = factories.CLINFactory.create(\n start_date=invalid_start, end_date=invalid_end\n )\n clin_form = CLINForm(obj=invalid_clin)\n assert not clin_form.validate()\n assert (\n translate(\"forms.task_order.pop_errors.date_order\")\n in clin_form.start_date.errors\n )\n valid_start = pendulum.date(2020, 1, 1)\n valid_end = pendulum.date(2020, 12, 12)\n valid_clin = factories.CLINFactory.create(\n start_date=valid_start, end_date=valid_end\n )\n valid_clin_form = CLINForm(obj=valid_clin)\n assert valid_clin_form.validate()\n\n\ndef test_clin_form_pop_dates_within_contract_dates():\n CONTRACT_START_DATE = app.config.get(\"CONTRACT_START_DATE\")\n CONTRACT_END_DATE = app.config.get(\"CONTRACT_END_DATE\")\n\n invalid_start = CONTRACT_START_DATE - relativedelta(months=1)\n invalid_end = CONTRACT_END_DATE + relativedelta(months=1)\n invalid_clin = factories.CLINFactory.create(\n start_date=invalid_start, end_date=invalid_end\n )\n clin_form = CLINForm(obj=invalid_clin)\n\n assert not clin_form.validate()\n assert (\n translate(\n \"forms.task_order.pop_errors.range\",\n {\n \"start\": CONTRACT_START_DATE.strftime(\"%b %d, %Y\"),\n \"end\": CONTRACT_END_DATE.strftime(\"%b %d, %Y\"),\n },\n )\n ) in clin_form.start_date.errors\n assert (\n translate(\n \"forms.task_order.pop_errors.range\",\n {\n \"start\": CONTRACT_START_DATE.strftime(\"%b %d, %Y\"),\n \"end\": CONTRACT_END_DATE.strftime(\"%b %d, %Y\"),\n },\n )\n ) in clin_form.end_date.errors\n\n valid_start = CONTRACT_START_DATE + relativedelta(months=1)\n valid_end = CONTRACT_END_DATE - relativedelta(months=1)\n valid_clin = factories.CLINFactory.create(\n start_date=valid_start, end_date=valid_end\n )\n valid_clin_form = CLINForm(obj=valid_clin)\n assert valid_clin_form.validate()\n\n\ndef test_clin_form_obligated_greater_than_total():\n invalid_clin = factories.CLINFactory.create(\n total_amount=0,\n obligated_amount=1,\n start_date=pendulum.date(2019, 9, 15),\n end_date=pendulum.date(2020, 9, 14),\n )\n invalid_clin_form = CLINForm(obj=invalid_clin)\n assert not invalid_clin_form.validate()\n assert (\n translate(\"forms.task_order.clin_funding_errors.obligated_amount_error\")\n ) in invalid_clin_form.obligated_amount.errors\n\n\ndef test_clin_form_dollar_amounts_out_of_range():\n invalid_clin = factories.CLINFactory.create(\n total_amount=-1,\n obligated_amount=1000000001,\n start_date=pendulum.date(2019, 9, 15),\n end_date=pendulum.date(2020, 9, 14),\n )\n invalid_clin_form = CLINForm(obj=invalid_clin)\n assert not invalid_clin_form.validate()\n assert (\n translate(\"forms.task_order.clin_funding_errors.funding_range_error\")\n ) in invalid_clin_form.total_amount.errors\n assert (\n translate(\"forms.task_order.clin_funding_errors.funding_range_error\")\n ) in invalid_clin_form.obligated_amount.errors\n\n\ndef test_no_number():\n http_request_form_data = {}\n form = TaskOrderForm(http_request_form_data)\n assert form.data[\"number\"] is None\n\n\ndef test_number_allows_alphanumeric():\n valid_to_numbers = [\"1234567890123\", \"ABC1234567890\"]\n\n for number in valid_to_numbers:\n form = TaskOrderForm({\"number\": number})\n assert form.validate()\n\n\ndef test_number_allows_between_13_and_17_characters():\n valid_to_numbers = [\"123456789012345\", \"ABCDEFG1234567890\"]\n\n for number in valid_to_numbers:\n form = TaskOrderForm({\"number\": number})\n assert form.validate()\n\n\ndef test_number_strips_dashes():\n valid_to_numbers = [\"123-456789-012345\", \"ABCD-EFG12345-67890\"]\n\n for number in valid_to_numbers:\n form = TaskOrderForm({\"number\": number})\n assert form.validate()\n assert not \"-\" in form.number.data\n\n\ndef test_number_case_coerces_all_caps():\n valid_to_numbers = [\"12345678012345\", \"AbcEFg1234567890\"]\n\n for number in valid_to_numbers:\n form = TaskOrderForm({\"number\": number})\n assert form.validate()\n assert form.number.data == number.upper()\n","sub_path":"tests/forms/test_task_order.py","file_name":"test_task_order.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"48975735","text":"import numpy as np\nimport logging\nfrom itertools import product\nfrom copy import copy\nimport random\n\n\nclass FreqBandit:\n\n def __init__(self, num_pops, num_strats, num_players, max_payoff=1, min_payoff=0, delta=0.1, alpha_rank_func=None,mask=None):\n self.num_pops = num_pops\n self.num_strats = num_strats\n self.num_players = num_players\n\n assert alpha_rank_func is not None\n self.alpha_rank = alpha_rank_func\n\n self.delta = delta\n self.range = max_payoff - min_payoff\n print(\"range:\",self.range)\n shape = (num_pops, *[num_strats for _ in range(num_players)])\n self.means = np.zeros(shape=shape)\n self.counts = np.zeros(shape=shape)\n\n self.logger = logging.getLogger(\"Freq_Bandit\")\n np.random.seed()\n\n self.unresolved_pairs = set()\n if self.num_pops == 1:\n for i in range(num_strats):\n for j in range(num_strats):\n #if i == j:\n # self.means[0,i,j]=0.5\n # continue\n if (mask is not None) and((i,j) not in mask):\n continue\n self.unresolved_pairs.add((\n (i, j),\n (j, i),\n 0\n ))\n else:\n for base_strat in product(range(num_strats), repeat=num_players):\n for n in range(num_players):\n # For each player that can deviate\n for strat_index in range(num_strats):\n # For each strategy they can change to\n if strat_index == base_strat[n]:\n continue # Not a different strategy, move on\n new_strat = copy(list(base_strat))\n new_strat[n] = strat_index\n new_strat = tuple(new_strat)\n for p in range(num_pops):\n # For each payoff entry in the #num_pop matrices for this deviation\n\n # Unresolved pair is base_strat, new_strat, payoff_matrix\n unresolved_pair = (base_strat, new_strat, p)\n self.unresolved_pairs.add(unresolved_pair)\n\n def choose_entry_to_sample(self):\n if len(self.unresolved_pairs) == 0:\n return None, {}\n self.logger.debug(\"Unresolved pairs has {} elements\".format(len(self.unresolved_pairs)))\n\n # Uniformly pick a an unresolved pair and uniformly pick a strategy\n pair = random.sample(self.unresolved_pairs, k=1)[0]#from list select one\n #print(\"pair:\",pair)\n\n strat = pair[0]#[random.randint(0, 1)]\n #print('strat:',strat)\n return strat, {}\n\n def update_entry(self, strats, payoffs):\n # Update the entries for the strategy\n strats_=[]\n strats_.append(strats[1])\n strats_.append(strats[0])\n strats_=tuple(strats_)\n #print('strats_:',strats_)\n #print('strats:',strats)\n K=10 #This parameter corresponds to the number of independent repetitions in game.py\n\n for player, payoff in enumerate(payoffs):\n self.counts[player][tuple(strats)] += K\n #self.counts[player][tuple(strats_)]+= 100\n N = self.counts[player][tuple(strats)]\n self.means[player][tuple(strats)] = ((N - K) * self.means[player][tuple(strats)] + payoff) / N\n #N = self.counts[player][tuple(strats_)]\n #self.means[player][tuple(strats_)] = ((N - 100) * self.means[player][tuple(strats_)] + 100-payoff) / N\n\n # Update the unresolved strategy pairs\n # Brute force for now\n pairs_to_remove = set()\n tocheck=set()\n tocheck.add((strats,strats_,0))\n tocheck.add((strats,strats_,0))\n for pair in tocheck:#self.unresolved_pairs:\n base_strat, new_strat, p = pair\n # Test if the confidence intervals don't overlap\n bm = self.means[p][tuple(base_strat)]\n bc = self.counts[p][tuple(base_strat)]\n nm = self.means[p][tuple(new_strat)]\n nc = self.counts[p][tuple(new_strat)]\n if bc == 0 or nc == 0:\n continue # We have no observed evaluations, CI overlaps\n bi = np.sqrt((np.log(2 / self.delta) * (self.range ** 2)) / (2 * bc))\n base_lower = bm - bi\n base_upper = bm + bi\n ni = np.sqrt((np.log(2 / self.delta) * (self.range ** 2)) / (2 * nc))\n new_lower = nm - ni\n new_upper = nm + ni\n\n if bm >= nm and new_upper > base_lower:\n pass\n elif bm < nm and base_upper > new_lower:\n pass\n else:\n # Remove the pair\n pairs_to_remove.add(pair)\n\n self.logger.debug(\n \"Removing {} elements. After seeing {} with payoffs {}\".format(len(pairs_to_remove), strats, payoffs))\n for pair_to_remove in pairs_to_remove:\n self.unresolved_pairs.discard(pair_to_remove)\n\n def sample(self):\n # Sample from the distribution over payoff entries\n # Uniform over the confidence interval\n counts = np.maximum(self.counts, 1)\n interval = np.sqrt((np.log(2 / self.delta) * (self.range ** 2)) / (2 * counts))\n\n min_vals = self.means - interval\n max_vals = self.means + interval\n\n sampled_values = np.random.rand(*self.means.shape) * (max_vals - min_vals) + min_vals\n\n return sampled_values\n\n def alpha_rankings_distrib(self, graph_samples=None, mean=False):\n # Return the alpha rank of the mean payoff matrix\n phi = self.alpha_rank(self.means)\n if mean:\n return np.array(phi)\n else:\n samples = [self.sample() for _ in range(graph_samples)]\n phis = [self.alpha_rank(p) for p in samples]\n return np.array(phis), np.array([phi])\n\n def payoff_distrib(self):\n return np.copy(self.means), np.zeros_like(self.means)\n #def get_stop(self):\n # if","sub_path":"PayoffwithNoisy/RGUCB.py","file_name":"RGUCB.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"90127410","text":"import discord\nimport random\nfrom random import randint\nfrom discord.ext import commands\n\nclass Rolls(commands.Cog):\n\tdef __init__(self, client):\n\t\tself.client = client\n\t\t\n\t@commands.command()\n\tasync def r(self, ctx, dice='d20'):\n\t\tprefix = ['Managed to roll ',\n\t\t\t\t 'Landed on ',\n\t\t\t\t 'Rolled ']\n\t\tdef grammar(roll):\n\t\t\tdefinite = 'an'\n\t\t\tanvalues = [8, 11, 18]\n\t\t\tif roll in anvalues:\n\t\t\t\treturnval = f'{definite} {roll}.'\n\t\t\telse:\n\t\t\t\treturnval = f'{definite[:1]} {roll}.'\n\t\t\treturn returnval\n\t\tif '+' in dice:\n\t\t\tdice_die, dice_modifier = dice.split('+')\n\t\telif '-' in dice:\n\t\t\tdice_die, dice_modiier = dice.split('-')\n\t\telse:\n\t\t\tdice_die = dice\n\t\t\tdice_modifier = 0\n\t\tif dice_die[0] != 'd':\n\t\t\tdice_coefficient, dice_value = dice_die.split('d')\n\t\telse:\n\t\t\tdice_coefficient = 1\n\t\t\tdice_value = dice_die[1:]\n\t\tawait ctx.channel.send(f'{random.choice(prefix)}{grammar(randint(int(dice_modifier) + 1, int(dice_coefficient)*int(dice_value) + int(dice_modifier)))}')\n\t\t\ndef setup(client):\n\tclient.add_cog(Rolls(client))\n","sub_path":"cogs/roll.py","file_name":"roll.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"575960062","text":"# Copyright 2015 IBM Corp.\n# Copyright 2015, Hewlett-Packard Development Company, L.P.\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\nfrom django.conf import settings\nfrom django.views import generic\n\nfrom horizon import conf\n\nfrom openstack_dashboard.api.rest import urls\nfrom openstack_dashboard.api.rest import utils as rest_utils\n\n\n# properties we know are admin config\nadmin_configs = ['ajax_queue_limit', 'ajax_poll_interval',\n 'user_home', 'help_url',\n 'password_autocomplete', 'disable_password_reveal']\n\n# settings that we allow to be retrieved via REST API\n# these settings are available to the client and are not secured.\n# *** THEY SHOULD BE TREATED WITH EXTREME CAUTION ***\nsettings_required = getattr(settings, 'REST_API_REQUIRED_SETTINGS', [])\nsettings_additional = getattr(settings, 'REST_API_ADDITIONAL_SETTINGS', [])\n\nsettings_allowed = settings_required + settings_additional\n\n# properties we know are user config\n# this is a white list of keys under HORIZON_CONFIG in settings.pys\n# that we want to pass onto client\nuser_configs = ['auto_fade_alerts', 'modal_backdrop']\n\n\n@urls.register\nclass DefaultUserConfigs(generic.View):\n \"\"\"API for retrieving user configurations.\n\n This API returns read-only-default configuration values.\n This configuration object is ideally fetched once per application life\n or when a user needs to restore the default values.\n Examples of user config: modal_backdrop, disable_password_reveal\n \"\"\"\n url_regex = r'config/user/$'\n\n @rest_utils.ajax()\n def get(self, request):\n \"\"\"Get default user configurations\n \"\"\"\n config = {}\n for key in user_configs:\n config[key] = conf.HORIZON_CONFIG.get(key, None)\n return config\n\n\n@urls.register\nclass AdminConfigs(generic.View):\n \"\"\"API for retrieving admin configurations.\n\n This API returns read-only admin configuration values.\n This configuration object can be fetched as needed.\n Examples of admin config: help_url, user_home\n \"\"\"\n url_regex = r'config/admin/$'\n\n @rest_utils.ajax()\n def get(self, request):\n \"\"\"Get read-only admin configurations\n \"\"\"\n config = {}\n for key in admin_configs:\n config[key] = conf.HORIZON_CONFIG.get(key, None)\n return config\n\n\n@urls.register\nclass Settings(generic.View):\n \"\"\"API for retrieving settings.\n\n This API returns read-only settings values.\n This configuration object can be fetched as needed.\n Examples of settings: OPENSTACK_HYPERVISOR_FEATURES\n \"\"\"\n url_regex = r'settings/$'\n\n @rest_utils.ajax()\n def get(self, request):\n return {k: getattr(settings, k, None) for k in settings_allowed}\n","sub_path":"horizon/openstack_dashboard/api/rest/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"489317309","text":"# create a slide show quickly\n\nimport yaml\nimport markdown\nimport re\nimport time\nimport codecs\n\n# import the configs\nf = open('config.yaml')\nconfig = yaml.load(f)\nf.close()\nfilename = config['filename']\ntheme = config['theme']\ntitle = config['meta']['title']\nsubtitle = config['meta']['subtitle']\nauthor = config['meta']['author']\nemail = config['meta']['email']\norganization = config['meta']['organization']\ngooglefonts = config['googlefonts']\nnavi_enable = config['slide']['navi']\nribbon_enable = config['slide']['ribbon']\n\n# read the markdown file and convert it to html\nfmd = codecs.open(filename, mode=\"r\", encoding=\"utf8\")\ntext = fmd.read()\nhtml = markdown.markdown(text)\n\n\n\ncontent = '''\n \n\n \n \n ''' \ncontent += title\n\ncontent += '''\n \n\n \n\n \n \n \n \n \n'''\n# set up fonts\n\nif googlefonts:\n content += '''\n \n'''\n\n\n# set up theme\n\ncontent +=''' \n \n \n '''\n\n\n# navi bar\n\nif navi_enable:\n content += '''\n
'''\n # get the headlines ready \n headlines = re.compile(r'

.+

').findall(html)\n if headlines: \n for i in range(len(headlines)):\n headlines[i] = headlines[i][4:-5]\n for h in headlines:\n content += (\"\" + h + \"\")\n content += '''\n
'''\n\ncontent += '''\n
\n
\n\t
''' \n\n# set up the first slide with meta infomations\n \ncontent += title\n\ncontent += '''
\n\t
'''\ncontent += subtitle\n\ncontent += '''
\n
\n\t
''' \ncontent += author\n\n\nif email:\n content += '''
\n\t
'''\n content += email\n\nif organization:\n content += '''
\n
'''\n content += organization\n \ncontent += '''
\n
'''\ncontent += time.strftime(\"%Y-%m-%d\", time.localtime())\n\n\ncontent += '''
\n
'''\ncontent += theme\n\n\ncontent += ''' theme
\n
\n'''\n\n# Markdown Starts\n\n# a little trick here\n\nhtml = html.replace('

', '
\\n

')\nhtml = html.replace('

', '
\\n

')\np = re.compile(r'
')\nslides = p.split(html)\nslides.remove('')\nfor one in slides:\n content += '''\n
'''\n content += one\n content += '''\n
'''\n\n# Markdown Ends\n\n\ncontent += '''\n
\n
Thanks!
\n
\n

\n \n \n '''\n\nif ribbon_enable:\n content += '''\n \"Fork'''\n\n content += '''\n \n'''\n\n\nfslide = codecs.open('index.html', mode=\"w\", encoding=\"utf8\")\nfslide.write(content)\nfslide.close()\n","sub_path":"bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"191679496","text":"import numpy as np\nfrom numpy import random as rnd\nimport random\nfrom matplotlib import pyplot as plt\nimport torch\nimport torch.nn\n\n# ## First, tabular Q-learning\n# game from Shaked Zychlinski\n#\n# https://github.com/shakedzy/notebooks/blob/master/q_learning_and_dqn/Q%20Learning%20and%20Deep%20Q%20Network.ipynb\n#\n# and structure inspired by Gaston Sivori, Okinawa Institute of Science and Technology\nclass Environment:\n \"\"\"\n A generalizable class for board environments for Qlearning agents\n \"\"\"\n\n board = None\n board_size = 0\n\n def __init__(self, board_size=4):\n self.board_size = board_size\n self.game_over = False\n self.terminal_state = np.ones(4).astype(int)\n self.reset()\n\n def reset(self): # new game\n self.state = np.zeros(self.board_size).astype(\n int\n ) # [0,0,0,0,...0]: an empty board\n self.game_over = False\n\n def execute_action(self, action): # execute the agent's action\n if self.state[action] == 0:\n self.state[action] = 1\n self.game_over = len(np.where(self.state == 0)[0]) == 0\n return 1\n else:\n return -1\n\n\nclass Agent:\n \"\"\"\n A generalizable calss for Q learning agents in our game environment\n \"\"\"\n\n def __init__(self, board_size):\n # this qdim definition looks a bit hairy, but is just saying we want a qtable w/ dimensions like [2,2,2,2,4]\n # meaning that there are boardsize binary states and boardsize actions we can take in the last index\n qdim = tuple([2] * board_size) + (board_size,)\n self.Q = np.zeros(\n qdim\n ) # just make 4x1 games for now: 4 actions per 2^4 possible game states\n self.epsilon = 0.9 # exploration rate\n self.gamma = 0.9 # discount\n self.lr = 0.1 # learning rate\n\n def select_action(self, state):\n if rnd.rand() < self.epsilon: # take a greedy action\n return np.argmax(self.Q[tuple(state)])\n else:\n return random.choice(list(range(board_size))) # take a random action\n\n def greedy_action(self, state):\n return np.argmax(self.Q[tuple(state)])\n\n def update(self, old_state, new_state, action, reward):\n q_old = self.Q[tuple(old_state) + (action,)] # Old Q value\n future_action = self.greedy_action(new_state) # Select next best action\n\n EV_new = self.Q[\n tuple(new_state) + (future_action,)\n ] # What is reward for the best next action?\n\n if sum(new_state) == board_size:\n EV_new = 0 # we are in a terminal state, so EV not a meaningful value\n\n rpe = self.lr * (reward + self.gamma * EV_new - q_old)\n\n self.Q[tuple(old_state) + (action,)] += rpe # update\n\n\nclass RLInterface:\n \"\"\"\n A class that brings the Qlearning agent together with its environment\n \"\"\"\n\n def __init__(self, agent, environment):\n self.agent = agent\n self.env = environment\n self.rewlist = []\n\n def step(self): # advance one timestep\n old_state = env.state.copy() # take a copy of the agent's current state\n\n action = self.agent.select_action(old_state) # agent selects action\n rew = self.env.execute_action(\n action\n ) # execute agent action into the environment\n new_state = (\n env.state.copy()\n ) # find out what state this brought us to for new expected value approximation\n\n rpe = self.agent.update(old_state, new_state, action, rew) # update Q\n\n return rew\n\n def runTrials(self, nTrials): # run the agent and environment through nTrials games\n for i in range(nTrials):\n env.reset()\n total_rew = 0\n while not self.env.game_over:\n rew = self.step()\n total_rew += rew\n self.rewlist.append(total_rew)\n\n\nboard_size = 4 # default board size is 4\nagent = Agent(board_size)\nenv = Environment(board_size)\nrl = RLInterface(\n agent, env\n) # give the interface an agent and environment to bring together\n\nrl.runTrials(1000)\n\nplt.title(\"Reward Over time\")\nplt.xlabel(\"Game Number\")\nplt.ylabel(\"Rewards Received in Game\")\nplt.plot(rl.rewlist)\n\nimport torch\nimport torch.nn as nn\nimport torch.autograd as autograd\nimport torch.nn.functional as F\n\n\n# just a feed forward neural network to estimate Q(s,a) values\nclass DQN(nn.Module):\n def __init__(self, envstate_dim, action_dim):\n super(DQN, self).__init__()\n self.input_dim = envstate_dim\n self.output_dim = action_dim\n\n self.ff = nn.Sequential(\n nn.Linear(self.input_dim, 64),\n nn.ReLU(),\n nn.Linear(64, 124),\n nn.ReLU(),\n nn.Linear(124, 64),\n nn.ReLU(),\n nn.Linear(64, self.output_dim),\n )\n\n def forward(self, state):\n qvals = self.ff(state)\n return qvals\n\n\n# replay buffers implemented as lists. this is actually recommended by Python over Deques for random retrieval\nclass Buffer:\n def __init__(self):\n self.buffer = []\n\n def size(self):\n return len(self.buffer)\n\n # add a memory\n def push(self, state, action, new_state, reward):\n experience = (state, action, new_state, reward)\n self.buffer.append(experience)\n\n # take a random sample to perform learning on decorrelated transitions\n def sample(self, batch_size):\n batchSample = random.sample(self.buffer, batch_size)\n # now need to put everyone in the correct columns\n state_batch = []\n action_batch = []\n new_state_batch = []\n reward_batch = []\n\n # prepare the batch sample for training\n for experience in batchSample:\n state, action, new_state, reward = experience\n state_batch.append(state)\n action_batch.append(action)\n new_state_batch.append(new_state)\n reward_batch.append(reward)\n return (state_batch, action_batch, reward_batch, new_state_batch)\n\n\n# a class for agents that use feedforward neural networks to calculate Q(s,a)\nclass DeepAgent:\n def __init__(self, board_size):\n self.policy_net = DQN(\n board_size, board_size\n ) # network used to calculate policy\n self.target_net = DQN(\n board_size, board_size\n ) # network used to calculate target\n self.target_net.eval() # throw that baby in eval mode because we don't care about its gradients\n self.target_update = 50 # update our target network ever 50 timesteps\n self.replay_buffer = Buffer() # replay buffer implemented as a list\n self.eps_start = 0.1 # initial exploration rate\n self.eps_end = 0.95 # ultimate exploration value\n self.eps_decay = 300 # decay parameter for exploration rate\n self.epsilon = self.eps_start # initialize epsilon\n self.gamma = 0.99 # discount\n\n self.optimizer = torch.optim.SGD(\n self.policy_net.parameters(), lr=0.01, momentum=0.9\n )\n # self.optimizer = torch.optim.RMSprop(self.policy_net.parameters()) # experiment w/ different optimizers\n # self.optimizer = torch.optim.Adam(self.policy_net.parameters())\n self.huber_loss = F.smooth_l1_loss\n\n def select_action(self, state):\n state = torch.FloatTensor(state).float()\n if rnd.rand() < self.epsilon: # greedy action\n with torch.no_grad():\n qvals = self.policy_net.forward(\n state\n ) # forward run through the policy network\n action = np.argmax(\n qvals.detach().numpy()\n ) # need to detach from auto_grad before sending to numpy\n else:\n action = random.choice(list(range(board_size)))\n return action\n\n def update(self, batch_size):\n if self.replay_buffer.size() < batch_size:\n return\n batch = self.replay_buffer.sample(batch_size)\n\n self.optimizer.zero_grad() # zero_grad before computing loss\n\n loss = self.compute_loss(batch)\n\n loss.backward() # get the gradients\n\n for param in self.policy_net.parameters():\n param.grad.data.clamp_(-1, 1)\n\n self.optimizer.step() # backpropagate\n\n return loss\n\n def compute_loss(self, batch):\n states, actions, rewards, next_states = batch\n states = torch.FloatTensor(states)\n actions = torch.LongTensor(actions)\n rewards = torch.FloatTensor(rewards)\n next_states = torch.FloatTensor(next_states)\n\n curr_Q = self.policy_net.forward(states).gather(\n 1, actions.unsqueeze(1)\n ) # calculate the current Q(s,a) estimates\n next_Q = self.target_net.forward(next_states) # calculate Q'(s,a) (EV)\n max_next_Q = torch.max(next_Q, 1)[0] # equivalent of taking a greedy action\n expected_Q = rewards + self.gamma * max_next_Q # Calculate total Q(s,a)\n\n loss = self.huber_loss(\n curr_Q, expected_Q.unsqueeze(1)\n ) # unsqueeze is really important here to match dims!\n return loss\n\n\nclass DeepRLInterface:\n def __init__(self, agent, environment):\n self.agent = agent\n self.env = environment\n self.rewlist = []\n self.batch_size = 50 # sample 50 experiences when we update\n\n def step(self): # same process as above\n state = env.state.copy()\n action = self.agent.select_action(state) # agent selects action\n rew = self.env.execute_action(\n action\n ) # execute agent action into the environment\n new_state = env.state.copy()\n if not np.all(\n rl.env.state == rl.env.terminal_state\n ): # don't add terminal states to replay buffer\n self.agent.replay_buffer.push(state, action, new_state, rew)\n\n loss = self.agent.update(self.batch_size)\n self.losslist.append(loss) # append loss to assess performance over time\n return state, action, rew, new_state\n\n def runTrials(self, nTrials):\n counter = 0 # for batch training\n self.clist = []\n self.rewlist = []\n self.losslist = []\n self.eps = []\n for i in range(nTrials):\n env.reset()\n total_rew = 0\n tstates, tactions, trews, tnewstates = (\n [],\n [],\n [],\n [],\n ) # accumulate states to debug\n while (\n not self.env.game_over\n ): # while the game is not over, keep taking actions\n state, action, rew, new_state = self.step()\n total_rew += rew\n\n tstates.append(state)\n tactions.append(action)\n trews.append(rew)\n tnewstates.append(tnewstates)\n counter += 1\n\n self.rewlist.append(total_rew)\n\n if counter % self.agent.target_update == 0: # update the target network\n self.agent.target_net.load_state_dict(\n self.agent.policy_net.state_dict()\n )\n # update agent epsilon\n self.agent.epsilon = self.agent.eps_end + (\n self.agent.eps_start - self.agent.eps_end\n ) * np.exp(-1.0 * counter / self.agent.eps_decay)\n self.eps.append(self.agent.epsilon)\n\n\n# %%\nboard_size = 4\nagent = DeepAgent(board_size)\nenv = Environment(board_size)\nrl = DeepRLInterface(agent, env)\n\nrl.runTrials(500)\n\n\n# %%\n\n\nloss_list = [el for el in rl.losslist]\nloss_list_ = []\nfor el in loss_list:\n if type(el) == torch.Tensor:\n el = float(el.detach().numpy())\n loss_list_.append(el)\n\nrew_list = [el for el in rl.rewlist]\nrew_list_ = []\nfor el in rew_list:\n if type(el) == torch.Tensor:\n el = float(el.detach().numpy())\n rew_list_.append(el)\n\nplt.title(\"Batch Loss\")\nplt.plot(loss_list_)\nplt.xlabel(\"Timestep\")\nplt.ylabel(\"Loss\")\nplt.figure()\nplt.title(\"Game Rewards\")\nplt.xlabel(\"Game\")\nplt.ylabel(\"Accumulated Reward\")\nplt.plot(rew_list_)\n\n# Q values check out (this is for a boardsize = 4 case)\nfor state in [\n [0, 1, 1, 1],\n [1, 0, 1, 1],\n [1, 1, 0, 1],\n [1, 1, 1, 0],\n [0, 0, 1, 1],\n [0, 1, 0, 1],\n [1, 0, 0, 1],\n [0, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 1, 0],\n [0, 1, 0, 0],\n]:\n q = list(rl.agent.policy_net(torch.FloatTensor(state)).detach().numpy())\n argmax = np.argmax(\n list(rl.agent.policy_net(torch.FloatTensor(state)).detach().numpy())\n )\n print(\"Q values for state \", state, \": \", q, \"-> action\", argmax)\n","sub_path":"simpleDQN.py","file_name":"simpleDQN.py","file_ext":"py","file_size_in_byte":12641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"566025032","text":"from django.urls import path\nfrom book.views import index,login,get_cookie_01,set_session_01,get_session_01\nfrom book import views\nurlpatterns = [\n path('index/', index),\n path('login/', login),\n path('get_cookie_01/',get_cookie_01),\n path('set_session/',set_session_01),\n path('get_session/',get_session_01),\n path('register_method/',views.register_method),\n path('class+method/',views.RegisterView.as_view()),\n path('vue_template/',views.vue_template),\n # 中间件不需要设置路径,在SETTING注册,注册后不需有调用语句即可按照信息处理流程自行执行\n # path('TestMiddleware1/',views.TestMiddleware1.as_view()),\n]","sub_path":"bookmanage01/book/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"587713856","text":"# -*- coding: utf-8 -*-\n__author__ = \"Lee.li\"\n\nimport unittest\nfrom airtest.core.api import *\nfrom Script.skill import Skill\nfrom multi_processframe.Tools import initial, screenshot\n\n\ndef Main(devices):\n class TCSkillscholar(unittest.TestCase):\n u'''测试用例以下为学者分支的集合'''\n\n @classmethod\n def setUpClass(self):\n u''' 这里放需要在所有用例执行前执行的部分'''\n pass\n\n def setUp(self):\n u'''这里放需要在每条用例前执行的部分'''\n initial.startgame(devices)\n\n def test_scholar_1(self):\n \"\"\"\n 技能测试--学者转职--重炮手\n \"\"\"\n try:\n print(\"测试Prof5-转职为学者分支、工程师分支、重炮手分支\")\n self.assertEqual(\"重炮手\", Skill.test_scholar_1(devices))\n except:\n start_Screenshot = \"这里是启动报错场景截图的功能\"\n screenshot.get_screen_shot(time.time(), devices, \"学者角色技能测试脚本\")\n self.assertEqual(\"此条的信息请忽略\", start_Screenshot)\n\n\n\n def test_scholar_2(self):\n \"\"\"\n 技能测试--学者转职--机械大师\n \"\"\"\n try:\n print(\"测试Prof5-转职为学者分支、工程师分支、机械大师分支\")\n self.assertEqual(\"机械大师\", Skill.test_scholar_2(devices))\n except:\n start_Screenshot = \"这里是启动报错场景截图的功能\"\n screenshot.get_screen_shot(time.time(), devices, \"学者角色技能测试脚本\")\n self.assertEqual(\"此条的信息请忽略\", start_Screenshot)\n\n\n\n def test_scholar_3(self):\n \"\"\"\n 技能测试--学者转职--炼金圣士\n \"\"\"\n try:\n print(\"Prof5-转职为学者分支、炼金术士分支、炼金圣士分支\")\n self.assertEqual(\"炼金圣士\", Skill.test_scholar_3(devices))\n except:\n start_Screenshot = \"这里是启动报错场景截图的功能\"\n screenshot.get_screen_shot(time.time(), devices, \"学者角色技能测试脚本\")\n self.assertEqual(\"此条的信息请忽略\", start_Screenshot)\n\n\n\n def test_scholar_4(self):\n \"\"\"\n 技能测试--学者转职--药剂师\n \"\"\"\n try:\n print(\"Prof5-转职为学者分支、炼金术士分支、药剂师分支\")\n self.assertEqual(\"药剂师\", Skill.test_scholar_4(devices))\n except:\n start_Screenshot = \"这里是启动报错场景截图的功能\"\n screenshot.get_screen_shot(time.time(), devices, \"学者角色技能测试脚本\")\n self.assertEqual(\"此条的信息请忽略\", start_Screenshot)\n\n\n\n\n def tearDown(self):\n u'''这里放需要在每条用例后执行的部分'''\n print(f\"{devices}结束运行\")\n\n @classmethod\n def tearDownClass(self):\n u'''这里放需要在所有用例后执行的部分'''\n pass\n\n srcSuite = unittest.makeSuite(TCSkillscholar)\n return srcSuite\n","sub_path":"multi_processframe/TestCase/TC_skillscholar.py","file_name":"TC_skillscholar.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"247118386","text":"from random import randint\n#funkcija, ki žreba nakjlučno število iz vrednosti za posamezn črko\ndef zrebaj_crko(stevec):\n\tstevilo_crk = 0\n\t#funkcija sesteje vrednosti useh crk (kolikokrat se te crke pojavijo)\n\tfor vrednost in stevec.values():\n\t\tstevilo_crk += vrednost\n\t#zreb je random stevilka med 1 in stevilom vseh crk\n\tzreb = randint(1, stevilo_crk)\n\tfor indeks in stevec:\n\t\t#če je naključna številka manjša od števca črke\n\t\tif zreb <= stevec[indeks]:\n\t\t\treturn(indeks)\n\t\telse:\n\t\t\tzreb -= stevec[indeks]\n#stara koda, ki naredi seznam dict\nwith open(\"besede.txt\") as besede:\n\tstevec = dict()\n\tfor beseda in besede:\n\t\tbeseda = beseda.split()[0]\n\t\tbeseda = beseda + \" \"\n\t\tprej = \" \"\n\t\tfor crka in beseda:\n\t\t\tif prej not in stevec:\n\t\t\t\tstevec[prej] = dict()\n\t\t\tstevec[prej][crka] = 1 + stevec[prej].get(crka, 0)\n\t\t\tprej = crka\n#kliče funkcijo zrebaj_crko 10-krat\n\tprej = \" \"\n\tfor i in range(500):\n\t\tcrka = zrebaj_crko(stevec[prej])\n\t\tprint(crka, end=\"\")\n\t\tprej = crka\nprint()","sub_path":"Slovar/slovar.py","file_name":"slovar.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"139732384","text":"import praw, requests, re, time\n\nreddit = praw.Reddit('bot1')\n\n\n\n\n\n#posts = subreddit.search(query=\"reeves\", sort='new', syntax='lucene', time_filter='all')\nposts = reddit.subreddit(\"aww\").search(query='kitty', time_filter='all', limit=100, params={'include_over_18': 'on'})\n\nallPosts = ''\npostCount = 1\n\nfor post in posts:\n # print(\"Title: \", post.title)\n # print(\"Text: \", post.selftext)\n # print(\"Score: \", post.score)\n url = (post.url)\n file_name = url.split(\"/\")\n print(file_name)\n if len(file_name) == 0:\n file_name = re.findall(\"/(.*?)\", url)\n file_name = file_name[-1]\n if \".\" not in file_name:\n continue\n print(file_name)\n r = requests.get(url)\n\n with open('./pics/' + file_name,\"wb\") as f:\n f.write(r.content)\n # print(\"---------------------------------\\n\")\n # if post.over_18:\n\n allPosts+= str(postCount) + ' ' + post.title+'\\n'+post.url+'\\n\\n'\n postCount += 1\n\n # time.sleep(2)\nwith open('result', 'w', encoding='utf-8') as f:\n f.write(str(postCount) + \" Inhalte gefunden\\n\\n\" + allPosts)\nprint(str(postCount) + \" Inhalte gefunden\\n\\n\" + allPosts)\n\n# PyFuBot\n# web app\n# T-VYrrTnA_WsLqG6Hb14kA\n# change icon\n# secret\tyvDtgIu4MONMZOJevl63EKJEToz3FQ\n# name\t\n# PyFuBot\n# description\t\n# about url\t\n# redirect uri\t\n# http://127.0.0.1\n# update app\n# developers\t\n# MoeWithTheO (that's you!) remove\n\n# add developer:\n\n","sub_path":"PyFuBot.py","file_name":"PyFuBot.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"91137539","text":"from bs4 import BeautifulSoup\n\ndef weatherAfterTommorow(pageString):\n bsObj = BeautifulSoup(pageString, \"html.parser\")\n div = bsObj.find(\"div\", {\"class\": \"main_info\"})\n if div is None:\n return None\n ondo = div.find(\"p\", {\"class\": \"info_temperature\"})\n weather = div.find(\"ul\", {\"class\": \"info_list\"})\n week = weather.findAll(\"li\", {\"class\": \"\"})\n aftertomorrowAll = {}\n # 오늘\n # 두번째칸-1\n todayTemp = bsObj.findAll(\"ul\", {\"class\": \"list_area\"})\n\n\n weekWeather = bsObj.findAll(\"ul\", {\"class\": \"list_area _pageList\"})\n weekWeather1 = weekWeather[0].findAll(\"li\", {\"class\": \"date_info today\"})\n weekWeather2 = weekWeather[1].findAll(\"li\", {\"class\": \"date_info today\"})\n\n area = bsObj.find(\"div\", {\"class\": \"select_box\"})\n areaA = area.find(\"em\")\n # 오늘 끝\n\n # 내일 시작\n # 내일 - 첫번째칸\n tomorrow = bsObj.findAll(\"div\", {\"class\": \"main_info morning_box\"})\n\n # 모레 시작\n # 내일 - 첫번째칸\n aftertomorrowMorningondo = tomorrow[2].find(\"p\", {\"class\": \"info_temperature\"})\n aftertomorrowMorningWeath = tomorrow[2].find(\"ul\", {\"class\": \"info_list\"})\n aftertomorrowMorningWeath_1 = aftertomorrowMorningWeath.findAll(\"li\", {\"class\": \"\"})\n aftertomorrowAfternoonondo = tomorrow[3].find(\"p\", {\"class\", \"info_temperature\"})\n aftertomorrowAfternoonWeath = tomorrow[3].find(\"ul\", {\"class\", \"info_list\"})\n aftertomorrowAfternoonWeath_1 = aftertomorrowAfternoonWeath.findAll(\"li\", {\"class\": \"\"})\n # 내일 - 두번째칸1\n\n aftertomorrowTimeTemp1 = todayTemp[8].findAll(\"li\")\n # 모레 끝\n\n # 오늘 시작\n weekWeather1_1 = []\n weekWeather2_1 = []\n weekWeatherSum = {}\n weekWeatherOndo = []\n for i in range(0, 5):\n weekWeather1_1.append(weekWeather1[i].text.split())\n\n weekWeatherOndo.append(weekWeather1_1[i][8].split('/'))\n for i in range(0, 5):\n weekWeather2_1.append(weekWeather2[i].text.split())\n weekWeatherOndo.append(weekWeather2_1[i][8].split('/'))\n\n weekWeatherSum = {0: {\"요일\": weekWeather1_1[0][0], \"날짜\": weekWeather1_1[0][1], \"오전강수\": weekWeather1_1[0][3],\n \"오후강수\": weekWeather1_1[0][5], \"최고기온\": weekWeatherOndo[0][0], \"최저기온\": weekWeatherOndo[0][1]},\n 1: {\"요일\": weekWeather1_1[1][0], \"날짜\": weekWeather1_1[1][1], \"오전강수\": weekWeather1_1[1][3],\n \"오후강수\": weekWeather1_1[1][5], \"최고기온\": weekWeatherOndo[1][0], \"최저기온\": weekWeatherOndo[1][1]},\n 2: {\"요일\": weekWeather1_1[2][0], \"날짜\": weekWeather1_1[2][1], \"오전강수\": weekWeather1_1[2][3],\n \"오후강수\": weekWeather1_1[2][5], \"최고기온\": weekWeatherOndo[2][0], \"최저기온\": weekWeatherOndo[2][1]},\n 3: {\"요일\": weekWeather1_1[3][0], \"날짜\": weekWeather1_1[3][1], \"오전강수\": weekWeather1_1[3][3],\n \"오후강수\": weekWeather1_1[3][5], \"최고기온\": weekWeatherOndo[3][0], \"최저기온\": weekWeatherOndo[3][1]},\n 4: {\"요일\": weekWeather1_1[4][0], \"날짜\": weekWeather1_1[4][1], \"오전강수\": weekWeather1_1[4][3],\n \"오후강수\": weekWeather1_1[4][5], \"최고기온\": weekWeatherOndo[4][0], \"최저기온\": weekWeatherOndo[4][1]},\n 5: {\"요일\": weekWeather2_1[0][0], \"날짜\": weekWeather2_1[0][1], \"오전강수\": weekWeather2_1[0][3],\n \"오후강수\": weekWeather2_1[0][5], \"최고기온\": weekWeatherOndo[5][0], \"최저기온\": weekWeatherOndo[5][1]},\n 6: {\"요일\": weekWeather2_1[1][0], \"날짜\": weekWeather2_1[1][1], \"오전강수\": weekWeather2_1[1][3],\n \"오후강수\": weekWeather2_1[1][5], \"최고기온\": weekWeatherOndo[6][0], \"최저기온\": weekWeatherOndo[6][1]},\n 7: {\"요일\": weekWeather2_1[2][0], \"날짜\": weekWeather2_1[2][1], \"오전강수\": weekWeather2_1[2][3],\n \"오후강수\": weekWeather2_1[2][5], \"최고기온\": weekWeatherOndo[7][0], \"최저기온\": weekWeatherOndo[7][1]},\n 8: {\"요일\": weekWeather2_1[3][0], \"날짜\": weekWeather2_1[3][1], \"오전강수\": weekWeather2_1[3][3],\n \"오후강수\": weekWeather2_1[3][5], \"최고기온\": weekWeatherOndo[8][0], \"최저기온\": weekWeatherOndo[8][1]},\n 9: {\"요일\": weekWeather2_1[4][0], \"날짜\": weekWeather2_1[4][1], \"오전강수\": weekWeather2_1[4][3],\n \"오후강수\": weekWeather2_1[4][5], \"최고기온\": weekWeatherOndo[9][0], \"최저기온\": weekWeatherOndo[9][1]}\n }\n\n\n # 모레 시작\n AftertomorrowWeather = {\"지역\":areaA.text,\"오전날씨\": aftertomorrowMorningWeath_1[0].text, \"오전온도\": aftertomorrowMorningondo.text,\n \"오전미세먼지\": aftertomorrowMorningWeath_1[1].text, \"오후온도\": aftertomorrowAfternoonondo.text,\n \"오후날씨\": aftertomorrowAfternoonWeath_1[0].text,\n \"오후미세먼지\": aftertomorrowAfternoonWeath_1[1].text}\n aftertomorrowWeatherOndo = []\n for i in range(0, 8):\n aftertomorrowWeatherOndo.append(aftertomorrowTimeTemp1[i].text.split())\n\n aftertomorrowWeatherSum = {}\n aftertomorrowWeatherSum = {0: {\"시간\": aftertomorrowWeatherOndo[0][6], \"온도\": aftertomorrowWeatherOndo[0][2],\n \"날씨\": aftertomorrowWeatherOndo[0][4]},1: {\"시간\": aftertomorrowWeatherOndo[1][6], \"온도\": aftertomorrowWeatherOndo[1][2],\n \"날씨\": aftertomorrowWeatherOndo[1][4]},2: {\"시간\": aftertomorrowWeatherOndo[2][6], \"온도\": aftertomorrowWeatherOndo[2][2],\n \"날씨\": aftertomorrowWeatherOndo[2][4]},3: {\"시간\": aftertomorrowWeatherOndo[3][6], \"온도\": aftertomorrowWeatherOndo[3][2],\n \"날씨\": aftertomorrowWeatherOndo[3][4]},4: {\"시간\": aftertomorrowWeatherOndo[4][6], \"온도\": aftertomorrowWeatherOndo[4][2],\n \"날씨\": aftertomorrowWeatherOndo[4][4]},5: {\"시간\": aftertomorrowWeatherOndo[5][6], \"온도\": aftertomorrowWeatherOndo[5][2],\n \"날씨\": aftertomorrowWeatherOndo[5][4]},6: {\"시간\": aftertomorrowWeatherOndo[6][6], \"온도\": aftertomorrowWeatherOndo[6][2],\n \"날씨\": aftertomorrowWeatherOndo[6][4]},7: {\"시간\": aftertomorrowWeatherOndo[7][6], \"온도\": aftertomorrowWeatherOndo[7][2],\n \"날씨\": aftertomorrowWeatherOndo[7][4]}}\n\n aftertomorrowAll = {\"날씨\": AftertomorrowWeather, \"시간별날씨\": aftertomorrowWeatherSum, \"주간날씨\": weekWeatherSum}\n return aftertomorrowAll","sub_path":"crawler/weatherAfterTommorow.py","file_name":"weatherAfterTommorow.py","file_ext":"py","file_size_in_byte":6770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"579036478","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 29 17:11:03 2019\n\n@author: cristinamulas\n\"\"\"\n\nimport re\nimport sys\nfor line in sys.stdin:\n\n ip = r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'\n time = r':\\d{2}:\\d{2}:\\d{2}'\n\n time_list = re.findall(time, line)\n ips_list = re.findall(ip, line)\n for time, ip in zip(time_list , ips_list):\n new_list = '[' + time[1: 3] + ':' + '00'+']'+ ip + ' ' + '1'\n print(new_list) ","sub_path":"user_log/ma_f.py","file_name":"ma_f.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"203162744","text":"#!/usr/bin/python2.7\nimport logging\nimport sys\n\nlogger = logging.getLogger('testlog')\n\nhandler = logging.FileHandler('log/teste.log')\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\nhandler.setFormatter(formatter)\n\nch = logging.StreamHandler(sys.stdout)\nch.setLevel(logging.WARNING)\n\nlogger.addHandler(handler)\nlogger.addHandler(ch)\nlogger.setLevel(logging.DEBUG)\n\nlogging.disable(logging.INFO)\nlogging.disable(logging.ERROR)\nlogging.disable(logging.WARNING)\n\nlogger.error(\"some error occurred\")\nlogger.info('some info msg')\nlogger.info('another info msg')\nlogger.info('last info msg')\nlogger.warning('last info msg')\n","sub_path":"tmp/logging/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"303703322","text":"#!/usr/bin/env python3\n\"\"\"Analyze coverage obtained by designs.\"\"\"\n\nimport argparse\nimport logging\n\nfrom adapt import coverage_analysis\nfrom adapt.prepare import ncbi_neighbors\nfrom adapt.utils import log\nfrom adapt.utils import predict_activity\nfrom adapt.utils import seq_io\n\n__author__ = 'Hayden Metsky '\n\nlogger = logging.getLogger(__name__)\n\n\ndef read_designs(fn):\n \"\"\"Read a collection of targets from a file.\n\n Each target represents a design.\n\n Args:\n fn: path to a TSV file giving targets\n\n Returns:\n dict {design_id: design} where design_id is the row number\n of the target in fn (starting at 1 for the first target) and\n design is a coverage_analysis.Design object\n \"\"\"\n rows = []\n with open(fn) as f:\n col_names = {}\n for i, line in enumerate(f):\n line = line.rstrip()\n ls = line.split('\\t')\n if i == 0:\n # Parse header\n for j in range(len(ls)):\n col_names[j] = ls[j]\n else:\n # Read each column as a variable\n cols = {}\n for j in range(len(ls)):\n cols[col_names[j]] = ls[j]\n rows += [cols]\n\n designs = {}\n for i, row in enumerate(rows):\n cols = row\n if 'target-sequences' in cols:\n # This design only contains guides\n design = coverage_analysis.Design(\n cols['target-sequences'].split(' '))\n else:\n # This design contains primers and guides\n design = coverage_analysis.Design(\n cols['guide-target-sequences'].split(' '),\n (cols['left-primer-target-sequences'].split(' '),\n cols['right-primer-target-sequences'].split(' ')))\n designs[i + 1] = design\n return designs\n\n\ndef read_accessions(fn):\n \"\"\"Read a list of accessions from a file.\n\n Args:\n fn: path to file where each line gives an accession\n\n Returns:\n collection of accessions\n \"\"\"\n accs = []\n with open(fn) as f:\n for line in f:\n line = line.rstrip()\n accs += [line]\n return accs\n\n\ndef write_frac_bound(designs, frac_bound, out_fn):\n \"\"\"Write table giving the fraction of sequences bound by a target.\n\n Args:\n designs: dict {design_id: design} where design_id is an\n identifier for design and design is a coverage_analysis.\n Design object\n frac_bound: dict {design_id: frac_bound} where design_id is\n an identifier for a design and frac_bound is the fraction\n of target sequences that are bound by the design\n out_fn: path to TSV file at which to write table\n \"\"\"\n header = ['design_id',\n 'guide-target-sequences',\n 'left-primer-target-sequences',\n 'right-primer-target-sequences',\n 'frac-bound']\n with open(out_fn, 'w') as fw:\n fw.write('\\t'.join(header) + '\\n')\n for design_id in sorted(list(designs.keys())):\n guides = designs[design_id].guides\n guides = ' '.join(sorted(guides))\n if designs[design_id].primers is not None:\n left_primers, right_primers = designs[design_id].primers\n left_primers = ' '.join(sorted(left_primers))\n right_primers = ' '.join(sorted(right_primers))\n else:\n left_primers, right_primers = 'n/a', 'n/a'\n row = [design_id, guides, left_primers, right_primers,\n frac_bound[design_id]]\n fw.write('\\t'.join([str(x) for x in row]) + '\\n')\n\n\ndef write_mean_activity_of_guides(designs, mean_activities, out_fn):\n \"\"\"Write table giving the mean activity of guide sets.\n\n Args:\n designs: dict {design_id: design} where design_id is an\n identifier for design and design is a coverage_analysis.\n Design object\n mean_activities: dict {design_id: activity} where design_id is\n an identifier for a design and activity is the mean activity,\n across the target sequences, of its guide set\n out_fn: path to TSV file at which to write table\n \"\"\"\n header = ['design_id',\n 'guide-target-sequences',\n 'mean-activity']\n with open(out_fn, 'w') as fw:\n fw.write('\\t'.join(header) + '\\n')\n for design_id in sorted(list(designs.keys())):\n guides = designs[design_id].guides\n guides = ' '.join(sorted(guides))\n row = [design_id, guides, mean_activities[design_id]]\n fw.write('\\t'.join([str(x) for x in row]) + '\\n')\n\n\ndef main(args):\n # Allow G-U base pairing, unless it is explicitly disallowed\n allow_gu_pairs = not args.do_not_allow_gu_pairing\n\n # Read the designs\n designs = read_designs(args.designs_fn)\n\n # If accessions were given, fetch them as use them as input\n if args.use_accessions:\n accessions = read_accessions(args.seqs_fn)\n seqs_tempfile = ncbi_neighbors.fetch_fastas(accessions)\n seqs_fn = seqs_tempfile.name\n else:\n seqs_tempfile = None\n seqs_fn = args.seqs_fn\n\n # Read the input sequences to compute coverage against; use\n # skip_gaps=True so that, if an alignment is input, this\n # is read as unaligned sequences\n seqs = seq_io.read_fasta(seqs_fn, skip_gaps=True)\n\n if (args.guide_mismatches is not None) and args.predict_activity_model_path:\n raise Exception((\"Cannot set both --guide-mismatches and \"\n \"--predict-activity-model-path. Choose --guide-mismatches \"\n \"for a model based on mismatches, and --predict-activity-model-\"\n \"path to make determinations based on whether predicted \"\n \"activity is high.\"))\n elif args.guide_mismatches is not None:\n analyzer = coverage_analysis.CoverageAnalyzerWithMismatchModel(\n seqs, designs, args.guide_mismatches, args.primer_mismatches,\n allow_gu_pairs, fully_sensitive=args.fully_sensitive)\n elif args.predict_activity_model_path:\n cla_path, reg_path = args.predict_activity_model_path\n if args.predict_activity_thres:\n # Use specified thresholds on classification and regression\n cla_thres, reg_thres = args.predict_activity_thres\n else:\n # Use default thresholds specified with the model\n cla_thres, reg_thres = None, None\n predictor = predict_activity.Predictor(cla_path, reg_path,\n classification_threshold=cla_thres,\n regression_threshold=reg_thres)\n highly_active = args.predict_activity_require_highly_active\n analyzer = coverage_analysis.CoverageAnalyzerWithPredictedActivity(\n seqs, designs, predictor, args.primer_mismatches,\n highly_active=highly_active,\n fully_sensitive=args.fully_sensitive)\n else:\n raise Exception((\"One of --guide-mismatches or \"\n \"--predict-activity-model-path must be set\"))\n\n # Perform analyses\n performed_analysis = False\n if args.write_frac_bound:\n frac_bound = analyzer.frac_of_seqs_bound()\n write_frac_bound(designs, frac_bound, args.write_frac_bound)\n performed_analysis = True\n if args.write_mean_activity_of_guides:\n if (not args.predict_activity_model_path or\n args.predict_activity_require_highly_active):\n raise Exception((\"To use --write-mean-activity-of-guides, \"\n \"a predictive model must be set and \"\n \"--predict-activity-require-highly-active must *not* \"\n \"be set\"))\n mean_activity = analyzer.mean_activity_of_guides()\n write_mean_activity_of_guides(designs, mean_activity,\n args.write_mean_activity_of_guides)\n performed_analysis = True\n\n if not performed_analysis:\n logger.warning((\"No analysis was requested\"))\n\n # Close tempfiles\n if seqs_tempfile is not None:\n seqs_tempfile.close()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n # Required inputs\n parser.add_argument('designs_fn',\n help=(\"Path to output of running design.py; a TSV file where \"\n \"each row contains a design (target)\"))\n parser.add_argument('seqs_fn',\n help=(\"Path to FASTA file giving sequences against which to \"\n \"compute coverage. (See --use-accessions to pass accessions \"\n \"as input rather than a FASTA file.)\"))\n\n # Analyses to output\n parser.add_argument('--write-frac-bound',\n help=(\"If set, write a table in which each row represents an \"\n \"input design and gives the fraction of all sequences that \"\n \"are covered by the design. The 'design_id' column gives \"\n \"the row number of the design in the designs input (1 for \"\n \"the first design). The provided argument is a path to \"\n \"a TSV file at which to the write the table.\"))\n parser.add_argument('--write-mean-activity-of-guides',\n help=(\"If set, write a table in which each row represents an \"\n \"input design and gives the mean activity across the target \"\n \"sequences of the guide set. The 'design_id' column gives \"\n \"the row number of the design in the designs input (1 for \"\n \"the first design). The provided argument is a path to \"\n \"a TSV file at which to write the table. If set, a predictive \"\n \"model must be set without \"\n \"--predict-activity-require-highly-active\"))\n\n # Parameter determining whether a primer binds to target\n parser.add_argument('-pm', '--primer-mismatches',\n type=int, default=0,\n help=(\"Allow for this number of mismatches when determining \"\n \"whether a primer covers a sequence (ignore this if \"\n \"the targets only consist of guides)\"))\n\n # Parameters determining whether a guide binds to target based on\n # mismatch model\n parser.add_argument('-gm', '--guide-mismatches',\n type=int,\n help=(\"Allow for this number of mismatches when \"\n \"determining whether a guide covers a sequence; either this \"\n \"or --predict-activity-model-path should be set\"))\n parser.add_argument('--do-not-allow-gu-pairing',\n action='store_true',\n help=(\"When determining whether a guide binds to a region of \"\n \"target sequence, do not count G-U (wobble) base pairs as \"\n \"matching. Default is to tolerate G-U pairing: namely, \"\n \"A in an output guide sequence matches G in the \"\n \"target and C in an output guide sequence matches T \"\n \"in the target (since the synthesized guide is the reverse \"\n \"complement of the output guide sequence)\"))\n\n # Parameters determining whether a guide binds to target based on\n # trained model\n parser.add_argument('--predict-activity-model-path',\n nargs=2,\n help=(\"Paths to directories containing serialized models in \"\n \"TensorFlow's SavedModel format for predicting guide-target \"\n \"activity. There are two arguments: (1) classification \"\n \"model to determine which guides are active; (2) regression \"\n \"model, which is used to determine which guides (among \"\n \"active ones) are highly active. The models/ directory \"\n \"contains example models. Either this or --guide-mismatches \"\n \"should be set.\"))\n parser.add_argument('--predict-activity-thres',\n type=float,\n nargs=2,\n help=(\"Thresholds to use for decisions on output of predictive \"\n \"models. There are two arguments: (1) classification threshold \"\n \"for deciding which guide-target pairs are active (in [0,1], \"\n \"where higher values have higher precision but less recall); \"\n \"(2) regression threshold for deciding which guide-target pairs \"\n \"are highly active (>= 0, where higher values limit the number \"\n \"determined to be highly active). If not set but --predict-\"\n \"activity-model-path is set, then this uses default thresholds \"\n \"stored with the models. To 'bind to' or 'cover' a target, \"\n \"the guide-target pair must be active or, if \"\n \"--predict-activity-require-highly-active is set, highly active.\"))\n parser.add_argument('--predict-activity-require-highly-active',\n action='store_true',\n help=(\"When determining whether a guide-target pair binds using an \"\n \"activity model, require that the pair be predicted to be \"\n \"highly active (not just active)\"))\n\n # Miscellaneous\n parser.add_argument('--use-accessions',\n action='store_true',\n help=(\"When set, the input file of sequences gives accessions rather \"\n \"than being a FASTA of sequences -- each line in the file gives \"\n \"an accession. This fetches the sequences of those accessions \"\n \"uses them as input.\"))\n parser.add_argument('--fully-sensitive',\n action='store_true',\n help=(\"When set, use a naive, slow sliding approach to find binding \"\n \"for primers and guides; otherwise, this uses an index to \"\n \"more quickly identify binding sites\"))\n\n # Log levels\n parser.add_argument(\"--debug\",\n dest=\"log_level\",\n action=\"store_const\",\n const=logging.DEBUG,\n default=logging.WARNING,\n help=(\"Debug output\"))\n parser.add_argument(\"--verbose\",\n dest=\"log_level\",\n action=\"store_const\",\n const=logging.INFO,\n help=(\"Verbose output\"))\n\n args = parser.parse_args()\n log.configure_logging(args.log_level)\n main(args)\n","sub_path":"bin/analyze_coverage.py","file_name":"analyze_coverage.py","file_ext":"py","file_size_in_byte":13994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"415105311","text":"from django.contrib import admin\n\nfrom .models import Review\n\n\n@admin.register(Review)\nclass ReviewAdmin(admin.ModelAdmin):\n fields = [\n 'reviewer', 'stage', 'proposal', 'vote', 'comment',\n 'note',\n # 'updated',\n ]\n list_display = [\n 'proposal', 'vote', 'reviewer', 'stage',\n ]\n list_filter = [\n 'vote', 'stage',\n ]\n","sub_path":"src/reviews/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"35572205","text":"from selenium import webdriver\n\nclass Sele_cz():\n\n def __init__(self,cz_url):\n self.cz_url=cz_url\n self.lxs={1:'.find_element_by_name',2:'find_element_by_id',3:'find_element_by_xpath'}\n\n def open_url(self):\n self.op_url = webdriver.Firefox()\n self.op_url.get(self.cz_url)\n return self.op_url\n\n def url_input(self,lx,name,input_nr):\n \n self.lx=lx\n self.name=\"'%s'\" % name\n self.input_nr=\"'%s'\" % input_nr\n self. input_str=self.op_url.find_element_by_id(name)\n self. input_str.send_keys(self.input_nr)\n\n def url_click(self,lx,name):\n self.lx=lx\n self.name=\"'%s'\" % name\n self. input_str=self.op_url.find_element_by_lx(name)\n self. input_str.click()\n \n\n\n\n\n\nif __name__=='__main__':\n sl=Sele_cz('http://bbs.gogopzh.com/forum.php')\n sl.open_url()\n # sl.url_input('id','ls_username','yhpzh')","sub_path":"yh_package/selenium操作/sele_firefox.py","file_name":"sele_firefox.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"164676899","text":"import com.ihsan.foundation.pobjecthelper as phelper\r\n\r\ndef FunctionMain(config, request, response):\r\n kode_jabatan = request['Kode_Jabatan']\r\n\r\n helper = phelper.PObjectHelper(config)\r\n jabatan = helper.GetObject('Jabatan', kode_jabatan)\r\n\r\n response['Nama_Jabatan'] = jabatan.Nama_Jabatan\r\n response['Deskripsi'] = jabatan.Deskripsi\r\n\r\n","sub_path":"scripts/simpleinterface/info_jabatan.py","file_name":"info_jabatan.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"524278363","text":"import os\n\n\ndef pod_service(namespace='default'):\n while True:\n print(\"\\n\\t\\t\\tEnter 0: run yaml file\\n\\t\\t\\tEnter 1: List Pod\\n\\t\\t\\tEnter 2: List Pod with Labels\\n\\t\\t\\tEnter 3: Wide List Pod\\n\\t\\t\\tEnter 4: Get YAML file for running Pod\"\n \"\\n\\t\\t\\tEnter 5: Describe Pod\\n\\t\\t\\tEnter 6: Create Pod\\n\\t\\t\\tEnter 7: Expose Pod\\n\\t\\t\\tEnter 8: Delete Pod\\n\\t\\t\\tEnter 9: Delete All Pods\\n\\t\\t\\tEnter 10: see Logs of Pod\"\n \"\\n\\t\\t\\tEnter 11: To Exit\")\n choice = input(\"\\t\\t\\tEnter your choice: \")\n if choice == '0':\n yml = input(\"\\t\\t\\tEnter: \\n\")\n with open('pod.yml', \"w+\") as pod_file:\n pod_file.write(yml)\n os.system(f'kubectl apply -f pod.yml -n {namespace}')\n elif choice == '1':\n os.system(f'kubectl get pods -n {namespace}')\n elif choice == '2':\n os.system(f'kubectl get pod --show-labels -n {namespace}')\n elif choice == '3':\n os.system(f'kubectl get pod -o wide -n {namespace}')\n elif choice == '4':\n pod_name = input(\"\\t\\t\\tEnter pod_name: \")\n os.system(f'kubectl get pod {pod_name} -o yaml -n {namespace}')\n elif choice == '5':\n pod = input(\"\\t\\t\\tEnter Pod Name: \")\n os.system(f'kubectl describe {pod} -n {namespace}')\n elif choice == '6':\n pod_name = input(\"\\t\\t\\tEnter pod_name: \")\n image = input('\\t\\t\\tEnter image name: ')\n os.system(f\"\\t\\t\\tkubectl run {pod_name} --image {image} -n {namespace}\")\n elif choice == '7':\n pod_name = input(\"\\t\\t\\tEnter pod_name: \")\n expose_type = input(\"\\t\\t\\tEnter expose type [NodePort/ClusterIP/LoadBalancer]: \")\n port = input('\\t\\t\\tEnter port number: ')\n os.system(f'kubectl expose pod/{pod_name} --type={expose_type} --port={port} -n {namespace}')\n os.system(f'kubectl get svc {pod_name} -n {namespace}')\n elif choice == '8':\n pod_name = input(\"\\t\\t\\tEnter pod_name: \")\n os.system(f'kubectl delete pod {pod_name} -n {namespace}')\n elif choice == '9':\n os.system(f'kubectl delete pod --all -n {namespace}')\n elif choice == '10':\n pod_name = input(\"\\t\\t\\tEnter pod_name: \")\n os.system(f'kubectl logs pod {pod_name} -n {namespace}')\n else:\n if choice != \"11\":\n print(\"\\t\\t\\tWrong Choice\")\n return\n","sub_path":"script/key_script/kubernetes/pods/pod.py","file_name":"pod.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"170832729","text":"from django import forms\nfrom django.db import models\n\nfrom .models import Image\nfrom django.forms.widgets import Textarea\nfrom projects.models import Projects\nfrom api.models import OfflineModel\n\n\nclass ImageForm(forms.ModelForm):\n image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False)\n class Meta:\n model = Image \n fields = ('title', 'description', #'user', \n 'lat', 'lng', 'image', 'project')\n labels = {\n # 'user':'User',\n 'lat':'Latitude',\n 'lng':'Longitude'\n }\n widgets = {\n 'description': Textarea(attrs={'rows':4, 'cols':20}),\n }\n\n def __init__(self, *args, **kwargs):\n super(ImageForm, self).__init__(*args, **kwargs)\n # self.fields['user'].empty_label = \"-- Keep Unselected for Setting to Yourself --\"\n self.fields['project'].empty_label = \"No Project Linked Yet !!\"\n if self.instance.user and self.instance.user.is_admin:\n self.fields['project'].queryset = Projects.objects.all()\n elif self.instance.user:\n self.fields['project'].queryset = Projects.objects.filter(users__id=self.instance.user.id)\n self.fields['image'].label = \"Multiple Images\"\n self.fields['lat'].widget.attrs['min'] = -90\n self.fields['lat'].widget.attrs['max'] = 90\n self.fields['lng'].widget.attrs['min'] = -180\n self.fields['lng'].widget.attrs['max'] = 180\n\n\nclass OfflineModelForm(forms.ModelForm):\n model_type = forms.ChoiceField(choices=[('OBJECT_DETECT','Object Detect'),('CLASSIFIER','Classifier')], widget=forms.Select, initial = 'model_type')\n model_format = forms.CharField(widget=forms.Select, initial = 'model_format')\n class Meta:\n model = OfflineModel \n fields = ('name', 'model_type', 'model_format', 'file')\n labels = {\n 'model_type':'Model Type',\n 'model_format':'Model File Format',\n 'file':'File',\n }\n\n def __init__(self, *args, **kwargs):\n super(OfflineModelForm, self).__init__(*args, **kwargs)\n self.fields['model_format'].help_text = 'Choose a format or type yourself'\n if self.instance and (self.instance.projects.all().count() or self.instance.classifiers.all().count()): # Done, to check if offline model is linked to projects or classifiers to disable editing object type\n self.fields['model_type'].widget = forms.HiddenInput()\n self.fields['model_format'].help_text = 'Choose a format or type yourself
Model Type is Unable to change because it is used by some projects or classifier actively'","sub_path":"django-backend/isac_simo/api/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"1852230","text":"\"\"\"\nimg2tex cement app for command-line use\n\"\"\"\n\nfrom cement.core.foundation import CementApp\nfrom cement.core.controller import CementBaseController, expose\nimport ansi\nfrom img2txtlib import *\n\n\nclass BaseController(CementBaseController):\n class Meta:\n label = 'base'\n description = \"The base controller\"\n arguments = [\n (['-if', '--inputfile'],\n dict(action='store',\n metavar='STR',\n help=\"Path to an image file.\")),\n (['--ansi'],\n dict(action='store_true',\n help=\"Use ANSI BG tiles instead of ASCII\")),\n (['--color'],\n dict(action='store_true',\n help=\"Enable color output.\")),\n (['--dither'],\n dict(action='store_true',\n help=\"Dither the image to web pallete.\")),\n (['--antialias'],\n dict(action='store_true',\n help=\"Enables antialiassing for any resizing operations.\")),\n (['--bgcolor'],\n dict(action='store',\n metavar='STR',\n help=\"If specified, is blended with transparent pixels to\"\n \"produce the output.\")),\n (['--maxlen'],\n dict(action='store',\n metavar='INT',\n help=\"Resize image to the supplied value in pixels. \"\n \"Default: 100\")),\n (['--targetaspect'],\n dict(action='store',\n metavar='FLOAT',\n help=\"Set width to height ratio. Default: 1.0\"))\n ]\n\n @expose(hide=True)\n def default(self):\n if self.app.pargs.inputfile:\n try:\n bgcolor = HTMLColorToRGB(self.app.pargs.bgcolor) + (255, )\n except:\n bgcolor = None\n try:\n maxlen = float(self.app.pargs.maxlen)\n except:\n maxlen = 100.0\n try:\n target_aspect_ratio = float(self.app.pargs.target_aspect_ratio)\n except:\n target_aspect_ratio = 1.0\n try:\n img = load_and_resize_image(\n self.app.pargs.inputfile, self.app.pargs.antialias, maxlen,\n target_aspect_ratio)\n except IOError:\n exit(\"File not found: \" + imgname)\n if self.app.pargs.dither:\n img = dither_image_to_web_palette(img, bgcolor)\n\n pixel = img.load()\n width, height = img.size\n\n if self.app.pargs.ansi:\n if bgcolor is not None:\n fill_string = ansi.getANSIbgstring_for_ANSIcolor(\n ansi.getANSIcolor_for_rgb(bgcolor))\n else:\n fill_string = \"\\x1b[49m\"\n fill_string += \"\\x1b[K\"\n sys.stdout.write(fill_string)\n\n sys.stdout.write(\n ansi.generate_ANSI_from_pixels(\n pixel, width, height, bgcolor)[0])\n sys.stdout.write(\"\\x1b[0m\\n\")\n\n else:\n string = \"\"\n ascii_matrix = generate_grayscale_for_image(\n pixel, width, height, bgcolor)\n if self.app.pargs.color:\n ansi_matrix = generate_ansi_color_matrix(\n pixel, width, height)\n ansi_matrix = generate_ansi_color_matrix(\n pixel, width, height)\n for h in range(height):\n for w in range(width):\n string += ansi_matrix[h][w]\n string += ascii_matrix[h][w]\n string += \"\\n\"\n\n if not string:\n for h in range(height):\n string += ascii_matrix[h] + \"\\n\"\n\n sys.stdout.write(string)\n\n sys.stdout.flush()\n\n else:\n print(\"ERROR: No file specified\")\n self.app.args.print_help()\n\n\nclass MapRest(CementApp):\n class Meta:\n label = 'img2txt'\n base_controler = 'base'\n handlers = [BaseController]\n\n\nwith MapRest() as app:\n app.run()\n","sub_path":"img2txt.py","file_name":"img2txt.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"143243461","text":"# coding=utf-8\nfrom django.conf.urls import patterns, include, url\nimport views\n\nurlpatterns = patterns('',\n url(r'^$', views.index),\n url(r'file_manage/$', views.file_manage),\n url(r'file_manage/upload/$', views.file_manage_upload),\n url(r'file_manage/delete/(.+)/$', views.file_manage_delete),\n url(r'client_download/$', views.client_download),\n url(r'client_download/transfer/(.+)/', views.client_transfer),\n url(r'^update/(.+)/$', views.crawler_51job_update2),\n# url('^crawler/update_program_version/(.+)/$', views_crawler.crawler_51job_update_program_version),\n)\n","sub_path":"crawler_51job/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"329237637","text":"# coding:utf-8\n'''\n@Copyright:LintCode\n@Author: monolake\n@Problem: http://www.lintcode.com/problem/search-a-2d-matrix\n@Language: Python\n@Datetime: 16-10-25 22:41\n'''\n\nclass Solution:\n \"\"\"\n @param matrix, a list of lists of integers\n @param target, an integer\n @return a boolean, indicate whether matrix contains target\n \"\"\"\n def searchMatrix(self, matrix, target):\n # write your code here\n if len(matrix) == 0:\n return False\n \n m = len(matrix)\n n = len(matrix[0])\n start = 0\n end = m * n - 1\n while start + 1 < end:\n mid = start + (end - start) / 2\n row = mid / n\n col = mid % n\n mid_val = matrix[row][col]\n if target == mid_val:\n return True\n elif target < mid_val:\n end = mid - 1\n else:\n start = mid + 1\n \n row_start = start / n\n col_start = start % n\n\n row_end = end / n\n col_end = end % n\n\n if matrix[row_start][col_start] == target:\n return True\n elif matrix[row_end][col_end] == target:\n return True\n else:\n return False\n \n","sub_path":"28_search-a-2d-matrix/search-a-2d-matrix.py","file_name":"search-a-2d-matrix.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"198578048","text":"import pandas as pd\nimport os\n\n\ndef get_line(date):\n filename = sourcePath + \"bus\" + str(date) + \".csv\"\n df=pd.read_csv(filename) \n\n for each_line in lines:\n # Get specific line\n route_df = df.loc[df[\"route\"] == each_line]\n route_df = route_df.dropna().sort_values(by=[\"date\",\"time\"])\n\n out_file = outPath + \"2018-3-\" + str(date) + \"-\" + each_line + \".csv\"\n\n # remove trajectory type\n route_df.to_csv(out_file,index=False)\n\n print(\"finish \"+ str(date) + each_line + \": \" + str(route_df.shape[0]))\n\n\n\n\nif __name__ == \"__main__\":\n lines = [\"451路\",\"779路\",\"沪南线\"]\n dates = [28,31]\n sourcePath = \"E:\\\\SODA_use\\\\bus_card\\\\BusData\\\\\"\n outPath = \"E:\\\\SODA_use\\\\bus_card\\\\LineData\\\\\"\n for date in dates:\n get_line(date)","sub_path":"代码/一卡通数据/代码/GetLineData.py","file_name":"GetLineData.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"471807502","text":"# coding: utf-8\n# https://github.com/materialsproject/pymatgen/blob/1eb2f2f/pymatgen/matproj/rest.py\nfrom __future__ import division, unicode_literals\nimport os, requests, warnings, urlparse\nfrom bson.json_util import loads\n\nclass MPResterBase(object):\n \"\"\"\n A base class to conveniently interface with a REST interface in the style of\n the Materials Project. For your own \"rester\", inherit from MPResterBase and\n add convenience functions which return the result of HTTP requests via\n `MPResterBase._make_request(, ..)`. The recommended way to use the\n resulting `MPCustomRester` is with the \"with\" context manager to ensure that\n sessions are properly closed after usage::\n\n with MPCustomRester(\"API_KEY\") as m:\n m.do_something()\n\n MPResterBase uses the \"requests\" package, which provides for HTTP connection\n pooling.\n\n Args:\n api_key (str): A String API key for accessing the REST interface. If\n this is None, the code will check if there is a \"MAPI_KEY\"\n environment variable set. If so, it will use that environment\n variable. This makes it easier for heavy users to simply add this\n environment variable to their setups and MPResterBase can then be\n called without any arguments.\n endpoint (str): URL of endpoint to access the REST interface. Defaults\n to the standard Materials Project REST address, but can be changed\n to other urls implementing a similar interface.\n \"\"\"\n def __init__(self, api_key=None,\n endpoint=\"https://www.materialsproject.org/rest/v2\"):\n if api_key is not None:\n self.api_key = api_key\n else:\n self.api_key = os.environ.get(\"MAPI_KEY\", \"\")\n self.preamble = endpoint\n self.session = requests.Session()\n self.session.headers = {\"x-api-key\": self.api_key}\n\n def __enter__(self):\n \"\"\"Support for \"with\" context.\"\"\"\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"Support for \"with\" context.\"\"\"\n self.session.close()\n\n def _make_request(self, sub_url, payload=None, method=\"GET\"):\n response = None\n url = self.preamble + sub_url\n try:\n headers = {}\n if not 'materialsproject' in self.preamble:\n if self.session.cookies.get('csrftoken') is None:\n from django.core.urlresolvers import reverse\n uri = urlparse.urlparse(self.preamble)\n domain = '{uri.scheme}://{uri.netloc}'.format(uri=uri)\n site_url = uri.path.split('/')[1] # test_site/\n browserid_csrf = reverse('browserid.csrf')\n if site_url[:-1] not in browserid_csrf:\n domain += '/' + site_url\n domain += browserid_csrf\n self.session.get(domain)\n headers = {\"X-CSRFToken\": self.session.cookies.get('csrftoken')}\n response = self.session.post(url, data=payload, headers=headers) \\\n if method == \"POST\" else self.session.get(url, params=payload)\n if response.status_code in [200, 400]:\n data = loads(response.text)\n if data[\"valid_response\"]:\n if data.get(\"warning\"):\n warnings.warn(data[\"warning\"])\n return data[\"response\"]\n else:\n raise MPResterError(data[\"error\"])\n raise MPResterError(\n \"REST query returned with error status code {}\"\n .format(response.status_code)\n )\n except Exception as ex:\n msg = \"{}. Content: {}\".format(str(ex), repr(response.content)) \\\n if hasattr(response, \"content\") else str(ex)\n raise MPResterError(msg)\n\nclass MPResterError(Exception):\n \"\"\"\n Exception class for MPResterBase.\n Raised when the query has problems, e.g., bad query format.\n \"\"\"\n pass\n","sub_path":"webtzite/rester.py","file_name":"rester.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"384721710","text":"from copy import deepcopy\n\n\ndef get_initial_state():\n return [[0 for _ in range(3)] for __ in range(3)]\n\n\ndef get_valid_moves(state):\n if get_winner(state):\n return False\n else:\n valid_moves = []\n for i in range(len(state)):\n for j in range(len(state[i])):\n if state[i][j] == 0:\n valid_moves.append(i*3 + j)\n\n return valid_moves\n\n\ndef make_move(state, action, tile):\n new_state = deepcopy(state)\n i = int(action / 3)\n j = action % 3\n new_state[i][j] = tile\n\n return new_state\n\n\ndef get_winner(state):\n # check horizontal\n for i in range(len(state)):\n if state[i][0] == state[i][1] == state[i][2] != 0:\n return state[i][0]\n\n # check verticals\n for j in range(len(state[0])):\n if state[0][j] == state[1][j] == state[2][j] != 0:\n return state[0][j]\n\n # check \\ diagonal\n if state[0][0] == state[1][1] == state[2][2] != 0:\n return state[0][0]\n\n # check \\ diagonal\n if state[0][2] == state[1][1] == state[2][0] != 0:\n return state[1][1]\n\n return 0\n","sub_path":"environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"446195175","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nIn[1]: b'\\x0d'.decode('ascii')\r\nOut[1]: '\\r'\r\n\r\nSome non-printable bytes ranges from b'\\x80' to b'\\xFF'.\r\n\"\"\"\r\nimport sys\r\nfrom PyQt5.QtCore import QObject, QIODevice, Qt\r\nfrom PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo\r\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QHBoxLayout\r\n\r\n\r\nclass MySerialPort1(QObject):\r\n\r\n def __init__(self, port_name, parent = None):\r\n \"\"\"\r\n :param serial_port: for example, 'COM3'.\r\n :param parent:\r\n \"\"\"\r\n super(MySerialPort1, self).__init__()\r\n self.parent = parent\r\n self.current_data = None\r\n self.last_data = None\r\n # the setting about the QSerialPort;\r\n # list_serialPort = QSerialPortInfo.availablePorts() # returns a list of the PyQt5.QtSerialPort.QSerialPortInfo class\r\n # for port in list_serialPort:\r\n # print(port.portName())\r\n self.serial = QSerialPort() # It is the subclass of the QIODevice class;\r\n self.serial.setPortName(port_name) # passing name such as 'COM1'\r\n self.serial.setBaudRate(9600)\r\n self.serial.setDataBits(QSerialPort.DataBits(8))\r\n self.serial.setStopBits(QSerialPort.StopBits(1))\r\n self.serial.readyRead.connect(self.acceptData1)\r\n # self.serial.readyRead.connect(self.acceptData1, type=Qt.QueuedConnection)\r\n # self.serial.bytesWritten.connect(self.acceptData2)\r\n\r\n if self.serial.open(QIODevice.ReadOnly):\r\n # self.serial.setDataTerminalReady(True) # setting the specific pin to the high-value voltage;\r\n print('The initialization of serial port is successful.')\r\n else:\r\n print('Opening the serial port fails.')\r\n\r\n\r\n def acceptData1(self):\r\n \"\"\"\r\n This function will be executed when the new data arrive on the serial port;\r\n the fixed length of the original string is 13;\r\n In string format, it looks like this '+ 0.123 kg \\n'.\r\n \"\"\"\r\n data1 = self.serial.readLine() # the data type is the PyQt5.QtCore.QByteArray class;\r\n data2 = data1.data().decode('ascii') # converting the data type to str (the original string);\r\n data3 = float(data2[1:-4]) # the value part of the original string;\r\n print(data3)\r\n\r\n\r\nclass MainWindow(QMainWindow):\r\n def __init__(self):\r\n super(MainWindow, self).__init__()\r\n self.main_widget = QWidget()\r\n self.main_layout = QHBoxLayout()\r\n self.button = QPushButton('disconnect')\r\n self.button.clicked.connect(self._mydisconnect)\r\n self.button2 = QPushButton('connect')\r\n self.button2.clicked.connect(self._myconnect)\r\n self.main_layout.addWidget(self.button)\r\n self.main_layout.addWidget(self.button2)\r\n self.main_widget.setLayout(self.main_layout)\r\n self.setCentralWidget(self.main_widget)\r\n #\r\n self.serial_port = MySerialPort1(port_name='COM3')\r\n\r\n\r\n def _mydisconnect(self):\r\n # The serial port has to be open before trying to close it; otherwise sets the NotOpenError error code\r\n self.serial_port.serial.close()\r\n print('disconnection is successful.')\r\n\r\n\r\n def _myconnect(self):\r\n if self.serial_port.serial.open(QIODevice.ReadOnly):\r\n print('connection is successful.')\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n mywindow = MainWindow()\r\n mywindow.show()\r\n sys.exit(app.exec_())\r\n\r\n\r\n","sub_path":"test_QSerialPort.py","file_name":"test_QSerialPort.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"461711530","text":"# Copyright (C) 2012 Massachusetts Institute of Technology and Institute \n# for Institutional Innovation by Data Driven Design Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n# \n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE MASSACHUSETTS INSTITUTE OF\n# TECHNOLOGY AND THE INSTITUTE FOR INSTITUTIONAL INNOVATION BY DATA\n# DRIVEN DESIGN INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, \n# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE \n# USE OR OTHER DEALINGS IN THE SOFTWARE.\n# \n# Except as contained in this notice, the names of the Massachusetts \n# Institute of Technology and the Institute for Institutional \n# Innovation by Data Driven Design Inc. shall not be used in \n# advertising or otherwise to promote the sale, use or other dealings\n# in this Software without prior written authorization from the \n# Massachusetts Institute of Technology and the Institute for \n# Institutional Innovation by Data Driven Design Inc\n\nimport re\n\nfrom django.utils.text import compress_string\nfrom django.utils.cache import patch_vary_headers\n\nfrom django import http\n\ntry:\n import settings \n XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS\n XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS\nexcept:\n XS_SHARING_ALLOWED_ORIGINS = '*'\n XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE']\n\n\nclass XsSharing(object):\n \"\"\"\n This middleware allows cross-domain XHR using the html5 postMessage API.\n \n\n Access-Control-Allow-Origin: http://foo.example\n Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE\n \"\"\"\n def process_request(self, request):\n\n if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:\n response = http.HttpResponse()\n response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS \n response['Access-Control-Allow-Methods'] = \",\".join( XS_SHARING_ALLOWED_METHODS ) \n \n return response\n\n return None\n\n def process_response(self, request, response):\n # Avoid unnecessary work\n if response.has_header('Access-Control-Allow-Origin'):\n return response\n\n response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS \n response['Access-Control-Allow-Methods'] = \",\".join( XS_SHARING_ALLOWED_METHODS )\n\n return response\n","sub_path":"oms_pds/django-crossdomainxhr-middleware.py","file_name":"django-crossdomainxhr-middleware.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"396205611","text":"#Seleksi Calon IRK 2019\r\n#NIM / Nama : 13517048 / Leonardo\r\n#Topik Program : Dynamic Programming - Another Path Finding Case\r\n\r\nfrom time import time\r\n\r\ndef printMatrix(mat):\r\n for i in mat:\r\n print(i)\r\n\r\ndef addUnique(li, elmt):\r\n #seperti add pada set, namun pada list\r\n if (elmt not in li): li.append(elmt)\r\n\r\ndef countTotal(total_move, currentPoint, finalPoint, matrix_of_boolean):\r\n #pendekatan rekursif, top down\r\n if (currentPoint == finalPoint):\r\n #Basis 1: sudah sampai ke poin final, maka 1 buah move ditemukan\r\n return 1\r\n elif (not matrix_of_boolean[currentPoint[0]][currentPoint[1]]):\r\n #Basis 2: stuck di Point yang tidak bisa menuju ke Point solusi\r\n return 0\r\n else: #Rekurens\r\n moves = 0\r\n for i in total_move:\r\n if (i[0] == currentPoint):\r\n moves += countTotal(total_move, i[1], finalPoint, matrix_of_boolean)\r\n return moves\r\n\r\ndef DFS(matrix_of_int, matrix_of_boolean, initialPoint, initPoint2, finalPoint, moves, total_move):\r\n #bentuk initialPoint, finalPoint = [i, j] (Point)\r\n if (initPoint2 == finalPoint and moves == 0):\r\n matrix_of_boolean[initialPoint[0]][initialPoint[1]] = True\r\n addUnique(total_move, [initialPoint, finalPoint])\r\n elif (initPoint2 == finalPoint and moves != 0):\r\n return\r\n elif (initPoint2 != finalPoint and moves == 0):\r\n return\r\n else:\r\n #vertikal ke bawah\r\n nextPoint = [initPoint2[0]+1, initPoint2[1]]\r\n if (nextPoint[0] < len(matrix_of_boolean)):\r\n new_moves = moves - 1\r\n DFS(matrix_of_int, matrix_of_boolean, initialPoint, nextPoint, finalPoint, new_moves, total_move)\r\n #horizontal ke kanan\r\n nextPoint = [initPoint2[0], initPoint2[1]+1]\r\n if (nextPoint[1] < len(matrix_of_boolean)):\r\n new_moves = moves - 1\r\n DFS(matrix_of_int, matrix_of_boolean, initialPoint, nextPoint, finalPoint, new_moves, total_move)\r\n\r\ndef setInitialBool(matrix_of_int):\r\n #set semua elemen sebagai False di matrix of boolean, kecuali elemen N,N\r\n matrix_of_boolean = [[False for i in range(len(matrix_of_int))] for i in range(len(matrix_of_int))]\r\n matrix_of_boolean[-1][-1] = True\r\n return matrix_of_boolean\r\n\r\ndef getTruePoints(matrix_of_boolean):\r\n #mengembalikan semua Point yang bernilai True di matrix of boolean\r\n truePoints = []\r\n for a in range(len(matrix_of_boolean)):\r\n js = [b for b, v in enumerate(matrix_of_boolean[a]) if v]\r\n for c in js:\r\n temp_final = [a, c]\r\n truePoints.append(temp_final)\r\n return truePoints\r\n \r\ndef DPAlgorithm(matrix_of_input, matrix_of_boolean, total_move):\r\n #DYNAMIC PROGRAMMING: memoization dengan pendekatan bottom up\r\n mat_len = len(matrix_of_boolean)\r\n #Mengisi matrix of boolean\r\n truePoints = getTruePoints(matrix_of_boolean)\r\n while (True):\r\n truePoints2 = truePoints\r\n for i in range(mat_len):\r\n for j in range(len(matrix_of_boolean[0])):\r\n initialPoint = [i,j]\r\n moves = matrix_of_input[i][j]\r\n for truePoint in truePoints:\r\n DFS(matrix_of_input, matrix_of_boolean, initialPoint, initialPoint, truePoint, moves, total_move)\r\n \r\n #printMatrix(matrix_of_boolean)\r\n truePoints = getTruePoints(matrix_of_boolean)\r\n if (truePoints == truePoints2):\r\n #sudah tidak ada Point yang berubah nilai\r\n break\r\n #menghilangkan semua kemunculan [N,N] pada total_move\r\n total_move = list(filter((([[mat_len-1, mat_len-1], [mat_len-1, mat_len-1]]).__ne__), total_move))\r\n return countTotal(total_move, [0,0], [mat_len-1, mat_len-1], matrix_of_boolean)\r\n\r\ndef pathFinding(matrix_of_input):\r\n matrix_of_boolean = setInitialBool(matrix_of_input)\r\n start = time()\r\n total_move = []\r\n #mengisi matrix of boolean dan menghitung total gerakan yang dibutuhkan\r\n total = DPAlgorithm(matrix_of_input, matrix_of_boolean, total_move)\r\n end = time()\r\n print(total)\r\n print(str(round((end-start)*1000)) + \"ms\")\r\n return total\r\n\r\nif __name__ == '__main__':\r\n initial_input = input()\r\n #ASUMSI: jika matrix berukuran 1x1, tidak ada path yang ditemukan karena dianggap sudah sampai\r\n final_input = initial_input.split()\r\n final_input = [int(i) for i in final_input]\r\n matrix_of_input = []\r\n matrix_of_input.append(final_input) #dapat panjang(N) input\r\n for _ in range(1, len(final_input)):#lakukan input baris sebanyak N-1\r\n temp_input = input()\r\n temp_list = temp_input.split()[:len(final_input)]\r\n temp_list = [int(elem) for elem in temp_list]\r\n matrix_of_input.append(temp_list)\r\n\r\n total = pathFinding(matrix_of_input)\r\n \r\n","sub_path":"APF.py","file_name":"APF.py","file_ext":"py","file_size_in_byte":4825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"274258239","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom tieba.items import TiebaItem\n\nclass BaiduSpider(scrapy.Spider):\n name = 'baidu'\n allowed_domains = ['baidu.com']\n start_urls = ['http://tieba.baidu.com/f?kw=%E6%B7%B1%E5%9C%B3']\n url_set = set()\n\n def parse(self, response):\n Tiezi = response.xpath('//div[contains(@class,\"threadlist_title\")]')\n pre = 'http://tieba.baidu.com'\n i = 0\n for post in Tiezi:\n if i>2:\n item = TiebaItem()\n name = post.xpath('./a/@title').extract()[0]\n url = pre + post.xpath('./a/@href').extract()[0]\n item['name'] = name\n item['url'] = url\n yield item\n i += 1\n urls = response.xpath('//a[contains(@class,\"pagination-item\")]/@href').extract()\n i = 0\n for u in urls:\n if i>1:\n break\n u = 'http:' + u\n if u in BaiduSpider.url_set:\n pass\n else:\n BaiduSpider.url_set.add(u)\n yield self.make_requests_from_url(u)\n i += 1\n\n","sub_path":"tieba/spiders/baidu.py","file_name":"baidu.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"377290724","text":"import os\nimport cv2\nimport pydarknet\n\nDETECTION_THRESHOLD = 0.1\nBOUND_RATIO_THRESHOLD = 0.5\n\n\ndef find_all(video_path, darknet_model,\n class_labels, start_frame=0,\n end_frame=None):\n video_capture = cv2.VideoCapture(video_path)\n\n if end_frame is None:\n end_frame = video_capture.get(cv2.CAP_PROP_FRAME_COUNT)\n\n with tqdm(total=end_frame-start_frame, desc=\"Detect and find\") as progress_bar:\n frame_counter = 0\n frames_bounds = []\n while video_capture.isOpened():\n ret, frame = video_capture.read()\n if ret:\n if end_frame > frame_counter > start_frame:\n\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # todo: is this a must ?\n frame_results_bounds = find_bounds_in_image(image_frame=frame,\n darknet_model=darknet_model,\n class_label=class_labels)\n frames_bounds.append(frame_results_bounds)\n progress_bar.update(1)\n frame_counter += 1\n\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break\n\n # Release everything if job is finished\n video_capture.release()\n cv2.destroyAllWindows()\n return frames_bounds\n\n\ndef blur_the_video(video_path, output_path, frames_bounds, start_frame=0,\n end_frame=None):\n cap = cv2.VideoCapture(video_path)\n\n if cap.isOpened():\n width, height, fps, fourcc = get_video_params(video_capture=cap)\n print(width, height, fps, fourcc)\n\n if end_frame is None:\n end_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n\n output = cv2.VideoWriter(output_path, fourcc, fps, (width, height))\n\n with tqdm(total=end_frame - start_frame, desc=\"Blur found boundaries\") as progress_bar:\n frame_counter = 0\n while cap.isOpened():\n ret, frame = cap.read()\n if ret:\n if end_frame > frame_counter > start_frame:\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n for i in range(-AMOUNT_OF_NEAR_FRAMES_INCLUDE_BLUR, AMOUNT_OF_NEAR_FRAMES_INCLUDE_BLUR+1):\n real_index = frame_counter - start_frame\n if 0 <= real_index + i < len(frames_bounds):\n bounds = frames_bounds[real_index + i]\n\n frame = add_blur(frame,\n bounds,\n expand=False)\n\n new_frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n output.write(new_frame)\n progress_bar.update(1)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n frame_counter += 1\n\n\n else:\n break\n\n # Release everything if job is finished\n output.release()\n\n cap.release()\n cv2.destroyAllWindows()\n\n\ndef get_box_size_ratio(y1, y2, x1, x2, image_shape):\n return (abs(y2 - y1) * abs(x2 - x1)) / (image_shape[0] * image_shape[1])\n\n\ndef expand_mask(image_shape, x_left, x_right, y_buttom, y_top, expand_amount=5):\n max_x = image_shape[0]\n max_y = image_shape[1]\n\n expanded_x_right = x_right + expand_amount\n expanded_y_top = y_top + expand_amount\n expanded_x_left = x_left - expand_amount\n expanded_y_buttom = y_buttom - expand_amount\n\n if expanded_x_left < 0: # min_x\n expanded_x_left = 0\n\n if expanded_y_buttom < 0: # min_y\n expanded_y_buttom = 0\n\n if expanded_x_right > max_x:\n expanded_x_right = max_x\n\n if expanded_y_top > max_y:\n expanded_y_top = max_y\n\n return expanded_x_left, expanded_x_right, expanded_y_buttom, expanded_y_top\n\n\ndef get_video_params(video_capture):\n width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = video_capture.get(cv2.CAP_PROP_FPS)\n # # Define the codec and create VideoWriter object\n # fourcc = int(video_capture.get(cv2.CAP_PROP_FOURCC))\n fourcc = cv2.VideoWriter_fourcc(*'MP4V')\n # print(video_capture.get(cv2.CAP_PROP_FORMAT))\n\n return width, height, fps, fourcc\n\n\ndef add_mask(image_frame, results_bounds):\n for (y1, y2, x1, x2) in results_bounds:\n cv2.rectangle(image_frame, (x1, y1), (x2, y2), (255, 0, 0), thickness=2)\n # cv2.putText(image_frame, category, (int(x), int(y)), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 0))\n\n return image_frame\n\n\ndef add_blur(image_frame, results_bounds, expand=False):\n for (y1, y2, x1, x2) in results_bounds:\n if expand:\n x1, x2, y1, y2 = expand_mask(image_shape=image_frame.shape,\n x_left=x1,\n x_right=x2,\n y_buttom=y1,\n y_top=y2,\n expand_amount=20)\n\n\n y1 = max(y1, 0)\n y2 = max(y2, 0)\n x1 = max(x1, 0)\n x2 = max(x2, 0)\n image_frame[y1:y2, x1:x2] = cv2.GaussianBlur(image_frame[y1:y2, x1:x2], (11, 11), cv2.BORDER_DEFAULT)\n\n return image_frame\n\n\ndef find_bounds_in_image(image_frame, darknet_model, class_label):\n darknet_image_frame = pydarknet.Image(image_frame)\n\n results = darknet_model.detect(darknet_image_frame,\n thresh=DETECTION_THRESHOLD,\n hier_thresh=.5, nms=.45) # todo: change this thresh-params thresh=0.01 #0.00051,\n results_bounds = []\n for category, score, bounds in results:\n category = str(category.decode(\"utf-8\"))\n if category.lower() in class_label:\n x, y, w, h = bounds\n y1, y2 = int(y - h / 2), int(y + h / 2)\n x1, x2 = int(x - w / 2), int(x + w / 2)\n\n image_box_size_ratio = get_box_size_ratio(y1, y2, x1, x2, image_shape=image_frame.shape)\n if image_box_size_ratio < BOUND_RATIO_THRESHOLD:\n results_bounds.append((y1, y2, x1, x2))\n\n return results_bounds\n","sub_path":"video_blurring/detection.py","file_name":"detection.py","file_ext":"py","file_size_in_byte":6356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"62992529","text":"import unittest\nclass Libro:\n def __init__ (self,paginas, titulo, genero, fechafinal, periodoprestamo):\n self.paginas = paginas\n self.titulo = titulo\n self.genero = genero\n self.fechafinal = fechafinal\n self.periodoprestamo = periodoprestamo\n def dame_info(self, paginas, titulo, genero):\n informacion = []\n informacion.append(self.paginas)\n informacion.append(self.titulo)\n informacion.append(self.genero)\n return informacion\n def prestamo(self, periodoprestamo = None):\n if periodoprestamo is None:\n self.periodoprestamo = '15 días'\n return periodoprestamo\nharrypotter = Libro(345, 'Harry Potter', 'fantasia', 27, None)\ninformacion_libro = harrypotter.dame_info(345, 'Harry Potter', 'fantasia')\nprestamo_libro = harrypotter.prestamo('15 días')\nprint('El libro cuyas páginas, título y género respectivamente son : ', informacion_libro, 'será prestado durante : ', prestamo_libro)\nclass Test_libro (unittest.TestCase):\n c1 = Libro(345, 'Harry Potter', 'fantasia', 27, None)\n def dame_info_test(self):\n self.assertEqual(c1.informacion, informacion)\n def prestamo_test(self):\n self.assertEqual(c1.prestamo, '15 días' )\nif __name__ == '__main__':\n unittest.main()\n\n \n","sub_path":"ejercicio_3.py","file_name":"ejercicio_3.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"517127638","text":"#Deena Dayal\n\n\nimport tkinter\nimport tkinter.messagebox as box\n\nclass MyGUI:\n def __init__(self):\n # Create the main window.\n self.mainWindow = tkinter.Tk()\n self.mainWindow.geometry(\"200x200\")\n self.mainWindow.title(\"ATM\")\n #counter for running total in account\n self.total = 0\n\n # Create two frames. One for the Radiobuttons\n # and another for the regular Button widgets.\n self.radioFrame = tkinter.Frame(self.mainWindow)\n self.buttonFrame = tkinter.Frame(self.mainWindow)\n\n # Create an StringVar object to use with\n # the Radiobuttons.\n self.radioVar = tkinter.StringVar()\n\n # Set the StringVar object to 1.\n self.radioVar.set(1)\n\n # Create the Radiobutton widgets in the top_frame.\n self.rb1 = tkinter.Radiobutton(self.radioFrame, text='Deposit', variable=self.radioVar, value='Deposit')\n self.rb2 = tkinter.Radiobutton(self.radioFrame, text='Withdrawal', variable=self.radioVar, value='Withdrawal')\n self.rb3 = tkinter.Radiobutton(self.radioFrame, text='Check Account Balance', variable=self.radioVar, value='Check Account Balance')\n\n # Pack the Radiobuttons.\n self.rb1.pack()\n self.rb2.pack()\n self.rb3.pack()\n\n # Set up buttons\n self.proceedButton = tkinter.Button(self.buttonFrame, text='Proceed', command=self.showOption)\n self.quitButton = tkinter.Button(self.buttonFrame, text='Quit', command=self.mainWindow.destroy)\n\n # Pack the Buttons.\n self.proceedButton.pack(side='left')\n self.quitButton.pack(side='left')\n\n # Pack the frames.\n self.radioFrame.pack()\n self.buttonFrame.pack()\n\n # Start the mainloop.\n tkinter.mainloop()\n \n\n #runs once user choose their bank option \n def showOption(self):\n #if user chooses deposit\n if self.radioVar.get() == \"Deposit\":\n\n #create deposit window\n self.depositWindow = tkinter.Tk()\n self.depositWindow.geometry(\"250x80\")\n self.depositWindow.title(\"Deposit\")\n\n #give it a label, entry and button frame\n self.depositLabelFrame = tkinter.Frame(self.depositWindow)\n self.depositEntryFrame = tkinter.Frame(self.depositWindow)\n self.depositButtonFrame = tkinter.Frame(self.depositWindow)\n\n #create label, entry \n self.depositLabel = tkinter.Label(self.depositLabelFrame, text=\"Enter the amount you want to deposit.\")\n self.depositEntry = tkinter.Entry(self.depositEntryFrame)\n\n #create ok button uses balance method\n self.depositOkButton = tkinter.Button(self.depositButtonFrame, text='OK', command=self.balance)\n #create cancel button returns to main window\n self.depositCancelButton = tkinter.Button(self.depositButtonFrame, text='Cancel', command=self.depositWindow.destroy)\n\n #pack all widgets and frames\n self.depositOkButton.pack(side='left')\n self.depositCancelButton.pack(side='left')\n self.depositLabelFrame.pack()\n self.depositEntryFrame.pack()\n self.depositButtonFrame.pack()\n self.depositEntry.pack()\n self.depositLabel.pack()\n \n #if user chooses withdrawal\n elif self.radioVar.get() == \"Withdrawal\":\n \n #create withdrawal window\n self.withdrawalWindow = tkinter.Tk()\n self.withdrawalWindow.geometry(\"250x80\")\n self.withdrawalWindow.title(\"Withdrawal\")\n #give it a label, entry and button frame\n self.withdrawalLabelFrame = tkinter.Frame(self.withdrawalWindow)\n self.withdrawalEntryFrame = tkinter.Frame(self.withdrawalWindow)\n self.withdrawalButtonFrame = tkinter.Frame(self.withdrawalWindow)\n\n #create label, entry\n self.withdrawalLabel = tkinter.Label(self.withdrawalLabelFrame, text=\"Enter the amount you want to withdrawal\")\n self.withdrawalEntry = tkinter.Entry(self.withdrawalEntryFrame)\n\n #create ok button uses balance method\n self.withdrawalOkButton = tkinter.Button(self.withdrawalButtonFrame, text='OK', command=self.balance)\n #create cancel button returns to main window\n self.withdrawalCancelButton = tkinter.Button(self.withdrawalButtonFrame, text='Cancel', command=self.withdrawalWindow.destroy)\n\n #pack all widgets and frames\n self.withdrawalOkButton.pack(side='left')\n self.withdrawalCancelButton.pack(side='left')\n self.withdrawalLabelFrame.pack()\n self.withdrawalEntryFrame.pack()\n self.withdrawalButtonFrame.pack()\n self.withdrawalEntry.pack()\n self.withdrawalLabel.pack()\n\n #if user chooses check account balance\n elif self.radioVar.get() == \"Check Account Balance\":\n\n #show current balance in account using running total\n balance = \"You have ${:.2f} in your account.\".format(self.total)\n box.showinfo(\"Check Account Balance\", balance)\n\n \n #runs after user has clicked enter and deposited/withdrew amount \n def balance(self):\n #if user chose deposit\n if self.radioVar.get() == \"Deposit\":\n #show amount they deposited\n deposit = \"You have deposited ${:.2f} into your account.\".format(float(self.depositEntry.get()))\n #add amount to running total\n self.total += float(self.depositEntry.get())\n box.showinfo(\"Deposit\", deposit)\n \n #if user chose withdrawal\n elif self.radioVar.get() == \"Withdrawal\":\n #show amount they withdrew\n withdrawal = \"You withdrew ${:.2f} from your account.\".format(float(self.withdrawalEntry.get()))\n #subtract amount from running total\n self.total -= float(self.withdrawalEntry.get())\n box.showinfo(\"Withdrawal\", withdrawal)\n \n #after user chooses either deposit or withdrawal, show updated balance\n finalBalance = \"Your new balance is ${:.2f}\".format(self.total)\n box.showinfo(\"Updated Account Balance\", finalBalance)\n\n#call class mygui\nrun = MyGUI()\n","sub_path":"ATM.py","file_name":"ATM.py","file_ext":"py","file_size_in_byte":6296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"283114685","text":"import sys\nimport re\nimport datetime\nfrom collections import defaultdict\nimport numpy as np\nfrom copy import deepcopy\n\nNEW_GUARD = re.compile('Guard #(\\d+) begins shift')\n\nevents = []\nwith open(sys.argv[1], 'r') as f:\n for line in f:\n date = datetime.datetime.strptime(line[:18], '[%Y-%m-%d %H:%M]')\n m = NEW_GUARD.search(line)\n if m is not None:\n events.append((deepcopy(date), int(m.group(1))))\n elif 'falls asleep' in line:\n events.append((date, 'falls asleep'))\n elif 'wakes up' in line:\n events.append((date, 'wakes up'))\n\nevents.sort()\nsleepy_time = defaultdict(lambda: np.zeros(60))\nguard = 0\nfor i, (date, event) in enumerate(events):\n if type(event) is int:\n guard = event\n continue\n if event == 'wakes up':\n prev_date = events[i-1][0]\n print(guard, prev_date.minute, date.minute)\n sleepy_time[guard][prev_date.minute:date.minute] += 1\n\nguard_sleep = {time.max(): guard for guard, time in sleepy_time.items()}\nprint(guard_sleep)\nmaximum_sleep = max(guard_sleep)\nsleepy_guard = guard_sleep[maximum_sleep]\nprint(sleepy_guard)\nprint(sleepy_time[sleepy_guard])\nprint(sleepy_time[sleepy_guard].argmax())\nprint(sleepy_guard * sleepy_time[sleepy_guard].argmax())\n","sub_path":"day_4/sol_2.py","file_name":"sol_2.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"213173843","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport logging\nimport time\n\nfrom telegram.ext import CommandHandler\n\n# Bomb feature:\n# once in 24h you can plant word-bomb. If someone in the chat uses this word - he becomes a pidor for 24h\n\nBOMB_TIMEOUT = 60 * 60 * 24\nBOMB_PIDOR_TIMEOUT = 60 * 60 * 24\nMIN_LENGTH = 3\nlog = logging.getLogger()\n\n\ndef remove_bomb(bot, job):\n bomber = job.context['bomber']\n chat_data = job.context['chat_data']\n if bomber in chat_data['bombs']:\n word = chat_data['bombs'].pop(bomber)\n log.debug(\"Bomb %s removed!\" % word)\n\n\ndef bomb_triggered(bot, job_queue, update, chat_data, word):\n user_id = update.message.from_user.id\n\n chat_data['bomb_pidors'][user_id] = time.time()\n\n if 'not_pidors' in chat_data and str(user_id) in chat_data['not_pidors']:\n chat_data['not_pidors'].remove(str(user_id))\n\n job_queue.run_once(remove_pidor, BOMB_PIDOR_TIMEOUT, context={'id': user_id, 'chat_data': chat_data})\n\n update.message.reply_text('Ты обосрался! Слово \\\"%s\\\" было бомбой! Теперь ты пидор на целый день! Л*ОХ' % word)\n\n\ndef remove_pidor(bot, job):\n user_id = job.context['id']\n bomb_pidors = job.context['chat_data']['bomb_pidors']\n\n if user_id in bomb_pidors and time.time() - bomb_pidors[user_id] >= BOMB_PIDOR_TIMEOUT:\n bomb_pidors.pop(user_id)\n log.debug(\"Pidor removed\")\n else:\n log.debug(\"Pidor checked but not removed!\")\n\n\ndef bomb_word(bot, update, args, job_queue, chat_data):\n if len(args) == 0:\n update.message.reply_text('/bomb ' % MIN_LENGTH)\n return\n\n if len(args) > 1:\n update.message.reply_text('Ска, ты тупой? Одно слово бля!')\n return\n\n word = str(args[0]).lower()\n user_id = update.message.from_user.id\n\n if 'bombs' not in chat_data:\n chat_data['bombs'] = {}\n\n if 'bomb_pidors' not in chat_data:\n chat_data['bomb_pidors'] = {}\n\n log.debug(chat_data['bombs'])\n if user_id in chat_data['bombs']:\n update.message.reply_text('Ска не еби до завтра!')\n elif len(word) < MIN_LENGTH:\n update.message.reply_text('Слово слишком короткое, как и твой член!')\n else:\n chat_data['bombs'][user_id] = word\n chat_data['chat_id'] = update.message.chat_id\n job_queue.run_once(remove_bomb, BOMB_TIMEOUT, context={'bomber': user_id, 'chat_data': chat_data})\n update.message.reply_text('Word bomb has been planted: %s' % word)\n\n\ndef start():\n return [CommandHandler('bomb', bomb_word, pass_args=True, pass_job_queue=True, pass_chat_data=True)]\n","sub_path":"modules/bomb_word.py","file_name":"bomb_word.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"325927463","text":"import vim\n\ndef runCmd(cmd):\n\t\"\"\"Runs a command using vim's !\"\"\"\n\tvim.command(\"!\"+cmd)\n\ndef runSystemCmd(cmd, fileOutput=None):\n\t\"\"\"Runs the command using vim's system mechanism.\n\t\tfileOutput - specifies the file on disk to save the output of the cmd to\n\t\t\t\t\tif null doesn't save anything\n\t\treturns the results of the command\"\"\"\n\tvim.command(\"let cmdOutput = system('{0}')\".format(cmd))\n\toutput = vim.eval(\"cmdOutput\")\n\tif fileOutput != None:\n\t\tfile = open(fileOutput, \"w\")\n\t\tfile.write(output)\n\t\tfile.close()\n\treturn output\n\ndef input(message):\n\t\"\"\"Prompt the user for input with. Supply the message as a prompt\n\t\treturns the input from the user\"\"\"\n\tvim.command(\"let inputText = input('{0}')\".format(message))\n\ttext = vim.eval(\"inputText\")\n\treturn text\n\ndef inputSecret(message):\n\t\"\"\"Prompt the user for hidden input. Supplies the message as a prompt\n\t\treturns the input from the user\"\"\"\n\tvim.command(\"let inputText = inputsecret('{0}')\".format(message))\n\ttext = vim.eval(\"inputText\")\n\treturn text\n\ndef splitWindowLeft(size, fileName=None):\n\t\"\"\"Split the vim window vertically with the new window appearing on the west\n\tof the screen\n\t\tsize is the horizontal screen size the window should take\n\t\tfileName is an optional name of a file to open in the new window\n\t\treturns the newly created buffer\"\"\"\n\tif fileName is None:\n\t\tvim.command(\"aboveleft {0}vsplit {1}\".format(size, fileName))\n\telse:\n\t\tvim.command(\"aboveleft {0}vnew\".format(size))\n\tgotoStart()\n\treturn vim.current.buffer\n\ndef splitWindodwRight(size, fileName=None):\n\t\"\"\"Split the vim window vertically with the new window appearing on the east\n\tof the screen\n\t\tsize is the horizontal screen size the window should take\n\t\tfileName is an optional name of a file to open in the new window\n\t\treturns the newly created buffer\"\"\"\n\tif fileName is None:\n\t\tvim.command(\"botright {0}vsplit {1}\".format(size, fileName))\n\telse:\n\t\tvim.command(\"botright {0}vnew\".format(size))\n\tgotoStart()\n\treturn vim.current.buffer\n\ndef splitWindowBottom(size, fileName=None):\n\t\"\"\"Split the vim window horizontally with the new window appearing on the south\n\tof the screen\n\t\tsize is the vertical screen size (in lines) that the window should use\n\t\tfileName is an optional name of a file to open in the new window\n\t\treturns the newly created buffer\"\"\"\n\tif fileName is None:\n\t\tvim.command(\"belowright {0}split {1}\".format(size, fileName))\n\telse:\n\t\tvim.command(\"belowright {0}new\".format(size))\n\tgotoStart()\n\treturn vim.current.buffer\n\ndef splitWindowTop(size, fileName=None):\n\t\"\"\"Split the vim window horizontally with the new window appearing on the north\n\tof the screen\n\t\tsize is the vertical screen size (in lines) that the window should use\n\t\tfileName is an optional name of a file to open in the new window\n\t\treturns the newly created buffer\"\"\"\n\tif fileName is None:\n\t\tvim.command(\"{0}split {1}\".format(size, fileName))\n\telse:\n\t\tvim.command(\"belowright {0}new\".format(size))\n\tgotoStart()\n\treturn vim.current.buffer\n\ndef setBufferTypeScratch():\n\t\"\"\"Make the current buffer a scratch buffer (i.e. where a temporary buffer that can be discarded)\n\tat any time\"\"\"\n\tvim.command(\"setlocal buftype=nofile\")\n\tvim.command(\"setlocal bufhidden=hide\")\n\tvim.command(\"setlocal noswapfile\")\n\ndef gotoStart():\n\t\"\"\"Moves the cursor to the start of the current buffer\"\"\"\n\tvim.command(\"normal gg\")\n\ndef setupCompletion(onKeys, completionMethod):\n\t\"\"\"The vimplus complete method, which display a list of available autocompletions\n\tcan only be called from insert mode. This method sets up the appropriate key bindings\n\tthat will trigger calling the method\n\t\tonKeys - the keys that will trigger the method\n\t\tcompletionMethod - the completion method to call\"\"\"\n\tpass\n\ndef complete(words):\n\t\"\"\"Shows the vim autocompletion menu\"\"\"\n\tvim.command(\"call complete(col('.'), {0})\".format(words))\n\ndef onEvent(event, action):\n\t\"\"\"Registers a call back that will be invoked when a vim event occurs\n\t\tevent is the name of the vim event to register (use event members of vimplus)\n\t\taction is the python method to call when the event occurs\"\"\"\n\tpyMethodName = action.__name__\n\tvimFuncName = pyMethodName\n\tvimFuncName = pyMethodName[0].upper() + pyMethodName[1:]\n\tvim.command(\"autocmd {event} * call {functionName}()\".format(event=event, functionName=vimFuncName))\t\n\tvim.command(\"\"\"fun! {functionName}()\npy {pyMethodName}()\nendf\"\"\".format(functionName=vimFuncName, pyMethodName=pyMethodName))\n\neventBuferWrite = \"BuferWrite\"\neventCursorMoved = \"CursorMoved\"\n","sub_path":"plugin/vimplus.py","file_name":"vimplus.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"418321826","text":"from selenium import webdriver\nimport time\n\nimport pymongo\n\nconnection = pymongo.MongoClient('127.0.0.1',27017)\n\n# SERVICE_ARGS = ['--load-images=false', '--disk-cache=true']\n\n# driver = webdriver.PhantomJS(service_args=SERVICE_ARGS)\ndriver = webdriver.Chrome()\n\nurl = 'https://book.douban.com/tag/?view=type&icn=index-sorttags-hot'\n\ndriver.get(url)\n\ntagCols = driver.find_elements_by_class_name('tagCol')\n\nallTags = {}\nkinds = ['文学', '流行', '文化', '生活', '经管', '科技']\n\nfor i in range(6):\n\ttags = tagCols[i].find_elements_by_tag_name('a')\n\ttags = list(map(lambda a: a.text, tags))\n\n\tallTags[kinds[i]] = tags\n\nbookInfo = {}\n\ndef spide(kind):\n\tdb = connection[kind]\n\n\tprint(kind + '...')\n\n\tfor tag in allTags[kind]:\n\t\ttable = db[tag]\n\n\t\tprint(' ' + tag + '...')\n\n\t\t# bookInfo_smallTag = {}\n\n\t\turl = 'https://book.douban.com/tag/' + tag\n\t\ttime.sleep(2)\n\n\t\tdriver.get(url)\n\n\t\ti = 1\n\n\t\twhile True:\n\t\t\tprint('==========正在爬第%d 页...==========' % i)\n\t\t\titems = driver.find_elements_by_class_name('subject-item')\n\t\t\n\t\t\tfor item in items:\n\t\t\t\tbookName = item.find_element_by_tag_name('h2').text\n\n\t\t\t\tprint(' ' + bookName + '...')\n\n\t\t\t\tbook_url = item.find_element_by_tag_name('a').get_attribute('href')\n\t\t\t\tpic_url = item.find_element_by_tag_name('img').get_attribute('src')\n\t\t\t\tpub_info = item.find_element_by_class_name('pub').text\n\t\t\t\tstar_people = item.find_element_by_class_name('star').text\n\n\t\t\t\ttry:\n\t\t\t\t\tintroduction = item.find_element_by_tag_name('p').text\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tintroduction = ''\n\n\t\t\t\tprint('正在插入%s...' % bookName)\n\t\t\t\ttable.insert({'bookName': bookName, 'book_url': book_url, 'pic_url': pic_url, 'pub_info': pub_info, 'star_people': star_people, 'introduction': introduction})\n\t\t\t\tprint('插入%s完成...' % bookName)\n\n\t\t\ttry:\n\t\t\t\tdriver.find_element_by_css_selector('#subject_list > div.paginator > span.next > a').click()\n\t\t\t\ttime.sleep(2)\n\t\t\t\ti += 1\n\t\t\texcept Exception as e:\n\t\t\t\tbreak\n\n\t\tprint()\n\tprint()\n\nif __name__ == '__main__':\n\t# for kind in kinds:\n\t# \tspide(kind)\n\tfor j in range(2, 6):\n\t\tspide(kinds[j])\n\n\n# driver = webdriver.Chrome()\n# driver.get('https://book.douban.com/tag/小说')\n\n# items = driver.find_elements_by_class_name('subject-item')\n\t\t\n# for item in items:\n# \tbookName = item.find_element_by_tag_name('h2').text\n\n# \tprint(' ' + bookName + '...')\n\n# \tbook_url = item.find_element_by_tag_name('a').get_attribute('href')\n# \tpic_url = item.find_element_by_tag_name('img').get_attribute('src')\n# \tpub_info = item.find_element_by_class_name('pub').text\n# \tstar_people = item.find_element_by_class_name('star').text\n# \tintroduction = item.find_element_by_tag_name('p').text\n\n","sub_path":"ProjectCode/DouBanRead/spide.py","file_name":"spide.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"181229291","text":"def test_download_model_from_blob(test_env, afs_models, model, blob_info, delete_model_respository):\n resp = afs_models.download_model_from_blob(\n instance_id=model['owner'], \n model_repository_id=model['model_repository'], \n model_id=model['uuid'], \n save_path=\"download_model.h5\",\n blob_endpoint=blob_info['blob_endpoint'],\n blob_accessKey=blob_info['blob_accessKey'],\n blob_secretKey=blob_info['blob_secretKey'],\n bucket_name=blob_info['bucket_name'],\n )\n\n assert resp == True\n with open(\"download_model.h5\", \"r\") as f:\n content = f.read()\n assert content == \"unit test\"\n","sub_path":"tests/v2/test_models_dev.py","file_name":"test_models_dev.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"54071900","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def inorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n return self.func(root, [])\n\n def func(self, root, re):\n '''\n :type root: TreeNode\n :rtype: List[int]\n '''\n if root and root.val is not None:\n self.func(root.left, re)\n re.append(root.val)\n self.func(root.right, re)\n return re\n\n\nif __name__ == \"__main__\":\n tree0 = TreeNode(0)\n tree1 = TreeNode(1)\n tree2 = TreeNode(2)\n tree3 = TreeNode(3)\n tree4 = TreeNode(4)\n tree5 = TreeNode(5)\n tree6 = TreeNode(6)\n tree0.left = tree1\n tree0.right = tree2\n tree1.left = tree3\n tree2.left = tree4\n tree3.left = tree5\n tree3.right = tree6\n\n print(str(Solution().inorderTraversal(tree0)))\n","sub_path":"done/94_binary_tree_inorder_traversal.py","file_name":"94_binary_tree_inorder_traversal.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"487491547","text":"'''\ntraceback.print_exc() 는 에러가 무엇인지 찍어주는 역\n'''\ndef changeInt (age):\n try:\n number = int(age)\n except Exception as ex:\n import traceback\n traceback.print_exc()\n print('너의 나이는 {} [{}]'.format(age, ex))\n return number\n\n\ntext = '100%'\n\ntry:\n number = int(text)\nexcept ValueError:\n print('{} is not number'.format(text))\n\n\nlists = ['1','B',3]\n\nfor list in enumerate(lists):\n\n try:\n print('No.{}: int{}'.format(list[0],int(list[1])))\n except ValueError:\n print('No.{}: String{}'.format(list[0],list[1]))\n\n\ntry:\n import guhala\nexcept Exception as ex:\n print('에러 발생:',ex)\n\n\nchangeInt('rk')","sub_path":"com/base/basic09_exception.py","file_name":"basic09_exception.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"218190474","text":"def linear_search(arr, target):\n # Your code here \n for i in range(0, len(arr)):\n if arr[i]==target:\n return i\n return -1 # not found\n\n\n# Write an iterative implementation of Binary Search\ndef binary_search(arr, target): \n #if target is in middle\n #if target< arr[middle], it would be in the left\n # else it would be in right\n # middle= len(arr)//2\n low= 0\n high= len(arr)-1\n while low <= high:\n middle= (low+high)//2 \n #if target is in middle\n if arr[middle]== target:\n return middle \n #if target is smaller than the middle value,\n #target would be on the left of the search tree\n #Search range would be: low=0, high= (middle-1 ) \n elif arr[middle]>target:\n high = middle-1\n #if target is larger than the middle value,\n # it wouuld be on the right of the search tree\n #Search range would be: low=middle+1, high= (len(arr)-1)\n # low would be more than middle \n elif arr[middle]= count:\n page = 1\n paginator = Paginator(lists, length)\n try:\n lists = paginator.page(page)\n except (EmptyPage, InvalidPage):\n lists = paginator.page(paginator.num_pages)\n\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n re_str = '(.*?)'\n number = length * (page-1) + 1\n\n for d in lists.object_list:\n is_not_share = True if d.customer_id == request.user.id else False\n t = TemplateResponse(request, 'address/ajax_ml_maillist.html', {'d': d, 'number': number, 'is_not_share': is_not_share,})\n t.render()\n rs[\"aaData\"].append(re.findall(re_str, t.content, re.DOTALL))\n number += 1\n return HttpResponse(json.dumps(rs, ensure_ascii=False), content_type=\"application/json\")\n\n@login_required\ndef ajax_export_limit(request, user_id, list_id):\n msg = 'Y'\n if request.user.service().disabled == '1':\n return HttpResponse(json.dumps({'msg': \"N\"}), content_type=\"application/json\")\n obj = MailList.objects.filter(id=list_id, customer_id=user_id).first()\n if obj and not obj.is_allow_export:\n return HttpResponse(json.dumps({'msg': \"N\"}), content_type=\"application/json\")\n cr = connections['mm-pool'].cursor()\n try:\n sql = \"SELECT COUNT(1) FROM ml_subscriber_{} WHERE list_id={};\".format(user_id, list_id)\n cr.execute(sql)\n data = cr.fetchone()\n count = data[0] if data else 0\n except:\n count = 0\n if count > 100000:\n msg = 'N'\n return HttpResponse(json.dumps({'msg': msg}), content_type=\"application/json\")\n\n# 获取数量\n@login_required\ndef ajax_maillist_count(request, list_id):\n status = request.GET.get('status', '')\n cr = connections['mm-pool'].cursor()\n user_id = model_addresses.get_address_userid(request, list_id)\n if status == '1':\n count = address_sqls.get_addr_count(cr, user_id, list_id, status)\n html = '{}'.format(list_id, _(u'查看联系人分类邮箱列表'), count)\n return HttpResponse(json.dumps({'info': html}), content_type=\"application/json\")\n elif status == '2':\n count = address_sqls.get_addr_count(cr, user_id, list_id, status)\n html = '{}'.format(list_id, _(u'查看订阅用户列表'), count)\n return HttpResponse(json.dumps({'info': html}), content_type=\"application/json\")\n elif status == '3':\n count = address_sqls.get_addr_count(cr, user_id, list_id, status)\n html = '{}'.format(list_id, _(u'查看退订用户列表'), count)\n return HttpResponse(json.dumps({'info': html}), content_type=\"application/json\")\n else:\n raise Http404\n\n# 添加 联系人分类\n@login_required\ndef ml_maillist_add(request):\n form = MailListForm(request.user)\n if request.method == \"POST\":\n form = MailListForm(request.user, request.POST)\n if form.is_valid():\n obj = form.save()\n return HttpResponseRedirect('/address/maintain/{}/'.format(obj.id))\n return render(request, 'address/ml_maillist_modify.html', context={\n 'form': form,\n 'ml_maillist_flag': 1,\n 'list_id': '',\n 'edm_web_url': settings.EDM_WEB_URL,\n 'is_allow_export': True,\n })\n\n# 修改 联系人分类\n@login_required\ndef ml_maillist_modify(request, list_id):\n obj = get_object(MailList, request.user, list_id)\n form = MailListForm(request.user, instance=obj)\n if request.method == \"POST\":\n status = request.POST.get('status', '')\n form = MailListForm(request.user, request.POST, instance=obj)\n if status == 'allow':\n url = '/address/maintain/{}/'.format(list_id)\n elif status == 'notallow':\n url = '/address/?isvalid=1'\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(url)\n return render(request, 'address/ml_maillist_modify.html', context={\n 'form': form,\n 'ml_maillist_flag': 2,\n 'list_id': list_id,\n 'edm_web_url': settings.EDM_WEB_URL,\n 'is_allow_export': obj.is_allow_export,\n })\n\n# 批量上传地址文件\n@csrf_exempt\ndef ml_addr_multi_upload(request, list_id):\n user_id = request.POST.get('user_id', '')\n # is_disorder = request.POST.get('is_disorder', '')\n # is_disorder = True if is_disorder.lower() == 'true' else False\n is_disorder=True\n is_ignore = request.POST.get('is_ignore', '')\n is_ignore = True if is_ignore.lower() == 'true' else False\n try:\n obj = MailList.objects.get(customer_id=user_id, id=list_id)\n except:\n return HttpResponse(json.dumps({'status': 'M'}), content_type=\"application/json\")\n\n attachfile = request.FILES.get('filedata', None)\n if not attachfile:\n return HttpResponse(json.dumps({'status': 'N'}), content_type=\"application/json\")\n\n filename = attachfile.name\n suffix = filename.split('.')[-1]\n if suffix.lower() not in ('xls', 'xlsx', 'csv', 'txt', 'zip', 'rar', 'docx'):\n return HttpResponse(json.dumps({'status': 'S'}), content_type=\"application/json\")\n\n filepath = os.path.join(\n settings.ADDRESS_IMPORT_PATH,\n '{}_{}.{}'.format(int(time.time()), random.randint(10000, 99999), suffix)\n )\n with open(filepath, 'w') as fw:\n fw.write(attachfile.read())\n cr = connections['mm-pool'].cursor()\n address_sqls.checkTable(cr, request.user.id)\n # 标志列表正在导入\n obj.is_importing = True\n obj.save()\n AddressImportLog.objects.create(\n maillist_id=list_id, customer_id=user_id, filename=filename,\n filepath=filepath, is_disorder=is_disorder, is_newimport=True, is_ignore=is_ignore\n )\n if request.user.service().is_auto_duplicate:\n redis = get_redis_connection()\n redis.rpush(EDM_WEB_MAIL_DUPLICATE_QUEUE, int(user_id))\n return HttpResponse(json.dumps({'status': 'Y'}), content_type=\"application/json\")\n\n# 上传 地址文件\n@login_required\ndef ml_maillist_upload(request):\n if request.method == \"POST\":\n file = request.FILES[u'files[]']\n is_disorder = request.POST.get('is_disorder', '')\n is_ignore = request.POST.get('is_ignore', '')\n maillist_id = int(request.GET.get('maillist', 0))\n is_disorder = True if is_disorder.lower() == 'true' else False\n is_ignore = True if is_ignore.lower() == 'true' else False\n\n if not maillist_id or (maillist_id and MailList.objects.filter(id=maillist_id, customer=request.user)):\n filepath = os.path.join(\n settings.ADDRESS_IMPORT_PATH,\n '{}_{}.{}'.format(int(time.time()), random.randint(10000, 99999),\n file.name.split('.')[-1])\n )\n with open(filepath, 'w') as fw:\n fw.write(file.read())\n cr = connections['mm-pool'].cursor()\n address_sqls.checkTable(cr, request.user.id)\n AddressImportLog.objects.create(\n maillist_id=maillist_id, customer=request.user, filename=file.name,\n filepath=filepath, is_disorder=is_disorder, is_newimport=True, is_ignore=is_ignore\n )\n return JsonResponse({'result': {}})\n return render(request, 'address/ml_maillist_upload.html', context={})\n\n# 地址导入记录\n@login_required\ndef ml_import_log(request):\n if request.method == 'POST':\n id = request.POST.get('id')\n type = request.POST.get('type')\n filename = '{}_maillist_err_t{}.txt'.format(id, type)\n filepath = os.path.join(\"/usr/local/mail-import/data/\", filename)\n if os.path.exists(filepath):\n wrapper = FileWrapper(file(filepath))\n response = HttpResponse(wrapper, content_type='application/octet-stream')\n response['Content-Length'] = os.path.getsize(filepath)\n response['Content-Disposition'] = 'attachment; filename=%s' % filename\n return response\n else:\n messages.add_message(request, messages.ERROR, _(u'文件不存在'))\n return HttpResponseRedirect(reverse('ml_import_log'))\n return render(request, 'address/ml_import_log.html', context={})\n\n@login_required\ndef ajax_ml_import_log(request):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n colums = ['id', 'id', 'filename', 'maillist_id', 'status', 'count_all', 'count_err_1']\n\n lists = AddressImportLog.objects.filter(customer_id=request.user.id)\n\n if search:\n lists = lists.filter(filename__icontains=search)\n\n if order_column and int(order_column) < len(colums):\n if order_dir == 'desc':\n lists = lists.order_by('-%s' % colums[int(order_column)])\n else:\n lists = lists.order_by('%s' % colums[int(order_column)])\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n\n try:\n start_num = int(data.get('start', '0'))\n page = start_num / length + 1\n except ValueError:\n start_num = 0\n page = 1\n count = lists.count()\n if start_num >= count:\n page = 1\n paginator = Paginator(lists, length)\n try:\n lists = paginator.page(page)\n except (EmptyPage, InvalidPage):\n lists = paginator.page(paginator.num_pages)\n\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n re_str = '(.*?)'\n number = length * (page-1) + 1\n\n for d in lists.object_list:\n t = TemplateResponse(request, 'address/ajax_ml_import_log.html', {'d': d, 'number': number})\n t.render()\n rs[\"aaData\"].append(re.findall(re_str, t.content, re.DOTALL))\n number += 1\n return HttpResponse(json.dumps(rs, ensure_ascii=False), content_type=\"application/json\")\n\n################################\n# 查看无效地址\n@login_required\ndef invalid_view(request, log_id):\n return invalidView(request, log_id)\n\n################################\n# 联系人分类管理: 添加地址\n@login_required\ndef ml_maillist_maintain_address(request, list_id):\n obj = get_object(MailList, request.user, list_id)\n if not obj.is_allow_export:\n raise Http404\n subject = model_addresses.get_subject(request, list_id)\n return render(request, 'address/ml_maillist_maintain_address.html', context={\n 'subject': subject,\n 'list_id': list_id,\n })\n\n# 联系人分类管理: 添加地址到联系人分类\n@csrf_exempt\n@login_required\ndef ajax_add_address(request, list_id):\n data = request.POST\n post_data = data.get('post_data', '')\n cr = connections['mm-pool'].cursor()\n customer_id = request.user.id\n address_sqls.checkTable(cr, customer_id)\n tablename = 'ml_subscriber_' + str(customer_id)\n values, _addresses = [], []\n success, fail, repeat, valid = 0, 0, 0, 0\n p = re.compile('^(\\w|[-+=.])+@\\w+([-.]\\w+)*\\.(\\w+)$')\n p_phone = re.compile(\n r'((\\+?86)|(\\(\\+86\\)))?(\\s)?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|14[57][0-9]{8}|1349[0-9]{7}|177[0-9]{8})')\n var_lists = get_addr_var_fields(cr, request.user.id)\n # field_str = u'(list_id, address, fullname, sex, birthday, phone, area, {}, created)'.format(','.join(var_lists))\n mongo = pymongo.MongoClient(host='mongodb://{username}:{password}@{host}:{port}/{dbname}'.format(**mongo_cfg))\n db = mongo['mm-mc'].badmail\n\n import_obj = AddressImportLog.objects.create(\n maillist_id=list_id, customer=request.user, filename=None,\n filepath=None, status='1', count_all=0,\n count_err_1=0, count_err_2=0,\n time_import=time.strftime(\"%Y-%m-%d %H:%M:%S\"), time_finish=time.strftime(\"%Y-%m-%d %H:%M:%S\")\n )\n # 错误类型 1\n err_t1_name = '{}_maillist_err_t1.txt'.format(import_obj.id)\n err_t1_path = os.path.join(\"/usr/local/mail-import/data/\", err_t1_name)\n fp_err_t1 = open(err_t1_path, \"a\")\n\n # 错误类型 2\n err_t2_name = '{}_maillist_err_t2.txt'.format(import_obj.id)\n err_t2_path = os.path.join(\"/usr/local/mail-import/data/\", err_t2_name)\n fp_err_t2 = open(err_t2_path, \"a\")\n\n redis = get_redis_connection()\n for d in post_data.split('\\n'):\n l = d.strip().replace('\\r', '').replace(u';', ';')\n l = l.split(\";\")\n length = len(l)\n if ( length == 1 and not l[0].strip() ) or ( not l ):\n continue\n\n # 判断邮箱地址格式\n if l and not p.match(l[0].strip()):\n fail += 1\n address_tools.save_error_addr(fp_err_t1, l[0])\n continue\n\n address = l[0].strip()\n if address.split('@')[-1] in (u'yahoo.com.cn', u'yahoo.cn'):\n valid += 1\n address_tools.save_error_addr(fp_err_t1, l[0])\n continue\n\n if db.find_one({\"addr\": address}):\n valid += 1\n address_tools.save_error_addr(fp_err_t1, l[0])\n continue\n\n # 判断重复\n cr.execute(u\"SELECT address_id FROM {} WHERE address='{}' AND list_id={} LIMIT 1;\".format(tablename, address, list_id))\n if cr.fetchone():\n repeat += 1\n address_tools.save_error_addr(fp_err_t2, l[0])\n continue\n\n if address in _addresses:\n repeat += 1\n address_tools.save_error_addr(fp_err_t2, l[0])\n continue\n\n if check_qq_addr(address):\n redis.lpush(GLB_REDIS_REMOTE_GET_QQ, address)\n\n _addresses.append(address)\n try:\n fullname = l[1].strip() if l[1].strip() else '@'.join(address.split(\"@\")[:-1])\n except:\n fullname = '@'.join(address.split(\"@\")[:-1])\n\n sex = l[2].strip() if length > 2 else ''\n sex = address_tools.handleSex(sex)\n\n birthday = l[3].strip() if length > 3 else ''\n birthday = address_tools.hanfBirthday(birthday)\n\n phone = l[4].strip() if length > 4 else ''\n m = p_phone.search(phone)\n phone = m.group() if m else ''\n\n area = l[5].strip() if length > 5 else ''\n vars = l[6:]\n sql_parts, sql_args = get_fields_args(var_lists, vars)\n sql = \"INSERT INTO `mm-pool`.`ml_subscriber_%s` SET list_id=%s, address=%s, fullname=%s, sex=%s, birthday=%s, phone=%s, area=%s, created=%s{}\".format(sql_parts)\n args = [customer_id, list_id, address, fullname, sex, birthday, phone, area, time.strftime(\"%Y-%m-%d %H:%M:%S\")] + sql_args\n cr.execute(sql, args)\n success += 1\n msg = _(\n u'成功提交%(success)d条记录, 其中有%(repeat)d条重复记录, %(fail)d条格式错误, %(valid)d条无效地址'\n ) % {\n 'success': success,\n 'repeat': repeat,\n 'fail': fail,\n 'valid': valid,\n }\n\n obj = MailList.objects.filter(id=list_id).first()\n if obj:\n obj.count_all = F('count_all') + success + fail + valid\n obj.count_err = F('count_err') + fail + valid\n obj.updated = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n obj.save()\n\n import_obj.count_all = success + fail + valid + repeat\n import_obj.count_err_1 = fail + valid\n import_obj.count_err_2 = repeat\n import_obj.time_finish = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n import_obj.save()\n if int(success) > 0:\n redis.rpush(EDM_WEB_USER_MAIL_IMPORT_COUNT_QUEUE, '{}_{}'.format(customer_id, list_id))\n if request.user.service().is_auto_duplicate:\n redis.rpush(EDM_WEB_MAIL_DUPLICATE_QUEUE, int(customer_id))\n\n return HttpResponse(json.dumps({'msg': msg}), content_type=\"application/json\")\n\n# #### 订阅地址 #####\n@login_required\ndef ml_subscribe_list(request, list_id):\n obj = model_addresses.get_address_obj(request, list_id)\n user_id = obj.customer_id\n if request.user.id == user_id:\n is_modify_flag = obj.is_allow_export\n else:\n is_modify_flag = False\n # obj = get_object(MailList, request.user, list_id)\n # is_modify_flag = obj.is_allow_export\n subject = model_addresses.get_subject(request, list_id, obj)\n is_subscribe = request.GET.get('is_subscribe', '')\n cr = connections['mm-pool'].cursor()\n address_sqls.checkTable(cr, user_id)\n if request.method == \"POST\":\n obj2 = get_object(MailList, request.user, list_id)\n tablename = 'ml_subscriber_' + str(request.user.id)\n id = request.POST.get('id', False)\n ids = request.POST.get('ids', '')\n status = int(request.POST.get('status', False))\n redis = get_redis_connection()\n if int(status) == -2: # 单个删除\n sql = \"DELETE FROM {0} WHERE address_id={1}\".format(tablename, id)\n cr.execute(sql)\n messages.add_message(request, messages.SUCCESS, _(u'成功删除'))\n redis.rpush(EDM_WEB_USER_MAIL_IMPORT_COUNT_QUEUE, '{}_{}'.format(request.user.id, list_id))\n return HttpResponseRedirect(\"/address/subscribe/{}/\".format(list_id))\n if int(status) == -1: # 批量删除\n sql = \"DELETE FROM {0} WHERE address_id IN ({1})\".format(tablename, ids)\n cr.execute(sql)\n messages.add_message(request, messages.SUCCESS, _(u'成功删除'))\n redis.rpush(EDM_WEB_USER_MAIL_IMPORT_COUNT_QUEUE, '{}_{}'.format(request.user.id, list_id))\n return HttpResponseRedirect(\"/address/subscribe/{}/\".format(list_id))\n\n var_lists = get_addr_var_fields(cr, request.user.id)\n field_lists = []\n for i in xrange(len(var_lists)-10):\n field_lists.append(u'变量{}'.format(11+i))\n return render(request, 'address/ml_subscribe_list.html', context={\n 'subject': subject,\n 'list_id': list_id,\n 'is_subscribe': is_subscribe,\n 'field_lists': field_lists,\n 'is_modify_flag': is_modify_flag,\n })\n\n\n@login_required\ndef ajax_subscribe_list(request, list_id):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n is_subscribe = data.get('is_subscribe', '')\n colums = ['address_id', 'address_id', 'address', 'is_subscribe', 'activity']\n\n obj = model_addresses.get_address_obj(request, list_id)\n user_id = obj.customer_id\n if request.user.id == user_id:\n is_modify_flag = obj.is_allow_export\n else:\n is_modify_flag = False\n # obj = get_object(MailList, request.user, list_id)\n # is_modify_flag = obj.is_allow_export\n\n where_str = u'list_id={}'.format(list_id)\n if is_subscribe == '1':\n where_str += u\" and is_subscribe=0 \"\n elif is_subscribe == '2':\n where_str += u\" and is_subscribe=1 \"\n elif is_subscribe == '3':\n where_str += u\" and is_subscribe=2 \"\n\n order_by_str = ''\n if order_column and int(order_column) < len(colums):\n if order_dir == 'desc':\n order_by_str = u'order by %s desc' % colums[int(order_column)]\n else:\n order_by_str = u'order by %s asc' % colums[int(order_column)]\n\n if not is_modify_flag:\n if validators.check_email(search):\n where_str += u\"\"\" and address='{}' \"\"\".format(search)\n elif search:\n where_str += u\"\"\" and 1=0 \"\"\"\n elif is_modify_flag and search:\n where_str += u\"\"\" and address like '%{0}%' \"\"\".format(search)\n\n cr = connections['mm-pool'].cursor()\n tablename = 'ml_subscriber_' + str(user_id)\n sql = u\"SELECT COUNT(1) FROM %s WHERE %s;\" % (tablename, where_str)\n cr.execute(sql)\n rows = cr.fetchall()\n count = rows[0][0]\n\n var_lists = get_addr_var_fields(cr, user_id)\n field_str = ','.join(var_lists)\n\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n if not is_modify_flag and length > 25:\n length = 25\n else:\n length = min(length, 500)\n\n try:\n start_num = int(data.get('start', '0'))\n except ValueError:\n start_num = 0\n if start_num >= count:\n start_num = 0\n page = start_num / length + 1\n\n if not is_modify_flag and page>5:\n rows = []\n else:\n limit_str = u'limit %s offset %s' % (length, start_num)\n sql = u\"\"\"\n SELECT address_id, address, fullname, is_subscribe,\n sex, birthday, phone, activity, area, created, updated,\n %s\n FROM %s WHERE %s %s %s;\n \"\"\" % (field_str, tablename, where_str, order_by_str, limit_str)\n cr.execute(sql)\n rows = cr.fetchall()\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n\n # number = length * (page - 1) + 1\n _lambda_var = lambda s: s if s else ''\n for r in rows:\n address_id, address, fullname, is_subscribe, sex, birthday, phone, activity, area, created, updated = r[:11]\n varList = [_lambda_var(i) for i in list(r[11:])]\n if is_modify_flag:\n operate = u\"\"\"\n {2}\n {3}\n \"\"\".format(list_id, address_id, _(u'修改'), _(u'删除'))\n else:\n operate = \"\"\n issubscribe = u'是' if is_subscribe else u'否'\n if sex == 'M':\n sex = _(u'男')\n elif sex == 'F':\n sex = _(u\"女\")\n else:\n sex = ''\n\n activity_obj = EmailOpenClick.objects.filter(email=address).first()\n activity = activity_obj.activity if activity_obj else 0\n\n birthday = birthday if birthday != '0000-00-00' else '-'\n activity_s = u'' * 5\n if 0 < activity < 5:\n activity_r = u'' * activity\n activity_v = u'' * (5 - activity)\n activity_s = u\"{}{}\".format(activity_r, activity_v)\n elif activity >= 5:\n activity_s = u'' * 5\n other = u\"\"\"\n {6}: {0}
\n {7}: {1}
\n {8}: {2}
\n {9}: {3}
\n {10}: {4}
\n {11}: {5}
\n \"\"\".format(\n fullname, sex, show_click_date(birthday), phone, area, activity_s,\n _(u'姓名'), _(u'性别'), _(u'生日'), _(u'手机'), _(u'地区'), _(u'活跃度')\n )\n aaData = [address_id, address, issubscribe, other] + varList + [\n # u\"{}
{}\".format(\n # show_click_datetime(created), show_click_datetime(updated)\n # ),\n operate,\n \"\",\n ]\n rs[\"aaData\"].append(aaData)\n # number += 1\n return HttpResponse(json.dumps(rs, ensure_ascii=False), content_type=\"application/json\")\n\n# ajax 加载 订阅地址的域名占比\n@login_required\ndef ajax_domain_content(request, list_id):\n is_subscribe = request.GET.get('is_subscribe', '')\n cr = connections['mm-pool'].cursor()\n user_id = model_addresses.get_address_userid(request, list_id)\n tablename = 'ml_subscriber_' + str(user_id)\n vals, count, html = {}, 0, ''\n sql = u\"SELECT address FROM {0} WHERE list_id={1}\".format(tablename, list_id)\n if is_subscribe == '1':\n sql += u\" and is_subscribe=0 \"\n elif is_subscribe == '2':\n sql += u\" and is_subscribe=1 \"\n cr.execute(sql)\n data = cr.fetchall()\n for address in data:\n count += 1\n domain = address[0].split(\"@\")[-1]\n if domain in vals:\n vals[domain] += 1\n else:\n vals.update({domain: 1})\n sortVals = sorted(vals.iteritems(), key=lambda d: d[1], reverse=True)\n i = 0\n for key, value in sortVals:\n occupy = u\"{}\".format(round(value * 100.00 / count, 2))\n html += u\"\" + key + u\":\" + occupy + u\"%  \"\n i += 1\n if i == 5:\n break\n if not html:\n html = u\"{}\".format(_(u'无'))\n return HttpResponse(html, content_type='text/html')\n\n# 修改单个订阅地址属性\n@login_required\ndef ml_subscribe_modify(request, list_id, address_id):\n cr = connections['mm-pool'].cursor()\n tablename = 'ml_subscriber_' + str(request.user.id)\n var_lists = get_addr_var_fields(cr, request.user.id)\n if request.method == \"POST\":\n data = request.POST\n address = data.get('address', '').strip()\n fullname = data.get('fullname', '').strip()\n if not fullname:\n fullname = '@'.join(address.split(\"@\")[:-1])\n phone = data.get('phone', '')\n area = data.get('area', '')\n sex = data.get('sex', '')\n birthday = data.get('birthday', '')\n vars_x =[]\n for var_i in var_lists:\n var_x = data.get(var_i, '')\n vars_x.append(var_x)\n\n sql_parts, sql_args = get_fields_args(var_lists, vars_x)\n sql = \"UPDATE `mm-pool`.`ml_subscriber_%s` SET fullname=%s, sex=%s, birthday=%s, phone=%s, area=%s, created=%s{} WHERE list_id=%s AND address=%s\".format(sql_parts)\n args = [request.user.id, fullname, sex, birthday, phone, area, time.strftime(\"%Y-%m-%d %H:%M:%S\")] + sql_args + [list_id, address]\n cr.execute(sql, args)\n messages.add_message(request, messages.SUCCESS, _(u'修改成功'))\n return HttpResponseRedirect(\"/address/subscribe/{}/\".format(list_id))\n\n field_str = ','.join(var_lists)\n sql = u\"\"\"\n SELECT address, fullname, phone, area, sex, birthday, {3}\n FROM {0} WHERE address_id={1} AND list_id={2};\n \"\"\".format(tablename, address_id, list_id, field_str)\n cr.execute(sql)\n res = cr.fetchone()\n address, fullname, phone, area, sex, birthday, var1, var2, var3, var4, var5, var6, var7, var8, var9, var10 = res[:16]\n varsList = res[16:]\n forloops = [i+11 for i in xrange(len(varsList))]\n var_vals = zip(forloops, var_lists[:10], varsList)\n return render(request, 'address/ml_subscribe_modify.html', {\n 'list_id': list_id,\n 'address_id': address_id,\n 'address': address,\n 'fullname': fullname,\n 'phone': phone,\n 'area': area,\n 'sex': sex,\n 'birthday': birthday,\n 'var1': var1,\n 'var2': var2,\n 'var3': var3,\n 'var4': var4,\n 'var5': var5,\n 'var6': var6,\n 'var7': var7,\n 'var8': var8,\n 'var9': var9,\n 'var10': var10,\n 'var_vals': var_vals,\n })\n\n\n# #### 退订记录 #####\n@login_required\ndef ml_unsubscribe_list(request, list_id):\n obj = model_addresses.get_address_obj(request, list_id)\n user_id = obj.customer_id\n subject = model_addresses.get_subject(request, list_id, obj)\n cr = connections['mm-pool'].cursor()\n address_sqls.checkTable(cr, user_id)\n if request.method == \"POST\":\n obj2 = get_object(MailList, request.user, list_id)\n tablename = 'ml_unsubscribe_' + str(request.user.id)\n address = request.POST.get('address', '')\n id = request.POST.get('id', False)\n status = int(request.POST.get('status', False))\n if int(status) == -2: # 删除\n sql = u\"DELETE FROM {0} WHERE list_id={1} AND address='{2}'\".format(tablename, id, address)\n cr.execute(sql)\n redis = get_redis_connection()\n redis.rpush(EDM_WEB_USER_MAIL_IMPORT_COUNT_QUEUE, '{}_{}'.format(request.user.id, list_id))\n messages.add_message(request, messages.SUCCESS, _(u'删除成功'))\n return HttpResponseRedirect(\"/address/unsubscribe/{}/\".format(list_id))\n return render(request, 'address/ml_unsubscribe_list.html', context={\n 'subject': subject, 'list_id': list_id\n })\n\n\n@login_required\ndef ajax_unsubscribe_list(request, list_id):\n data = request.GET\n order_column = data.get('order[0][column]', '')\n order_dir = data.get('order[0][dir]', '')\n search = data.get('search[value]', '')\n colums = ['list_id', 'address', 'datetime']\n\n obj = model_addresses.get_address_obj(request, list_id)\n user_id = obj.customer_id\n if request.user.id == user_id:\n is_modify_flag = obj.is_allow_export\n else:\n is_modify_flag = False\n\n where_str = u'list_id={}'.format(list_id)\n if search:\n where_str += u\"\"\" and address like '%{0}%' \"\"\".format(search)\n\n order_by_str = ''\n if order_column and int(order_column) < len(colums):\n if order_dir == 'desc':\n order_by_str = u'order by %s desc' % colums[int(order_column)]\n else:\n order_by_str = u'order by %s asc' % colums[int(order_column)]\n\n cr = connections['mm-pool'].cursor()\n tablename = 'ml_unsubscribe_' + str(user_id)\n\n count_sql = u\"SELECT COUNT(1) FROM %s WHERE %s;\" % (tablename, where_str)\n cr.execute(count_sql)\n rows = cr.fetchall()\n count = rows[0][0]\n\n try:\n length = int(data.get('length', 1))\n except ValueError:\n length = 1\n\n try:\n start_num = int(data.get('start', '0'))\n except ValueError:\n start_num = 0\n if start_num >= count:\n start_num = 0\n limit_str = u'limit %s offset %s' % (length, start_num)\n sql = u\"SELECT address, datetime, list_id FROM %s WHERE %s %s %s\" % (tablename, where_str, order_by_str, limit_str)\n cr.execute(sql)\n rows = cr.fetchall()\n rs = {\"sEcho\": 0, \"iTotalRecords\": count, \"iTotalDisplayRecords\": count, \"aaData\": []}\n page = start_num / length + 1\n number = length * (page - 1) + 1\n for r in rows:\n if is_modify_flag:\n modify_str = u'''{}'''.format(\n r[2], r[0], _(u'删除'))\n else:\n modify_str = \"\"\n rs[\"aaData\"].append([\n number, r[0], dateformat(r[1], 'Y-m-d H:i:s'),\n modify_str,\n \"\",\n ])\n number += 1\n return HttpResponse(json.dumps(rs, ensure_ascii=False), content_type=\"application/json\")\n\n\n# #### 增加订阅记录 #####\n@xframe_options_exempt\ndef add_subscribe_rec(request):\n try:\n id = request.GET.get('id', '')\n user_id, list_id = id.split(\",\")\n language = request.GET.get('language', '')\n template_name = 'address/add_subscribe_rec_en.html' if language == 'en' else 'address/add_subscribe_rec.html'\n return render(request, template_name, context={'user_id': user_id, 'list_id': list_id})\n except:\n return HttpResponse(u\"

{}

\".format(_(u'提示信息:参数错误!')))\n\n@csrf_exempt\ndef ajax_add_subscriber(request):\n if request.method == 'GET':\n raise Http404\n data = request.POST\n user_id = data.get('user_id', '').strip()\n list_id = data.get('list_id', '').strip()\n address = data.get('address', '').strip()\n if not user_id or not address:\n raise Http404\n # fullname = data.get('fullname', '').strip()\n fields = ['list_id', 'address', 'fullname', 'sex', 'birthday', 'phone', 'area', 'var1', 'var2', 'var3', 'var4', 'var5', 'var6', 'var7', 'var8', 'var9', 'var10']\n kwargs = {}\n for f in fields:\n v = data.get(f, '').strip()\n if f == 'sex':\n v = address_tools.handleSex(v)\n elif f == 'birthday':\n v = address_tools.hanfBirthday(v)\n kwargs[f] = v\n\n cr = connections['mm-pool'].cursor()\n tablename = 'ml_subscriber_' + str(user_id)\n list_id = list_id if MailList.objects.filter(id=list_id).exists() else 0\n if address_sqls.select_address(cr, tablename, address, list_id):\n msg = address_sqls.update_address(cr, tablename, address, list_id)\n else:\n msg = address_sqls.insert_address(cr, tablename, **kwargs)\n redis = get_redis_connection()\n redis.rpush(EDM_WEB_USER_MAIL_IMPORT_COUNT_QUEUE, '{}_{}'.format(user_id, list_id))\n response = HttpResponse(msg, content_type=\"text/plain\")\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n# 导出模板格式文件\n@login_required\ndef export_template_format(request):\n data = request.GET\n file_ext = data.get('file_ext', '').strip()\n cr = connections['mm-pool'].cursor()\n var_lists = get_addr_var_fields(cr, request.user.id)\n forloops = [i+1 for i in xrange(len(var_lists))]\n if request.user.lang_code == 'en-us':\n list = [ [u'Address', u'Name', u'Gender', u'birthday', u'phone', u'area'] + var_lists ]\n else:\n list = [ [u'邮件地址', u'姓名', u'性别', u'生日', u'手机', u'地区'] + [u'变量{}'.format(i) for i in forloops] ]\n if file_ext == 'csv':\n force_csv = True\n mimetype = 'text/csv'\n response = FormatExcelResponse(\n data=list, output_name='address', force_csv=force_csv,\n encoding='gbk', mimetype=mimetype, file_ext=file_ext\n )\n elif file_ext == 'txt':\n force_csv = False\n mimetype = 'text/plain'\n response = FormatExcelResponse(\n data=list, output_name='address', force_csv=force_csv,\n encoding='gbk', mimetype=mimetype, file_ext=file_ext\n )\n elif file_ext == 'xls':\n force_csv = False\n mimetype = 'application/vnd.ms-excel'\n response = FormatExcelResponse(\n data=list, output_name='address', force_csv=force_csv,\n encoding='gbk', mimetype=mimetype, file_ext=file_ext\n )\n elif file_ext == 'xlsx':\n force_csv = False\n mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n response = FormatExcelResponse(\n data=list, output_name='address', force_csv=force_csv,\n encoding='gbk', mimetype=mimetype, file_ext=file_ext\n )\n return response\n\n# 导出地址文件\n@login_required\ndef export_address(request, list_id):\n data = request.GET\n cr = connections['mm-pool'].cursor()\n tablename = 'ml_subscriber_' + str(request.user.id)\n file_name = data.get('file_name', '').strip()\n var_lists = get_addr_var_fields(cr, request.user.id)\n forloops = [i+1 for i in xrange(len(var_lists))]\n if request.user.lang_code == 'en-us':\n alist = [ [u'email', u'name', u'gender', u'birthday', u'phone', u'area'] + var_lists ]\n else:\n alist = [ [u'邮件地址', u'姓名', u'性别', u'生日', u'手机', u'地区'] + [u'变量{}'.format(i) for i in forloops] ]\n sql = u\"\"\"\n SELECT address, fullname, sex, birthday, phone, area, {2}\n FROM {0} WHERE list_id={1};\n \"\"\".format(tablename, list_id, ','.join(var_lists))\n cr.execute(sql)\n for row in cr.fetchall():\n address, fullname, sex, birthday, phone, area = row[:6]\n aaData = list(row[6:])\n if sex == 'M':\n sex = u'男'\n elif sex == 'F':\n sex = u'女'\n else:\n sex = ''\n alist.append([address, fullname, sex, birthday, phone, area] + aaData)\n return ExcelResponse(alist, file_name, encoding='gbk')\n","sub_path":"edm_web/app/address/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":45365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"196104922","text":"import numpy as np\nimport pandas as pd\nfrom scipy.stats import gamma\nimport matplotlib.pyplot as plt\n\nSIM_NUM = 1000\ndef show_player(player_id, stat= 'PTS', cdf=False, color='blue'):\n\n a, loc, scale = (stat+'_a', stat+'_loc', stat+'_scale')\n is_player = player_data['ID'] == player_id\n player = player_data[is_player]\n\n rv = gamma(a=player[a], loc=player[loc], scale=player[scale])\n\n x = np.linspace(0,50, 100)\n\n if not cdf:\n y = rv.pdf(x)\n\n else:\n y = rv.cdf(x)\n \n plt.plot(x,y, color=color)\n\n\n\nclass PlayerStat():\n\n def __init__(self, name, a, loc, scale):\n\n self.a = a\n self.loc = loc\n self.scale = scale\n self.name = name\n\n self.rv = gamma(a=a, loc=loc, scale=scale)\n\n self.real = self.rv.rvs(SIM_NUM)\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return self.name\n \n def __lt__(self, other):\n\n val = sum(self.real < other.real)/SIM_NUM\n\n return np.round(val) \n\n \n def __gt__(self, other):\n\n val = sum(self.real > other.real)/SIM_NUM\n\n return np.round(val)\n\n\n\n\ndef order_players(stat='PTS'):\n '''\n Orders player by chosen stats via simulating gamma ditribution draws\n @param str stat: the stat you want to compare\n @rtype list: a list ordered from best to worst players for a given stat\n '''\n PARAMS = [stat+'_a', stat+'_loc', stat+'_scale']\n \n \n \n data = [PlayerStat(name=player_data.loc[i]['Name'], a=player_data.loc[i][PARAMS[0]], \n loc= player_data.loc[i][PARAMS[1]], scale=player_data.loc[i][PARAMS[2]])\n for i in player_data.index]\n \n\n data.sort()\n return data\n \nif __name__ == '__main__':\n player_data = pd.read_csv('player_dist_2018-19.csv')\n player_data = player_data.dropna()\n print(order_players('PTS')[-10:])\n ","sub_path":"view_stats.py","file_name":"view_stats.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"60386435","text":"import dataclasses\nimport os\nimport time\n\nimport pytest\n\nfrom socialhub import SocialHub\nfrom socialhub import SocialHubEntity\nfrom socialhub import SocialHubError\nfrom socialhub import SocialHubSignatureError\nfrom socialhub import SocialHubSignatureTimestampError\nfrom socialhub import TicketAction\nfrom socialhub import TicketInteractor\n\n\n@pytest.fixture(scope='module')\ndef vcr_config():\n def scrub_headers(*headers):\n def before_record_response(response):\n for header in headers:\n if header in response['headers']:\n del response['headers'][header]\n return response\n return before_record_response\n\n return {\n 'filter_query_parameters': [('accesstoken', 'XXX_filtered_accesstoken_XXX')],\n 'filter_headers': ['Content-Length'],\n 'before_record_response': scrub_headers(\n 'Date', 'ETag', 'Server', 'Content-Length',\n 'X-RateLimit-Limit', 'X-RateLimit-Remaining',\n ),\n }\n\n\n@pytest.fixture(scope='module')\ndef vcr_cassette_dir(request):\n return os.path.join(os.path.dirname(__file__), 'cassette', request.module.__name__)\n\n\n@pytest.fixture()\ndef accesstoken():\n return os.environ.get('SOCIALHUB_ACCESSTOKEN', 'fake_accesstoken_1337')\n\n\n@pytest.fixture()\ndef client(accesstoken):\n return SocialHub(accesstoken)\n\n\n@pytest.mark.vcr()\ndef test_ctor(accesstoken):\n SocialHub(accesstoken)\n\n\n@pytest.mark.vcr()\ndef test_ctor_wrong_token():\n with pytest.raises(SocialHubError, match='AccessTokenInvalidError'):\n SocialHub('fake_accesstoken_1337')\n\n\n@pytest.mark.vcr()\ndef test_get_manifest(client):\n manifest = client.get_manifest()\n assert '_id' in manifest\n assert 'inbox' in manifest\n\n\n@pytest.mark.vcr()\ndef test_set_ticket_actions(client):\n client.set_ticket_actions([\n TicketAction('reply', 'reply-public', 'Reply')\n ])\n manifest = client.get_manifest()\n actions = manifest['inbox']['ticketActions']\n assert len(actions) == 1\n assert actions[0]['type'] == 'reply'\n assert actions[0]['id'] == 'reply-public'\n assert actions[0]['label'] == 'Reply'\n\n\n@pytest.mark.vcr()\ndef test_set_webhook(client):\n # we can't fully set the hook without hosting a server, but we can at least\n # test that we get past the input validation.\n with pytest.raises(\n SocialHubError,\n match='An error occurred while attempting to validate the WebHook',\n ):\n client.set_webhook('https://example.com/webhook', 't' * 32)\n\n\n@pytest.mark.vcr()\ndef test_create_ticket(client):\n id_ = client.create_ticket('foo', f'social-test-{int(time.time()*1000)}', 'https://example.com')\n assert isinstance(id_, str)\n assert len(id_) > 16\n\n\n@pytest.mark.vcr()\ndef test_create_ticket_root(client):\n id_ = client.create_ticket('foo', f'social-test-{int(time.time()*1000)}', 'https://example.com')\n id_ = client.create_ticket(\n 'foo', f'social-test-{int(time.time()*1000)}', 'https://example.com', root_id=id_,\n )\n assert isinstance(id_, str)\n assert len(id_) > 16\n\n\n@pytest.mark.vcr()\ndef test_create_ticket_interactor(client):\n id_ = client.create_ticket(\n 'foo', f'social-test-{int(time.time()*1000)}', 'https://example.com',\n interactor=TicketInteractor(\n interactorId='social-interactor-1337',\n name='Mr. Social',\n url='https://uberspace.de/',\n picture='https://uberspace.de/img/logo.svg',\n )\n )\n assert isinstance(id_, str)\n assert len(id_) > 16\n\n\ndef test_socialhubentity():\n @dataclasses.dataclass\n class TicketAction(SocialHubEntity):\n reserved_field_: str\n unreserved_field: str\n\n d = TicketAction('reserved_field_value', 'unreserved_field_value').json_dict()\n assert len(d) == 2\n assert 'reserved_field_' not in d\n assert d['reserved_field'] == 'reserved_field_value'\n assert d['unreserved_field'] == 'unreserved_field_value'\n\n\ndef test_verify_webhook_signature():\n challenge = SocialHub.verify_webhook_signature(\n 'zieShi0besu7aiZae2mequieveo6ahNg',\n 1588761201236,\n b'{\"manifestId\":\"5ea028554e1570519e982403\",\"accountId\":\"5ea023d6677493519f10710e\",\"channelId\":\"5ea028554e1570519e982404\",\"events\":{}}', # NOQA\n '836372be68a3d48c99ebb6aec104909e2fc2c5aca3ebe319607f242759124022',\n ignore_time=True\n )\n # generated by the PHP implementation\n assert challenge == '93f4b03366741ddadd603d7ab4155c8891c673e87fc770fd3620d61cb793abab'\n\n\ndef test_verify_webhook_signature_fail():\n with pytest.raises(SocialHubSignatureError):\n SocialHub.verify_webhook_signature(\n 'zieShi0besu7aiZae2mequieveo6ahNg',\n 1588761201236,\n # \"manifest\" has a capital M, which it should not have.\n b'{\"ManifestId\":\"5ea028554e1570519e982403\",\"accountId\":\"5ea023d6677493519f10710e\",\"channelId\":\"5ea028554e1570519e982404\",\"events\":{}}', # NOQA\n '836372be68a3d48c99ebb6aec104909e2fc2c5aca3ebe319607f242759124022',\n ignore_time=True\n )\n\n\ndef test_verify_webhook_signature_fail_time_past():\n with pytest.raises(SocialHubSignatureTimestampError):\n SocialHub.verify_webhook_signature('xxx', 1588761201236, b'xxx', 'xxx')\n\n\ndef test_verify_webhook_signature_fail_time_future():\n with pytest.raises(SocialHubSignatureTimestampError):\n SocialHub.verify_webhook_signature('xxx', 5588761201236, b'xxx', 'xxx')\n","sub_path":"test/test_socialhub.py","file_name":"test_socialhub.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"407494182","text":"import tkinter\nimport pymysql\nimport threading\nimport time\nfrom queue import Queue\nimport socket\n\n\nqSqlQuery = Queue()\nqCheck = Queue()\nqLamp = Queue()\n\ndef connectie():\n TCP_IP = '192.168.2.2'\n TCP_PORT = 5005\n BUFFER_SIZE = 1024\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((TCP_IP, TCP_PORT))\n s.listen(1)\n\n\n conn, addr = s.accept()\n print('Connected with {} {}'.format(addr[0], addr[1]))\n while True:\n message = conn.recv(1024)\n print(message.decode('ascii'))\n qSqlQuery.put(message.decode('ascii'))\n qCheck.put(message.decode('ascii'))\n time.sleep(1)\n\n\ndef dbSchrijver():\n while True:\n db = pymysql.connect(\"localhost\", \"root\", \"raspberry\", \"IDP\")\n info = qSqlQuery.get()\n info = eval(info)\n # prepare a cursor object using cursor() method\n cursor = db.cursor()\n\n\n\n sql = \"INSERT INTO data(LampID,Decibel,Tijd) VALUES ({},{},'{}')\".format(info['lampId'],info['Decibel'],info['Tijd'])\n print(sql)\n\n\n\n cursor.execute(sql)\n db.commit()\n\n db.close()\n\n\ndef check():\n while True:\n info = qCheck.get()\n info = eval(info)\n decibel = info['Decibel']\n lampid = info['lampId']\n\n db = pymysql.connect(\"localhost\", \"root\", \"raspberry\", \"IDP\")\n\n # prepare a cursor object using cursor() method\n cursor = db.cursor()\n\n sql = \"SELECT MaxDecibel FROM Lamp WHERE Lamp.LampID = {}\".format(lampid)\n cursor.execute(sql)\n MaxDecibel = cursor.fetchall()\n MaxDecibel = MaxDecibel[0]\n MaxDecibel = MaxDecibel[0]\n MaxDecibel = float(MaxDecibel)\n decibel = float(decibel)\n print(MaxDecibel)\n if decibel > MaxDecibel + 5:\n print('RODE LAMP')\n qLamp.put('rood')\n elif decibel > MaxDecibel - 5 and decibel < MaxDecibel + 5:\n print('gele lamp')\n qLamp.put('geel')\n else:\n qLamp.put('groen')\n print('GROENE LAMP')\n\n\ndef sendlamp():\n TCP_IP = '145.89.222.215'\n TCP_PORT = 2425\n BUFFER_SIZE = 1024\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((TCP_IP, TCP_PORT))\n s.listen(1)\n\n print('socket bind gemaakt')\n s.listen(10)\n\n conn, addr = s.accept()\n print('Connected with {} {}'.format(addr[0], addr[1]))\n\n while True:\n message = qLamp.get()\n conn.send(message.encode('UTF-8'))\n print('Message send')\n\n\n\n\n\nenabled = 0\n\n\n\ndef gui():\n def select():\n ## Hierin wordt de data uit de database gehaald en weergegeven op de infopagina\n Tabel = Label(master=InfoPage, text='Decibel | Tijd | Lokaal ').pack()\n db = pymysql.connect(\"localhost\", \"root\", \"raspberry\", \"IDP\")\n # prepare a cursor object using cursor() method\n cursor = db.cursor()\n\n # De sql query die de juiste data uit de database haalt.\n sql = \"SELECT data.Decibel, data.Tijd, Lamp.LokaalNummer FROM data, Lamp WHERE data.LampID = Lamp.LampID\"\n # Execute the SQL command\n cursor.execute(sql)\n # Fetch all the rows in a list of lists.\n results = cursor.fetchall()\n for row in results:\n decibel = row[0]\n tijd = row[1]\n lokaal = row[2]\n # Show fetched data in label\n InfoLabel = Label(master=InfoPage, text=' {} | {} | {}'.format(decibel, tijd, lokaal))\n InfoLabel.pack()\n\n\n\n class FullScreenApp(object):\n ## Zorgt ervoor dat de tkinter gui in fullscreen geopend zal worden\n def __init__(self, master, **kwargs):\n self.master = master\n pad = 3\n self._geom = '200x200+0+0'\n master.geometry(\"{0}x{1}+0+0\".format(\n master.winfo_screenwidth() - pad, master.winfo_screenheight() - pad))\n master.bind('', self.toggle_geom)\n\n def toggle_geom(self, event):\n geom = self.master.winfo_geometry()\n print(geom, self._geom)\n self.master.geometry(self._geom)\n self._geom = geom\n\n def toonHomePage():\n ## Dit start de gui\n HomePage.pack()\n\n def toonSettingsPage():\n ## Verlaat de homepage en open settingspage\n HomePage.pack_forget()\n SettingsPage.pack()\n\n def toonInfoPage():\n ## Verlaat homepage en open infopage\n HomePage.pack_forget()\n InfoPage.pack()\n select()\n\n def backhomesettingspage():\n ## Verlaat settingspage open homepage\n SettingsPage.pack_forget()\n HomePage.pack()\n\n def TerugHome():\n InfoPage.pack_forget()\n HomePage.pack()\n\n def refresh():\n ## Refresht de data op de infopage\n InfoPage.pack_forget()\n for keys in InfoPage.children:\n if type(InfoPage.children[keys]) == tkinter.Label:\n InfoPage.children[keys].pack_forget()\n select()\n # lees key & value uit InfoPage.children\n # if type() van value == Label\n # pack_forget op value\n InfoPage.pack()\n\n\n\n def changeSettings():\n x = LampIDEntry.get()\n LampID = int(x)\n y = MaxDecibeleEntry.get()\n MaxDecibel = float(y)\n z = LokaalNummerEntry.get()\n LokaalNummer = float(z)\n\n print('{} {} {}'.format(LampID,MaxDecibel,LokaalNummer))\n\n ## Connect met database\n db = pymysql.connect(\"localhost\", \"root\", \"raspberry\", \"IDP\")\n\n # prepare a cursor object using cursor() method\n cursor = db.cursor()\n\n sql = \"UPDATE Lamp SET MaxDecibel = {}, LokaalNummer = {} WHERE Lamp.LampID = {};\".format(MaxDecibel,LokaalNummer,LampID)\n print(sql)\n cursor.execute(sql)\n db.commit()\n db.close()\n\n\n\n root = Tk()\n app = FullScreenApp(root)\n\n ## HOMEPAGE\n HomePage = Frame(master=root)\n labelHomePage = Label(master=HomePage, text='Homepage').pack()\n button = Button(master=HomePage, text='Settings Page', command=toonSettingsPage).pack()\n button1 = Button(master=HomePage, text='Info Page', command=toonInfoPage).pack()\n toonHomePage()\n\n ## SETTINGSPAGE\n SettingsPage = Frame(master=root)\n Label1 = Label(master=SettingsPage, text='Settings Page\\n\\n').pack()\n LabelLampId = Label(master=SettingsPage,text='Lamp ID').pack()\n LampIDEntry = Entry(master=SettingsPage)\n LampIDEntry.pack()\n DecibelLabel = Label(master=SettingsPage, text='\\nMax Decibel').pack()\n MaxDecibeleEntry = Entry(master=SettingsPage)\n MaxDecibeleEntry.pack()\n LokaalNummerLabel = Label(master=SettingsPage,text='\\nLokaal nummer').pack()\n LokaalNummerEntry = Entry(master=SettingsPage)\n LokaalNummerEntry.pack()\n EnterButton = Button(master=SettingsPage, text='Save', command=changeSettings)\n EnterButton.pack()\n BackHomoButtonSettingsPage = Button(master=SettingsPage, text='Home', command=backhomesettingspage)\n BackHomoButtonSettingsPage.pack()\n\n ## INFO PAGE\n InfoPage = Frame(master=root)\n HomePageButton = Button(master=InfoPage,text='Home',command=TerugHome).pack()\n RefreshButton = Button(master=InfoPage, text='Refresh', command=refresh).pack()\n\n root.mainloop()\n\n\n\ndef startup():\n ## Threads worden hier gemaakt en gestart\n\n d = threading.Thread(target=connectie)\n e = threading.Thread(target=gui)\n f = threading.Thread(target=dbSchrijver)\n g = threading.Thread(target=check)\n h = threading.Thread(target=sendlamp)\n h.daemon = False\n g.daemon = False\n f.daemon = False\n e.daemon = False\n d.daemon = False\n h.start()\n f.start()\n g.start()\n d.start()\n e.start()\n\n\n## start de functie\nstartup()\n\n","sub_path":"test files/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"249123425","text":"import re\n\nfrom telepot.namedtuple import ReplyKeyboardMarkup\n\nfrom bot.terms_string import terms_text\n\npatterns = [\n \"شرایط و قوانین🚫\",\n]\n\ndefualt_keyboard = ReplyKeyboardMarkup(keyboard=[\n [{\"text\": \"بیخیال\"}]], resize_keyboard=True)\n\n\ndef run(msg, user, matches, bot, ):\n print(msg[\"from\"][\"id\"], \" \", msg[\"from\"][\"first_name\"] if \"first_name\" in msg[\"from\"] else \"no_first_name\",\n \" \", msg[\"from\"][\"username\"] if \"username\" in msg[\"from\"] else \"no_username\", \" \", msg[\"text\"])\n\n if re.match(\"شرایط و قوانین🚫\", msg[\"text\"]):\n bot.sendMessage(msg[\"from\"][\"id\"], terms_text[\"terms\"], reply_markup=defualt_keyboard)\n","sub_path":"bot/plugins/terms.py","file_name":"terms.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"271789619","text":"from math import sqrt, factorial\n\n\ndef memoize(func):\n class MemoCache(dict):\n def __init__(self, f):\n super().__init__()\n self.f = f\n\n def __call__(self, *args):\n return self[args]\n\n def __missing__(self, key):\n ret = self[key] = self.f(*key)\n return ret\n\n return MemoCache(func)\n\n\n# PRIME NUMBERS\ndef prime_sieve(ceiling, min_value=2):\n results = [True] * ceiling\n results[0] = results[1] = False\n for i, prime in enumerate(results):\n if prime:\n for n in range(i * i, ceiling, i):\n results[n] = False\n return [i for i, n in enumerate(results) if n if i >= min_value]\n\n\ndef is_prime(x):\n if x < 2:\n return False\n for i in range(2, int(sqrt(x) + 1)):\n if x % i == 0:\n return False\n return True\n\n\ndef miller_rabin_test(n):\n # Some simple checks\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n if n < 9:\n return True\n if n % 3 == 0 or n % 5 == 0:\n return False\n # Create candidate lists\n if n < 2047:\n test_nums = (2,)\n elif n < 1373653:\n test_nums = (2, 3)\n elif n < 9080191:\n test_nums = (31, 73)\n elif n < 25326001:\n test_nums = (2, 3, 5)\n elif n < 3215031751:\n test_nums = (2, 3, 5, 7)\n elif n < 4759123141:\n test_nums = (2, 7, 61)\n elif n < 1122004669633:\n test_nums = (2, 13, 23, 1662803)\n else:\n raise ValueError(\"Didn't account for witnesses that high.\")\n return not any(_miller_rabin_witness(n, a) for a in test_nums)\n\n\ndef _miller_rabin_witness(n, a):\n d = n - 1\n s = 0\n while d % 2 == 0:\n d //= 2\n s += 1\n # Two conditions: a^d != 1 and a^(2^r*d) != -1 for all 0= int: \n '''get the number of columns and rows'''\n print('Please specify the number of columns and rows of the board') \n while True: \n try: \n columns = int(input('Number of columns: ').strip()) \n rows = int(input('Number of rows: ').strip())\n break \n except ValueError: \n print('Invalid colums and rows number, please try agin') \n return columns, rows \n\ndef make_new_game(columns, rows): \n while True: \n try: \n new_game = connectfour.new_game(columns, rows) \n break\n except: \n print(f'columns must be an int between {connectfour.MIN_COLUMNS} and {connectfour.MAX_COLUMNS}')\n print(f'rows must be an int between {connectfour.MIN_ROWS} and {connectfour.MAX_ROWS}')\n return new_game\n\ndef print_format_board(game_state: connectfour.GameState): \n '''print the board in certain format''' \n _print_header(game_state) \n _print_body(game_state)\n\ndef print_turn(game_state: connectfour.GameState): \n '''print who's turn now is'''\n if game_state.turn == 1: \n print('Now is RED\\'s turn') \n elif game_state.turn == 2: \n print('Now is YELLOW\\'s turn')\n\ndef get_move_cmd(game_state: connectfour.GameState): # how to annotate multiple returns\n '''get the move command from user''' \n print('Please enter your move and column') \n move = input('Move(DROP / POP): ').strip() \n column = int(input(f'Column(1, {connectfour.columns(game_state)}): ').strip()) - 1\n \n return move, column\n\ndef perform_game_move(game_state: connectfour.GameState) -> connectfour.GameState: \n '''return the new board and turn after a game move'''\n while True: \n try: \n move, column = get_move_cmd(game_state) \n if move == 'DROP': \n return connectfour.drop(game_state, column), move, column \n elif move == 'POP': \n return connectfour.pop(game_state, column), move, column \n else: \n raise connectfour.InvalidMoveError\n except ValueError: \n print(f'column_number must be an int between 1 and {connectfour.columns(game_state)}.')\n except connectfour.GameOverError: \n print('Game is over.') \n except connectfour.InvalidMoveError:\n print('This move cannot be made, please enter the move and column again.')\n\ndef _print_header(game_state: connectfour.GameState): \n '''prin the header of the board'''\n for i in range(1, connectfour.columns(game_state)+1): \n if i < 10: \n print(str(i) + ' ', end='') \n elif i >= 10: \n print(str(i) + ' ', end='') \n print('\\n')\n\ndef _print_body(game_state: connectfour.GameState): \n '''print the body of the board'''\n for i in range(connectfour.rows(game_state)):\n for j in range(connectfour.columns(game_state)): \n if game_state.board[j][i] == connectfour.EMPTY: \n print('. ', end='') \n elif game_state.board[j][i] == connectfour.RED: \n print('R ', end='') \n else: \n print('Y ', end='')\n print('\\n')\n","sub_path":"shared_functions.py","file_name":"shared_functions.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"541725254","text":"# Neutron star thermal evolution\n# --------------------------------------\n# neutrino.py\n# --------------------------------------\n# This module provides specific neutrino\n# emissivity per unit volume\n# via URCA process (Direct and Modified)\n# _Q (erg/s/cm^3)\n\nimport numpy\n\nfrom physics import sf_gap\nfrom other import routines\nfrom control.manager import *\nfrom control.constants import *\nfrom data import loaddata\n\n\nNnu1 = 2. # number of neutrino species other than the electron\nsin2TW = 0.2319 # sine squared of the Weinberg angle\nCv = (0.5+2.*sin2TW)\nCa2 = 0.75\nCv2 = (routines.sqr(Cv)+Nnu1*routines.sqr(1.-(Cv)))\nTr = 5.9302e9 # electron relativistic temperature\nQc = 1.0226e23 # Compton neutrino loss unit\nNnu = 3. # number of neutrino types\n\n\ndef fun_1(t):\n\n p1 = 7.662048E+00\n p2 = 1.919637E+00\n\n F = 2.*t/routines.sqr(2.*pi)*numpy.sqrt((2.*pi*t+p1*t*t+p2*t*t*t)/(1.+p2/4.*t))*numpy.exp(-1./t)\n\n return F\n\ndef fun0(t):\n\n p1 = 2.361340E+01\n p2 = 3.210783E+01\n\n t2 = t*t\n t3 = t2*t\n t4 = t3*t\n\n u = 2.*pi*t + p1*t2 + p2*t3 + 16.*t4\n F = 2.*t/routines.sqr(2.*pi)*numpy.sqrt(u)*numpy.exp(-1./t)\n\n return F\n\ndef fun1(t):\n\n p1 = 4.243553E+01\n p2 = 1.407638E+02\n p3 = 2.651583E+02\n p4 = 2.878642E+02\n\n t2 = t*t\n t3 = t2*t\n t4 = t3*t\n t5 = t4*t\n t6 = t5*t\n\n u = 2.*pi*t + p1*t2 + p2*t3 + p3*t4 + p4*t5 + 144.*t6\n F = 2.*t/routines.sqr(2.*pi)*numpy.sqrt(u)*numpy.exp(-1./t)\n\n return F\n\ndef fun2(t):\n\n p1 = 6.133312E+01\n p2 = 3.219052E+02\n p3 = 1.153307E+03\n p4 = 2.624424E+03\n p5 = 4.468395E+03\n p6 = 4.600400E+03\n\n t2 = t*t\n t3 = t2*t\n t4 = t3*t\n t5 = t4*t\n t6 = t5*t\n t7 = t6*t\n t8 = t7*t\n\n u = 2.*pi*t + p1*t2 + p2*t3 + p3*t4 + p4*t5 + p5*t6 + p6*t7 + 144.*16.*t8\n F = 2.*t/routines.sqr(2.*pi)*numpy.sqrt(u)*numpy.exp(-1./t)\n\n return F\n\n\ndef _Qpair(T_K, x): # Relativistic version, cold plasma\n\n t = T_K/Tr\n mu = numpy.sqrt(1.+x*x)\n\n if(mu/t > 500.):\n F = 0.\n\n else:\n\n f_1 = fun_1(t) # positron functions\n f0 = fun0(t)\n f1 = fun1(t)\n f2 = fun2(t)\n u_1 = 0.5/routines.sqr(pi)*(x*mu-numpy.log(x+mu)) # electron functions\n u0 = x*x*x/3./routines.sqr(pi)\n u1 = (mu*x*(x*x+mu*mu)-numpy.log(x+mu))/8./routines.sqr(pi)\n u2 = x*x*x*(1.+0.6*x*x)/3./routines.sqr(pi)\n u = ((Cv2+Ca2)*(8.*(u1*f2+u2*f1)+7.*(u1*f0+u0*f1)-\n 2.*(u2*f_1+u_1*f2)+5.*(u_1*f0+u0*f_1))+\n 9.*(Cv2-Ca2)*(f0*(u1+u_1)+u0*(f_1+f1)))\n\n F = Qc*numpy.exp(-mu/t)*u/(36.*pi)\n\n return F\n\n# Neutrino emission due to Cooper pairing of neutrons and protons\ndef _Qcooper(T, nn, np, Tc_nt, Tc_ns, Tc_p):\n\n # T = temperature in K\n # rho = matter density in g cm^-3\n # nn = neutron number density in fm^-3\n # np = proton number density in fm^-3\n # Tc_nt = crit. T of neutron triplet superfluidity in K\n # Tc_ns = crit. T of neutron singlet superfluidity in K\n # Tc_p = crit. T of proton superfluidity in K\n # n0 = 0.16 fm^-3 -- nuclear number density\n\n T7 = numpy.power(T/1.e9,7)\n\n if(var_meff == 1):\n mn_eff = routines._Meff(nn)\n mp_eff = routines._Meff(np)\n elif(var_meff == 2):\n nbb = nn+np\n mn_eff = 1.369/(1+3.133*nbb+3.570*nbb*nbb-0.9797*nbb*nbb*nbb)\n mp_eff = 0.9937/(1+2.217*nbb+0.8850*nbb*nbb)\n else:\n mn_eff = Mn/Mn0\n mp_eff = Mp/Mp0\n\n v1 = v2 = R_recomb = 0. # neutron Cooper's neutrions\n\n if(Tv2): # recombination in singlet state\n # rms error = 0.0045, max error = 0.0096 at v1 = 4\n\n if(v1>0. and v1<30.):\n\n R_recomb = (v1*v1*(0.602 + 0.5942*v1*v1 + 0.2880*v1*v1*v1*v1)*\n numpy.sqrt(0.5547+numpy.sqrt(routines.sqr(0.4453) + routines.sqr(0.1063)*v1*v1))*\n numpy.exp(-numpy.sqrt(4*v1*v1 + routines.sqr(2.245)) + 2.245))\n\n else: # recombination in triplet state\n # rms error = 0.0102, max error = 0.0338 at v2 = 2\n\n if(v2 > 0. and v2 < 30.):\n R_recomb = (v2*v2*(0.602*2.+3.733*v2*v2+0.3191*v2*v2*v2*v2)*\n routines.sqr(0.7591+numpy.sqrt(routines.sqr(0.2409)+0.3145*v2*v2))\n /(1.+0.3511*v2*v2)*numpy.exp(-numpy.sqrt(4.*v2*v2+routines.sqr(0.4616))+0.4616))\n R_recomb *= 4.17 # to account for axial-vector term\n\n Qn = 3.*1.17e21*T7*0.353*numpy.power(nn/n0,1./3.)*mn_eff*R_recomb\n\n if(T0. and v<100.): # pp recombination\n # rms error = 0.0045, max error = 0.0096 at v = 4\n R_recomb = (v*v*(0.602 + 0.5942*v*v + 0.2880*v*v*v*v)*\n numpy.sqrt(0.5547+numpy.sqrt(routines.sqr(0.4453) + routines.sqr(0.1063)*v*v))*\n numpy.exp(-numpy.sqrt(4*v*v + routines.sqr(2.245)) + 2.245))\n else:\n R_recomb = 0.\n\n Qp = (3.*1.17e21*T7*0.353*numpy.power(np/n0,1./3.)*mp_eff*R_recomb*\n (routines.sqr(0.08) + routines.sqr(1.26)*(11./42. + routines.sqr(mp_eff))*\n routines.sqr(0.353/mp_eff)*numpy.power(np/n0,2./3.)))\n\n return Qn*0.8+Qp\n\ndef _Qbremss_eZ(T, rho):\n\n # T = temperature of matter in K\n # rho = mass density in g/cc\n\n tau = numpy.log10(T*1.e-8)\n r = numpy.log10(rho*1.e-12)\n\n lgQ = (11.204 + 7.304*tau + 0.2976*r - 0.37*tau*tau + 0.188*tau*r - 0.103*r*r +\n 0.0547*tau*tau*r - 6.77*numpy.log10(1. + 0.228*rho/2.8e14))\n\n Q = numpy.power(10,lgQ)\n\n return Q\n\n\ndef _Qcrust(T, rho, ne, nn, Tc_nt, Tc_ns):\n\n Qplasma = Qbremss = Qpair = Qnn = 0.\n\n x = routines.pF(ne)/(Me*c) # electron relativistic parameter\n\n Qbremss = _Qbremss_eZ(T, rho)\n Qplasma = _Qplasma(T, x)\n Qpair = _Qpair(T, x)\n\n if((T200.0):\n R = 0.0 # superstrong superfluidity\n else:\n R = (numpy.power(a + numpy.sqrt(routines.sqr(1.0 - a) + routines.sqr(b*Tgap)), 5.0)*\n numpy.exp(d-numpy.sqrt(d*d + Tgap*Tgap)))\n\n return R\n\ndef _Rp(Sgap): # proton superfluidity reduction factor for DURCA\n # Sgap - singlet-state energy gap\n\n a = 0.2311517\n b = 0.1438319\n d = 3.427262\n\n if(Sgap == 0.0):\n R = 1.0 # no superfluidity\n elif(Sgap>200.0):\n R = 0.0 # superstrong superfluidity\n else:\n R = (numpy.power(a+numpy.sqrt(routines.sqr(1.0-a)+routines.sqr(b*Sgap)), 5.5)*\n numpy.exp(d-numpy.sqrt(d*d+Sgap*Sgap)))\n return R\n\ndef _Rnp(Ngap, Pgap):\n\n if((Ngap>200.0) or (Pgap>200.0)):\n return(0.0)\n\n lgR = loaddata.lgR(Ngap, Pgap)\n R = numpy.power(10,lgR)\n\n return R\n\n# reduction of neutron-branch of MURCA by singlet superfluidity \ndef _Rmodn_s(gap):\n\n if(gap == 0.0):\n R = 1.0 # no superfluidity\n elif(gap>200.0):\n R = 0.0 # superstrong superfluidity\n else :\n\n a = 0.1477+numpy.sqrt(routines.sqr(0.8523)+routines.sqr(0.1175*gap))\n b = 0.1477+numpy.sqrt(routines.sqr(0.8523)+routines.sqr(0.1297*gap))\n R = 0.5*(numpy.power(a,7.5)+numpy.power(b,5.5))*numpy.exp(3.437-numpy.sqrt(routines.sqr(3.437)+gap*gap))\n\n return R\n\n# reduction of proton-branch of MURCA by singlet superfluidity \ndef _Rmodp_s(gap):\n\n if(gap == 0.0):\n R = 1.0 # no superfluidity\n elif(gap>200.0):\n R = 0.0 # superstrong superfluidity\n else:\n\n a = 0.2414+numpy.sqrt(routines.sqr(0.7586)+routines.sqr(0.1318*gap))\n R = numpy.power(a, 7.0)*numpy.exp(5.339-numpy.sqrt(routines.sqr(5.339)+4.0*gap*gap))\n\n return R\n\n# reduction of proton-branch of MURCA by triplet superfluidity \ndef _Rmodp_t(gap):\n\n if(gap == 0.0):\n R = 1.0 # no superfluidity\n elif(gap>200.0):\n R = 0.0 # superstrong superfluidity\n else:\n\n a = 0.1612+numpy.sqrt(routines.sqr(0.8388)+routines.sqr(0.1117*gap))\n b = 0.1612+numpy.sqrt(routines.sqr(0.8388)+routines.sqr(0.1274*gap))\n R = 0.5*(numpy.power(a,7.0)+numpy.power(b,5.0))*numpy.exp(2.398-numpy.sqrt(routines.sqr(2.398)+gap*gap))\n\n return R\n\n# reduction of neutron-branch of MURCA by triplet superfluidity\n# asymptote for T << Tc (tau = T/Tc << 1)\ndef _Rmodn_t_asy(tau):\n\n if(tau>1):\n R = 1.0 # no superfluidity\n elif(tau<1.0e-3):\n R = 0.0 # superstrong superfluidity\n else:\n R = 1.56e-4*numpy.power(tau,-6.0)*numpy.exp(-2.376/tau) # asymptote!\n return R\n\n# reduction of p-MURCA by combined neutron and proton superfluidity \ndef _Rmodp(Ngap, Pgap):\n\n if((Ngap>200.0)or(Pgap>200.0)):\n return(0.0)\n\n Rn = _Rn(Ngap)\n Rnp = _Rnp(Ngap, 2.0*Pgap)\n\n if(Rn>1.0e-10):\n R = Rnp*_Rmodp_t(Ngap)/Rn\n else:\n R = Rnp*0.0023*Ngap*Ngap\n\n return R\n\n# reduction of n-MURCA by combined neutron and proton superfluidity \ndef _Rmodn(Ngap, Pgap):\n\n if((Ngap>200.0) or (Pgap>200.0)):\n return(0.0)\n\n Rp = _Rp(Pgap)\n Rnp = _Rnp(2.0*Ngap, Pgap)\n\n if(Rp>1.0e-10):\n R = Rnp*_Rmodn_s(Pgap)/Rp\n else:\n R = Rnp*0.0023*Pgap*Pgap\n\n return R\n\n# reduction of np-bremsstrahlung by singlet superfluidity \ndef _Rbremss_np_s(gap):\n\n if(gap<= 0.0):\n R = 1.0 # no superfluidity\n elif(gap>100.0):\n R = 0.0 # superstrong superfluidity\n else:\n\n a = 0.9982+numpy.sqrt(routines.sqr(0.0018)+routines.sqr(0.3815*gap))\n b = 0.3949+numpy.sqrt(routines.sqr(0.6051)+routines.sqr(0.2666*gap))\n R = 1.0/2.732*( a*numpy.exp(1.306-numpy.sqrt(routines.sqr(1.306)+gap*gap)) +\n 1.732*numpy.power(b, 7.0)*numpy.exp(3.303-numpy.sqrt(routines.sqr(3.303)+4.0*gap*gap)) )\n\n return R\n\n# reduction of pp-bremsstrahlung by singlet superfluidity \ndef _Rbremss_pp_s(gap):\n\n if(gap<= 0.0):\n R = 1.0 # no superfluidity\n elif(gap>100.0):\n R = 0.0 # superstrong superfluidity\n else:\n a = 0.1747+numpy.sqrt(routines.sqr(0.8253)+routines.sqr(0.07933*gap))\n b = 0.7333+numpy.sqrt(routines.sqr(0.2667)+routines.sqr(0.1678*gap))\n R = 0.5*( a*a*numpy.exp(4.228-numpy.sqrt(routines.sqr(4.228)+4.0*gap*gap)) +\n numpy.power(b, 7.5)*numpy.exp(7.762-numpy.sqrt(routines.sqr(7.762)+9.0*gap*gap)) )\n\n return R\n\n# reduction of np-bremssstrahlung by neutron and proton superfluidity \n# *** UNDER CONSTRUCTION *** \ndef _Rbremss_np(Ngap, Pgap):\n\n if((Ngap>200.0) or (Pgap>200.0)):\n return(0.0)\n Rp = _Rp(Pgap)\n Rnp = _Rnp(Ngap, Pgap)\n\n if(Rp>1.0e-30):\n R = Rnp*_Rbremss_np_s(Pgap)/Rp\n else:\n R = 0.0\n\n return R\n\ndef Threshold( fB1, fB2, fL ):\n\n cond1 = ( fB2 + fL >= fB1 )\n cond2 = ( fB1 >= numpy.fabs(fB2-fL) )\n cond3 = ( (fB1>0.) and (fB2>0.) and (fL>0.))\n cond = (cond1 and cond2 and cond3)\n\n if(cond1):\n return 1\n else:\n return 0\n\ndef _Qurca(T, nn, ne, nm, Tc_nt, Tc_ns, Tc_p):\n\n # T = temperature in K\n # nn = number density of free neutrons in fm^-3\n # ne = electron number density in fm^-3\n # nm = muon number density in fm^-3\n # Tc_nt = crit. temp. of neutron triplet superfluidity in K\n # Tc_ns = crit. temp. of neutron singlet superfluidity in K\n # Tc_p = critical temperature of proton superfluidity in K\n # a_n, a_p, a_nn, a_np, a_pp - Born corrections\n # b_n, b_p, b_nn, b_np, b_pp - non-Born corrections\n # Ngap, Pgap, Ngap1 - neutron & proton SF gaps\n # Rdir, Rmodn, Rmodp - reduction factors for URCAs\n # Rbremss_nn, Rbremss_np, Rbremss_pp - reduction factors for Bremss\n\n if(TNgap):\n Ngap = Ngap1\n\n if(T= Tc_p)): # neutron superfluidity\n\n Rdir = _Rn(Ngap) # reduction of DURCA by neutrons\n Rmodn = _Rmodn(Ngap, 0.) # reduction of n-MURCA by neutrons\n # asymptote is _Rmodn_t_asy(T/Tc_n)\n Rmodp = _Rmodp_t(Ngap) # reduction of p-MURCA by neutrons\n Rbremss_nn = _Rbremss_pp_s(Ngap) # *** UNDER CONSTRUCTION ***\n Rbremss_np = _Rbremss_np(Ngap, 0.) # *** UNDER CONSTRUCTION ***\n Rbremss_pp = 1. # no reduction of pp-bremss\n\n elif((T>= Tc_nt) and (T p + e + nu_e~, p + e -> n + nu_e\n if(Threshold(nn13, np13, ne13)):\n Qdurca_e = 4.0e27*(mn_eff)*(mp_eff)*ne13*T6 # DURCA emissivity\n # Qdurca_e = 1.0e23*T6 # to simulate pi-K-condensation\n\n else:\n Qdurca_e = 0.\n\n Qdurca_e *= Rdir # superfluidity reduction factor\n\n # ***** Direct URCA process with muons: *****\n # n -> p + mu + nu_mu~, p + mu -> n + nu_mu\n if(Threshold(nn13, np13, nm13)):\n Qdurca_m = 4.0e27*(mn_eff)*(mp_eff)*ne13*T6 # DURCA emissivity\n # here we take into account that me_eff = mm_eff = chem. potential_e/c^2\n # Qdurca_m = 1.0e25*T6 # to simulate pi-condensation\n\n else:\n Qdurca_m = 0.\n\n Qdurca_m *= Rdir # superfluidity reduction factor\n\n Qdurca = Qdurca_e + Qdurca_m\n\n # Modified URCA process with electrons:\n # n + n -> n + p + e + nu_e~, n + p + e -> n + n + nu_e\n # p + n -> p + p + e + nu_e~, p + p + e -> p + n + nu_e\n\n a_n = a_p = 1.76-0.63/(nn13*nn13)\n b_n = b_p = 0.68\n\n Qmurca_n_e = 8.55e21*numpy.power(mn_eff, 3.)*(mp_eff)*np13*T8*a_n*b_n\n\n if(nn13 >= 3.*np13 - ne13):\n\n p_factor1 = routines.sqr(ne13+3.*np13-nn13)/(8.*ne13*np13)\n Qmurca_p_e = 8.53e21*numpy.power(mp_eff, 3.)*(mn_eff)*np13*T8*a_p*b_p*p_factor1\n\n else:\n\n p_factor2 = 1./2.*(3. - nn13/np13)\n Qmurca_p_e = 8.53e21*numpy.power(mp_eff, 3.)*(mn_eff)*np13*T8*a_p*b_p*p_factor2\n\n Qmurca_n_e*= Rmodn # superfluidity reduction factor\n Qmurca_p_e*= Rmodp # superfluidity reduction factor\n\n # if(ne < nn/64.) Qmurca_p = 0. - momentum conservation condition\n\n if(nn13 > 3.*np13 + ne13):\n Qmurca_p_e = 0.\n\n Qmurca_e = Qmurca_n_e + Qmurca_p_e # total electron MURCA emissivity\n\n # Modified URCA process with muons:\n # n + n -> n + p + mu + nu_m~, n + p + mu -> n + n + nu_m\n # p + n -> p + p + mu + nu_m~, p + p + mu -> p + n + nu_m\n\n Corrector = nm13/ne13\n Qmurca_n_m = 8.55e21*numpy.power(mn_eff, 3.)*(mp_eff)*np13*T8*a_n*b_n*Corrector\n\n if(nn13 >= 3.*np13 - nm13):\n Qmurca_p_m = (8.53e21*numpy.power(mp_eff, 3.)*(mn_eff)*np13*T8*a_p*\n b_p*routines.sqr(nm13+3.*np13-nn13)/(8.*ne13*np13))\n\n else:\n\n p_factor2 = 1./2.*(3. - nn13/np13)\n Qmurca_p_m = 8.53e21*numpy.power(mp_eff, 3.)*(mn_eff)*np13*T8*a_p*b_p*p_factor2*Corrector\n\n Qmurca_n_m *= Rmodn # superfluidity reduction factor\n Qmurca_p_m *= Rmodp # superfluidity reduction factor\n\n if(nn13 > 3.*np13 + nm13):\n Qmurca_p_m = 0.\n\n Qmurca_m = Qmurca_n_m + Qmurca_p_m # total electron MURCA emissivity\n Qmurca = Qmurca_e + Qmurca_m\n\n # Bremsstrahlung:\n # n + n -> n + n + nu + nu~\n # n + p -> n + p + nu + nu~\n # p + p -> p + p + nu + nu~\n\n a_nn = 0.59\n a_np = 1.06\n a_pp = 0.11\n b_nn = 0.56\n b_np = 0.66\n b_pp = 0.7\n\n QBnn = 7.4e19*numpy.power(mn_eff, 4.)*nn13*T8*a_nn*b_nn*Nnu\n QBpp = 7.4e19*numpy.power(mp_eff, 4.)*np13*T8*a_pp*b_pp*Nnu\n QBnp = 1.5e20*routines.sqr(mn_eff)*routines.sqr(mp_eff)*np13*T8*a_np*b_np*Nnu\n\n QBnn*= Rbremss_nn # superfluidity reduction factor\n QBpp*= Rbremss_pp # superfluidity reduction factor\n QBnp*= Rbremss_np # superfluidity reduction factor\n\n Qbremss = QBnn + QBpp + QBnp # total Bremsstrahlung emissivity\n\n Q = Qdurca + Qmurca + Qbremss\n\n return Q\n\n# Neutrino emissivity (total, redshifted, per unit volume)\ndef _Q(T, nn, ne, nm, rho, phi, Tc_nt, Tc_ns, Tc_p):\n\n # T = temperature in K\n # nn = number density of free neutrons in fm^-3\n # ne = electron number density in fm^-3\n # nm = muon number density in fm^-3\n # Vion = fraction of volume occupied by ions in the crust\n # rho = mass density in g/cm^3\n # phi = dimensionless gravitational potential\n # Tc_nt = crit. temp. of neutron triplet superfluidity in K\n # Tc_nt = crit. temp. of neutron singlet superfluidity in K\n # Tc_p = crit. temp. of proton singlet superfluidity in K\n\n CoreCrustBound2 = 0.9999667*CoreCrustBound\n redshift = numpy.exp(2.*phi) # gravitational redshift factor\n np = ne + nm\n\n if(rho < CoreCrustBound): # CRUST\n\n Qcrust = _Qcrust(T, rho, ne, nn, Tc_nt, Tc_ns)\n Qcrust *= redshift\n\n if(rho > CoreCrustBound2): # CORE\n\n Qurca = _Qurca(T, nn, ne, nm, Tc_nt, Tc_ns, Tc_p)\n\n if((T= CoreCrustBound):\n Q = Qcore\n else:\n Q = ((rho-CoreCrustBound2)/(CoreCrustBound-CoreCrustBound2)*Qcore +\n (CoreCrustBound-rho)/(CoreCrustBound-CoreCrustBound2)*Qcrust)\n\n return Q\n\n","sub_path":"physics/neutrino.py","file_name":"neutrino.py","file_ext":"py","file_size_in_byte":23233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"364110636","text":"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\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\"\"\"Generate tensorflow graphs for testing tfcompile.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.core.protobuf import saver_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import app\nfrom tensorflow.python.platform import flags as flags_lib\nfrom tensorflow.python.training import saver as saver_lib\n\nflags = flags_lib\nFLAGS = flags.FLAGS\nflags.DEFINE_string('out_dir', '',\n 'Output directory for graphs, checkpoints and savers.')\n\n\ndef tfadd():\n x = constant_op.constant([1], name='x_const')\n y = constant_op.constant([2], name='y_const')\n math_ops.add(x, y, name='x_y_sum')\n\n\ndef tfadd_with_ckpt():\n x = array_ops.placeholder(dtypes.int32, name='x_hold')\n y = variables.Variable(constant_op.constant([0]), name='y_saved')\n math_ops.add(x, y, name='x_y_sum')\n\n init_op = variables.initialize_all_variables()\n saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V1)\n with session.Session() as sess:\n sess.run(init_op)\n sess.run(y.assign(y + 42))\n # Without the checkpoint, the variable won't be set to 42.\n ckpt = '%s/test_graph_tfadd_with_ckpt.ckpt' % FLAGS.out_dir\n saver.save(sess, ckpt)\n\n\ndef tfadd_with_ckpt_saver():\n x = array_ops.placeholder(dtypes.int32, name='x_hold')\n y = variables.Variable(constant_op.constant([0]), name='y_saved')\n math_ops.add(x, y, name='x_y_sum')\n\n init_op = variables.initialize_all_variables()\n saver = saver_lib.Saver(name='abcprefix', write_version=saver_pb2.SaverDef.V1)\n with session.Session() as sess:\n sess.run(init_op)\n sess.run(y.assign(y + 42))\n # Without the checkpoint, the variable won't be set to 42.\n ckpt_file = '%s/test_graph_tfadd_with_ckpt_saver.ckpt' % FLAGS.out_dir\n saver.save(sess, ckpt_file)\n # Without the SaverDef, the restore op won't be named correctly.\n saver_file = '%s/test_graph_tfadd_with_ckpt_saver.saver' % FLAGS.out_dir\n with open(saver_file, 'w') as f:\n f.write(saver.as_saver_def().SerializeToString())\n\n\ndef tfgather():\n params = array_ops.placeholder(dtypes.float32, name='params')\n indices = array_ops.placeholder(dtypes.int32, name='indices')\n array_ops.gather(params, indices, name='gather_output')\n\n\ndef tfmatmul():\n x = array_ops.placeholder(dtypes.float32, name='x_hold')\n y = array_ops.placeholder(dtypes.float32, name='y_hold')\n math_ops.matmul(x, y, name='x_y_prod')\n\n\ndef tfmatmulandadd():\n # This tests multiple outputs.\n x = array_ops.placeholder(dtypes.float32, name='x_hold')\n y = array_ops.placeholder(dtypes.float32, name='y_hold')\n math_ops.matmul(x, y, name='x_y_prod')\n math_ops.add(x, y, name='x_y_sum')\n\n\ndef write_graph(build_graph):\n \"\"\"Build a graph using build_graph and write it out.\"\"\"\n g = ops.Graph()\n with g.as_default():\n build_graph()\n filename = '%s/test_graph_%s.pb' % (FLAGS.out_dir, build_graph.__name__)\n with open(filename, 'w') as f:\n f.write(g.as_graph_def().SerializeToString())\n\n\ndef main(_):\n write_graph(tfadd)\n write_graph(tfadd_with_ckpt)\n write_graph(tfadd_with_ckpt_saver)\n write_graph(tfgather)\n write_graph(tfmatmul)\n write_graph(tfmatmulandadd)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"tensorflow/compiler/aot/tests/make_test_graphs.py","file_name":"make_test_graphs.py","file_ext":"py","file_size_in_byte":4210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"624563882","text":"#!/usr/bin/env python3\n\n\"\"\"Problem 94: Almost equilateral triangles\"\"\"\n\n\ndef main():\n max_perimeter = 10**9\n psum = 0\n # By writing x = (3*a +- 1)/2 and y = h, we get the Pell equation:\n # x^2 - 3*y^2 = 1.\n\n # fundamental solution\n x1, y1 = 2, 1\n\n # the first solution\n x, y = 7, 4\n\n sign = 1\n\n while 2*x <= max_perimeter:\n a = (2*x + sign*1)//3\n psum += 3*a + sign*1\n x, y, sign = x1*x + 3*y1*y, x1*y + y1*x, -sign\n\n return psum\n\nif __name__ == \"__main__\":\n print(main())\n","sub_path":"python/p094.py","file_name":"p094.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"71156714","text":"from lgh_rh_202111001_func import *\nfrom joblib import Parallel, delayed, load, dump\nfrom optbinning import BinningProcess\nfrom catboost import CatBoostClassifier, Pool, cv\nfrom time import *\nimport math\n\n\n# 人行模型\ndef lgh_rh_20211001(train_df):\n \"\"\"\n lgh人行模型 日期版本:lgh_rh_20211001\n :param train_df: 上方 rhDataOnline函数 加工完毕后的 特征数据\n :return: 模型:y_pred\n \"\"\"\n\n memoryKeys = {'rh_dpd60_raw_cross_model_cat_fold', 'rh_dpd60_raw_cross_feature',\n 'pboc2_fpd20_raw_cross_model_cat_fold_coor','pboc2_fpd20_raw_cross_feature_coor'}\n\n # 判断变量有无加载到内存中\n if memoryKeys.issubset(locals().keys()):\n pass\n else:\n\n rh_dpd60_raw_cross_model_cat_fold = load('./rh_model/rh_dpd60_raw_cross_model_cat_fold.joblib')\n rh_dpd60_raw_cross_feature = load('./rh_model/rh_dpd60_raw_cross_feature.joblib')\n\n\n pboc2_fpd20_raw_cross_feature_coor = load('./rh_model/pboc2_fpd20_raw_cross_feature_coor.joblib')\n pboc2_fpd20_raw_cross_model_cat_fold_coor = load('./rh_model/pboc2_fpd20_raw_cross_model_cat_fold_coor.joblib')\n\n dict_in = train_df[pboc2_fpd20_raw_cross_feature_coor].iloc[0].to_dict()\n pboc2_fpd20_raw_coor_score = get_raw_cross_score(dict_in, pboc2_fpd20_raw_cross_feature_coor, pboc2_fpd20_raw_cross_model_cat_fold_coor)\n\n\n dict_in = train_df[rh_dpd60_raw_cross_feature].iloc[0].to_dict()\n rh_dpd60_raw_score = get_raw_cross_score(dict_in, rh_dpd60_raw_cross_feature, rh_dpd60_raw_cross_model_cat_fold)\n\n\n data = {'rh_dpd60_raw_score': rh_dpd60_raw_score,\n 'pboc2_fpd20_raw_coor_score': pboc2_fpd20_raw_coor_score}\n\n return data\n\n\n# 百融模型\ndef lgh_br_20211001(train_df):\n memoryKeys = {'bairong_dpd60_raw_cross_model_cat_fold', 'bairong_dpd60_raw_cross_feature'}\n\n # 判断变量有无加载到内存中\n if memoryKeys.issubset(locals().keys()):\n pass\n else:\n bairong_dpd60_raw_cross_model_cat_fold = load('./br_model/bairong_dpd60_raw_cross_model_cat_fold.joblib')\n bairong_dpd60_raw_cross_feature = load('./br_model/bairong_dpd60_raw_cross_feature.joblib')\n\n\n dict_in = train_df[bairong_dpd60_raw_cross_feature].iloc[0].to_dict()\n bairong_dpd60_raw_score = get_raw_cross_score(dict_in, bairong_dpd60_raw_cross_feature,bairong_dpd60_raw_cross_model_cat_fold)\n\n dict_out = {'bairong_dpd60_raw_score': bairong_dpd60_raw_score}\n\n return dict_out\n\n\n\n# 京东模型\ndef lgh_jd_20211001(train_df):\n memoryKeys = {'jingdong_fpd20_raw_cross_feature_block3', 'jingdong_fpd20_raw_cross_model_cat_fold_block3'}\n\n # 判断变量有无加载到内存中\n if memoryKeys.issubset(locals().keys()):\n pass\n else:\n jingdong_fpd20_raw_cross_feature_block3 = load('./jd_model/jingdong_fpd20_raw_cross_feature_block3.joblib')\n jingdong_fpd20_raw_cross_model_cat_fold_block3 = load('./jd_model/jingdong_fpd20_raw_cross_model_cat_fold_block3.joblib')\n\n\n dict_in = train_df[jingdong_fpd20_raw_cross_feature_block3].iloc[0].to_dict()\n jingdong_fpd20_raw_block3_score = get_raw_cross_score(dict_in, jingdong_fpd20_raw_cross_feature_block3,\n jingdong_fpd20_raw_cross_model_cat_fold_block3)\n\n\n dict_out = {'jingdong_fpd20_raw_block3_score': jingdong_fpd20_raw_block3_score}\n\n return dict_out\n\n\n# 大数据模型\ndef lgh_big_20211001(train_df):\n\n big_time = time()\n\n memoryKeys = {'cross_feature_big3_dpd60_raw_block3', 'cross_model_big3_dpd60_raw_block3',\n 'cross_feature_big3_dpd60_raw_n3', 'cross_model_big3_dpd60_raw_n3',\n 'cross_feature_big3_fpd20_raw_coor', 'cross_model_big3_fpd20_raw_coor',\n 'big_fpd20_raw_cross_feature', 'big_fpd20_raw_cross_model_cat_fold',\n 'big_fpd20_raw_cross_model_cat_fold_coor_1', 'big_fpd20_raw_cross_feature_coor_1'}\n\n # 判断变量有无加载到内存中\n if memoryKeys.issubset(locals().keys()):\n pass\n else:\n\n cross_feature_big3_dpd60_raw_block3 = load('./big_model/cross_feature_big3_dpd60_raw_block3.joblib')\n cross_model_big3_dpd60_raw_block3 = load('./big_model/cross_model_big3_dpd60_raw_block3.joblib')\n\n cross_feature_big3_dpd60_raw_n3 = load('./big_model/cross_feature_big3_dpd60_raw_n3.joblib')\n cross_model_big3_dpd60_raw_n3 = load('./big_model/cross_model_big3_dpd60_raw_n3.joblib')\n\n cross_feature_big3_fpd20_raw_coor = load('./big_model/cross_feature_big3_fpd20_raw_coor.joblib')\n cross_model_big3_fpd20_raw_coor = load('./big_model/cross_model_big3_fpd20_raw_coor.joblib')\n\n big_fpd20_raw_cross_model_cat_fold = load('./big_model/big_fpd20_raw_cross_model_cat_fold.joblib')\n big_fpd20_raw_cross_feature = load('./big_model/big_fpd20_raw_cross_feature.joblib')\n\n big_fpd20_raw_cross_model_cat_fold_coor_1 = load('./big_model/big_fpd20_raw_cross_model_cat_fold_coor_1.joblib')\n big_fpd20_raw_cross_feature_coor_1 = load('./big_model/big_fpd20_raw_cross_feature_coor_1.joblib')\n\n big1_time = time()\n print(\"big模型变量加载时间:\", big1_time - big_time)\n\n dict_in = train_df[big_fpd20_raw_cross_feature].iloc[0].to_dict()\n big_fpd20_raw_score = get_raw_cross_score(dict_in, big_fpd20_raw_cross_feature, big_fpd20_raw_cross_model_cat_fold)\n\n time1 = time()\n print(\"big_fpd20_raw_score模型计算时间:\", time1 - big1_time)\n\n dict_in = train_df[cross_feature_big3_dpd60_raw_block3].iloc[0].to_dict()\n big3_dpd60_raw_block3_score = get_raw_cross_score(dict_in, cross_feature_big3_dpd60_raw_block3, cross_model_big3_dpd60_raw_block3)\n\n time2 = time()\n print(\"big3_dpd60_raw_block3_score模型计算时间:\", time2 - time1)\n\n dict_in = train_df[cross_feature_big3_dpd60_raw_n3].iloc[0].to_dict()\n big3_dpd60_raw_n3_score = get_raw_cross_score(dict_in, cross_feature_big3_dpd60_raw_n3,cross_model_big3_dpd60_raw_n3)\n\n time3 = time()\n print(\"big3_dpd60_raw_n3_score模型计算时间:\", time3 - time2)\n\n dict_in = train_df[cross_feature_big3_fpd20_raw_coor].iloc[0].to_dict()\n big3_fpd20_raw_coor_score = get_raw_cross_score(dict_in, cross_feature_big3_fpd20_raw_coor, cross_model_big3_fpd20_raw_coor)\n\n time4 = time()\n print(\"big3_fpd20_raw_coor_score模型计算时间:\", time4 - time3)\n\n dict_in = train_df[big_fpd20_raw_cross_feature_coor_1].iloc[0].to_dict()\n big_fpd20_raw_coor_1_score = get_raw_cross_score(dict_in, big_fpd20_raw_cross_feature_coor_1, big_fpd20_raw_cross_model_cat_fold_coor_1)\n\n time5 = time()\n print(\"big_fpd20_raw_coor_1_score模型计算时间:\", time5 - time4)\n\n dict_out = {'big3_dpd60_raw_block3_score': big3_dpd60_raw_block3_score,\n 'big3_dpd60_raw_n3_score': big3_dpd60_raw_n3_score,\n 'big3_fpd20_raw_coor_score': big3_fpd20_raw_coor_score,\n 'big_fpd20_raw_coor_1_score': big_fpd20_raw_coor_1_score,\n 'big_fpd20_raw_score': big_fpd20_raw_score}\n\n return dict_out\n\n\n# 全数据模型\ndef lgh_all_20211001(train_df):\n\n all_time = time()\n\n memoryKeys = {'cross_feature_all3_dpd60_raw_block3', 'cross_model_all3_dpd60_raw_block3',\n 'cross_feature_all3_fpd20_raw_block3', 'cross_model_all3_fpd20_raw_block3',\n 'cross_feature_all3_fpd20_raw_coor', 'cross_model_all3_fpd20_raw_coor',\n 'all_dpd60_raw_cross_model_cat_fold', 'all_dpd60_raw_cross_feature'}\n\n # 判断变量有无加载到内存中\n if memoryKeys.issubset(locals().keys()):\n pass\n else:\n cross_model_all3_dpd60_raw_block3 = load('./all_model/cross_model_all3_dpd60_raw_block3.joblib')\n cross_feature_all3_dpd60_raw_block3 = load('./all_model/cross_feature_all3_dpd60_raw_block3.joblib')\n\n cross_feature_all3_fpd20_raw_block3 = load('./all_model/cross_feature_all3_fpd20_raw_block3.joblib')\n cross_model_all3_fpd20_raw_block3 = load('./all_model/cross_model_all3_fpd20_raw_block3.joblib')\n\n cross_feature_all3_fpd20_raw_coor = load('./all_model/cross_feature_all3_fpd20_raw_coor.joblib')\n cross_model_all3_fpd20_raw_coor = load('./all_model/cross_model_all3_fpd20_raw_coor.joblib')\n\n all_dpd60_raw_cross_model_cat_fold = load('./all_model/all_dpd60_raw_cross_model_cat_fold.joblib')\n all_dpd60_raw_cross_feature = load('./all_model/all_dpd60_raw_cross_feature.joblib')\n\n time1 = time()\n print(\"all模型变量加载时间:\", time1 - all_time)\n\n dict_in = train_df[cross_feature_all3_dpd60_raw_block3].iloc[0].to_dict()\n all3_dpd60_raw_block3_score = get_raw_cross_score(dict_in, cross_feature_all3_dpd60_raw_block3,cross_model_all3_dpd60_raw_block3)\n\n time2 = time()\n print(\"all3_dpd60_raw_block3_score计算时间:\", time2 - time1)\n\n\n dict_in = train_df[cross_feature_all3_fpd20_raw_block3].iloc[0].to_dict()\n all3_fpd20_raw_block3_score = get_raw_cross_score(dict_in, cross_feature_all3_fpd20_raw_block3,cross_model_all3_fpd20_raw_block3)\n\n time3 = time()\n print(\"all3_fpd20_raw_block3_score计算时间:\", time3 - time2)\n\n dict_in = train_df[cross_feature_all3_fpd20_raw_coor].iloc[0].to_dict()\n all3_fpd20_raw_coor_score = get_raw_cross_score(dict_in, cross_feature_all3_fpd20_raw_coor,cross_model_all3_fpd20_raw_coor)\n\n time4 = time()\n print(\"all3_fpd20_raw_coor_score计算时间:\", time4 - time3)\n\n dict_in = train_df[all_dpd60_raw_cross_feature].iloc[0].to_dict()\n all_dpd60_raw_score = get_raw_cross_score(dict_in, all_dpd60_raw_cross_feature,all_dpd60_raw_cross_model_cat_fold)\n\n time5 = time()\n print(\"all_dpd60_raw_score计算时间:\", time5 - time4)\n\n\n dict_out = {'all3_dpd60_raw_block3_score': all3_dpd60_raw_block3_score,\n 'all3_fpd20_raw_block3_score': all3_fpd20_raw_block3_score,\n 'all3_fpd20_raw_coor_score': all3_fpd20_raw_coor_score,\n 'all_dpd60_raw_score': all_dpd60_raw_score}\n\n return dict_out\n\n\n# 优分数据模型\ndef lgh_youfen_20211001(train_df):\n memoryKeys = {'youfen_fpd20_raw_cross_feature_coor3', 'youfen_fpd20_raw_cross_model_cat_fold_coor3'}\n\n # 判断变量有无加载到内存中\n if memoryKeys.issubset(locals().keys()):\n pass\n else:\n\n youfen_fpd20_raw_cross_model_cat_fold_coor3 = load('./youfen_model/youfen_fpd20_raw_cross_model_cat_fold_coor3.joblib')\n youfen_fpd20_raw_cross_feature_coor3 = load('./youfen_model/youfen_fpd20_raw_cross_feature_coor3.joblib')\n\n\n dict_in = train_df[youfen_fpd20_raw_cross_feature_coor3].iloc[0].to_dict()\n youfen_fpd20_raw_coor3_score = get_raw_cross_score(dict_in, youfen_fpd20_raw_cross_feature_coor3,youfen_fpd20_raw_cross_model_cat_fold_coor3)\n\n\n\n dict_out = {'youfen_fpd20_raw_coor3_score': youfen_fpd20_raw_coor3_score}\n\n return dict_out\n\n\n# yzj全数据模型\ndef yzj_all_20211001(train_df):\n\n memoryKeys = {'yzj_binning5','yzj_model5','yzj_feature5'}\n\n # 判断变量有无加载到内存中\n if memoryKeys.issubset(locals().keys()):\n pass\n else:\n # 分箱表和模型和特征加载\n # yzj_binning1 = BinningProcess.load(\"./yzj_model/binning1.pkl\")\n # yzj_binning2 = BinningProcess.load(\"./yzj_model/binning2.pkl\")\n # yzj_binning3 = BinningProcess.load(\"./yzj_model/binning3.pkl\")\n # yzj_binning4 = BinningProcess.load(\"./yzj_model/binning4.pkl\")\n yzj_binning5 = BinningProcess.load(\"./yzj_model/binning5.pkl\")\n\n # model1 = CatBoostClassifier()\n # yzj_model1 = model1.load_model('./yzj_model/catboost_model1.dump')\n #\n # model2 = CatBoostClassifier()\n # yzj_model2 = model2.load_model('./yzj_model/catboost_model2.dump')\n #\n # model3 = CatBoostClassifier()\n # yzj_model3 = model3.load_model('./yzj_model/catboost_model3.dump')\n #\n # model4 = CatBoostClassifier()\n # yzj_model4 = model4.load_model('./yzj_model/catboost_model4.dump')\n\n model5 = CatBoostClassifier()\n yzj_model5 = model5.load_model('./yzj_model/catboost_model5.dump')\n\n # yzj_feature1 = load('./yzj_model/feature_model1.joblib')\n # yzj_feature2 = load('./yzj_model/feature_model2.joblib')\n # yzj_feature3 = load('./yzj_model/feature_model3.joblib')\n # yzj_feature4 = load('./yzj_model/feature_model4.joblib')\n yzj_feature5 = load('./yzj_model/feature_model5.joblib')\n\n # 特征加工\n train_df = train_df.replace('--', np.nan).reset_index(drop=True)\n\n # test1_woe = yzj_binning1.transform(train_df[yzj_feature1], metric=\"woe\")\n # y_pred_1 = yzj_model1.predict_proba(test1_woe[yzj_feature1])[:, 1]\n # # score1 = p_to_score(y_pred_1)\n #\n # test2_woe = yzj_binning2.transform(train_df[yzj_feature2], metric=\"woe\")\n # y_pred_2 = yzj_model2.predict_proba(test2_woe[yzj_feature2])[:, 1]\n # # score2 = p_to_score(y_pred_2)\n #\n # test3_woe = yzj_binning3.transform(train_df[yzj_feature3], metric=\"woe\")\n # y_pred_3 = yzj_model3.predict_proba(test3_woe[yzj_feature3])[:, 1]\n # # score3 = p_to_score(y_pred_3)\n #\n # test4_woe = yzj_binning4.transform(train_df[yzj_feature4], metric=\"woe\")\n # y_pred_4 = yzj_model4.predict_proba(test4_woe[yzj_feature4])[:, 1]\n # score4 = p_to_score(y_pred_4)\n\n test5_woe = yzj_binning5.transform(train_df[yzj_feature5], metric=\"woe\")\n y_pred_5 = yzj_model5.predict_proba(test5_woe[yzj_feature5])[:, 1]\n # score5 = p_to_score(y_pred_5)\n\n # score = (score1 + score2 + score3 + score4 + score5)/5\n\n # 测试返回 dataframe\n # y_pred = pd.DataFrame({\"y_pred_1\":y_pred_1,\"y_pred_2\":y_pred_2,\"y_pred_3\":y_pred_3, \"y_pred_4\":y_pred_4, \"y_pred_5\":y_pred_5})\n # y_pred = (y_pred_1 + y_pred_2 + y_pred_3 + y_pred_4 + y_pred_5) / 5\n y_pred = y_pred_5[0]\n return {'yzj_all_model_score': y_pred}\n\n\n# cxt全数据模型\ndef cxt_all_20211001(train_df):\n\n memoryKeys = {'cxt_model', 'cxt_binning_process'}\n\n # 判断变量有无加载到内存中\n if memoryKeys.issubset(locals().keys()):\n pass\n else:\n model = CatBoostClassifier()\n cxt_model = model.load_model('./cxt_model/cxt_model_01.bin')\n cxt_binning_process = BinningProcess.load('./cxt_model/binning_process_01.pkl')\n\n cxt_features = cxt_model.feature_names_\n data_woe = cxt_binning_process.transform(train_df[cxt_features], metric=\"woe\")\n proba = cxt_model.predict_proba(data_woe)[:, 1]\n\n return {'cxt_all_model_score': proba[0]}\n\n\n# 综合决策数据模型\ndef lgh_final_20211001(train_df):\n memoryKeys = {'final_cross_feature', 'final_cross_model_cat_fold'}\n\n # 判断变量有无加载到内存中\n if memoryKeys.issubset(locals().keys()):\n pass\n else:\n\n final_cross_feature = load('./final_model/final_cross_feature.joblib')\n final_cross_model_cat_fold = load('./final_model/final_cross_model_cat_fold.joblib')\n\n\n dict_in = train_df[final_cross_feature].iloc[0].to_dict()\n final_score = get_raw_cross_score(dict_in, final_cross_feature,final_cross_model_cat_fold)\n\n\n\n dict_out = {'final_score': final_score}\n\n return dict_out","sub_path":"model_handle.py","file_name":"model_handle.py","file_ext":"py","file_size_in_byte":15110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"378665412","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass Plotter:\n def __init__(self):\n self.barNum = 1\n self.pieNum = 1\n\n def bar(self, vals, names, x_lable, y_lable, title, save=True, show=True):\n ind = np.arange(len(vals))\n plt.bar(ind, vals,0.35)\n plt.ylabel(y_lable)\n plt.title(title)\n\n plt.xticks(ind, names)\n plt.yticks(np.arange(0, max(vals)*1.1, np.round(max(vals)/10)))\n if save:\n plt.savefig(title + str(self.barNum) + \".png\")\n self.barNum += 1\n if show:\n plt.show()\n plt.close()\n\n def pie(self, x, y, x_lable, y_lable, title, save=True, show=True):\n plt.xlabel(x_lable)\n plt.ylabel(y_lable)\n plt.title(title)\n plt.pie(x, y)\n if save:\n plt.savefig(title + str(self.pieNum) + \".png\")\n self.pieNum += 1\n if show:\n plt.show()\n plt.close()\n\n def line(self, x, y, x_lable, y_lable, title, save=True, show=True):\n\n plt.xlabel(x_lable)\n plt.ylabel(y_lable)\n plt.title(title)\n plt.plot(x, y,0.35)\n if save:\n plt.savefig(title + str(self.pieNum) + \".png\")\n self.pieNum += 1\n if show:\n plt.show()\n\n\n# heuristics_str= ['original', 'fn_lost_marbles', 'sumito', 'defensive', 'aggressive']\n# heuristics_str2 = [13243432422,3,4,4,4]\n#\n# pl = Plotter()\n# pl.bar(heuristics_str2, heuristics_str, 'td', 'sd', 'title')\n# pl.bar(heuristics_str2, heuristics_str, 'tasd', 'ssad', 'title')\n","sub_path":"plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"47814802","text":"#! /usr/bin/env python3\n# coding: gbk\nimport requests\nfrom bs4 import BeautifulSoup \n\ndef main():\n C_CHAR = '℃'\n hdr = {\n 'Accept' : '*/*',\n 'Accept-Encoding' : 'gzip, deflate, br',\n 'Accept-Language' : 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Connection' : 'keep-alive',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0',\n }\n req = requests.get(\"http://www.weather.com.cn/weather/101010100.shtml\", headers=hdr)\n req.encoding='utf-8'\n soup = BeautifulSoup(req.text, features='html.parser')\n day = soup.find('li', class_='sky skyid lv1 on')\n wea = day.find('p', class_='wea')['title']\n tems = day.find('p', class_='tem')\n daytem = int(tems.find('span').text)\n nigtem = int(tems.find('i').text[:-1])\n \n wea = wea.replace('晴', 'S')\n wae = wea.replace('多云', 'C')\n wea = wea.replace('阴', 'G')\n wea = wea.replace('小雨', 'r')\n wea = wea.replace('中雨', 'R')\n wea = wea.replace('大雨', 's')\n wea = wea.replace('转', ' ')\n return wea, daytem, nigtem, C_CHAR\n\n\nif __name__=='__main__':\n print(main())\n\n","sub_path":"getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"319890608","text":"import numpy as np\n\n\nvec1 = np.array([ -1., 4., -9. ])\nmat1 = np.array([[ 1., 3., 5. ], [7., -9., 2.], [4., 6., 8. ]])\n\nvec2 = (np.pi/4) * vec1\nvec2\nvec2 = np.cos(vec2)\nvec2\nvec3 = vec1 + 2*vec2\nvec3\nla.norm(vec3)\nvec4 = vec3 * mat1\nvec4\n\nmat1_transpose = mat1.transpose()\nmat1_transpose\n\nmat1_determinant = np.linalg.det(vec4)\nmat1_determinant\n\nmat1_trace = np.ndarray.trace(mat1)\nmat1_trace\n\nnp.min(vec1) #smallest element in vec1\n\nnp.where(vec1 == np.min(vec1)) #location of smallest element\n\nmat1.min()\n\na=np.array([[17, 24, 1, 8, 15],\n [23, 5, 7, 14, 16],\n [ 4, 6, 13, 20, 22 ],\n [10, 12, 19, 21, 3],\n [11, 18, 25, 2, 9]])\n\nnp.sum(a, axis=0)\nnp.sum(a, axis=1)\nnp.sum(np.diag(a))\nnp.sum(np.fliplr(a))\n\nm=np.random.randn(10,10)\nm\n\nmul = m[:5, :5]\nmul\n\nmur = m[5:, :5]\nmur\n\nmll = m[:5, 5:]\nmll\n\nmlr = m[5:, 5:]\nmlr\n","sub_path":"maxine/python/ex8_numpy.py","file_name":"ex8_numpy.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"384671394","text":"from django.shortcuts import render\nfrom .models import Cliente\nfrom django.utils import timezone\nfrom django.shortcuts import redirect, get_object_or_404\nfrom .forms import PostForm, PostFormEdit\nfrom django.views.generic.list import ListView\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\n\n\n\n# Create your views here.\n\nclass ClienteListView(ListView): \n model = Cliente\n paginated_by = 10\n template_name = 'cliente_list.html'\n context_object_name = 'Cliente'\n\n def get_queryset(self):\n queryset = Cliente.objects.all()\n if self.request.GET.get('publish'):\n queryset = queryset.filter(publish__icontains=self.request.GET.get('publish'))\n\n return queryset.order_by('-status')\n\n def get_context_data(self, **kwargs):\n context = super(ClienteListView, self).get_context_data(**kwargs)\n clientes = self.get_queryset()\n page = self.request.GET.get('page')\n paginator = Paginator(clientes, '30')\n try:\n clientes = paginator.page(page)\n except PageNotAnInteger:\n clientes = paginator.page(1)\n except EmptyPage:\n clientes = paginator.page(paginator.num_pages)\n context['clientes'] = clientes\n context['nome_cliente'] = self.request.GET.get('nome_cliente', '')\n return context\n\n \n\n\ndef home(request):\n clientes = Cliente.objects.all().order_by(\"status\")\n return render(request, 'home.html', {'clientes': clientes})\n\n\n\ndef detalhe_cliente(request, pk):\n cliente = Cliente.objects.get(pk=pk)\n return render(request, 'detalhe_cliente.html', {'cliente': cliente})\n\ndef delete(request, pk):\n transacao = Transacao.Cliente.get(pk=pk)\n transacao.delete()\n return redirect('home')\n\n\ndef adicionar_cliente(request):\n #Quando para salvar\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n cliente = form.save(commit=False)\n cliente.autor = request.user \n cliente.save()\n return redirect('home')\n else:\n form = PostForm() \n\n return render(request, 'edit_cliente.html', {'form':form})\n\n\ndef editar_cliente(request, pk):\n cliente = get_object_or_404(Cliente, pk=pk)\n if request.method == \"POST\":\n form = PostFormEdit(request.POST, instance=cliente)\n if form.is_valid():\n cliente = form.save(commit=False)\n cliente.save()\n return redirect('home')\n else:\n form = PostFormEdit(instance=cliente)\n\n return render(request, 'edit_cliente.html', {'form':form})\n\n\ndef lista_cliente(request):\n def get_queryset(self):\n return super(lista_cliente,self).get_queryset().filter(status='condicao_atendimento')\n def get_absolute_url(self):\n return reverse('centro_sul_clientes_cadastro:cliente_list', args=[self.publish.year, self.publish.month, self.publish.day, slugify(self.slug)])\n return render(request, 'cliente_list.html') \n","sub_path":"centro_sul_clientes_cadastro/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"59658569","text":"#!/usr/bin/python\n\nimport os\nimport sys\nimport subprocess\n\n\n\n# define\n#\nLINE_END =\"=================================================================\"\nLINE_NET_DOWN=\" [ Network Down ] Blockchain Network Containers are Down. \"\nLINE_NET_UP =\" [ Network Up ] Blockchain Network Containers are Up \"\n\n\n\n# display func\n#\ndef display_network_down():\n os.system('clear')\n print(\"\")\n print(LINE_END)\n print(LINE_NET_DOWN)\n print(LINE_END)\n print(\"\")\n\ndef display_network_up():\n os.system('clear')\n print(\"\")\n print(LINE_END)\n print(LINE_NET_UP)\n print(LINE_END)\n print(\"\")\n\n\n\n# func\n#\ndef network_down_cmd():\n network_down_cmd = \"docker-compose -f docker-compose.yaml down\"\n cmd_result = subprocess.call(network_down_cmd, stdin=None, stdout=None, stderr=subprocess.STDOUT, shell=True)\n return cmd_result\n\ndef network_up_cmd():\n network_up_cmd = \"docker-compose -f docker-compose.yaml up -d\"\n cmd_result = subprocess.call(network_up_cmd, stdin=None, stdout=None, stderr=subprocess.STDOUT, shell=True)\n return cmd_result\n\ndef wait_time_cmd():\n wait_time_cmd = \"sleep 5\"\n cmd_result = subprocess.call(wait_time_cmd, stdin=None, stdout=None, stderr=subprocess.STDOUT, shell=True)\n return cmd_result\n\n\ndef main():\n\n display_network_down() \n result = network_down_cmd()\n if 0 != result:\n sys.exit(-1)\n\n display_network_up()\n result = network_up_cmd()\n if 0 != result:\n sys.exit(-1)\n\n wait_time_cmd\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/network/first-network/cli/0-network-start.py","file_name":"0-network-start.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"434257003","text":"a = {}\n\n\ndef do_bet(ho, stavka):\n global a\n if ho not in a and stavka > 0 and ho < 11 and ho > 0:\n print('Ваша ставка в размере ' + str(stavka) + ' на лошадь ' + str(ho) + ' принята')\n a[ho] = stavka\n else:\n print('Что-то пошло не так, попробуйте еще раз')\n\n\n","sub_path":"First year/Функция/Делайте ваши ставки.py","file_name":"Делайте ваши ставки.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"507448077","text":"# encoding:utf-8\nimport requests\nimport re\nimport random\nimport time\n\ndomain_list = [\n 'github.com',\n]\n\ngithub_subdomain = [\n 'gist',\n 'assets-cdn',\n]\n\ngithubusercontent_subdomain = [\n 'raw',\n 'gist',\n 'cloud',\n 'camo',\n 'user-images',\n 'avatars',\n]\n\navatars_list = []\nfor num in range(9):\n avatars_list.append(\"avatars\" + str(num))\n\n# https://github.com.ipaddress.com/\nheaders = {\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36\",\n}\n\n\ndef isIP(str):\n p = re.compile('^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$')\n if p.match(str):\n return True\n else:\n return False\n\n\nhosts = {}\nprint(\"处理domain...\")\nfor domain in domain_list:\n url = \"https://\" + domain + \".ipaddress.com/\"\n response = requests.get(url=url, headers=headers)\n raw_data = response.text\n pattern = re.compile(r'IP Address
  • (.*?)
')\n find_data = pattern.findall(raw_data)\n if find_data:\n hosts[find_data[0]] = domain\n else:\n hosts['None'] = domain\n time.sleep(1)\nprint(\"处理github_subdomain...\")\nfor subdomain in github_subdomain:\n url = \"https://github.com.ipaddress.com/\" + subdomain + \".github.com\"\n response = requests.get(url=url, headers=headers)\n raw_data = response.text\n pattern = re.compile(r'IP Address
  • (.*?)
')\n find_data = pattern.findall(raw_data)\n if find_data:\n hosts[find_data[0]] = subdomain + \".github.com\"\n else:\n # 目前不做处理,进行预设\n PreIP = ['185.199.108.153', '185.199.109.153', '185.199.110.153', '185.199.111.153']\n hosts[PreIP[random.randint(0, 3)]] = subdomain + \".github.com\"\n time.sleep(1)\n\nprint(\"处理githubusercontent_subdomain...\")\nglobal duplicate_data\nfor subdomain in githubusercontent_subdomain:\n url = \"https://githubusercontent.com.ipaddress.com/\" + subdomain + \".githubusercontent.com\"\n response = requests.get(url=url, headers=headers)\n raw_data = response.text\n pattern = re.compile(r'IP Address
  • (.*?)
')\n find_data = pattern.findall(raw_data)\n if find_data:\n hosts[find_data[0]] = subdomain + \".githubusercontent.com\"\n duplicate_data = find_data[0]\n else:\n hosts['None'] = subdomain + \".githubusercontent.com\"\n time.sleep(1)\n # 已知githubusercontent_subdomain为重复数据,跳出\n break\n\nErrorData = {}\nprint(\"======================Valid-Data======================\")\n\nfor ip, domain in hosts.items():\n if ip != \"None\":\n print(ip + \" \" + domain)\n else:\n # 查询异常的ip,暂无需处理\n ErrorData[ip] = domain\n# 重复数据处理\nfor duplicateData in githubusercontent_subdomain[1:]:\n print(duplicate_data + \" \" + duplicateData + \".githubusercontent.com\")\nfor duplicateData in avatars_list:\n print(duplicate_data + \" \" + duplicateData + \".githubusercontent.com\")\nprint(\"======================================================\")\n","sub_path":"src/GithubIP_Address.py","file_name":"GithubIP_Address.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"209483312","text":"# Reverse bits of a given 32 bits unsigned integer.\n# For example, given input 43261596(represented in binary as 00000010100101000001111010011100)\n# return 964176192 (represented in binary as 00111001011110000010100101000000)\n\n# 思路是借助一个初始值a=0的值,把n的最后一位跟a的最后一位进行或运算\n# 然后将a左移,n右移,这样原本n的最后一位就移到了a的倒数第二位上面,\n# 而n现在的最后一位的值,实际上是初始值的最后第二位的值\n# 这样经过一个32次的循环,就可以把n的值翻转复制到a中\n\n\nclass Solution(object):\n def reverse_bits(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n result = 0\n for i in range(32):\n result <<= 1\n result |= (n & 1)\n n >>= 1\n return result\n\nif __name__ == '__main__':\n print(Solution().reverse_bits(43261596))\n","sub_path":"LeetCode/Easy/Reverse_Bits/Reverse_Bits.py","file_name":"Reverse_Bits.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"247163675","text":"class Matriz:\n\n def __init__(self, linha=10, coluna=0, valor_padrao=0):\n if coluna == 0:\n coluna = linha\n\n self._matriz = []\n\n for lin in range(linha):\n linha_da_matriz = []\n for col in range(coluna):\n linha_da_matriz.append(valor_padrao)\n self._matriz.append(linha_da_matriz)\n\n def __str__(self):\n retorno = ''\n for lin in range(self.linha):\n for col in range(self.coluna):\n if col == 0:\n retorno += str(self._matriz[lin][col])\n else:\n retorno += ' ' + str(self._matriz[lin][col])\n retorno += '\\n'\n return retorno\n\n @property\n def linha(self) -> int:\n return len(self._matriz)\n\n @property\n def coluna(self) -> int:\n return len(self._matriz[0])\n\n def set(self, linha: int, coluna: int, valor) -> None:\n self._matriz[linha][coluna] = valor\n\n def get(self, linha: int, coluna: int):\n return self._matriz[linha][coluna]\n\n def tem(self, elemento) -> bool:\n for lin in range(self.linha):\n for col in range(self.coluna):\n if self._matriz[lin][col] == elemento:\n return True\n return False\n","sub_path":"utils/matriz.py","file_name":"matriz.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"511344483","text":"\"\"\"Callbacks that apply to all pages\n\"\"\"\nfrom data import get_test_code_to_name_map\nfrom data import get_entity_label_to_id_map\n\n\ndef get_sorted_group_keys(df, group_by):\n \"\"\"Compute a sort order for the practice charts, based on the mean\n calc_value of the last 6 months\"\"\"\n df2 = df.pivot_table(index=group_by, columns=\"month\", values=\"calc_value\")\n entity_ids = df2.reindex(\n df2.fillna(0).iloc[:, -6:].mean(axis=1).sort_values(ascending=False).index,\n axis=0,\n ).index\n return list(entity_ids)\n\n\ndef get_title_fragment(numerators, denominators, result_filter):\n numerators_text = humanise_test_code_list(numerators)\n if result_filter is None or result_filter == \"all\":\n result_filter_text = None\n else:\n result_filter_text = humanise_result_filter(result_filter)\n if result_filter_text:\n numerators_text += f\" test results {result_filter_text}\"\n else:\n numerators_text += \" tests\"\n if result_filter_text and set(numerators) == set(denominators):\n fragment = f\"proportion of {numerators_text}\"\n elif not denominators or denominators == [\"raw\"]:\n fragment = numerators_text\n elif denominators == [\"per1000\"]:\n fragment = f\"{numerators_text} per 1000 patients\"\n else:\n denominators_text = humanise_test_code_list(denominators)\n fragment = f\"ratio of {numerators_text} to {denominators_text} tests\"\n return fragment\n\n\ndef initial_capital(s):\n # Note this is distinct from `capitalize` which will lowercase the other\n # characters in the string\n return s[0:1].upper() + s[1:]\n\n\ndef humanise_result_filter(result_filter):\n assert result_filter is not None and result_filter != \"all\"\n result_filter = str(result_filter)\n if result_filter == \"0\" or result_filter == \"within_range\":\n return \"within range\"\n elif result_filter == \"-1\" or result_filter == \"under_range\":\n return \"under range\"\n elif result_filter == \"1\" or result_filter == \"over_range\":\n return \"over range\"\n elif result_filter == \"error\":\n return \"with errors\"\n elif result_filter == \"2\":\n return \"with no reference range\"\n elif result_filter == \"3\":\n return \"without a numeric value\"\n elif result_filter == \"4\":\n return \"with an unknown sex\"\n elif result_filter == \"5\":\n return \"with insufficient data\"\n elif result_filter == \"6\":\n return \"where patient is underage for reference range\"\n elif result_filter == \"7\":\n return \"with an invalid reference range\"\n else:\n raise ValueError(result_filter)\n\n\ndef humanise_test_code_list(test_codes):\n if not test_codes or \"all\" in test_codes or test_codes == [\"None\"]:\n return \"all\"\n test_name_map = get_test_code_to_name_map()\n test_names = [test_name_map[code] for code in test_codes]\n return humanise_list(test_names)\n\n\ndef humanise_list(lst):\n \"\"\"\n [\"a\", \"b\", \"c\"] -> \"a, b and c\"\n \"\"\"\n assert len(lst) > 0\n if len(lst) == 1:\n return lst[0]\n head = \", \".join(lst[:-1])\n tail = lst[-1]\n return f\"{head} and {tail}\"\n\n\ndef humanise_column_name(col_name, plural=True):\n s = \"s\" if plural else \"\"\n if col_name == \"practice_id\":\n return f\"practice{s}\"\n elif col_name == \"ccg_id\":\n return f\"CCG{s}\"\n elif col_name == \"lab_id\":\n return f\"lab{s}\"\n elif col_name == \"test_code\":\n return f\"test{s}\"\n elif col_name == \"result_category\":\n return f\"result type{s}\"\n else:\n raise ValueError(col_name)\n\n\ndef toggle_entity_id_list_from_click_data(click_data, entity_ids):\n entity_label = click_data[\"points\"][0][\"y\"]\n # Hack: get the entity_id from the Y-axis label by working out the\n # labels for all entities and finding the one which matches. It ought\n # to be possible to pass the entity_id through using the `customdata`\n # property but this seems to have been broken for the last couple of\n # years. See:\n # https://community.plot.ly/t/plotly-dash-heatmap-customdata/5871\n entity_label_to_id = get_entity_label_to_id_map()\n entity_id = str(entity_label_to_id.get(entity_label, None))\n if entity_id is not None:\n if entity_id not in entity_ids:\n entity_ids.append(entity_id)\n else:\n entity_ids.remove(entity_id)\n return entity_ids\n","sub_path":"apps/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"202690229","text":"import sys\n\nimport lcm\nfrom senlcm import *\nfrom math import *\nfrom numpy import *\nimport scipy.io as sio\nimport scipy.linalg as LA\nimport time\nimport matplotlib.pyplot as plt\n#from mysaturation import mysaturation\n\neps = sys.float_info.epsilon\n\n\n\nr = 0.5\n\n\n\n\n\n\n\n\n\n\n\n\nkk = 1\n\nl0 = 0.3; l = 0.2; c0 = 500\nd11 = 1;m11 = 1; d33 = 1; m33 = 1\nk11 = -d11/m11;k21 = -d33/m33\nk31 = 1/m11;k41 = 1/(m33*l)\nA = diag( [k11,k21] )\nB = ([k31, k31] ,[-k41, k41])\nzreal = matrix([[23],[12]])\ntheta = 2*pi*0#random.rand(1,1)\nx_sur = zreal-l0*matrix([[float(cos(theta))],[float(sin(theta))]])\nxvector = zeros((2,0))\nu = matrix([ [.1], [.1] ])\nvd = matrix([ [.1], [.1] ])\nxytheta = matrix([[float(x_sur[0])],[float(x_sur[1])],[theta]])\n\n\n\n\nn = 1\nt0 = 0;\t\t\t\t\t#start time\nT_thresh = 2;\t\t\t#time point to release robot\nts = 10;\t\t\t\t#end time\ndt = 0.001; #Time step\nDt = 0.002;\t\t\t\t#visualization period\nT_leader \t= 6000;\t\t#time to start leader control\nDis_thresh \t= 2000;\t\t#distance to activate leader control\n\nk1 = 0.75; \nk2 = 0; \t\t\t\t#estimator gradient gain\nk3 = 5; #adaptive control for estimator gradient gain\nk4 = 5; \t\t\t\t#rotation gain--along the tangent direction\n\nXhatdot_max\t\t= 10; \t#maximum velocity -- estimated value \nV0_robot_max\t= 10; \t#robot velcity\nv_compensate\t= 1; #velocity compensation --- either 0 or 1, (on or off)\nfree_speed\t\t= 15; \t#leader free speed for partroling\nc_leader\t\t= 20; \t#leader gain to drive the two leader close\nc_r \t\t= 5; \t#robot gain to observed value\nU_s\t\t\t= 3; #Concentration of polutant at the source \nthreshold \t= 0.1*U_s; #threshold of concentration detection\n\nc1 = free_speed\n\n\n","sub_path":"plume/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"346901649","text":"from nltk.tree import Tree\n\nfrom config.sst import SSTCfg\nfrom my_library.dataset_readers.pre_text_cleaning import clean_dummy_text\n\n\ndef normalize_tree_file(input_path, output_path, clean_text):\n with open(input_path, 'r') as f_in, \\\n open(output_path, 'w', encoding='utf-8') as f_out:\n print(\"Reading instances from lines in file at: %s\" % input_path)\n for line in f_in.readlines():\n line = line.strip(\"\\n\")\n if not line:\n continue\n parsed_line = Tree.fromstring(line)\n\n text = ' '.join(parsed_line.leaves())\n text = clean_text(text)\n sentiment = parsed_line.label()\n if int(sentiment) == 2:\n continue\n if int(sentiment) < 2:\n label = '__label__negative'\n else:\n label = '__label__positive'\n\n f_out.write(label + '\\t' + text + '\\n')\n print('Saved to %s' % output_path)\n\n\nif __name__ == '__main__':\n normalize_tree_file(SSTCfg.train_raw_path, SSTCfg.train_path, clean_dummy_text)\n normalize_tree_file(SSTCfg.dev_raw_path, SSTCfg.dev_path, clean_dummy_text)\n normalize_tree_file(SSTCfg.test_raw_path, SSTCfg.test_path, clean_dummy_text)\n pass\n","sub_path":"my_library/dataset_readers/norm_sst.py","file_name":"norm_sst.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"144042161","text":"import os, time\nfrom subcmd import cmd2, subprocess, read_until, read_until2\nfrom send_input import send_input\nimport regions, cursor\n\nclass SelectCancel(Exception):\n pass\n\ndef select(l, prompt):\n print()\n print(prompt)\n for i, d in enumerate(l):\n print(\"%-3d: %s\"%(i,d))\n while True:\n i = input(\"Enter selection (or 'q' to quit): \")\n if i == 'q':\n raise SelectCancel\n try:\n n = int(i)\n s = l[n]\n except Exception:\n print(\"%r is not a valid selection.\"%i)\n continue\n return s\n\ndef _sort_types(s):\n \"\"\" Sort 'Mag' before 'Air' bioreactors \"\"\"\n s = s.lower()\n parts = s.split()\n am = parts[0]\n if am not in (\"mag\", \"air\"):\n return (2, am, 0, 0)\n sz = parts[1]\n date = parts[-1]\n if am.startswith(\"mag\"):\n i = 0\n elif am.startswith(\"air\"):\n i = 1\n return (i, am, int(sz), date) \n\ndef _filter(files):\n rv = []\n for f in files:\n if f[:3].lower() not in (\"mag\", \"air\"):\n continue\n rv.append(f)\n return rv\n\ndef choose_config(fp):\n return select(sorted(_filter(os.listdir(fp)), key=_sort_types), \"Select Bioreactor Type\")\n\n\ndef _findf(d,fn):\n f = None\n found = False\n for f in os.listdir(d):\n if fn in f:\n found = True\n break\n if not found or f is None:\n raise FileNotFoundError(\"Failed to find %r\"%fn)\n return f\n\n\ndef image_rio(d):\n \"\"\" Simplified image_rio function that just\n runs RIO installer and exits when done. \n Todo is to use mouseclicks/sikuli to automate\n password generation here. \n \"\"\"\n fp = os.path.join(d, _findf(d, \"install.bat\"))\n p = cmd2(fp, shell=True, stdout=subprocess.PIPE)\n read_until(p, b\"Press any key to continue . . .\")\n send_input(b\"\\r\\n\")\n\n# def image_rio(d):\n# fp = os.path.join(d, _findf(d, \"install.bat\"))\n# p = cmd2(fp, shell=True, stdout=subprocess.PIPE)\n# title = b\"Create An Encryption File.vi\"\n# reader = read_until2(p, b\"Press any key to continue . . .\")\n\n# # read text for user while waiting for encryption VI...\n# while not cursor.find_window(title):\n# time.sleep(1)\n# next(reader, None)\n\n# # run the encryption VI\n# # use hard coded wait timers\n# # to ensure everything works\n# time.sleep(10) # wait for window to open properly\n# regions.AUTH_SBRIO_PASSWORD.click()\n# time.sleep(3)\n# regions.AUTH_SBRIO_RUN.click()\n\n# while True:\n# try:\n# next(reader)\n# except StopIteration:\n# break\n# except Exception:\n# raise\n# send_input(b\"\\r\")","sub_path":"auto_hd_install/scripts/install_pbs.py","file_name":"install_pbs.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"43105857","text":"def numerical_propagator( ORBIT ):\n minStep = 0.001;\n maxstep = 1000.0;\n positionTolerance = 10.0;\n # set your tolerances\n tolerances = PO.NumericalPropagator.tolerances(positionTolerance, ORBIT, ORBIT.getType() )\n # pick your integrator\n integrator = PO.DormandPrince853Integrator(minStep, maxstep, tolerances[0], tolerances[1])\n PROP = PO.NumericalPropagator(integrator)\n # set your type\n #PROP.setOrbitType( OrbitType.CARTESIAN )\n # set the gravity provider\n PROP.addForceModel(holmesFeatherstone)\n # set the mode\n PROP.setSlaveMode()\n PROP.setInitialState( PO.SpacecraftState( ORBIT ) )\n return PROP\n","sub_path":"KerryNumPropdef.py","file_name":"KerryNumPropdef.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"493048133","text":"\"\"\"\nTests related to authenticating API requests\n\"\"\"\n\nimport mock\n\nfrom nose.tools import * # flake8: noqa\n\nfrom framework.auth import cas\nfrom website.util import api_v2_url\n\nfrom tests.base import ApiTestCase\nfrom tests.factories import ProjectFactory, UserFactory\n\nfrom api.base.settings import API_BASE\n\n\nclass TestOAuthValidation(ApiTestCase):\n \"\"\"Test that APIv2 requests can validate and respond to OAuth2 bearer tokens\"\"\"\n def setUp(self):\n super(TestOAuthValidation, self).setUp()\n self.user1 = UserFactory()\n self.user2 = UserFactory()\n\n # Test projects for which a given user DOES and DOES NOT have appropriate permissions\n self.reachable_project = ProjectFactory(title=\"Private Project User 1\", is_public=False, creator=self.user1)\n self.unreachable_project = ProjectFactory(title=\"Private Project User 2\", is_public=False, creator=self.user2)\n\n self.reachable_url = \"/{}nodes/{}/\".format(API_BASE, self.reachable_project._id)\n self.unreachable_url = \"/{}nodes/{}/\".format(API_BASE, self.unreachable_project._id) # User1 can't access this\n\n def test_missing_token_fails(self):\n res = self.app.get(self.reachable_url, auth=None, auth_type='jwt', expect_errors=True)\n assert_equal(res.status_code, 401)\n assert_equal(res.json.get(\"errors\")[0]['detail'],\n 'Authentication credentials were not provided.')\n\n @mock.patch('framework.auth.cas.CasClient.profile')\n def test_invalid_token_fails(self, mock_user_info):\n mock_user_info.return_value = cas.CasResponse(authenticated=False, user=None,\n attributes={'accessTokenScope': ['osf.full_read']})\n\n res = self.app.get(self.reachable_url, auth='invalid_token', auth_type='jwt', expect_errors=True)\n assert_equal(res.status_code, 401, msg=res.json)\n\n @mock.patch('framework.auth.cas.CasClient.profile')\n def test_valid_token_returns_unknown_user_thus_fails(self, mock_user_info):\n mock_user_info.return_value = cas.CasResponse(authenticated=True, user='fail',\n attributes={'accessTokenScope': ['osf.full_read']})\n\n res = self.app.get(self.reachable_url, auth='some_valid_token', auth_type='jwt', expect_errors=True)\n assert_equal(res.status_code, 401, msg=res.json)\n\n @mock.patch('framework.auth.cas.CasClient.profile')\n def test_valid_token_authenticates_and_has_permissions(self, mock_user_info):\n mock_user_info.return_value = cas.CasResponse(authenticated=True, user=self.user1._id,\n attributes={'accessTokenScope': ['osf.full_read']})\n\n res = self.app.get(self.reachable_url, auth='some_valid_token', auth_type='jwt')\n assert_equal(res.status_code, 200, msg=res.json)\n\n @mock.patch('framework.auth.cas.CasClient.profile')\n def test_valid_token_authenticates_but_user_lacks_object_permissions(self, mock_user_info):\n mock_user_info.return_value = cas.CasResponse(authenticated=True, user=self.user1._id,\n attributes={'accessTokenScope': ['osf.full_read']})\n\n res = self.app.get(self.unreachable_url, auth='some_valid_token', auth_type='jwt', expect_errors=True)\n assert_equal(res.status_code, 403, msg=res.json)\n\n\nclass TestOAuthScopedAccess(ApiTestCase):\n \"\"\"Verify that OAuth2 scopes restrict APIv2 access for a few sample views. These tests cover basic mechanics,\n but are not intended to be an exhaustive list of how all views respond to all scopes.\"\"\"\n def setUp(self):\n super(TestOAuthScopedAccess, self).setUp()\n self.user = UserFactory()\n self.user2 = UserFactory() # Todo move inside tests that need this\n self.project = ProjectFactory(creator=self.user)\n\n def _scoped_response(self, scopes_list, user=None):\n user = user or self.user\n return cas.CasResponse(authenticated=True, user=user._id, attributes={'accessTokenScope': scopes_list})\n\n @mock.patch('framework.auth.cas.CasClient.profile')\n def test_user_read_scope_can_read_user_view(self, mock_user_info):\n mock_user_info.return_value = self._scoped_response(['osf.users.all_read'])\n url = api_v2_url('users/me/', base_route='/', base_prefix='v2/')\n res = self.app.get(url, auth='some_valid_token', auth_type='jwt', expect_errors=True)\n assert_equal(res.status_code, 200)\n\n @mock.patch('framework.auth.cas.CasClient.profile')\n def test_user_read_scope_cant_write_user_view(self, mock_user_info):\n mock_user_info.return_value = self._scoped_response(['osf.users.all_read'])\n url = api_v2_url('users/me/', base_route='/', base_prefix='v2/')\n payload = {u'suffix': u'VIII'}\n\n res = self.app.patch_json_api(url, params=payload,\n auth='some_valid_token', auth_type='jwt', expect_errors=True)\n assert_equal(res.status_code, 403)\n\n @mock.patch('framework.auth.cas.CasClient.profile')\n def test_user_write_scope_implies_read_permissions_for_user_view(self, mock_user_info):\n mock_user_info.return_value = self._scoped_response(['osf.users.all_write'])\n url = api_v2_url('users/me/', base_route='/', base_prefix='v2/')\n res = self.app.get(url, auth='some_valid_token', auth_type='jwt', expect_errors=True)\n assert_equal(res.status_code, 200)\n\n @mock.patch('framework.auth.cas.CasClient.profile')\n def test_user_write_scope_can_write_user_view(self, mock_user_info):\n mock_user_info.return_value = self._scoped_response(['osf.users.all_write'])\n url = api_v2_url('users/me/', base_route='/', base_prefix='v2/')\n payload = {'data': {'type': 'users', 'id': self.user._id, 'attributes': {u'suffix': u'VIII'}}}\n\n res = self.app.patch_json_api(url, params=payload,\n auth='some_valid_token', auth_type='jwt', expect_errors=True)\n assert_equal(res.status_code, 200)\n assert_dict_contains_subset(payload['data']['attributes'],\n res.json['data']['attributes'])\n\n @mock.patch('framework.auth.cas.CasClient.profile')\n def test_node_write_scope_cant_read_user_view(self, mock_user_info):\n mock_user_info.return_value = self._scoped_response(['osf.nodes.all_write'])\n url = api_v2_url('users/me/', base_route='/', base_prefix='v2/')\n payload = {u'suffix': u'VIII'}\n\n res = self.app.get(url, params=payload, auth='some_valid_token', auth_type='jwt', expect_errors=True)\n assert_equal(res.status_code, 403)\n","sub_path":"api_tests/base/test_auth.py","file_name":"test_auth.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"333856208","text":"#\n# V-Ray For Blender\n#\n# http://chaosgroup.com\n#\n# Author: Andrei Izrantcev\n# E-Mail: andrei.izrantcev@chaosgroup.com\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# All Rights Reserved. V-Ray(R) is a registered trademark of Chaos Software.\n#\n\nimport bpy\nimport mathutils\n\nimport _vray_for_blender\n\nfrom vb30.lib import ExportUtils, LibUtils\nfrom vb30.plugins import PLUGINS\nfrom vb30 import debug\n\nfrom .utils import *\n\n\n## ## ######## #### ## #### ######## #### ######## ######\n## ## ## ## ## ## ## ## ## ## ##\n## ## ## ## ## ## ## ## ## ##\n## ## ## ## ## ## ## ## ###### ######\n## ## ## ## ## ## ## ## ## ##\n## ## ## ## ## ## ## ## ## ## ##\n ####### ## #### ######## #### ## #### ######## ######\n\ndef GetOutputNode(ntree):\n NtreeToOutputNodeType = {\n 'VRayNodeTreeScene' : 'VRayNodeRenderChannels',\n 'VRayNodeTreeWorld' : 'VRayNodeEnvironment',\n 'VRayNodeTreeMaterial' : 'VRayNodeOutputMaterial',\n 'VRayNodeTreeObject' : 'VRayNodeObjectOutput',\n 'VRayNodeTreeLight' : 'VRayNodeTreeLight',\n }\n\n outputNodeType = NtreeToOutputNodeType.get(ntree.bl_idname)\n if not outputNodeType:\n return None\n\n return GetNodeByType(ntree, outputNodeType)\n\n\n ###### ######## ## ######## ###### ######## ####### ######## ######\n## ## ## ## ## ## ## ## ## ## ## ## ## ##\n## ## ## ## ## ## ## ## ## ## ##\n ###### ###### ## ###### ## ## ## ## ######## ######\n ## ## ## ## ## ## ## ## ## ## ##\n## ## ## ## ## ## ## ## ## ## ## ## ## ##\n ###### ######## ######## ######## ###### ## ####### ## ## ######\n\ndef WriteVRayNodeSelectObject(bus, nodetree, node):\n if not node.objectName:\n return []\n scene = bpy.context.scene\n if node.objectName not in scene.objects:\n return []\n return [scene.objects[node.objectName]]\n\n\ndef WriteVRayNodeSelectGroup(bus, nodetree, node):\n if not node.groupName:\n return []\n if node.groupName not in bpy.data.groups:\n return []\n return bpy.data.groups[node.groupName].objects\n\n\ndef WriteVRayNodeSelectNodeTree(bus, nodetree, node):\n if not node.ntree:\n return None\n\n # XXX: Finish this...\n\n return node.ntree.name\n\n\n######## ## ######## ## ## ######## ######## ######## ####### ######## ## ######## ###### ########\n## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##\n## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ##\n######## ## ###### ## ## ## ## ## ###### ######## ## ## ######## ## ###### ## ##\n## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ##\n## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##\n######## ######## ######## ## ## ######## ######## ## ## ####### ######## ###### ######## ###### ##\n\ndef WriteVRayNodeBlenderOutputGeometry(bus, nodetree, node):\n scene = bus['scene']\n ob = bus['node']['object']\n o = bus['output']\n\n VRayScene = scene.vray\n VRayExporter = VRayScene.Exporter\n\n meshName = bus['node']['geometry']\n\n if not VRayExporter.auto_meshes:\n return meshName\n\n if meshName not in bus['cache']['mesh']:\n bus['cache']['mesh'].add(meshName)\n\n propGroup = node.GeomStaticMesh if node else ob.data.vray.GeomStaticMesh\n dynamic_geometry = propGroup.dynamic_geometry\n\n if bus['engine'] == 'VRAY_RENDER_RT' and VRayScene.RTEngine.use_opencl == '4':\n setattr(propGroup, 'dynamic_geometry', True)\n\n try:\n _vray_for_blender.exportMesh(\n bpy.context.as_pointer(), # Context\n ob.as_pointer(), # Object\n meshName, # Result plugin name\n propGroup, # PropertyGroup\n o.fileManager.getFileByPluginType('GEOMETRY') # Output file\n )\n except Exception as e:\n debug.ExceptionInfo(e)\n debug.Debug(\"Error exporting geometry for object '%s'\" % ob.name, msgType='ERROR')\n finally:\n meshName = None\n\n if bus['engine'] == 'VRAY_RENDER_RT' and VRayScene.RTEngine.use_opencl == '4':\n setattr(propGroup, 'dynamic_geometry', dynamic_geometry)\n\n return meshName\n\n\ndef WriteVRayNodeBlenderOutputMaterial(bus, nodetree, node):\n scene = bus['scene']\n ob = bus['node']['object']\n o = bus['output']\n\n if not len(ob.material_slots):\n bus['node']['material'] = bus['defaults']['material']\n return bus['node']['material']\n\n VRayScene = scene.vray\n\n VRayExporter = VRayScene.Exporter\n SettingsOptions = VRayScene.SettingsOptions\n\n # Multi-material name\n mtl_name = LibUtils.GetObjectName(ob, prefix='OBMA')\n\n # Collecting and exporting object materials\n mtls_list = []\n ids_list = []\n ma_id = 0\n\n for slot in ob.material_slots:\n if not slot.material:\n continue\n\n ma = slot.material\n\n if not ma.vray.ntree:\n continue\n\n nodeMaterial = WriteVRayMaterialNodeTree(bus, ma.vray.ntree)\n\n ma_id += 1\n mtls_list.append(nodeMaterial)\n ids_list.append(str(ma_id))\n\n # No materials assigned - use default material\n if len(mtls_list) == 0:\n bus['node']['material'] = bus['defaults']['material']\n\n # Only one material - no need for Multi-material\n elif len(mtls_list) == 1:\n bus['node']['material'] = mtls_list[0]\n\n # Several materials assigned - use Mutli-material\n else:\n bus['node']['material'] = mtl_name\n\n o.set('MATERIAL', 'MtlMulti', mtl_name)\n o.writeHeader()\n o.writeAttibute('mtls_list', \"List(%s)\" % ','.join(mtls_list))\n o.writeAttibute('ids_list', \"ListInt(%s)\" % ','.join(ids_list))\n if node:\n id_generator = WriteConnectedNode(bus, nodetree, node.inputs[\"ID Generator\"])\n o.writeAttibute('wrap_id', node.wrap_id)\n o.writeAttibute('mtlid_gen_float', id_generator)\n o.writeFooter()\n\n return bus['node']['material']\n\n\n## ### ## ## ######## ######## ######## ########\n## ## ## ## ## ## ## ## ## ## ##\n## ## ## #### ## ## ## ## ## ##\n## ## ## ## ###### ######## ###### ## ##\n## ######### ## ## ## ## ## ## ##\n## ## ## ## ## ## ## ## ## ##\n######## ## ## ## ######## ## ## ######## ########\n\ndef WriteVRayNodeTexLayered(bus, nodetree, node):\n scene = bus['scene']\n o = bus['output']\n\n pluginName = LibUtils.CleanString(\"nt%sn%s\" % (nodetree.name, node.name))\n\n textures = []\n blend_modes = []\n\n for inputSocket in node.inputs:\n if not inputSocket.is_linked:\n continue\n\n tex = WriteConnectedNode(bus, nodetree, inputSocket)\n\n # XXX: For some reason TexLayered doesn't like ::out_smth\n semiPos = tex.find(\"::\")\n if semiPos != -1:\n tex = tex[:semiPos]\n\n textures.append(tex)\n blend_modes.append(inputSocket.value)\n\n alpha = WriteConnectedNode(bus, nodetree, node.inputs['Alpha'])\n alpha_mult = WriteConnectedNode(bus, nodetree, node.inputs['Alpha Mult'])\n alpha_offset = WriteConnectedNode(bus, nodetree, node.inputs['Alpha Offset'])\n nouvw_color = WriteConnectedNode(bus, nodetree, node.inputs['No UV Color'])\n color_mult = WriteConnectedNode(bus, nodetree, node.inputs['Color Mult'])\n color_offset = WriteConnectedNode(bus, nodetree, node.inputs['Color Offset'])\n\n o.set('TEXTURE', 'TexLayered', pluginName)\n o.writeHeader()\n o.writeAttibute('textures', \"List(%s)\" % ','.join(reversed(textures)))\n o.writeAttibute('blend_modes', \"ListInt(%s)\" % ','.join(reversed(blend_modes)))\n o.writeAttibute('alpha_from_intensity', node.alpha_from_intensity)\n o.writeAttibute('invert', node.invert)\n o.writeAttibute('invert_alpha', node.invert_alpha)\n o.writeAttibute('alpha', alpha)\n o.writeAttibute('alpha_mult', alpha_mult)\n o.writeAttibute('alpha_offset', alpha_offset)\n o.writeAttibute('nouvw_color', nouvw_color)\n o.writeAttibute('color_mult', color_mult)\n o.writeAttibute('color_offset', color_offset)\n o.writeFooter()\n\n return pluginName\n\n\ndef WriteVRayNodeBRDFLayered(bus, nodetree, node):\n scene = bus['scene']\n o = bus['output']\n\n pluginName = LibUtils.CleanString(\"nt%sn%s\" % (nodetree.name, node.name))\n\n brdfs = []\n weights = []\n\n transparency = WriteConnectedNode(bus, nodetree, node.inputs[\"Transparency\"])\n\n for i in range(int(len(node.inputs) / 2)):\n layer = i+1\n brdfSocket = \"BRDF %i\" % layer\n weightSocket = \"Weight %i\" % layer\n\n if not node.inputs[brdfSocket].is_linked:\n continue\n\n brdfs.append(WriteConnectedNode(bus, nodetree, node.inputs[brdfSocket]))\n\n if node.inputs[weightSocket].is_linked:\n weights.append(WriteConnectedNode(bus, nodetree, node.inputs[weightSocket]))\n else:\n weightParam = \"%sW%sI%i\"%(pluginName, brdfs[i], i)\n\n weightColor = mathutils.Color([node.inputs[weightSocket].value]*3)\n\n o.set('TEXTURE', 'TexAColor', weightParam)\n o.writeHeader()\n o.writeAttibute('texture', weightColor)\n o.writeFooter()\n\n weights.append(weightParam)\n\n o.set('BRDF', 'BRDFLayered', pluginName)\n o.writeHeader()\n o.writeAttibute('brdfs', \"List(%s)\" % ','.join(brdfs))\n o.writeAttibute('weights', \"List(%s)\" % ','.join(weights))\n o.writeAttibute('additive_mode', node.additive_mode)\n o.writeAttibute('transparency_tex', transparency)\n o.writeFooter()\n\n return pluginName\n\n\n######## ## ## ######## ####### ######## ########\n## ## ## ## ## ## ## ## ## ##\n## ## ## ## ## ## ## ## ## ##\n###### ### ######## ## ## ######## ##\n## ## ## ## ## ## ## ## ##\n## ## ## ## ## ## ## ## ##\n######## ## ## ## ####### ## ## ##\n\ndef WriteConnectedNode(bus, nodetree, nodeSocket, linkedOnly=False):\n # Debug(\"Processing socket: %s [%s]\" % (nodeSocket.name, nodeSocket.vray_attr))\n\n if not nodeSocket.is_linked:\n if linkedOnly:\n return None\n else:\n if hasattr(nodeSocket, 'value'):\n return nodeSocket.value\n return None\n\n connectedNode = GetConnectedNode(nodetree, nodeSocket)\n connectedSocket = GetConnectedSocket(nodetree, nodeSocket)\n if connectedNode:\n vrayPlugin = WriteNode(bus, nodetree, connectedNode, linkedOnly=linkedOnly)\n\n if connectedSocket.vray_attr and connectedSocket.vray_attr not in {'NONE'}:\n # XXX: use as a workaround\n # TODO: get plugin desc and check if the attr is output,\n # but skip uvwgen anyway.\n #\n if connectedSocket.vray_attr not in {'uvwgen', 'bitmap'}:\n vrayPlugin = \"%s::%s\" % (vrayPlugin, connectedSocket.vray_attr)\n\n if connectedNode.bl_idname == 'VRayNodeTexMayaFluid':\n vrayPlugin = vrayPlugin.replace(\"::out_flame\", \"@Flame\")\n vrayPlugin = vrayPlugin.replace(\"::out_density\", \"@Density\")\n vrayPlugin = vrayPlugin.replace(\"::out_fuel\", \"@Fuel\")\n\n return vrayPlugin\n\n return None\n\n\ndef WriteNode(bus, nodetree, node, linkedOnly=False):\n # Debug(\"Processing node: %s...\" % node.name)\n\n # Write some nodes in a special way\n if node.bl_idname == 'VRayNodeBRDFLayered':\n return WriteVRayNodeBRDFLayered(bus, nodetree, node)\n elif node.bl_idname == 'VRayNodeTexLayered':\n return WriteVRayNodeTexLayered(bus, nodetree, node)\n elif node.bl_idname == 'VRayNodeSelectObject':\n return WriteVRayNodeSelectObject(bus, nodetree, node)\n elif node.bl_idname == 'VRayNodeSelectGroup':\n return WriteVRayNodeSelectGroup(bus, nodetree, node)\n elif node.bl_idname == 'VRayNodeSelectNodeTree':\n return WriteVRayNodeSelectNodeTree(bus, nodetree, node)\n elif node.bl_idname == 'VRayNodeBlenderOutputGeometry':\n return WriteVRayNodeBlenderOutputGeometry(bus, nodetree, node)\n elif node.bl_idname == 'VRayNodeBlenderOutputMaterial':\n return WriteVRayNodeBlenderOutputMaterial(bus, nodetree, node)\n elif node.bl_idname == 'VRayNodeTransform':\n return node.getTransform()\n elif node.bl_idname == 'VRayNodeMatrix':\n return node.getMatrix()\n elif node.bl_idname == 'VRayNodeVector':\n return node.getVector()\n\n pluginName = LibUtils.CleanString(\"NT%sN%s\" % (nodetree.name, node.name))\n if pluginName in bus['cache']['plugins']:\n return pluginName\n bus['cache']['plugins'].add(pluginName)\n\n vrayType = node.vray_type\n vrayPlugin = node.vray_plugin\n\n if vrayType == 'NONE' or vrayPlugin == 'NONE':\n return None\n\n # Debug(\"Generating plugin \\\"%s\\\" [%s, %s]\" % (pluginName, vrayType, vrayPlugin), msgType='INFO')\n\n propGroup = getattr(node, vrayPlugin)\n\n socketParams = {}\n\n for nodeSocket in node.inputs:\n vrayAttr = nodeSocket.vray_attr\n\n socketParams[vrayAttr] = WriteConnectedNode(bus, nodetree, nodeSocket)\n\n pluginModule = PLUGINS[vrayType][vrayPlugin]\n\n # XXX: Used to access 'image' pointer for BitmapBuffer\n # and 'texture' for TexGradRamp and TexRemap\n #\n bus['context']['node'] = node\n\n result = ExportUtils.WritePlugin(\n bus,\n pluginModule,\n pluginName,\n propGroup,\n socketParams\n )\n\n return result\n\n\n## ## ### ######## ######## ######## #### ### ##\n### ### ## ## ## ## ## ## ## ## ## ##\n#### #### ## ## ## ## ## ## ## ## ## ##\n## ### ## ## ## ## ###### ######## ## ## ## ##\n## ## ######### ## ## ## ## ## ######### ##\n## ## ## ## ## ## ## ## ## ## ## ##\n## ## ## ## ## ######## ## ## #### ## ## ########\n\ndef WriteVRayMaterialNodeTree(bus, ntree, force=False):\n scene = bus['scene']\n\n VRayScene = scene.vray\n SettingsOptions = VRayScene.SettingsOptions\n\n outputNode = GetNodeByType(ntree, 'VRayNodeOutputMaterial')\n if not outputNode:\n debug.Debug(\"Output node not found!\", msgType='ERROR')\n return bus['defaults']['material']\n\n # Check global material override\n #\n if 'material_override' in bus:\n if bus['material_override'] is not None and outputNode.dontOverride == False:\n return bus['material_override']\n\n # Check connection\n #\n materialSocket = outputNode.inputs['Material']\n if not materialSocket.is_linked:\n debug.Debug(\"NodeTree: %s\" % ntree.name, msgType='ERROR')\n debug.Debug(\" Node: %s\" % outputNode.name, msgType='ERROR')\n debug.Debug(\" Error: Material socket is not connected!\", msgType='ERROR')\n return bus['defaults']['material']\n\n return WriteConnectedNode(bus, ntree, materialSocket)\n","sub_path":"nodes/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":16447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"89676924","text":"from sfepy.terms.terms import *\n\n##\n# 22.08.2006, c\nclass LinearTractionTerm( Term ):\n r\"\"\"\n :Description:\n Linear traction forces (weak form), where, depending on dimension of\n 'material' argument, :math:`\\ull{\\sigma} \\cdot \\ul{n}` is\n :math:`\\bar{p} \\ull{I} \\cdot \\ul{n}` for a given scalar pressure,\n :math:`\\ul{f}` for a traction vector, and itself for a stress tensor.\n\n :Definition:\n .. math::\n \\int_{\\Gamma} \\ul{v} \\cdot \\ull{\\sigma} \\cdot \\ul{n}\n\n :Arguments:\n material : :math:`\\ull{\\sigma}`,\n virtual : :math:`\\ul{v}`\n \"\"\"\n name = 'dw_surface_ltr'\n arg_types = ('material', 'virtual')\n integration = 'surface'\n\n function = staticmethod(terms.dw_surface_ltr)\n\n def __call__( self, diff_var = None, chunk_size = None, **kwargs ):\n \"\"\"\n Should work in scalar, vector and tensor modes (tensor probably broken).\n \"\"\"\n traction, virtual = self.get_args( **kwargs )\n ap, sg = self.get_approximation(virtual)\n n_fa, n_qp, dim, n_fp = ap.get_s_data_shape( self.integral,\n self.region.name )\n if diff_var is None:\n shape = (chunk_size, 1, dim * n_fp, 1)\n else:\n raise StopIteration\n\n sd = ap.surface_data[self.region.name]\n bf = ap.get_base( sd.face_type, 0, self.integral )\n gbf = ap.get_base( sd.face_type, 0, self.integral,\n from_geometry = True )\n\n## sg.str( sys.stdout, 0 )\n## print ap.bf[sd.face_type]\n## pause()\n\n## if ap.bf[sd.face_type].shape != gbf.shape:\n## raise NotImplementedError, 'tractions on P1 edges only!'\n for out, chunk in self.char_fun( chunk_size, shape ):\n lchunk = self.char_fun.get_local_chunk()\n## print out.shape, lchunk.shape\n## print traction.shape\n status = self.function( out, bf, gbf,\n traction, sg, lchunk )\n## print out\n## print nm.sum( out )\n## pause()\n yield out, lchunk, status\n\nclass SurfaceJumpTerm(Term):\n r\"\"\"\n :Description:\n Interface jump condition.\n \n :Definition:\n .. math::\n \\int_{\\Gamma} q (p_1 - p_2 - c)\n\n :Arguments:\n material : :math:`c`,\n virtual : :math:`q`,\n state_1 : :math:`p_1`,\n state_2 : :math:`p_2`\n \"\"\"\n name = 'dw_jump'\n arg_types = ('material', 'virtual', 'state_1', 'state_2')\n integration = 'surface'\n\n function = staticmethod(terms.dw_jump)\n\n def __call__(self, diff_var=None, chunk_size=None, **kwargs):\n coef, virtual, state1, state2 = self.get_args(**kwargs)\n ap, sg = self.get_approximation(virtual)\n n_fa, n_qp, dim, n_fp = ap.get_s_data_shape(self.integral,\n self.region.name)\n if diff_var is None:\n shape, mode = (chunk_size, 1, n_fp, 1), 0\n elif diff_var == self.get_arg_name('state_1'):\n shape, mode = (chunk_size, 1, n_fp, n_fp), 1\n elif diff_var == self.get_arg_name('state_2'):\n shape, mode = (chunk_size, 1, n_fp, n_fp), 2\n else:\n raise StopIteration\n\n sd = ap.surface_data[self.region.name]\n bf = ap.get_base(sd.face_type, 0, self.integral)\n\n ap1, sg1 = self.get_approximation(state1)\n sd1 = ap1.surface_data[self.region.name]\n\n ap2, sg2 = self.get_approximation(state2)\n sd2 = ap2.surface_data[self.region.name]\n\n for out, chunk in self.char_fun( chunk_size, shape ):\n lchunk = self.char_fun.get_local_chunk()\n status = self.function(out, coef, state1(), state2(),\n bf, sg, sd1.econn, sd2.econn, lchunk, mode)\n## print out\n## print nm.sum( out )\n## pause()\n yield out, lchunk, status\n \n","sub_path":"sfepy/terms/termsSurface.py","file_name":"termsSurface.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"264896446","text":"##########################################################################\n# pySAP - Copyright (C) CEA, 2017 - 2018\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n##########################################################################\n\n\"\"\"\nGrid search method that helps launching multiple reconstructions at once.\n\"\"\"\n\n# System import\nimport sys\nimport itertools\nimport psutil\n\n# Package import\nfrom mri.numerics.utils import generate_operators\n\n# Third party import\nfrom joblib import Parallel, delayed\nimport numpy as np\n\n\ndef _default_wrapper(recons_func, **kwargs):\n \"\"\" Default wrapper to parallelize the image reconstruction.\n \"\"\"\n gradient_space = kwargs.pop(\"gradient_space\")\n gradient_op, linear_op, prox_op, cost_op = generate_operators(\n data=kwargs.pop(\"data\"),\n wavelet_name=kwargs.pop(\"wavelet_name\"),\n samples=kwargs.pop(\"samples\"),\n nb_scales=kwargs.pop(\"nb_scales\"),\n non_cartesian=kwargs.pop(\"non_cartesian\"),\n uniform_data_shape=kwargs.pop(\"uniform_data_shape\"),\n gradient_space=gradient_space)\n if gradient_space == \"analysis\":\n prox_name = \"prox_dual_op\"\n else:\n prox_name = \"prox_op\"\n for name, oper in (\n (\"gradient_op\", gradient_op),\n (\"linear_op\", linear_op),\n (prox_name, prox_op),\n (\"cost_op\", cost_op)):\n kwargs[name] = oper\n return recons_func(**kwargs),\n\n\ndef grid_search(func, param_grid, wrapper=None, n_jobs=1, verbose=0):\n \"\"\" Run `func` on the carthesian product of `param_grid`.\n\n Parameters\n ----------\n func: function\n The reconstruction function from whom to tune the hyperparameters.\n `func` return should be handle by wrapper if it's not a\n simple np.ndarray image.\n param_grid: dict or list of dictionaries\n Dictionary with parameters names (string) as keys and lists of\n parameter settings to try as values: the grids spanned by each\n dictionary in the list are explored.\n wrapper: function, (default: None)\n Handle the call of func if some pre-process or post-process\n should be done. `wrapper` has a specific API:\n `wrapper(func, **kwargs)`\n n_jobs: int (default: 1)\n The maximum number of concurrently running jobs, such as the number\n of Python worker processes when backend=multiprocessing or the\n size of the thread-pool when backend=threading. If -1 all CPUs\n are used. If 1 is given, no parallel computing code is used at all,\n which is useful for debugging. For n_jobs below -1,\n (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2,\n all CPUs but one are used.\n verbose: int (default: 0)\n The verbosity level: if non zero, progress messages are printed.\n Above 50, the output is sent to stdout. The frequency of the\n messages increases with the verbosity level. If it more than 10,\n all iterations are reported.\n\n Results\n -------\n metrics: dict\n the gridsearch results. Each key corresponds to a gridsearch parameters\n set. The values are 'params' the reconstruction parameters, 'image'\n the reconstructed image, and 'metrics' the different metrics as\n specified in the input parameters.\n \"\"\"\n # Define the default wrapper call function if necessary\n if wrapper is None:\n wrapper = _default_wrapper\n\n # Sanitize wrapper value to list type\n for key, value in param_grid.items():\n if not isinstance(value, list):\n param_grid[key] = [value]\n list_kwargs = [dict(zip(param_grid, x))\n for x in itertools.product(*param_grid.values())]\n\n # Run the reconstruction with joblib\n if verbose > 0:\n if n_jobs == -1:\n n_jobs_used = psutil.cpu_count()\n elif n_jobs == -2:\n n_jobs_used = psutil.cpu_count() - 1\n else:\n n_jobs_used = n_jobs\n print((\"Running grid_search for {0} candidates\"\n \" on {1} jobs\").format(len(list_kwargs), n_jobs_used))\n results = Parallel(n_jobs=n_jobs, verbose=verbose)(\n delayed(wrapper)(func, **kwargs)\n for kwargs in list_kwargs)\n\n # Reorganize the gridsearch outputs\n metrics = {}\n for cnt, (res, params) in enumerate(zip(results, list_kwargs)):\n params.pop(\"metrics\")\n params.pop(\"samples\")\n metrics[\"grid{0}\".format(cnt + 1)] = {\n \"params\": params,\n \"image\": res[0][0],\n \"metrics\": res[0][3]}\n\n return metrics\n","sub_path":"mri/gridsearch.py","file_name":"gridsearch.py","file_ext":"py","file_size_in_byte":4734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"530275048","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /Users/gabriel.falcao/Projetos/bolacha/bolacha/multipart.py\n# Compiled at: 2010-12-06 07:18:56\nimport types\nfrom uuid import uuid4\nfrom urllib import quote_plus, urlencode\nfrom glob import glob\nfrom os.path import basename\nfrom mimetypes import guess_type\nBOUNDARY = uuid4().hex\n\ndef is_file(obj):\n return hasattr(obj, 'read') and callable(obj.read)\n\n\ndef to_str(s, encoding='utf-8', strings_only=False, errors='strict'):\n \"\"\" took from django smart_str \"\"\"\n if strings_only and isinstance(s, (types.NoneType, int)):\n return s\n if not isinstance(s, basestring):\n try:\n return str(s)\n except UnicodeEncodeError:\n if isinstance(s, Exception):\n return (' ').join([ smart_str(arg, encoding, strings_only, errors) for arg in s\n ])\n return unicode(s).encode(encoding, errors)\n\n else:\n if isinstance(s, unicode):\n return s.encode(encoding, errors)\n else:\n if s and encoding != 'utf-8':\n return s.decode('utf-8', errors).encode(encoding, errors)\n return s\n\n\ndef expand_items(dictionary):\n \"\"\"\n Given a dict like {'key': ('value1', 'value2')} returns\n a list like [('key','value1'), ('key', 'value2')]\n \"\"\"\n items = []\n for (key, value) in dictionary.items():\n if isinstance(value, (list, tuple)):\n items.extend([ (key, item) for item in value ])\n else:\n items.append((key, value))\n\n return items\n\n\ndef encode_multipart(boundary, data):\n lines = []\n for (key, value) in expand_items(data):\n if is_file(value):\n lines.extend(encode_file(boundary, key, value))\n elif is_file(value):\n lines.extend(encode_file(boundary, key, value))\n else:\n lines.extend([\n '--' + boundary,\n 'Content-Disposition: form-data; name=\"%s\"' % to_str(key),\n '',\n to_str(value)])\n\n lines.extend([\n '--' + boundary + '--',\n ''])\n return ('\\r\\n').join(lines)\n\n\ndef guess_mime(path):\n (mime, x) = guess_type(path)\n return mime or 'application/octet-stream'\n\n\ndef encode_file(boundary, key, file):\n return [\n '--' + boundary,\n 'Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"' % (\n to_str(key), to_str(basename(file.name))),\n 'Content-Type: %s' % guess_mime(file.name),\n '',\n to_str(file.read())]","sub_path":"pycfiles/bolapy-0.0.2.tar/multipart.py","file_name":"multipart.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"614734035","text":"from flask import Flask, request\r\nimport logging\r\nimport json\r\nimport requests\r\nimport random\r\nfrom flask_ngrok import run_with_ngrok\r\napp = Flask(__name__)\r\nrun_with_ngrok(app)\r\nlogging.basicConfig(level=logging.INFO)\r\nsessionStorage = {}\r\n\r\n\r\n@app.route('/post', methods=['POST'])\r\ndef main():\r\n logging.info('Request: %r', request.json)\r\n response = {\r\n 'session': request.json['session'],\r\n 'version': request.json['version'],\r\n 'response': {\r\n 'end_session': False\r\n }\r\n }\r\n handle_dialog(response, request.json)\r\n logging.info('Response: %r', response)\r\n return json.dumps(response)\r\n\r\n\r\ndef handle_dialog(res, req):\r\n if req['session']['new']:\r\n res['response']['text'] = 'Привет! Введите запрос в формате <Переведите слово: \"слово\"> или ' \\\r\n '<Переведи слово: \"слово\"> и я верну перевод.'\r\n return\r\n if 'переведите слово:' in req['request']['original_utterance'].lower() \\\r\n or 'переведи слово:' in req['request']['original_utterance'].lower():\r\n params = {\r\n \"key\": 'trnsl.1.1.20200327T204712Z.1e49d3a0c4a100cd.bc3ab5e8db99fd7bec26e7e84092e4b5aceb054d',\r\n \"text\": req['request']['original_utterance'].split()[-1],\r\n \"lang\": 'ru-en'\r\n }\r\n response = requests.get(\"https://translate.yandex.net/api/v1.5/tr.json/translate\", params=params)\r\n res['response']['text'] = ' '.join(response.json()[\"text\"])\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"400097941","text":"import sys\n\nqueue = list()\n\n\ndef push(input):\n queue.append(input)\n\n\ndef pop():\n if (len(queue) == 0):\n print(-1)\n else:\n print(queue.pop(0))\n\n\ndef size():\n print(len(queue))\n\n\ndef empty():\n if (len(queue) == 0):\n print(1)\n else:\n print(0)\n\n\ndef front():\n if (len(queue) != 0):\n print(queue[0])\n else:\n print(-1)\n\n\ndef back():\n if (len(queue) != 0):\n print(queue[len(queue) - 1])\n else:\n print(-1)\n\n##main\nn = int(sys.stdin.readline())\nfor i in range(0, n):\n str = sys.stdin.readline().split()\n if (str[0] == \"pop\"):\n pop()\n elif (str[0] == \"size\"):\n size()\n elif (str[0] == \"back\"):\n back()\n elif (str[0] == \"empty\"):\n empty()\n elif (str[0] == \"front\"):\n front()\n elif (str[0] == \"push\"):\n push(int(str[1]))\n","sub_path":"BOJ_CPP/10845.py","file_name":"10845.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"572365022","text":"from appium import webdriver\n\ncaps = {}\ncaps[\"platformName\"] = \"android\"\ncaps[\"deviceName\"] = \"Jacky\"\ncaps[\"appPackage\"] = \"com.xueqiu.android\"\ncaps[\"appActivity\"] = \".view.WelcomeActivityAlias\"\n\ndriver = webdriver.Remote(\"http://localhost:4723/wd/hub\", caps)\ndriver.implicitly_wait(10)\nel1 = driver.find_element_by_id(\"com.xueqiu.android:id/tv_agree\")\nel1.click()\ndriver.find_element_by_id(\"com.xueqiu.android:id/tv_search\").click()\ndriver.find_element_by_id(\"com.xueqiu.android:id/search_input_text\").send_keys(\"alibaba\")\ndriver.quit()\n","sub_path":"test_appium/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"491797378","text":"import xml.etree.cElementTree as ET\nimport lxml.etree as etree\nimport numpy as np\nfrom xml.dom import minidom\nfrom itertools import cycle\n# grace doesnt work but everything else does -ALP\n\n\ndef xmlConverter(someFile, nameFile, piece_name, timeSig):\n \n timeSig = timeSig[0]\n def isAlter(alterednote):\n arrOfAlter = ['F#', 'G#', 'A#', 'C#', 'D#']\n arrOfNonAlter = ['F', 'G', 'A', 'C', 'D']\n if alterednote in arrOfAlter:\n return arrOfNonAlter[arrOfAlter.index(alterednote)]\n else:\n return False\n # =======CLASSES TO USE LATER=============\n\n class Note:\n letter = ''\n Octave = ''\n duration = ''\n typeOfNote = '' # type of note\n alter = 'not_altered' # sharp or not\n string = ''\n fret = ''\n voice = '1'\n grace = False\n position = 0\n hstart = False\n hstop = False\n pstart = False\n pstop = False\n isitslur = False\n slurAmount = 0\n\n\n\n def __init__(self, letter, Octave):\n if isAlter(letter):\n self.letter = isAlter(letter)\n self.alter = '1'\n else:\n self.letter = letter\n self.Octave = Octave\n\n def setDuration(self, duration):\n self.duration = str(duration)\n\n def setTypeOfNote(self, typeOfNote):\n self.typeOfNote = typeOfNote\n\n def isChord(self):\n return False\n\n def getType(self):\n return self.typeOfNote\n\n def setAlter(self):\n self.alter = '1'\n\n def getAlter(self):\n return self.alter\n\n def setString(self, string):\n self.string = string\n\n def setFret(self, fret):\n self.fret = str(fret)\n\n def setVoice(self, voice):\n self.voice = voice\n\n def isGrace(self):\n return self.grace\n\n def countSlurs(self):\n if self.hstart:\n self.slurAmount += 1\n if self.hstop:\n self.slurAmount += 1\n if self.pstart:\n self.slurAmount += 1\n if self.pstop:\n self.slurAmount += 1\n\n\n\n\n def whatOctave(string, fret):\n tempoctave = 0\n fret = int(fret)\n\n if string == 5:\n if fret <= 7: # indexed E = 0 and b = 7 for me -alp: kalin e teli bu\n tempoctave = 2\n else:\n tempoctave = 3\n elif string == 4: # A\n if fret <= 3:\n tempoctave = 2\n else:\n tempoctave = 3\n elif string == 3: # D\n if fret <= 9:\n tempoctave = 3\n else:\n tempoctave = 4\n elif string == 2:\n if fret <= 4:\n tempoctave = 3\n else:\n tempoctave = 4\n elif string == 1:\n if fret == 0:\n tempoctave = 3\n elif fret <= 12:\n tempoctave = 4\n else:\n tempoctave = 5\n elif string == 0:\n if fret <= 7:\n tempoctave = 4\n else:\n tempoctave = 5\n else:\n print(\"String input might be wrong\")\n # print string, 'string whattt'\n # print fret, 'fret'\n\n # print(tempoctave)\n return str(tempoctave)\n\n\n\n\n\n \n text = someFile.split()\n textarr = []\n\n\n\n # Python3 program to Split string into characters\n for t in text:\n textarr.append(list(t))\n\n numpy_array = np.array(textarr)\n transpose = numpy_array.T\n transpose_list = transpose.tolist()\n\n\n\n\n def duration(fret): # find the next occurence of a number\n dur = 0\n\n for i in range(fret, len(transpose_list)):\n if transpose_list[i][0] == \"-\" and len(\n set(transpose_list[i])) == 1: # if the first \"|\" occurs, then the first measure starts\n dur += 1\n else:\n break\n if dur > 8:\n return 8\n else:\n return dur\n\n\n durations = []\n for i in range(len(transpose_list)):\n durations.append(duration(i))\n\n notes = []\n\n\n ##function gets the name of the note that was played\n def noteFun(_string, fret):\n fret = int(fret)\n enote = [\"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\"]\n\n enote = [\"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\"]\n if fret >= 12:\n fret_use = fret - 12\n else:\n fret_use = fret\n\n switcher = { # default tuning mapping based of string.\n 0: [\"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\"],\n 1: [\"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\"],\n 2: [\"G\", \"G#\", \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\"],\n 3: [\"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\", \"C\", \"C#\"],\n 4: [\"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\"],\n 5: [\"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\"],\n }\n\n\n return switcher.get(_string)[fret_use]\n\n\n\n def isChord(fret):\n if len(set(fret)) > 2:\n return True\n else:\n return False\n\n\n def isNum(x):\n num = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"13\", \"14\"]\n return x in num\n\n\n def numToString(n):\n letters = [\"E\", \"A\", \"D\", \"G\", \"B\", \"E\"]\n return letters[n]\n\n\n score_partwise = ET.Element(\"score-partwise\", version=\"3.1\")\n part_list = ET.SubElement(score_partwise, \"part-list\")\n\n score_part = ET.SubElement(part_list, \"score-part\", id=\"P1\")\n\n part_name = ET.SubElement(score_part, \"part-name\").text = piece_name # input part name here from user\n\n part = ET.SubElement(score_partwise, \"part\", id=\"P1\")\n\n tree = ET.ElementTree(score_partwise)\n\n\n # place notes\n\n def makeNote(letter, octave):\n return Note(letter, octave)\n\n\n\n\n # function that takes one line until the '|' and sets everything for that line only, call a for loop later\n def isLetter(string):\n if string == '-':\n return False\n else:\n return True\n\n\n class Measure:\n notes = []\n repeates = 1\n measureLineLength = 0\n timeSig = \"\"\n changed = False\n\n def __init__(self):\n pass\n\n def setRepeats(self, repeats):\n self.repeates = repeats\n\n def addNotes(self, notes):\n self.notes = notes\n\n def chordType(self):\n # print self.notes\n if self.notes[0].typeOfNote == '':\n for idx, note in enumerate(self.notes):\n if note.typeOfNote != '':\n default = note.typeOfNote\n defaultDur = note.duration\n break\n for i in range(0, idx):\n self.notes[i].typeOfNote = default\n self.notes[i].duration = defaultDur\n\n for index, nt in enumerate(self.notes):\n if nt.typeOfNote == '':\n tempi = index\n beggining = index\n while(self.notes[tempi].typeOfNote == ''):\n tempi += 1\n for j in range(beggining, tempi):\n self.notes[j].typeOfNote = self.notes[tempi].typeOfNote\n self.notes[j].duration = self.notes[tempi].duration\n\n def doLastThing(self):\n for note in self.notes:\n if note.hstart or note.hstop or note.pstart or note.pstop:\n note.isitslur = True\n note.countSlurs()\n\n\n\n\n\n\n def MeasureNoteTypeHelper(note, ratio, timeSig):\n typeOfNotes = [\"16th\", \"eighth\", \"quarter\", \"half\", \"whole\"]\n total = 8\n\n if timeSig == \"4/4\":\n total = 8\n elif timeSig == \"3/4\":\n total = 6\n elif timeSig == \"3/8\":\n total = 3\n elif timeSig == \"2/4\":\n total = 4\n elif timeSig == \"2/2\":\n total = 8\n elif timeSig == \"5/4\":\n total = 10\n\n amountOfEight = float(total * ratio)\n # print float(total * ratio)\n\n if amountOfEight <= 0.65:\n note.typeOfNote = typeOfNotes[0]\n note.duration = \"1\"\n elif amountOfEight <= 1.25:\n note.typeOfNote = typeOfNotes[1]\n note.duration = \"1\"\n elif amountOfEight <= 2.5:\n note.typeOfNote = typeOfNotes[2]\n note.duration = \"2\"\n elif amountOfEight <= 5:\n note.typeOfNote = typeOfNotes[3]\n note.duration = \"4\"\n elif amountOfEight <= 7.9:\n note.typeOfNote = typeOfNotes[4]\n note.duration = \"8\"\n\n\n\n # ==The new type calculator\n def MeasureTypeCalculator(timeSig, measureList):\n for measure in measureList:\n # if position can not be assigned == 0 then leave it for later, if positions are the same,assign it later\n for idx, note in enumerate(measure.notes):\n\n notePosition = note.position\n if idx == len(measure.notes) - 1:\n NextNotePosition = measure.measureLineLength\n else:\n NextNotePosition = measure.notes[idx + 1].position\n\n\n\n if NextNotePosition - notePosition == 0:\n pass\n else:\n diff = NextNotePosition - notePosition\n ratio = float(diff) / measure.measureLineLength\n # print ratio, 'ratio ', note.fret, 'fret'\n MeasureNoteTypeHelper(note, ratio, timeSig)\n pass\n\n\n\n\n # if in fact the note itself has 0, that means its part of the chord so make\n # the note before and after part of the chord\n\n\n\n\n def noteArrayMaker(tra_list, timeSig):\n isItRepeatTime = False\n measures = [] # all the measures are gonna be stored here\n lengthOfMeasure = 0\n currentPos = 0\n measureObj = Measure()\n isitgrace = False\n\n for idx, vertLine in enumerate(tra_list):\n currentPos += 1\n lengthOfMeasure += 1\n\n # this part handles if it is a repeated measure below\n if isItRepeatTime:\n isItRepeatTime = False\n lengthOfMeasure -= 1\n elif idx == len(tra_list) - 1: # in case it is the very last character\n measureObj.measureLineLength = lengthOfMeasure\n measures.append(measureObj)\n pass\n elif tra_list[idx][0] == '|' and tra_list[idx + 1][0] == '|':\n lengthOfMeasure -= 1\n pass\n else:\n # main algo starts here before the for loop for measurement reset\n if tra_list[idx][1] == '|':\n tempListOfNotes = []\n currentPos = -1\n measures.append(measureObj)\n measureObj.measureLineLength = lengthOfMeasure\n lengthOfMeasure = -1\n\n measureObj = Measure()\n # main algo starts here\n # ntidx is whichever string it is\n for ntidx, char in enumerate(vertLine):\n # IRRELEVANT TO THE MAIN ALGO, JUST REPEATS AND STUFF\n if char == '*': # this needs to happen at first, doesnt matter later\n if tra_list[idx + 1][ntidx] == '|':\n isItRepeatTime = True\n measureObj.repeates = int(tra_list[idx + 1][0])\n\n # this is parser number or pull offs\n string = char\n if isNum(char):\n if isNum(tra_list[idx + 1][ntidx]):\n string = char + tra_list[idx + 1][ntidx]\n # print string\n tra_list[idx + 1][ntidx] = '-'\n tempNote = Note(noteFun(ntidx, string), whatOctave(ntidx, string))\n tempNote.setString(ntidx)\n tempNote.setFret(string)\n tempNote.position = currentPos\n \n # == THESE ARE FOR PULL AND HAMMER ENDING ==\n if tra_list[idx - 1][ntidx] == 'h':\n tempNote.hstop = True\n elif tra_list[idx - 1][ntidx] == 'p':\n tempNote.pstop = True\n # == END OF PULL AND HAMMER ENDS\n tempListOfNotes.append(tempNote)\n measureObj.notes = tempListOfNotes\n\n # == THESE ARE FOR HAMMER AND PULL BEGINNING DETECTION ==\n elif char == 'h':\n for note in reversed(measureObj.notes):\n if note.string == ntidx:\n note.hstart = True\n break\n elif char == 'p':\n for note in reversed(measureObj.notes):\n if note.string == ntidx:\n note.pstart = True\n break\n \n # == ENDING FOR HAMMER AND PULL BEGINNING DETECTION ==\n else:\n pass\n MeasureTypeCalculator(timeSig, measures)\n\n\n measures.pop(0) # stupid algo makes an empty measure so have to do this\n for meas in measures:\n meas.chordType()\n meas.doLastThing()\n meas.timeSig = timeSig\n return measures\n\n \n\n def changeMeasureTimeSig(measures, measureNumb, timeSig):\n measureToBeChanged = measures[measureNumb - 1]\n tempMeasureList = [measureToBeChanged]\n MeasureTypeCalculator(timeSig, measures)\n measureToBeChanged.changed = True\n\n def startProgram(arr):\n\n m = 1\n for meas in arr:\n repeat = False\n s = 1\n measure = ET.SubElement(part, \"measure\", number=str(m)) # place a measure\n if meas.repeates > 1:\n repeat = True\n barline = ET.SubElement(measure, \"barline\", location=\"left\")\n ET.SubElement(barline, \"bar-style\").text = \"heavy-light\"\n ET.SubElement(barline, \"repeat\", direction=\"forward\")\n direction = ET.SubElement(measure, \"direction\", placement=\"above\")\n directiontype = ET.SubElement(direction, \"direction-type\")\n ET.SubElement(directiontype, \"words\").text = \"Repeat \" + str(meas.repeates) + \" Times\"\n if m == 1:\n attributes = ET.SubElement(measure, \"attributes\")\n divisions = ET.SubElement(attributes, \"divisions\").text = str(2)\n key = ET.SubElement(attributes, \"key\")\n fifths = ET.SubElement(key, \"fifths\").text = str(0)\n t = ET.SubElement(attributes, \"time\")\n # print meas.timeSig\n _beats = ET.SubElement(t, \"beats\").text = meas.timeSig[0]\n beats_type = ET.SubElement(t, \"beats_type\").text = meas.timeSig[2]\n clef = ET.SubElement(attributes, \"clef\")\n sign = ET.SubElement(clef, \"sign\").text = \"TAB\"\n line = ET.SubElement(clef, \"line\").text = str(5)\n staff_details = ET.SubElement(attributes, \"staff-details\")\n staff_lines = ET.SubElement(staff_details, \"staff-lines\").text = \"6\"\n for i in range(6):\n staff_tuning_line = ET.SubElement(staff_details, \"staff-tuning\", line=\"{}\".format((i + 1)))\n tuning_step = ET.SubElement(staff_tuning_line, \"tuning-step\").text = numToString(i)\n switcher = { # default tuning mapping based of string.\n 0: \"2\",\n 1: \"2\",\n 2: \"3\",\n 3: \"3\",\n 4: \"3\",\n 5: \"4\",\n }\n tuning_octave = ET.SubElement(staff_tuning_line, \"tuning-octave\").text = switcher.get(i)\n m += 1\n for idx, noteObject in enumerate(meas.notes):\n\n\n note = ET.SubElement(measure, \"note\")\n # print noteObject.position, 'curr pos'\n # if noteObject.grace == True:\n # ET.SubElement(note, \"grace\")\n if noteObject.position == meas.notes[idx - 1].position:\n if len(meas.notes) != 1 and idx != 0:\n chord = ET.SubElement(note, \"chord\")\n\n pitch = ET.SubElement(note, \"pitch\")\n step = ET.SubElement(pitch, \"step\").text = noteObject.letter\n if noteObject.alter != 'not_altered':\n alter = ET.SubElement(pitch, \"alter\").text = noteObject.alter\n octave = ET.SubElement(pitch, \"octave\").text = noteObject.Octave\n ET.SubElement(note, \"duration\").text = noteObject.duration\n voice = ET.SubElement(note, \"voice\").text = noteObject.voice\n type = ET.SubElement(note, \"type\").text = noteObject.typeOfNote\n notations = ET.SubElement(note, \"notations\")\n technical = ET.SubElement(notations, \"technical\")\n\n\n if noteObject.hstop:\n hammeroff = ET.SubElement(technical, \"hammer-on\", number=str(s), type=\"stop\")\n if noteObject.pstop:\n hammeroff = ET.SubElement(technical, \"pull-off\", number=str(s), type=\"stop\")\n if noteObject.hstart:\n hammeron = ET.SubElement(technical, \"hammer-on\", number=str(s), type=\"start\").text = \"H\"\n if noteObject.pstart:\n hammeron = ET.SubElement(technical, \"pull-off\", number=str(s), type=\"start\").text = \"P\"\n\n\n string = ET.SubElement(technical, \"string\").text = str(int(noteObject.string) + 1)\n # print(noteObject.fret, 'fret is this one')\n fret = ET.SubElement(technical, \"fret\").text = str(noteObject.fret)\n\n if noteObject.slurAmount == 1 and (noteObject.hstart or noteObject.pstart):\n slurstart = ET.SubElement(notations, \"slur\", number=str(s), placement=\"above\", type=\"start\")\n\n if noteObject.slurAmount == 1 and (noteObject.hstop or noteObject.pstop):\n slurstop = ET.SubElement(notations, \"slur\", number=str(s), type=\"stop\")\n s += 1\n\n if repeat == True:\n barline = ET.SubElement(measure, \"barline\", location=\"right\")\n ET.SubElement(barline, \"bar-style\").text = \"light-heavy\"\n ET.SubElement(barline, \"repeat\", direction=\"backward\")\n \n\n\n\n\n\n\n startProgram(noteArrayMaker(transpose_list, timeSig))\n\n\n\n xmlstr = minidom.parseString(ET.tostring(score_partwise)).toprettyxml(indent=\" \")\n\n tree.write(nameFile)\n\n with open(nameFile, \"w\") as f:\n f.write(xmlstr)\n","sub_path":"Tabs2XML/conversionEngine-Mega-Boi.py","file_name":"conversionEngine-Mega-Boi.py","file_ext":"py","file_size_in_byte":19351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"448207022","text":"### API stuff\nimport gutils.apis.google as gc\n\n### general stuff\nimport re\nimport pdb\nimport json\n\n### email stuff:\nimport mimetypes\nimport base64\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email.utils import formataddr\nfrom apiclient import errors\nfrom apiclient.errors import HttpError\nimport httplib2\n\n\nclass MIMEemail(object):\n \"\"\"\n InsightEmail takes all of the pieces of an email (text, tags, attachments, etc) and returns\n a MIME message that can be sent through the google API\n \"\"\"\n\n def __init__(self,html=None,text=None,attachments=None,\n send_to=None,send_cc=None,send_bcc=None,send_from=None,subject=None,\n verbose=True,api_user=None,email_tag_dict={}):\n\n self.verbose = verbose\n\n if type(send_from) == tuple:\n if len(send_from) == 2:\n ## can continue\n if self.verbose:\n print(\"send_from formatted correctly.\")\n else:\n print(\"send_from is not formatted correctly. needs to be a tuple: ('name','email@address.com')\")\n return\n\n self.components = {'html': html,\n 'text': text,\n 'attachments': attachments,\n 'To': send_to,\n 'Bcc': send_bcc,\n 'Cc': send_cc,\n 'From': send_from,\n 'Subject': subject}\n\n self.email_tag_dict = email_tag_dict\n\n self.api_user = api_user\n self.complete_message = None\n self.message = None\n\n return\n\n def build_email(self):\n self.construct_message()\n self.set_text()\n self.set_html()\n self.set_from()\n self.set_subject()\n\n self.set_general('To')\n self.set_general('Cc')\n self.set_general('Bcc')\n\n self.add_attachments()\n return\n\n def return_email(self):\n return self.message\n\n def add_attachments(self):\n \"\"\" add an attachment to the message \"\"\"\n if self.message is None:\n self.construct_message()\n\n return\n\n def set_tags(self,email_tag_dict={}):\n \"\"\" set or reset the formatting tags or their fill values for this email \"\"\"\n self.email_tag_dict = email_tag_dict\n\n def __fill_tags(self,text_component):\n \"\"\" make sure that tags in an email text / subject / etc are filled \"\"\"\n ## formatting tags are the odd elements of a string split on { and }.\n tags_accounted_for = True\n tags = re.split(\"{|}\", text_component)[1::2]\n for tag in tags:\n if tag not in self.email_tag_dict.keys():\n print(\"{%s} is undefined in email_tag_dict\"%tag)\n tags_accounted_for = False\n\n if tags_accounted_for:\n return (True, text_component.format(**self.email_tag_dict))\n else:\n print(\"Some tags cannot be encoded! use .set_tags to fix the missing tags or update code to send correct email_tag_dict.\")\n return (False, '')\n\n def set_text(self):\n \"\"\" add text to the message \"\"\"\n\n if self.message is None:\n self.construct_message()\n\n if self.components['text'] is not None:\n text = self.__fill_tags(self.components['text'])\n if text[0] is False:\n return False\n self.message.attach(MIMEText(text[1],'text'))\n else:\n if self.verbose: print(\"No text to add!\")\n return True\n\n def set_html(self):\n \"\"\" add html to the message \"\"\"\n if self.message is None:\n self.construct_message()\n\n if self.components['html'] is not None:\n text = self.__fill_tags(self.components['html'])\n if text[0] is False:\n return False\n self.message.attach(MIMEText(text[1],'html'))\n else:\n print(\"No html to add!\")\n return True\n\n def set_subject(self):\n \"\"\" add subject to the message \"\"\"\n \"\"\" add html to the message \"\"\"\n if self.message is None:\n self.construct_message()\n\n if self.components['html'] is not None:\n text = self.__fill_tags(self.components['Subject'])\n if text[0] is False:\n return False\n self.message['Subject'] = text[1]\n else:\n print(\"No html to add!\")\n return True\n\n def set_to(self):\n \"\"\" set the message recipient(s) \"\"\"\n if self.message is None:\n self.construct_message()\n\n if self.components['To'] is not None:\n self.message['To'] = self.components['To']\n else:\n print(\"self.components['To'] is not set!\")\n return\n\n def set_general(self,tag):\n \"\"\" set the message recipient(s) \"\"\"\n if self.message is None:\n self.construct_message()\n\n if self.components[tag] is not None:\n self.message[tag] = self.components[tag]\n else:\n print(\"self.components['%s'] is not set!\"%(tag))\n return\n\n def set_from(self):\n if self.message is None:\n self.construct_message()\n\n if self.components['From'] is not None:\n self.message['From'] = formataddr(self.components['From'])\n else:\n print(\"self.components['From'] is not set or set improperly. Needs to be a tuple: ('name','email@')\")\n return\n\n def construct_message(self):\n \"\"\" build an initial message framework \"\"\"\n self.message = MIMEMultipart('alternative')\n return\n\n def __authorize_credentials(self,api_user=None):\n \"\"\" connect to the gmail API \"\"\"\n if api_user is not None:\n self.api_user = user\n\n self.gc = gc.handle_oauth2.CredentialManager(username=self.api_user)\n\n\n if self.api_user is not None:\n return True\n return False\n\n def draft_message(self):\n \"\"\"\n put a message into a drafts folder\n returns the return message from the google API\n \"\"\"\n if self.__message_complete() and self.__authorize_credentials():\n service = self.gc.get_service(api='gmail',scope='draft')\n #self.api_response = service.users().drafts().create(userId='me', body={'message': self.complete_message}).execute()\n try:\n self.api_response = service.users().drafts().create(userId='me', body={'message': self.complete_message}).execute()\n self.api_response['status'] = 'drafted'\n except HttpError as err:\n #print(json.load(err.content))\n errd = json.loads(err.content.decode(encoding='UTF-8'))\n #print(errd)\n self.api_response = {'status': 'error', 'code': errd['error']['code'], 'message': errd['error']['message']}\n pass\n\n # self.complete_message = None\n #except:\n # self.api_response = ('error',None)\n # print(\"Email NOT drafted, error connecting to google api service.\")\n return self.api_response\n else:\n print(\"Not drafting message, either incomplete or cannot get google connection\")\n\n def send_message(self):\n \"\"\"\n send a message directly\n returns the return message from the google API\n \"\"\"\n if self.__message_complete() and self.__authorize_credentials():\n service = self.gc.get_service(api='gmail',scope='send')\n try:\n self.api_response = ('sent',service.users().messages().send(userId='me', body=self.complete_message).execute())\n self.complete_message = None\n except:\n self.api_response = ('error',None)\n print(\"Email NOT sent, error connecting to google api service.\")\n return self.api_response\n else:\n print(\"Not sending message, either incomplete or cannot get google connection\")\n return None\n\n def __grab_headers(self,payload=None,header_arg=None,allhdr=False,ignore_case=False):\n \"\"\" grab which headers are in an email message \"\"\"\n if allhdr:\n return [x['name'] for x in payload['headers']]\n\n if ignore_case:\n return [x['value'] for x in payload['headers'] if x['name'].lower() == header_arg.lower()]\n return [x['value'] for x in payload['headers'] if x['name'] == header_arg]\n\n\n def __match_thread_subject(self,payload):\n \"\"\"\n when drafting into a thread, the Subject header must match the thread's subject\n \"\"\"\n self.components['Subject'] = self.__grab_headers(payload=payload,header_arg='Subject')\n return True\n\n\n def __build_thread_headers(self,payload):\n \"\"\"\n In-reply-to is critical addition to header of a message drafted into a thread.\n\n References are critical when drafting into an existing email thread.\n rules from https://tools.ietf.org/html/rfc2822:\n 1) contain parent's \"references\" followed by parents \"message-id\".. ref = [references, message-id]\n 2) if parent has no \"references\" but has \"in-reply-to\", then ref = [in-reply-to, message-id]\n 3) if parent has no references, in-reply-to, or message-id, new draft will have NO references header\n \"\"\"\n headers = self.__grab_headers(payload=payload,allhdr=True)\n\n if 'Message-ID'.lower() in [h.lower() for h in headers]:\n in_reply_to = self.__grab_headers(payload=payload,header_arg='Message-ID',ignore_case=True)\n self.message['In-Reply-To'] = ' '.join(in_reply_to)\n else:\n print(\"No in-reply-to... something wrong with thread\")\n pdb.set_trace()\n return False\n\n references = []\n ## rule 1:\n if 'References' in headers:\n active_tag = 'References'\n references = self.__grab_headers(payload=payload,header_arg=active_tag)\n ## rule 2:\n elif 'In-Reply-To' in headers:\n active_tag = 'In-Reply-To'\n references = self.__grab_headers(payload=payload,header_arg=active_tag)\n ## rule1,2 part b\n if 'Message-ID' in headers:\n active_tag = 'Message-ID'\n newref = self.__grab_headers(payload=payload,header_arg=active_tag)\n for ref in newref:\n references.append(ref)\n\n # rule 3: just don't put a references tag into the message.\n if references is not None:\n self.message['References'] = ' '.join(references)\n return True\n\n def draft_into_thread(self,existing_thread_id = None):\n \"\"\"\n put a message into an existing thread\n must add in-reply-to and may add references tags to self.message\n \"\"\"\n fail_return = False\n if existing_thread_id is None:\n print(\"Must specify a thread!\")\n fail_return = True\n if self.__authorize_credentials() is False:\n print(\"Must specify a user for gmail API!\")\n fail_return = True\n if fail_return:\n return False\n\n cred,service = self.gc.connectGmail(user=self.api_user,gtype='full')\n thread = service.users().threads().get(userId='me', id=existing_thread_id).execute()\n\n \"\"\" payload is the most recent message in the thread \"\"\"\n payload = thread['messages'][-1]['payload']\n\n \"\"\" is the thread okay and have the proper headers been transferred to the new message? \"\"\"\n if self.__build_thread_headers(payload) and self.__match_thread_subject(payload):\n if self.__message_complete():\n self.complete_message['threadId'] = existing_thread_id\n cred,service = self.gc.connectGmail(user=self.api_user,gtype='draft')\n try:\n self.api_response = ('drafted',service.users().drafts().create(userId='me', body={'message': self.complete_message}).execute())\n self.complete_message = None\n except:\n self.api_response = ('error',None)\n print(\"Email NOT sent, error connecting to google api service.\")\n return self.api_response\n else:\n print(\"Not sending message, either incomplete or cannot get google connection\")\n return None\n\n return\n\n def __message_complete(self):\n \"\"\" test to make sure message is ready to be sent/drafted \"\"\"\n # message must have To, From, subject, and a text and/or html segment\n base_checks = {}\n\n if len(self.message.get_payload()) == 0:\n base_checks['payload'] = \"No payload!\"\n if self.message['To'] is None:\n base_checks['To'] = \"No 'To'!\"\n if self.message['From'] is None:\n base_checks['From'] = \"No 'From'!\"\n if self.message['Subject'] is None:\n base_checks['Subject'] = \"No 'Subject'!\"\n\n ## did all the checks pass?\n if len(base_checks.keys()) == 0:\n if self.verbose:\n print(\"Email meets minimum checks\")\n\n ## encode email for transmission through gmail API\n raw = base64.urlsafe_b64encode(self.message.as_bytes())\n raw = raw.decode()\n\n # assign complete_message the properly crafted email\n self.complete_message = {'raw':raw}\n return True\n else:\n print(\"Please correct these issues:\")\n print(base_checks)\n self.complete_message = None\n\n return False\n","sub_path":"general/MIMEemail.py","file_name":"MIMEemail.py","file_ext":"py","file_size_in_byte":13690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"445010600","text":"#!/usr/bin/python\n\n\"\"\"\nExplores unproduced files due to condor job errors.\n\"\"\"\nimport argparse\nimport json\nimport os\nimport glob\nfrom math import ceil\n\nfrom condor.file_utils import loadFiles\n\n\ndef main(args):\n # username = os.environ[\"USER\"]\n\n homedir = f\"/store/user/{args.username}/boostedhiggs/\"\n outdir = \"/eos/uscms/\" + homedir + args.tag + \"_\" + args.year + \"/\"\n\n # check only specific samples\n slist = args.slist.split(\",\") if args.slist is not None else None\n\n prepend = \"\"\n metadata = prepend + f\"condor/{args.tag}_{args.year}/metadata_{args.configkey}.json\"\n\n try:\n with open(metadata, \"r\") as f:\n files = json.load(f)\n except KeyError:\n raise Exception(f\"Could not open file {metadata}\")\n\n config = prepend + f\"condor/{args.tag}_{args.year}/{args.config}\"\n splitname = prepend + f\"condor/{args.tag}_{args.year}/pfnano_splitting.yaml\"\n\n print(f\"Loading files from {splitname} and {config}\")\n _, nfiles_per_job = loadFiles(config, args.configkey, args.year, args.pfnano, slist, splitname)\n\n nfailed = 0\n # submit a cluster of jobs per sample\n for sample in files.keys():\n tot_files = len(files[sample])\n\n njobs = ceil(tot_files / nfiles_per_job[sample])\n\n njobs_produced = len(glob.glob1(f\"{outdir}/{sample}/outfiles\", \"*.pkl\"))\n\n id_failed = []\n if njobs_produced != njobs: # debug which pkl file wasn't produced\n print(f\"-----> SAMPLE {sample} HAS RAN INTO ERROR, #jobs produced: {njobs_produced}, # jobs {njobs}\")\n for i, x in enumerate(range(0, njobs * nfiles_per_job[sample], nfiles_per_job[sample])):\n fname = f\"{x}-{x+nfiles_per_job[sample]}\"\n if not os.path.exists(f\"{outdir}/{sample}/outfiles/{fname}.pkl\"):\n print(f\"file {fname}.pkl wasn't produced which means job_idx {i} failed..\")\n id_failed.append(i)\n nfailed = nfailed + 1\n else:\n print(f\"Sample {sample} produced {njobs_produced} files - as expected\")\n\n if args.resubmit and len(id_failed) > 0:\n fname = f\"condor/{args.tag}_{args.year}/{sample}.jdl\"\n condor_file = open(fname)\n\n resub_name = f\"condor/{args.tag}_{args.year}/{sample}_resubmit.txt\"\n iresub = 0\n while iresub < 100:\n if not os.path.exists(resub_name):\n break\n iresub = iresub + 1\n resub_name = resub_name.replace(\".txt\", f\"_{iresub}.txt\")\n\n tfile = open(resub_name, \"w\")\n for i in id_failed:\n tfile.write(f\"{i}\\n\")\n tfile.close()\n\n if iresub == 0:\n f_fail = fname.replace(\".jdl\", \"_resubmit.jdl\")\n else:\n f_fail = fname.replace(\".jdl\", \"_resubmit_{iresub}.jdl\")\n condor_new = open(f_fail, \"w\")\n for line in condor_file:\n if \"queue\" in line:\n line = f\"queue jobid from {resub_name}\"\n condor_new.write(line)\n condor_new.close()\n condor_file.close()\n\n print(\"Submit \", f_fail)\n os.system(f\"condor_submit {f_fail}\")\n\n print(\"-----------------------------------------------------------------------------------------\")\n print(f\"Number of jobs that failed: {nfailed}\")\n\n\nif __name__ == \"__main__\":\n \"\"\"\n e.g.\n python check_jobs.py --year 2017 --username cmantill --tag Mar19 --config samples_inclusive.yaml --key mc_s_over_b\n \"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--year\", dest=\"year\", default=\"2017\", help=\"year\", type=str)\n parser.add_argument(\n \"--username\",\n dest=\"username\",\n default=\"cmantill\",\n help=\"user who submitted the jobs\",\n type=str,\n )\n parser.add_argument(\"--tag\", dest=\"tag\", default=\"Test\", help=\"process tag\", type=str)\n parser.add_argument(\n \"--config\", dest=\"config\", required=True, help=\"path to datafiles, e.g. samples_inclusive.yaml\", type=str\n )\n parser.add_argument(\"--key\", dest=\"configkey\", default=None, help=\"config key: [data, mc, ... ]\", type=str)\n parser.add_argument(\n \"--slist\",\n dest=\"slist\",\n default=None,\n help=\"give sample list separated by commas\",\n )\n parser.add_argument(\n \"--pfnano\",\n dest=\"pfnano\",\n type=str,\n default=\"v2_2\",\n help=\"pfnano version\",\n )\n parser.add_argument(\"--resubmit\", action=\"store_true\")\n parser.add_argument(\"--no-resubmit\", dest=\"resubmit\", action=\"store_false\")\n parser.set_defaults(resubmit=False)\n\n args = parser.parse_args()\n\n main(args)\n","sub_path":"check_jobs.py","file_name":"check_jobs.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"165229651","text":"import pandas as pd\nimport os \nimport sqlite3\n\n\ndata = pd.read_csv('/Users/keinobaird/Desktop/DS-Unit-3-Sprint-2-SQL-and-Databases/module1-introduction-to-sql/buddymove_holidayiq.csv')\n\nconn = sqlite3.connect('buddymove_holiday.sqlite3')\ncurs = conn.cursor()\n\n#Use df.to_sql (documentation) to insert the data into a new table review in the SQLite3 database\nquery_1a = 'DROP TABLE review'\ncurs.execute(query_1a)\ndata.index.name = 'id'\n\n#print(data.columns) \n\npd.DataFrame.to_sql(self = data, name = \"review\", con = conn, index=True)\n\n\n\nquery_1 = 'SELECT COUNT(id) FROM review;'\nprint(curs.execute(query_1).fetchone())\n\n#query_1a = 'DROP TABLE review'\n# How many users who reviewed at least 100 Nature in the category also reviewed at least 100 \n# in the Shopping category?\n\n#query_2 = 'SELECT nature,Shopping FROM review WHERE nature=100 AND Shopping=100;'\n\n# What are the average number of reviews for each category?\n'''\nquery_3a = 'SELECT AVG(Sports)from review;'\nquery_3b = 'SELECT AVG(Religious)from review;'\nquery_3c = 'SELECT AVG(Nature)from review;'\nquery_3d = 'SELECT AVG(Shopping)from review;'\nquery_3e = 'SELECT AVG(Theatre)from review;'\nquery_3f = 'SELECT AVG(Picnic)from review;'\n'''","sub_path":"module1-introduction-to-sql/part2/assigment_p2.py","file_name":"assigment_p2.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"163057716","text":"import os\nimport sys\nimport glob\nimport math\nimport importlib\nfrom config import *\nimport subprocess\nfrom tkinter import *\n\n\nclass GuiUtils(object):\n \"\"\"\n A utility class for the FileComparerGui\n \"\"\"\n\n @staticmethod\n def get_adapted_height(text, width):\n \"\"\"\n Compute the number of rows needed to display the message, given that a mono spaced font and word wrap is used\n\n :param text: the text to be displayed\n :param width: the width in characters\n :return: the height in rows\n \"\"\"\n height = 0 # number of lines\n for msg in text.split('\\n'):\n # no word wrap\n if ' ' not in msg:\n height += int(math.ceil(len(msg)/width))\n if msg == '': # blank line\n height += 1\n continue\n # word wrap\n line_length = 0\n height += 1\n # word wrap\n for word in msg.split(' '):\n line_length += len(word) + 1\n if line_length > width:\n height += 1\n line_length = len(word) + 1\n return height\n\n @staticmethod\n def get_text(category, files):\n \"\"\"\n Return an info text about the number of file comparisons and the number of failed comparisons,\n as a (string, int) tuple\n\n :param category: the edi file category\n :param files: a dictionary of the tested files and the result, error message and differing segments\n :return: An info text about the number of file comparisons and the number of failed comparisons,\n as a (string, int) tuple\n \"\"\"\n fails = len([item for item in files.values() if item[0] == 'NOK'])\n total = len(list(files.values()))\n text = '{0} Total {1}, Failed {2}'.format(category, total, fails)\n return text, fails\n\n @staticmethod\n def open_config():\n \"\"\"\n Open the config file\n \"\"\"\n config = os.path.abspath('config.py')\n if CONFIG_EDITOR:\n subprocess.Popen([CONFIG_EDITOR, config])\n elif sys.platform.startswith('linux'):\n subprocess.call([\"xdg-open\", config])\n else:\n subprocess.Popen(['notepad.exe', config]) # Windows\n\n @staticmethod\n def open_log():\n \"\"\"\n Open the log file\n \"\"\"\n log_path = os.path.join('logs', '*.txt')\n newest_log = max(glob.glob(log_path), key=os.path.getctime)\n if LOG_VIEWER:\n subprocess.Popen([LOG_VIEWER, newest_log])\n # open with platform default editor if LOG_VIEWER not set in config\n elif sys.platform.startswith('linux'):\n subprocess.call([\"xdg-open\", newest_log])\n else:\n os.startfile(newest_log) # Windows\n\n @staticmethod\n def rerun(root, info):\n \"\"\"\n Reload the config module and rerun the file comparison\n\n :param root: the current window\n \"\"\"\n import FileComparer\n importlib.reload(FileComparer)\n root.destroy()\n cmp = FileComparer.FileComparer(info['key_dir'], info['test_dir'])\n cmp.compare()\n cmp.create_gui(Tk())","sub_path":"gui/GuiUtils.py","file_name":"GuiUtils.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"286468217","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2012-2013 Hector Martin \"marcan\" \n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 or version 3.\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, MA 02110-1301 USA\n\nimport song\nimport texture_font\nimport numpy as np\nimport OpenGL.GL as gl\nimport OpenGL.GL.shaders as shaders\nfrom contextlib import nested\nfrom OpenGL.arrays import vbo\nfrom util import map_from, map_to\n\nvs_karaoke = \"\"\"\n#version 120\n\nattribute vec3 border_color;\nattribute vec3 fill_color;\nattribute vec3 outline_color;\nattribute vec3 border_color_on;\nattribute vec3 fill_color_on;\nattribute vec3 outline_color_on;\n\nattribute float glyph_time;\nattribute vec2 atom_time;\nattribute vec2 line_time;\nuniform float time;\n\nvarying vec2 v_texcoord;\nvarying vec3 v_border_color;\nvarying vec3 v_fill_color;\nvarying vec3 v_outline_color;\nvarying vec3 v_border_color_on;\nvarying vec3 v_fill_color_on;\nvarying vec3 v_outline_color_on;\nvarying float v_alpha;\nvarying float v_time;\n\nfloat fade = 0.5;\n\nfloat linstep(float min, float max, float v) {\n return clamp((v - min) / (max - min), 0.0, 1.0);\n}\n\nvoid main() {\n v_texcoord = gl_MultiTexCoord0.st;\n\n v_time = glyph_time;\n\n v_fill_color = fill_color;\n v_border_color = border_color;\n v_outline_color = outline_color;\n v_fill_color_on = fill_color_on;\n v_border_color_on = border_color_on;\n v_outline_color_on = outline_color_on;\n\n float line_start = line_time.x;\n float line_end = line_time.y;\n\n float fade_in = linstep(line_start, line_start + fade, time);\n float fade_out = linstep(line_end - fade, line_end, time);\n\n v_alpha = fade_in - fade_out;\n\n vec4 pos = gl_Vertex;\n\n float x_shift = 0.03;\n\n pos.x -= x_shift * smoothstep(0, 2, 1-fade_in);\n pos.x += x_shift * smoothstep(0, 2, fade_out);\n\n gl_Position = gl_ModelViewProjectionMatrix * pos;\n}\n\"\"\"\n\nfs_karaoke = \"\"\"\n#version 120\n\nuniform float time;\nuniform sampler2D tex;\n\nvarying vec2 v_texcoord;\nvarying vec3 v_border_color;\nvarying vec3 v_fill_color;\nvarying vec3 v_outline_color;\nvarying vec3 v_border_color_on;\nvarying vec3 v_fill_color_on;\nvarying vec3 v_outline_color_on;\nvarying float v_alpha;\nvarying float v_time;\n\n\nvoid main() {\n vec4 texel = texture2D(tex, v_texcoord.st);\n float outline = texel.b;\n float border = texel.g;\n float fill = texel.r;\n\n vec3 outline_color, border_color, fill_color;\n if (v_time < time) {\n outline_color = v_outline_color_on;\n border_color = v_border_color_on;\n fill_color = v_fill_color_on;\n } else {\n outline_color = v_outline_color;\n border_color = v_border_color;\n fill_color = v_fill_color;\n }\n\n float a = (outline + border + fill);\n\n gl_FragColor.rgb = outline_color * outline;\n gl_FragColor.rgb += border_color * border;\n gl_FragColor.rgb += fill_color * fill;\n gl_FragColor.rgb /= clamp(a, 1, 255);\n gl_FragColor.a = a * v_alpha;\n}\n\"\"\"\n\nclass GlyphInstance(object):\n def __init__(self, glyph, x, y, style):\n self.glyph = glyph\n self.x = x\n self.y = y\n self.tx1 = self.tx2 = 0\n self.t1 = self.t2 = 0\n self.colors = style.colors\n self.colors_on = style.colors_on\n\n def set_timing(self, tx1, tx2, t1, t2):\n self.tx1 = tx1\n self.tx2 = tx2\n self.t1 = t1\n self.t2 = t2\n\n def __repr__(self):\n return \"Gl(%.04f,%.04f)\" % (self.x, self.y)\n\nclass DisplayLine(object):\n def __init__(self, display):\n self.display = display\n self.glyphs = []\n self.text = u\"\"\n self.px = 0\n self.py = 0\n self.x = 0.0\n self.y = 0.0\n self._start_t = None\n self._end_t = None\n self.start = None\n self.end = None\n self.fade_in_time = self.fade_out_time = 1\n\n self.descender = 0\n self.ascender = 0\n\n self.want_row = None\n\n def copy(self):\n l = DisplayLine(self.display)\n l.text = self.text\n l.glyphs = list(self.glyphs)\n l.px = self.px\n l.py = self.py\n l.x = self.x\n l.y = self.y\n l._start_t = self._start_t\n l._end_t = self._end_t\n l.start = self.start\n l.end = self.end\n l.ascender = self.ascender\n l.descender = self.descender\n\n l.want_row = self.want_row\n return l\n\n @property\n def width(self):\n return self.px\n\n @property\n def height(self):\n return self.ascender - self.descender\n\n @property\n def lim_start(self):\n return self._start_t - self.fade_in_time\n\n @property\n def lim_end(self):\n return self._end_t + self.fade_in_time\n\n def add(self, molecule, get_atom_time, style, font, ruby_font):\n # append a space if we are joining with a previous molecule\n space_char = molecule.SPACE\n if self.glyphs:\n glyph = font.get_glyph(space_char)\n self.px += glyph.dx\n self.py += glyph.dy\n self.text += space_char\n prev_char = None\n step = 0\n\n new_ascender = font.ascender\n if ruby_font:\n new_ascender += ruby_font.ascender - ruby_font.descender\n self.ascender = max(self.ascender, new_ascender)\n self.descender = min(self.descender, font.descender)\n\n # add the molecule's atoms\n for atom in molecule.atoms:\n atom_x, atom_y = self.px, self.py\n edge_px = None\n glyphs = []\n # add the atom's base text as glyphs\n for i,c in enumerate(atom.text):\n if atom.particle_edge is not None and i == atom.particle_edge:\n edge_px = self.px\n self.text += c\n glyph = font.get_glyph(c)\n gi = GlyphInstance(glyph, self.px, self.py, style)\n if prev_char is not None:\n kx, ky = font.get_kerning(prev_char, c)\n self.px += kx\n self.py += ky\n glyphs.append(gi)\n self.px += glyph.dx\n self.py += glyph.dy\n prev_char = c\n # assign the timing map for the atom's glyphs\n # atom_x (left) -> atom start time\n # self.px (right) -> atom end time\n for glyph in glyphs:\n start, end = get_atom_time(step, atom.steps)\n if self._start_t is None:\n self._start_t = start\n else:\n self._start_t = min(start, self._start_t)\n if self._end_t is None:\n self._end_t = end\n else:\n self._end_t = max(end, self._end_t)\n glyph.set_timing(atom_x, self.px, start, end)\n self.glyphs += glyphs\n # if the atom has subatomic particles (ruby text)\n if atom.particles is not None and ruby_font:\n # ruby pen. we will adjust X later when centering over atom.\n ruby_px = 0\n ruby_py = self.display.round_coord(atom_y + font.ascender - ruby_font.descender)\n ruby_prev_char = None\n ruby_glyphs = []\n par_step = step\n # add the particles\n for particle in atom.particles:\n par_glyphs = []\n particle_x = ruby_px\n # add the characters in the particle\n for c in particle.text:\n glyph = ruby_font.get_glyph(c)\n gi = GlyphInstance(glyph, ruby_px, ruby_py, style)\n if ruby_prev_char is not None:\n kx, ky = ruby_font.get_kerning(ruby_prev_char, c)\n ruby_px += kx\n ruby_py += ky\n par_glyphs.append(gi)\n ruby_px += glyph.dx\n ruby_py += glyph.dy\n ruby_prev_char = c\n for glyph in par_glyphs:\n start, end = get_atom_time(par_step, particle.steps)\n glyph.set_timing(particle_x, ruby_px, start, end)\n par_step += particle.steps\n ruby_glyphs += par_glyphs\n # center the ruby text over the atom\n if edge_px is not None:\n atom_width = edge_px - atom_x\n else:\n atom_width = self.px - atom_x\n dx = self.display.round_coord(atom_x + (atom_width - ruby_px) / 2.0)\n for glyph in ruby_glyphs:\n glyph.tx1 += dx\n glyph.tx2 += dx\n glyph.x += dx\n self.glyphs.append(glyph)\n step += atom.steps\n\n self.start = self.lim_start\n self.end = self.lim_end\n\n def build(self):\n vbodata = []\n idxdata = []\n for i,g in enumerate(self.glyphs):\n tleft = map_to(map_from(g.x + g.glyph.left, g.tx1, g.tx2), g.t1, g.t2)\n tright = map_to(map_from(g.x + g.glyph.right, g.tx1, g.tx2), g.t1, g.t2)\n const_vbodata = list(i/255.0 for i in sum(g.colors + g.colors_on, ()))\n const_vbodata += (g.t1, g.t2, self.start, self.end)\n vbodata.append(\n [g.x + g.glyph.left, g.y + g.glyph.bot,\n g.glyph.tex_left, g.glyph.tex_bot,\n tleft] + const_vbodata)\n vbodata.append(\n [g.x + g.glyph.left, g.y + g.glyph.top,\n g.glyph.tex_left, g.glyph.tex_top,\n tleft] + const_vbodata)\n vbodata.append(\n [g.x + g.glyph.right, g.y + g.glyph.top,\n g.glyph.tex_right, g.glyph.tex_top,\n tright] + const_vbodata)\n vbodata.append(\n [g.x + g.glyph.right, g.y + g.glyph.bot,\n g.glyph.tex_right, g.glyph.tex_bot,\n tright] + const_vbodata)\n idxdata += (i*4, i*4+1, i*4+2, i*4+2, i*4+3, i*4)\n self.vbo = vbo.VBO(np.asarray(vbodata, np.float32), gl.GL_STATIC_DRAW, gl.GL_ARRAY_BUFFER)\n self.ibo = vbo.VBO(np.asarray(idxdata, np.uint16), gl.GL_STATIC_DRAW, gl.GL_ELEMENT_ARRAY_BUFFER)\n self.count = len(self.glyphs)\n\n def draw(self, renderer):\n with nested(self.vbo, self.ibo):\n gl.glPushMatrix()\n x = self.display.round_coord(self.x)\n y = self.display.round_coord(self.y)\n gl.glTranslate(x, y, 0)\n\n gl.glEnableClientState(gl.GL_VERTEX_ARRAY)\n gl.glEnableClientState(gl.GL_TEXTURE_COORD_ARRAY)\n renderer.enable_attribs()\n\n stride = 27*4\n off = 0\n gl.glVertexPointer(2, gl.GL_FLOAT, stride, self.vbo + off)\n off += 2*4\n gl.glTexCoordPointer(2, gl.GL_FLOAT, stride, self.vbo + off)\n off += 2*4\n off += renderer.attrib_pointer(\"glyph_time\", stride, off, self.vbo)\n off += renderer.attrib_pointer(\"fill_color\", stride, off, self.vbo)\n off += renderer.attrib_pointer(\"border_color\", stride, off, self.vbo)\n off += renderer.attrib_pointer(\"outline_color\", stride, off, self.vbo)\n off += renderer.attrib_pointer(\"fill_color_on\", stride, off, self.vbo)\n off += renderer.attrib_pointer(\"border_color_on\", stride, off, self.vbo)\n off += renderer.attrib_pointer(\"outline_color_on\", stride, off, self.vbo)\n off += renderer.attrib_pointer(\"atom_time\", stride, off, self.vbo)\n off += renderer.attrib_pointer(\"line_time\", stride, off, self.vbo)\n assert off == stride\n\n gl.glDrawElements(gl.GL_TRIANGLES, 6*self.count, gl.GL_UNSIGNED_SHORT, self.ibo)\n\n gl.glDisableClientState(gl.GL_VERTEX_ARRAY)\n gl.glDisableClientState(gl.GL_TEXTURE_COORD_ARRAY)\n renderer.disable_attribs()\n gl.glPopMatrix()\n\n def __unicode__(self):\n return u\"DisplayLine<[%s]>\" % self.text\n\nclass SongLayout(object):\n def __init__(self, song_obj, variant, renderer):\n self.song = song_obj\n self.variant = song_obj.variants[variant]\n self.renderer = renderer\n\n self.margin = 0.07\n self.rowspacing = 0.01\n self.wrapwidth = 1.0 - self.margin * 2\n self.pre_line = 1.0\n self.post_line = 1.0\n\n self.lines = {}\n self.fonts = {}\n\n self._merge_lines()\n self._layout_lines(self.lines[song.TagInfo.BOTTOM], False)\n self._layout_lines(self.lines[song.TagInfo.TOP], True)\n self._build_lines()\n self.renderer.atlas.upload()\n\n def _get_font(self, style, ruby=False):\n font = style.font if not ruby else style.ruby_font\n size = style.size if not ruby else style.ruby_size\n if size == 0:\n return None\n ident = (font, size, style.border_width, style.outline_width)\n if ident in self.fonts:\n return self.fonts[ident]\n else:\n fontfile = self.song.get_font_path(font)\n font = texture_font.TextureFont(self.renderer.display.width, self.renderer.atlas, fontfile, size, style)\n self.fonts[ident] = font\n return font\n\n def _merge_lines(self):\n edges = {\n song.TagInfo.TOP: [],\n song.TagInfo.BOTTOM: []\n }\n for compound in self.song.compounds:\n for tag, molecule in compound.items():\n if tag in self.variant.tags:\n tag_info = self.variant.tags[tag]\n edges[tag_info.edge].append((compound.get_atom_time, tag_info, molecule))\n\n for edge, molecules in edges.items():\n lines = []\n line = None\n for get_atom_time, tag_info, molecule in molecules:\n font = self._get_font(tag_info.style, False)\n if molecule.has_ruby:\n ruby_font = self._get_font(tag_info.style, True)\n else:\n ruby_font = None\n if molecule.break_before or line is None:\n line = DisplayLine(self.renderer.display)\n line.add(molecule, get_atom_time, tag_info.style, font, ruby_font)\n lines.append(line)\n if molecule.row is not None:\n line.want_row = molecule.row\n else:\n tmp = line.copy()\n tmp.add(molecule, get_atom_time, tag_info.style, font, ruby_font)\n if tmp.px > self.wrapwidth:\n line = DisplayLine(self.renderer.display)\n line.add(molecule, get_atom_time, tag_info.style, font, ruby_font)\n lines.append(line)\n else:\n lines[-1] = line = tmp\n if molecule.break_after:\n line = None\n\n self.lines[edge] = lines\n\n def _build_lines(self):\n for lines in self.lines.values():\n for dl in lines:\n dl.build()\n\n def _layout_lines(self, lines, top=False):\n if not lines:\n return\n rows = [[] for i in range(10)]\n lines.sort(key = lambda x: x.start)\n\n def sortrow(rowid):\n rows[rowid].sort(key = lambda x: x.start)\n\n def collides(l, rowid):\n c = []\n for l2 in rows[rowid][::-1]:\n if l.start >= l2.end:\n return c\n elif l.end <= l2.start:\n continue\n else:\n c.append(l2)\n else:\n return c\n\n def canmoveup(l, limit=1):\n if l.row >= limit:\n return False\n for l2 in collides(l, l.row + 1):\n if not canmoveup(l2, limit):\n return False\n return True\n\n def moveup(l, limit=1):\n assert l.row < limit\n for l2 in collides(l, l.row + 1):\n moveup(l2, limit)\n rows[l.row].remove(l)\n sortrow(l.row)\n l.row += 1\n assert not collides(l, l.row)\n rows[l.row].append(l)\n sortrow(l.row)\n\n def canmovetop(l):\n return True\n\n def movetop(l):\n if l.row == 0:\n # FIXME: this can cause another line to violate the\n # \"no jumping ahead\" rule. meh.\n for row in range(len(rows)):\n if collides(l, row):\n need_row = row + 1\n else:\n need_row = l.row - 1\n for l2 in collides(l, need_row):\n movetop(l2)\n rows[l.row].remove(l)\n sortrow(l.row)\n l.row = need_row\n rows[l.row].append(l)\n sortrow(l.row)\n\n if not top:\n for i, l in enumerate(lines):\n if l.want_row is not None and not collides(l, l.want_row):\n l.row = l.want_row\n rows[l.want_row].append(l)\n elif not collides(l, 1):\n l.row = 1\n rows[1].append(l)\n elif not collides(l, 0):\n l.row = 0\n rows[0].append(l)\n else:\n need_row = 2\n while collides(l, need_row):\n need_row += 1\n for want_row in (lines[i-1].row,):\n if canmoveup(rows[want_row][-1], need_row):\n moveup(rows[want_row][-1], need_row)\n l.row = want_row\n rows[want_row].append(l)\n break\n else:\n l.row = need_row\n rows[need_row].append(l)\n else:\n for i, l in enumerate(lines):\n for row in range(len(rows)):\n if not collides(l, row):\n need_row = row\n break\n if i == 0 or need_row <= (lines[i-1].row + 1):\n l.row = need_row\n rows[need_row].append(l)\n else:\n for want_row in (lines[i-1].row, lines[i-1].row + 1):\n if canmovetop(rows[want_row][-1]):\n movetop(rows[want_row][-1])\n l.row = want_row\n rows[want_row].append(l)\n break\n else:\n l.row = need_row\n rows[need_row].append(l)\n\n max_ascender = max(l.ascender for l in lines)\n min_descender = min(l.descender for l in lines)\n row_height = max_ascender - min_descender + self.rowspacing\n\n lastrow = 1 if top else -1\n max_end = 0\n prev_l = None\n for i, l in enumerate(lines):\n next_l = lines[i+1] if i < len(lines)-1 else None\n if not top:\n if l.row == 0:\n l.x = self.margin + (self.wrapwidth - l.width) # right\n elif (l.start > max_end or l.row > lastrow) and (max_end > l.end or (next_l and next_l.start < l.end)):\n l.x = self.margin # left\n else:\n l.x = self.margin + (self.wrapwidth - l.width) / 2.0 # center\n else:\n if (l.start > max_end or l.row < lastrow) and (max_end > l.end or (next_l and next_l.start < l.end)):\n l.x = self.margin # left\n elif l.row >= 1 and not (next_l and next_l.row > l.row) and (max_end > l.end or (next_l and next_l.start < l.end)):\n l.x = self.margin + (self.wrapwidth - l.width) # right\n else:\n l.x = self.margin + (self.wrapwidth - l.width) / 2.0 # center\n if max_end > l.start and prev_l:\n orig_start = l.start\n l.start = max(min(l.start, prev_l.lim_start), l.start - 5)\n if prev_l.row < l.row:\n l.start = min(orig_start, max(l.start, prev_l.start + 1.5))\n prev_in_row = rows[l.row].index(l) - 1\n if prev_in_row >= 0:\n l.start = max(l.start, rows[l.row][prev_in_row].end)\n max_end = max(max_end, l.end)\n lastrow = l.row\n if not top:\n l.y = self.margin - min_descender + row_height * l.row\n else:\n l.y = self.renderer.display.top - self.margin - max_ascender - row_height * l.row\n prev_l = l\n\n def _layout_lines_top(self, lines):\n if not lines:\n return\n\n def draw(self, t, renderer):\n for edge, lines in self.lines.items():\n for l in lines:\n if l.start <= t <= l.end:\n l.draw(renderer)\n\nclass Renderer(object):\n UNIFORMS = [\n \"tex\", \"time\"\n ]\n ATTRIBUTES = {\n \"glyph_time\": (1, gl.GL_FLOAT),\n \"atom_time\": (2, gl.GL_FLOAT),\n \"line_time\": (2, gl.GL_FLOAT),\n \"border_color\": (3, gl.GL_FLOAT),\n \"fill_color\": (3, gl.GL_FLOAT),\n \"outline_color\": (3, gl.GL_FLOAT),\n \"border_color_on\": (3, gl.GL_FLOAT),\n \"fill_color_on\": (3, gl.GL_FLOAT),\n \"outline_color_on\": (3, gl.GL_FLOAT),\n }\n TYPE_LEN = {\n gl.GL_FLOAT: 4\n }\n def __init__(self, display):\n self.display = display\n self.shader = shaders.compileProgram(\n shaders.compileShader(vs_karaoke, gl.GL_VERTEX_SHADER),\n shaders.compileShader(fs_karaoke, gl.GL_FRAGMENT_SHADER),\n )\n for i in self.UNIFORMS:\n setattr(self, \"l_\" + i, gl.glGetUniformLocation(self.shader, i))\n self.attrib_loc = {i: gl.glGetAttribLocation(self.shader, i) for i in self.ATTRIBUTES}\n self.atlas = texture_font.TextureAtlas(depth=3)\n\n def attrib_pointer(self, attrib, stride, offset, vbo):\n size, data_type = self.ATTRIBUTES[attrib]\n loc = self.attrib_loc[attrib]\n if loc >= 0:\n gl.glVertexAttribPointer(loc, size, data_type, gl.GL_FALSE, stride, vbo + offset)\n return self.TYPE_LEN[data_type] * size\n\n def enable_attribs(self):\n for i in self.attrib_loc.values():\n if i >= 0:\n gl.glEnableVertexAttribArray(i)\n\n def disable_attribs(self):\n for i in self.attrib_loc.values():\n if i >= 0:\n gl.glDisableVertexAttribArray(i)\n\n def draw(self, time, layout):\n gl.glActiveTexture(gl.GL_TEXTURE0)\n gl.glBindTexture(gl.GL_TEXTURE_2D, self.atlas.texid)\n gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)\n gl.glEnable(gl.GL_BLEND)\n with self.shader:\n gl.glUniform1i(self.l_tex, 0)\n gl.glUniform1f(self.l_time, time)\n layout.draw(time, self)\n\n def reset(self):\n self.atlas = texture_font.TextureAtlas(depth=3)\n\nif __name__ == \"__main__\":\n import sys, song, graphics\n s = song.Song(sys.argv[1])\n display = graphics.Display(1280,720)\n renderer = Renderer(display)\n layout = SongLayout(s, s.variants.keys()[-1], renderer)\n def render():\n song_time = 1\n while True:\n gl.glClearColor(0, 0.3, 0, 1)\n gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)\n gl.glLoadIdentity()\n renderer.draw(song_time, layout)\n song_time += 1/70.0\n yield None\n display.set_render_gen(render)\n display.main_loop()\n","sub_path":"layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":24365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"117021392","text":"from sys import argv\nimport matplotlib.pyplot as plt\nimport re\n\ns, chemin = argv\n\ntry:\n\tresultats = open(chemin, mode='r')\nexcept:\n\tprint(\"Erreur d'ouverture de fichier\")\n\texit()\n\ndef getDonnees(res):\n\tdonnees = []\n\tlines = res.readlines()\n\tfor l in lines:\n\t\tm = re.search('[^|[].+ : (\\d+\\.?\\d*)', l)\n\t\tif m != None :\n\t\t\tdonnees.append(m.group(1))\n\t# Conversion des chaines en int et mise dans une liste\n\treturn list(map(float, donnees))\n\ndef extraire_1_2(donnees, debut):\n\t# Extraction d'une donnee sur 2 en commencant a 'debut'\n\treturn [donnees[i] for i in range(debut, len(donnees), 2)]\n\n# Recuperation des nombres : nb tweets puis resultat\ndonnees = getDonnees(resultats)\n\nprint(donnees)\n\nnb_tweets = extraire_1_2(donnees, 0)\n#print(nb_tweets)\nres_tweets = extraire_1_2(donnees, 1)\n#print(res_tweets)\n\nplt.plot(nb_tweets, res_tweets, 'ro')\nplt.bar(nb_tweets, res_tweets, linewidth=len(nb_tweets)*0.7)\nplt.axis([0, max(nb_tweets)*1.1, 0, 100])\nplt.show()\n\nresultats.close()\n","sub_path":"src/TracerApprentissage.py","file_name":"TracerApprentissage.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"397664254","text":"import os\nimport collections\n\nimport utils\nimport config.parser\n\nCONFIG_FILE = os.path.join(utils.getUserPreferenceFolder(),\n 'config.cfg')\nSECTION_PATHS = 'PATHS'\nOPTION_DB = 'database'\nCLIPS_PATH = 'clips'\n\nDEFAULT_CONFIG = {\n SECTION_PATHS: {\n OPTION_DB: os.path.join(utils.getUserPreferenceFolder(), 'data.sql'),\n CLIPS_PATH: '/mnt/work/ProxyTaMere/__Recordings/Clips'\n }\n}\n\nDB_DESCRIPTION = collections.OrderedDict(\n (\n ('Episodes', [\n 'id INTEGER',\n 'name VARCHAR(64) NOT NULL',\n 'PRIMARY KEY(id)',\n ]),\n ('Clips', [\n 'id INTEGER',\n 'name VARCHAR(64) NOT NULL',\n 'path VARCHAR(512)',\n 'length TIME',\n 'thumbnail VARCHAR(512)',\n 'recorderId INT',\n 'rating TINYINT',\n 'gameId INT',\n 'statusId INT',\n 'PRIMARY KEY(id)',\n 'FOREIGN KEY(recorderId) REFERENCES Recorders(id)',\n 'FOREIGN KEY(gameId) REFERENCES Games(id)',\n 'FOREIGN KEY(statusId) REFERENCES Statuses(id)',\n ]),\n ('Tags', [\n 'id INTEGER',\n 'name VARCHAR(64) NOT NULL',\n 'short VARCHAR(4)',\n 'PRIMARY KEY(id)',\n ]),\n ('Recorders', [\n 'id INTEGER',\n 'name VARCHAR(64) NOT NULL',\n 'PRIMARY KEY(id)',\n ]),\n ('Statuses', [\n 'id INTEGER',\n 'name VARCHAR(64) NOT NULL',\n 'PRIMARY KEY(id)',\n ]),\n ('Games', [\n 'id INTEGER',\n 'name VARCHAR(64) NOT NULL',\n 'PRIMARY KEY(id)',\n ]),\n ('EpisodeClips', [\n 'EpisodeId INT REFERENCES Episodes(id)',\n 'ClipsId INT REFERENCES Clips(id)',\n 'CONSTRAINT id PRIMARY KEY(EpisodeId, ClipsId)',\n ]),\n ('ClipsTags', [\n 'ClipsId INT REFERENCES Clips (id)',\n 'TagsId INT REFERENCES Tags (id)',\n 'CONSTRAINT id PRIMARY KEY (ClipsId, TagsId)',\n ]),\n )\n)\n\n\ndef init_config():\n \"\"\"Initializes the configuration file.\n \"\"\"\n if os.path.isfile(CONFIG_FILE):\n return\n\n cfgdir = os.path.dirname(CONFIG_FILE)\n if not os.path.isdir(cfgdir):\n os.makedirs(cfgdir)\n open(CONFIG_FILE, 'w+').close()\n\n cfg = config.parser.CaseSensitiveParser()\n\n for section, options in DEFAULT_CONFIG.iteritems():\n\n if not cfg.has_section(section):\n cfg.add_section(section)\n\n for option, value in options.iteritems():\n\n if not cfg.has_option(section, option):\n cfg.set(section, option, value)\n\n cfg.write(CONFIG_FILE)\n","sub_path":"Asset-Manager/config/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"259609766","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"====================================\n# @Time : 2019/7/30 17:56\n# @Author : Jing\n# @FileName: 111. Minimum Depth of Binary Tree.py\n# @IDE: PyCharm\n=======================================\"\"\"\n# https://leetcode.com/problems/minimum-depth-of-binary-tree/\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def minDepth(self, root: TreeNode) -> int:\n if root is None:\n return 0\n queue = [(root, 1)]\n while queue:\n node, level = queue.pop(0)\n if node:\n if node.left is None and node.right is None:\n return level\n else:\n queue.append((node.left, level+1))\n queue.append((node.right, level+1))\n\n\n\n\n\n\n\n\n","sub_path":"BFS/111. Minimum Depth of Binary Tree.py","file_name":"111. Minimum Depth of Binary Tree.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"380714465","text":"'''\n\nDetermine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.\n\nExample 1:\n\nInput: 121\nOutput: true\nExample 2:\n\nInput: -121\nOutput: false\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\nExample 3:\n\nInput: 10\nOutput: false\nExplanation: Reads 01 from right to left. Therefore it is not a palindrome.\nFollow up:\n\nCoud you solve it without converting the integer to a string?\n'''\n\n#11508 / 11508 test cases passed. Runtime: 304 ms\n# This running time beats 58.97% of python3 submissions. May 2018\n\nclass Solution:\n def isPalindrome(self, x):\n \"\"\"\n :type x: int\n :rtype: bool\n \"\"\"\n if x==0:\n return True\n elif x<0 or x%10==0:\n return False\n x_r=0\n x_copy=x\n while x:\n if (x>=1 and x<=9):\n x_r+=x\n else:\n r=x%10\n x_r=(x_r+r)*10\n x=x//10\n if x_copy==x_r:\n return True\n else:\n return False\n\n# cpp, rewrite\n\n'''\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n if (x < 0) return false;\n int res = 0, dummy = x;\n while (x){\n res = res * 10 + x % 10;\n x /= 10;\n }\n return res == dummy;\n \n }\n};\n\n'''\n","sub_path":"0009. isPalindrome.py","file_name":"0009. isPalindrome.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"424585230","text":"import os\nimport datetime as dt\n\nqs = open(r'D:\\360MoveData\\Users\\Windows10\\Desktop\\vpn实验\\ping.txt','r')\nqs = qs.readlines() \n\n\ndata=open(r\"D:\\360MoveData\\Users\\Windows10\\Desktop\\vpn实验\\data.txt\",'w+') \nfor qs in qs:\n\ta = os.system('ping '+qs+' -w 0.1ms')\n\tif a==0:\n\t\tprint(qs.rstrip(),file=data)\n\t\t\n\n# 获取当前时间\nnow_time = dt.datetime.now().strftime('%F %T')\n \n# 输出时间\nprint('更新于:' + now_time,file=data)\n","sub_path":"python/ping工具.py","file_name":"ping工具.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"274160159","text":"from django.conf.urls import url\r\nfrom . import views\r\n\r\napp_name = 'user1'\r\n\r\nurlpatterns = [\r\n url(r'^$', views.index, name='index'),\r\n #url(r'^login/$',views.LoginView.as_view(),name='login_user'),\r\n #url(r'^register/$', views.UserFormView.as_view(),name='register'),\r\n #url(r'^logout/$', views.logoutuser,name='logout_user'),\r\n url(r'^dashboard$', views.dash_board, name='dash_board')\r\n]\r\n","sub_path":"kysite-final/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"550712637","text":"\"\"\"\nTest sheets api logic\n\nNOTE: GSheet tests being skipped, they are slow and that code is mostly frozen.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\nimport pytest\n\nimport cog.exc\nimport cog.sheets\nimport cog.util\nfrom tests.conftest import SHEET_TEST\n\n\n@pytest.fixture()\ndef fort_sheet():\n \"\"\"\n Yield fixture returns fort sheet.\n \"\"\"\n sheet = cog.util.get_config('tests', 'hudson_cattle')\n paths = cog.util.get_config('paths')\n f_sheet = cog.sheets.GSheet(sheet, paths['json'], paths['token'])\n\n yield f_sheet\n\n\n@pytest.fixture()\ndef fort_sheet_reset():\n \"\"\"\n Yield fixture returns fort sheet and cleanups after running.\n\n N.B. Test in cells cleaned in cell_ranges.\n \"\"\"\n sheet = cog.util.get_config('tests', 'hudson_cattle')\n paths = cog.util.get_config('paths')\n f_sheet = cog.sheets.GSheet(sheet, paths['json'], paths['token'])\n\n yield f_sheet\n\n # Ensure scratch cells always reset, stuck in catch22 batch_update must work\n cell_ranges = ['!B13:B14', '!F6:G6']\n n_vals = [[['Shepron'], ['TiddyMun']], [[4910, 2671]]]\n f_sheet.batch_update(cell_ranges, n_vals)\n\n\n@SHEET_TEST\ndef test_gsheet_get(fort_sheet):\n assert fort_sheet.get('!B13:B13') == [['Shepron']]\n\n\n@SHEET_TEST\ndef test_gsheet_batch_get(fort_sheet):\n assert fort_sheet.batch_get(['!B13:B13', '!F6:G6']) == [[['Shepron']], [[4910, 2671]]]\n\n\n@SHEET_TEST\ndef test_ghseet_get_with_formatting(fort_sheet):\n fmt_cells = fort_sheet.get_with_formatting('!F10:F10')\n system_colors = {'red': 0.42745098, 'blue': 0.92156863, 'green': 0.61960787}\n\n for val in fmt_cells['sheets'][0]['data'][0]['rowData'][0]['values']:\n assert val['effectiveFormat']['backgroundColor'] == system_colors\n\n\n@SHEET_TEST\ndef test_gsheet_update(fort_sheet_reset):\n fort_sheet_reset.update('!B13:B13', [['NotShepron']])\n assert fort_sheet_reset.get('!B13:B13') == [['NotShepron']]\n\n\n@SHEET_TEST\ndef test_gsheet_batch_update(fort_sheet_reset):\n cell_ranges = ['!B13:B14', '!F6:G6']\n n_vals = [[['NotShepron'], ['Grimbald']], [[2222, 3333]]]\n fort_sheet_reset.batch_update(cell_ranges, n_vals)\n\n assert fort_sheet_reset.batch_get(cell_ranges) == n_vals\n\n\ndef test_colcnt__init__():\n col1 = cog.sheets.ColCnt('A')\n assert str(col1) == 'A'\n col2 = cog.sheets.ColCnt('Z')\n assert str(col2) == 'Z'\n\n\ndef test_colcnt__repr__():\n col1 = cog.sheets.ColCnt('A')\n assert repr(col1) == 'ColCnt(char=65, low_bound=64, high_bound=91)'\n\n\ndef test_colcnt_next():\n col1 = cog.sheets.ColCnt('A')\n col1.next()\n assert str(col1) == 'B'\n\n col2 = cog.sheets.ColCnt('Z')\n with pytest.raises(cog.exc.ColOverflow):\n col2.next()\n assert str(col2) == 'A'\n\n\ndef test_colcnt_prev():\n col1 = cog.sheets.ColCnt('B')\n col1.prev()\n assert str(col1) == 'A'\n\n with pytest.raises(cog.exc.ColOverflow):\n col1.prev()\n assert str(col1) == 'Z'\n\n\ndef test_colcnt_reset():\n col1 = cog.sheets.ColCnt('Z')\n col1.reset()\n assert str(col1) == 'A'\n\n col2 = cog.sheets.ColCnt('A')\n col2.reset(False)\n assert str(col2) == 'Z'\n\n\ndef test_column__init__():\n column = cog.sheets.Column('A')\n assert str(column) == 'A'\n assert str(column.counters[0]) == 'A'\n\n column = cog.sheets.Column('BA')\n assert str(column) == 'BA'\n assert str(column.counters[0]) == 'A'\n assert str(column.counters[1]) == 'B'\n\n\ndef test_column__repr__():\n col1 = cog.sheets.Column('AA')\n assert repr(col1) == \"Column(counters=[ColCnt(char=65, low_bound=64, high_bound=91), \"\\\n \"ColCnt(char=65, low_bound=64, high_bound=91)])\"\n\n\ndef test_column_next():\n column = cog.sheets.Column('A')\n assert column.next() == 'B'\n\n column = cog.sheets.Column('Z')\n assert column.next() == 'AA'\n assert column.next() == 'AB'\n\n\ndef test_column_prev():\n column = cog.sheets.Column('B')\n assert column.prev() == 'A'\n\n column = cog.sheets.Column('AA')\n assert column.prev() == 'Z'\n assert column.prev() == 'Y'\n\n\ndef test_column_offset():\n column = cog.sheets.Column('A')\n column.offset(5)\n assert str(column) == 'F'\n\n column.offset(-5)\n assert str(column) == 'A'\n\n\ndef test_column_to_index():\n column = cog.sheets.Column('A')\n assert cog.sheets.column_to_index(str(column)) == 0\n\n column2 = cog.sheets.Column('AA')\n assert cog.sheets.column_to_index(str(column2)) == 26\n","sub_path":"tests/cog/test_sheets.py","file_name":"test_sheets.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"19195315","text":"# -*- coding: utf-8 -*-\n\n# 2019/4/17 0017 下午 5:22 \n\n__author__ = 'RollingBear'\n\nimport pymysql\n\ndb = pymysql.connect('localhost', 'root', '1120', 'test')\n\ncursor = db.cursor()\n\nsql = 'INSERT INTO user(name)' \\\n 'VALUES (\"Mac\")'\n\ntry:\n cursor.execute(sql)\n db.commit()\nexcept:\n db.rollback()\n\ndb.close()\n","sub_path":"db_test.py","file_name":"db_test.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"55009804","text":"print('Analise de triângulo ')\nreta1 = float(input('Digite o valor do primeiro segmento: '))\nreta2 = float(input('Digite o valor do segundo segmento: '))\nreta3 = float(input('Digite o valor do terceiro segmento: '))\n\ncorreto = 0\nif reta1 - reta2 < reta3 < reta1 + reta3:\n correto = correto + 1\nif reta1 - reta3 < reta2 < reta1 + reta3:\n correto = correto + 2\nif reta3 - reta2 < reta1 < reta3 + reta2:\n correto = correto + 1\n\nif correto == 3:\n if reta1 == reta2 == reta3:\n print('Podemos formar um triângulo, Tipo EQUILÁTERO!!')\n elif reta1 != reta2 != reta3 != reta1:\n print('Podemos formar um triângulo, Tipo ESCALENO')\n else:\n print('Podemos formar um triângulo, Tipo ISÓSCELES')\nelse:\n print('Não forma um triângulo!!')\n","sub_path":"Exercicio41a50/ex042.py","file_name":"ex042.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"555064866","text":"# Write a program that calculates and prints the square of the sum of two values\n# (a+b)^2. Consider a = 2, and b = 3\n\nvalueA = 2\nvalueB = 3\n\nsum = valueA + valueB\nprint(\"The sum of valueA and valueB is: \", valueA + valueB)\n\nprint(\"(a+b)^2 equals: \", sum * sum)","sub_path":"practice/finalExercises/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"252927449","text":"import sys\nimport numpy as np\n\n# Read data file and build a dictionary\ndef readdata(fileName):\n with open(fileName) as f:\n content = f.readlines()\n\n Data = {}\n\n for line in content:\n if line.startswith('#'):\n pass\n elif '=' in line:\n a, b = line.split('=')\n tmp = {a.strip():b.strip()}\n Data.update(tmp)\n else:\n pass\n return(Data)\n\n\n### Parse data of the programs\n\n# Parse the dictionary: main program\ndef parsedata(Data):\n model, Nc = _parsedata_model(Data)\n\n country = Data['country']\n \n if 'param_type' in Data.keys():\n param_type =Data['param_type']\n else:\n param_type = 'const'\n param_file = Data['param_file']\n\n Tf = Data['Tf']\n dt = float(Data['dt'])\n\n if 'save_code' in Data.keys():\n save_code = bool(int(Data['save_code']))\n else:\n save_code = True\n\n if 'by_age' in Data.keys():\n by_age = bool(int(Data['by_age']))\n else:\n by_age = False\n\n if 'dataExtrapolation' in Data.keys():\n data_ext_deg = int(Data['dataExtrapolation'])\n else:\n data_ext_deg = None\n \n ext_deg = 0\n if 'extrapolation' in Data.keys():\n ext_deg = Data['extrapolation']\n if ext_deg not in ['exp','rbf']:\n try:\n ext_deg = int(ext_deg)\n except:\n raise ValueError(\"Error - 'extrapolation' can be only an integer, 'exp', or 'rbf'\")\n\n\n edges_file = Data['edges_file']\n borders_file = Data['borders_file']\n if 'map_file' in Data.keys():\n map_file = Data['map_file']\n else:\n map_file = \"\"\n mobility = Data['mobility']\n if mobility not in ['mixing', 'transport']:\n sys.exit('Error - mobility type should be either \\\"mixing\\\" or \\\"transport\\\"')\n mixing = float(Data['mixing'])\n\n estim_param, DPC_start, DPC_ndays = _parsedata_estim(Data)\n\n if 'only_forecast' in Data.keys():\n only_forecast = bool(int(Data['only_forecast']))\n else:\n only_forecast = False\n\n out_type = Data['out_type']\n if out_type not in ['csv','h5']:\n sys.exit('Error - only \\\"csv\\\" and \\\"h5\\\" output are allowed')\n\n return(model, Nc, country, param_type, param_file, Tf, dt, save_code, by_age, edges_file, \\\n borders_file, map_file, mobility, mixing, estim_param, DPC_start,\\\n DPC_ndays, data_ext_deg, ext_deg, out_type, only_forecast)\n\n# Parse the dictionary: plot\ndef parsedata_plot(Data):\n model, Nc = _parsedata_model(Data)\n\n CaseName = Data['CaseName']\n\n param_file = Data['param_file']\n\n out_type = Data['out_type']\n if out_type not in ['csv','h5']:\n sys.exit('Error - only \\\"csv\\\" and \\\"h5\\\" output are allowed')\n plotting_step = int(Data['plotting_step'])\n gen_video = bool(int(Data['gen_video']))\n shape_file = Data['shape_file']\n\n return(model, Nc, CaseName, param_file, \\\n out_type, plotting_step, gen_video, shape_file)\n\n### Parse subsections\n\n# Parse the model\ndef _parsedata_model(Data):\n model = Data['model']\n if model not in ['SUIHTER', 'SEIRD']:\n sys.exit('Error - model should be either \"SUIHTER\" or \"SEIRD\"')\n elif model == 'SUIHTER':\n Nc = 7\n elif model == 'SEIRD':\n Nc = 5\n\n return(model, Nc)\n\n# Parse the estimation\ndef _parsedata_estim(Data):\n estim_param = bool(int(Data['estim_param']))\n if 'DPC_start' in Data.keys():\n DPC_start = Data['DPC_start']\n DPC_ndays = Data['DPC_end']\n w_l = 0\n\n return(estim_param, DPC_start, DPC_ndays)\n\n","sub_path":"Tests/variant_last/epiMOX_new_model/epiMOX_new_model/epi/loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"330575618","text":"import viz\r\nimport viztask\r\n\r\nviz.go()\r\n\r\n#Position the viewpoint.\r\nviz.MainView.setPosition(0,1.8,6)\r\nviz.MainView.setEuler(180,0,0)\r\n\r\nwoman = viz.addAvatar('vcc_female.cfg')\r\nwoman.state(1)\r\n\r\n#Add a text message.\r\ntext = viz.addText('hit the spacebar to begin')\r\ntext.alignment( viz.TEXT_CENTER_BASE )\r\ntext.setEuler(180,0,0)\r\ntext.setScale(.3,.3,.3)\r\ntext.setPosition(0,2,0)\r\nappear = vizact.fadeTo(1, begin=0, time=1)\r\ndisappear = vizact.fadeTo(0, begin=1, time=1)\r\n\r\n#Add a balloon and an action for that balloon.\r\nduck = viz.add('duck.cfg')\r\nduck.scale( .01,.01,.01)\r\nduck.setPosition(0,0,-5)\r\nduck.state(1)\r\ngrow = vizact.sizeTo( [3,3,3], time=5)\r\njump = vizact.animation(2)\r\n\r\n#Add a woman who can walk away.\r\nrun = vizact.walkTo([10,0,10], walkSpeed=1.7, turnSpeed=90, walkAnim=11)\r\n\r\n#1. Wait for the spacebar.\r\ndef mytask():\r\n\tyield viztask.waitKeyDown( ' ' )\r\n\r\n#2. Make the text fade away.\r\n#This is the function you'll need to make the text visible.\r\n#text.addAction( disappear )\r\n\tyield viztask.addAction( text, disappear )\r\n\r\n#3. Change the text to 'something is happening'.\r\n\ttext.message( 'something is happening' )\r\n\t\r\n#4. Show the text and then hide the text.\r\n#These are the functions you'll need to make the text visible.\r\n#text.addAction( appear )\r\n#text.addAction( disappear )\r\n\tyield viztask.addAction( text, appear )\r\n\tyield viztask.addAction( text, disappear )\r\n\t\r\n#5. Make the duck grow (and wait for it to grow ).\r\n#This is the function you'll need to make the duck grow.\r\n#duck.addAction( grow )\r\n\tyield viztask.addAction( duck, grow )\r\n\r\n#6. Wait for a second and then make the duck jump\r\n#This is the function you'll need to make the duck hop.\r\n#duck.execute( 2 )\r\n\tyield viztask.waitTime( 1 )\r\n\tduck.execute( 2 )\r\n\t\r\n\r\n#7. Wait a fraction of a second and then make the woman run jump.\r\n#This is the function you'll need to make the woman run away.\r\n#woman.addAction( walk )\r\n\tyield viztask.waitTime( .5) \r\n\twoman.addAction( run )\r\n\r\n\r\n#Schedule the task.\t\r\nviztask.schedule( mytask() )\r\n\r\nvizact.onkeydown( 's', viz.window.startRecording, 'test.avi' )\r\nvizact.onkeydown( 't', viz.window.stopRecording )\r\n\r\n\r\n","sub_path":"Vizard/teacher in a book code snippets (R4)/the viztask challenge answer.py","file_name":"the viztask challenge answer.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"624263542","text":"\"\"\"Address Validator\"\"\"\nimport re\nimport address_constants as c\n\ndef validate_address(address):\n \"\"\"Validate address data\"\"\"\n result = { 'valid': True, 'errors': {} }\n validation = {\n 'project_id': False,\n 'address_type': False,\n 'country': False,\n 'place': False,\n 'sequence_number': False,\n }\n\n if re.match(c.address_schema['project_id'], address['project_id']):\n validation['project_id'] = True\n if address['address_type'] in c.address_schema['address_type']:\n validation['address_type'] = True\n if address['country'] in c.address_schema['country']:\n validation['country'] = True\n if re.match(c.address_schema['place'], address['place']):\n validation['place'] = True\n if re.match(c.address_schema['sequence_number'], address['sequence_number']):\n validation['sequence_number'] = True\n\n for test in validation.items():\n if test[1] is False:\n result['errors'] = validation\n result['valid'] = False\n break\n\n return result\n","sub_path":"src/migrations/address_validator.py","file_name":"address_validator.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"473293956","text":"import sys\nimport yaml\nfrom netmiko import ConnectHandler\n\n#COMMAND = sys.argv[1]\ndevices = yaml.load(open('devices.yaml'))\n\n\ndef connect_ssh(device_dict, commands):\n\n print('Connection to device {}'.format(device_dict['ip']))\n\n with ConnectHandler(**device_dict) as ssh:\n ssh.enable()\n\n result = ssh.send_config_set(commands)\n print(result)\n\n\ncommands_to_send = [\n 'logg 10.1.12.3', 'ip access-li ext TESST2', 'permit ip any any'\n]\n\nfor router in devices['routers']:\n connect_ssh(router, commands_to_send)\n","sub_path":"examples/25_additional_info/threading_multiprocessing/netmiko_function.py","file_name":"netmiko_function.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"493202902","text":"# as variaveis seguintes são globais \n#podem ser usadas de qulaquer lugar do programa\nmin = 10\nmax = 100\ndef existe(min,max):\n while True:\n #a variavel existe é uma variavel local\n #só pode ser chamada dentro da função\n existe = int(input(\"digite o valor:\"))\n if existe>=min and existe<=max:\n return print(f'o valor {existe} esta entre {min} e {max}')\n else:\n return print(f'o valor {existe} NÃO esta entre {min} e {max}')\n\nexiste(min,max)\n# DEFINIÇÃO DE PARAMETROS DEFAULTS EM UMA FUNÇÃO\n# se não colocar nada os padroes ja estão declarados\ndef barra(n=40, caractere='$'):\n print (caractere*n)\nbarra()","sub_path":"Python/escopo/aula7.py","file_name":"aula7.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"71994475","text":"# coding: utf-8\n\nfrom leancloud import Object\nfrom leancloud import Query\nfrom leancloud import LeanCloudError\nfrom flask import Blueprint\nfrom flask import request\nfrom flask import redirect\nfrom flask import url_for\nfrom flask import render_template\nimport pytz\n\n\nclass ImNews(Object):\n pass\n\nhds_view = Blueprint('im', __name__)\n\n\n@hds_view.route('')\ndef show():\n results = []\n tz = pytz.timezone('Asia/Shanghai')\n try:\n items = Query(ImNews).descending('createdAt').find()\n for item in items:\n result = {}\n result[\"title\"] = item.get('title')\n result[\"url\"] = item.get('url')\n result[\"createdAt\"] = item.created_at.astimezone(tz)\n results.append(result)\n except LeanCloudError as e:\n if e.code == 101: # 服务端对应的 Class 还没创建\n results = []\n else:\n raise e\n return render_template('hds.html', items=results)\n\n","sub_path":"views/hudong.py","file_name":"hudong.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"248197","text":"class App:\n def __init__(self, master):\n\n frame = Frame(master)\n frame.pack()\n\n self.text_write = Entry(frame)\n self.text_write.pack()\n\n self.button = Button(frame, text=\"quit\", fg=\"red\", command=frame.quit)\n self.button.pack(side=LEFT)\n\n self.hi_there = Button(frame, text='hello', fg='black', command=self.say_hi)\n self.hi_there.pack(side=RIGHT)\n\n def say_hi(self):\n print(self.text_write.get())","sub_path":"_src/om2py2w/2wex2/mode file.py","file_name":"mode file.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"420067462","text":"path = input(\"Enter the file path: \")\r\nf= open(path, \"r\") #we open file in read mode\r\n#f=open(\"C:/text.txt\", \"r\")\r\ncontents =f.read() # we keep file containt in this variable\r\nlines= contents.split('\\n') #create a table of lines in of the file \r\nminLength=1000000000 \r\nmaxLength=0 \r\nminID=0 \r\nmaxID=0\r\nfor i in range (len(lines)) :\r\n\twords = lines[i].split(' ')\r\n\tif len( words) < minLength :\r\n\t\tminLength = len( words)\r\n\t\tminID = i+1 #keep number of the line with the current least words \r\n\telif len( words) > maxLength :\r\n\t\tmaxLength = len( words)\r\n\t\tmaxID = i+1 #keep number of the line with the current upper words \r\nprint(\"Total lines: {}\".format( len(lines) ))\t\r\nprint(\"shorter line: line {}\".format(minID))\t\r\nprint(\"longer line : line {}\".format(maxID))\t\r\n\r\n\r\n","sub_path":"exercice1.py","file_name":"exercice1.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"650559677","text":"import numpy as np\nimport cv2\nimport time\nimport serial\nimport math\nfrom xbee import ZigBee\nfrom xbee.helpers.dispatch import Dispatch\n\ndef sendData(address, datatosend):\n zb.send('tx', dest_addr_long = address , dest_addr = UNKNOWN , data = datatosend)\n\n#declare variables for window\ncap = cv2.VideoCapture(1)\n\n#define the codec and create VideoWriter object\n#fourcc = cv2.VideoWriter_fourcc(*'XVID')\nfourcc = cv2.cv.CV_FOURCC(*'XVID')\nout0 = cv2.VideoWriter('output.avi',fourcc,20.0, (640,480))\n\nwhile(1):\n\n #take each frame\n ret,frame = cap.read()\n\n #making image blur to remove noise and edges\n frame = cv2.blur(frame,(5,5))\n\n #convert BGR to HSV\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n bool1 = False\n bool2 = False\n bool3 = False\n\n\n #image masking\n cx_b = 0\n cy_b = 0\n cx_g = 0\n cy_g = 0\n cx_y = 0\n cy_y = 0\n z=0\n\n\n #define range of yellow colors in HSV and threshold the hsv image to get yellow color\n lower_yellow = np.array([20, 97, 151])\n upper_yellow = np.array([40, 117, 231])\n\n\n yellow_mask = cv2.inRange(hsv, lower_yellow, upper_yellow)\n\n contours, hierarchy = cv2.findContours(yellow_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n idx = 0\n max_area = 0\n best_cnt = 0\n\n if(len(contours)>0):\n #print(\"coordinates :\")\n for cnt in contours :\n area = cv2.contourArea(cnt)\n if(area > max_area):\n max_area = area\n best_cnt = cnt\n\n M = cv2.moments(best_cnt)\n try:\n\n cx_y = int(M['m10']/M['m00'])\n cy_y = int(M['m01']/M['m00'])\n bool2 = True\n\n # print cx_y\n # print cy_y\n\n #drawing a circle\n cv2.circle(frame , (cx_y,cy_y), 5, (255,255,0), -1)#lime dot\n\n except Exception as e:\n bool2=True\n print(\"exdef\")\n\n\n else:\n print(\"sorry please put yellow color infront of camera\")\n\n #define range of green colors in HSV and threshold the hsv image to get green color\n lower_green = np.array([66, 70, 88])\n upper_green = np.array([86, 90, 168])\n\n\n green_mask = cv2.inRange(hsv, lower_green, upper_green)\n\n contours,hierarchy = cv2.findContours(green_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n idx = 0\n max_area = 0\n best_cnt = 0\n\n if(len(contours)>0):\n #print(\"coordinates :\")\n for cnt in contours:\n area = cv2.contourArea(cnt)\n if(area > max_area):\n max_area = area\n best_cnt = cnt\n\n M = cv2.moments(best_cnt)\n try:\n\n cx_g = int(M['m10']/M['m00'])\n cy_g = int(M['m01']/M['m00'])\n bool1 = True\n #print cx_g\n #print cy_g\n\n #drawing a circle\n cv2.circle(frame, (cx_g,cy_g), 5, (0,255,0), -1)#green dot\n\n except Exception as e:\n bool1=True\n print(\"exabc\")\n\n else:\n print(\"sorry please put green color infront of camera\")\n\n\n\n #define range of blue colors in HSV and threshold the hsv image to get blue color\n\n\n lower_blue = np.array([94, 142, 138])\n upper_blue = np.array([114, 162, 218])\n blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)\n\n contours, hierarchy = cv2.findContours(blue_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n idx = 0\n max_area = 0\n best_cnt = 0\n result = 0\n\n if(len(contours)>0):\n #print(\"coordinates :\")\n for cnt in contours :\n area = cv2.contourArea(cnt)\n if(area > max_area):\n max_area = area\n best_cnt = cnt\n\n M = cv2.moments(best_cnt)\n try:\n cx_b = int(M['m10']/M['m00'])\n cy_b = int(M['m01']/M['m00'])\n bool3 = True\n\n # print cx_b\n # print cy_b\n cv2.circle(frame,(cx_b,cy_b),5, (0,0,255), -1)#red\n except Exception as e:\n bool3=True\n print(\"ex_wxy\")\n\n\n #else:\n # print(\"sorry please put blue color\")\n\n cv2.line(frame,(cx_g,cy_g),(cx_y,cy_y),(255,0,0),5)\n cv2.line(frame,(cx_g,cy_g),(cx_b,cy_b),(255,255,0),5)\n temp1 = math.sqrt(math.pow(cx_b-cx_g,2) + math.pow(cy_b-cy_g,2));\n temp2 = math.sqrt(math.pow(cx_y-cx_g,2) + math.pow(cy_y-cy_g,2));\n\n # |i j k|\n # |\n\n cx_bcx_gdiff = cx_b-cx_g\n cy_bcy_gdiff = cy_b-cy_g\n cy_ycy_gdiff = cy_y-cy_g\n cx_ycx_gdiff = cx_y-cx_g\n\n diff1 = (cx_bcx_gdiff) * (cy_ycy_gdiff)\n diff2 = (cy_bcy_gdiff) * (cx_ycx_gdiff)\n\n\n\n z = diff1-diff2\n tmp = temp1 * temp2\n\n result=z/tmp #sin thita\n print(result)\n #print(z);\n\n #except Exception as e:\n # bool3=True\n # print(\"ex_wxy\")\n\n\n else:\n print(\"sorry please put blue color\")\n\n\n #else:\n # print(\"sorry please put blue color\")\n\n dataString = 'b'\n\n if((bool1 & bool2 & bool3)==False):\n dataString = dataString+'5'\n\n elif all([result<0.183 ,result>-0.113]):\n dataString = dataString+'2'\n\n elif(z<0):\n dataString = dataString+'4'\n\n elif(z>0):\n dataString = dataString+'1'\n\n else:\n dataString = dataString+'5'\n\n PORT = '/dev/ttyUSB0'\n BAUD_RATE = 9600\n\n UNKNOWN = '\\xff\\xfe'\n #WHERE = '\\x00\\x13\\xA2\\x00\\x41\\x6C\\x44\\xE9'\n WHERE = '\\x00\\x13\\xA2\\x00\\x41\\x5D\\x87\\xB3'\n\n ser = serial.Serial(PORT,BAUD_RATE)\n\n zb = ZigBee(ser)\n\n try:\n print(\"sending data\")\n sendData(WHERE, dataString)\n\n except KeyboardInterrupt:\n break\n\n out0.write(frame)\n\n cv2.imshow('frame',frame)\n\n if cv2.waitKey(5) & 0xFF == ord('a'):\n print(cv2.waitKey(5))\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"xbee_vector.py","file_name":"xbee_vector.py","file_ext":"py","file_size_in_byte":5793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"378849967","text":"# -*- coding:UTF-8 -*-\nimport tornado.web\nfrom handlers.handler import BaseHandler\nfrom handlers.util import exportExcel\nfrom database.models import db_Session\nfrom services.projectManager.projectProgressManager import *\nimport json\nimport os\nimport logging\nimport datetime\nimport uuid\nimport time\n\n\nclass ProProgressIndexHandler(BaseHandler):\n @tornado.web.authenticated\n async def get(self):\n self.render('projectManager/projectProgressManager.html')\n\n @tornado.web.authenticated\n async def post(self):\n page = int(self.get_argument('page'))\n limit = int(self.get_argument('limit'))\n project_no = self.get_argument('project_no')\n project_name = self.get_argument('project_name')\n project_charge_user = self.get_argument('project_charge_user')\n project_manager_user = self.get_argument('project_manager_user')\n db = db_Session()\n count, data = await get_pro_info(db,page,limit,project_no,project_name,\\\n project_charge_user,project_manager_user,self.session.get('user_id'))\n db.close()\n self.write(json.dumps({\"code\": 0, \"msg\": \"\", \"count\": count, \"data\": data}))\n\nclass ProWatchIndexHandler(BaseHandler):\n @tornado.web.authenticated\n async def post(self):\n pro_id = self.get_argument('pro_id')\n db = db_Session()\n manager_user_id, show_finish_btn = await get_pro_manager_user_id(db, pro_id)\n db.close()\n self.render('projectManager/projectWatch.html', pro_id=pro_id,user_id=self.session.get('user_id'),\\\n manager_user_id=manager_user_id, show_finish_btn=show_finish_btn)\n\nclass ProTeamListHandler(BaseHandler):\n @tornado.web.authenticated\n async def post(self):\n page = int(self.get_argument('page'))\n limit = int(self.get_argument('limit'))\n pro_id = self.get_argument('pro_id')\n db = db_Session()\n count, data = await get_pro_team_list(db, page, limit, pro_id, self.session.get('user_id'))\n db.close()\n self.write(json.dumps({\"code\": 0, \"msg\": \"\", \"count\": count, \"data\": data}))\n\nclass ProDevListHandler(BaseHandler):\n @tornado.web.authenticated\n async def post(self):\n pro_id = self.get_argument('pro_id')\n db = db_Session()\n count, data = await get_pro_dev_list(db, pro_id)\n db.close()\n self.write(json.dumps({\"code\": 0, \"msg\": \"\", \"count\": count, \"data\": data}))\n\nclass ProSingleDevHandler(BaseHandler):\n @tornado.web.authenticated\n async def post(self):\n dev_id = self.get_argument('dev_id')\n show_task_type = self.get_argument('show_task_type')\n if show_task_type == 'single':\n check = False\n else:\n check = True\n db = db_Session()\n pro_id, stage_name, tasks = await get_info_by_dev_id(db, dev_id, self.session.get(\"user_id\"), show_task_type)\n self.render('projectManager/projectDev.html', dev_id=dev_id,pro_id=pro_id,stage_name=stage_name, tasks=tasks,\\\n user_id=self.session.get(\"user_id\"), check=check)\n db.close()\n\nclass FinishTaskHandler(BaseHandler):\n @tornado.web.authenticated\n async def post(self):\n task_id = self.get_argument('task_id')\n db = db_Session()\n try:\n status, msg = await finish_task(db, task_id)\n db.commit()\n self.write({'status':status,'msg':msg})\n except Exception as e:\n logging.error(e)\n db.rollback()\n self.write({'status':-1,'msg':'发生异常,请重试'})\n finally:\n db.close()\n\nclass FinishDevHandler(BaseHandler):\n @tornado.web.authenticated\n async def post(self):\n dev_id = self.get_argument('dev_id')\n db = db_Session()\n try:\n status, msg = await finish_dev(db, dev_id)\n db.commit()\n self.write({'status':status, 'msg':msg})\n except Exception as e:\n logging.error(e)\n db.rollback()\n self.write({'status':-1,'msg':'发生异常,请重试'})\n finally:\n db.close()\n\nclass FinishProjectHandler(BaseHandler):\n @tornado.web.authenticated\n async def post(self):\n pro_id = self.get_argument('pro_id')\n db = db_Session()\n try:\n status, msg = await finish_project(db, pro_id)\n db.commit()\n self.write({'status':status, 'msg':msg})\n except Exception as e:\n logging.error(e)\n db.rollback()\n self.write({'status':-1,'msg':'发生异常,请重试'})\n finally:\n db.close()\n\nclass StartDevByHandHandler(BaseHandler):\n @tornado.web.authenticated\n async def post(self):\n dev_id = self.get_argument('dev_id')\n db = db_Session()\n try:\n status, msg = await start_dev_by_hand(db, dev_id)\n db.commit()\n self.write({'status':status, 'msg':msg})\n except Exception as e:\n logging.error(e)\n db.rollback()\n self.write({'status':-1,'msg':'发生异常,请重试'})\n finally:\n db.close()\n","sub_path":"handlers/projectManager/projectProgressManager.py","file_name":"projectProgressManager.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"410328369","text":"import binascii\n\n\nclass Hemming:\n def __init__(self, in_message: str, unit_length: int):\n assert not unit_length % 8, 'unit length must be multiples 8'\n self.encode_unit_length = unit_length\n self.message: str = in_message\n self.message_bin_array = self.chars_to_bin(in_message)\n self.control_bits_pos = [i - 1 for i in range(1, self.encode_unit_length + 1) if not i & (i - 1)]\n self.decode_unit_length = self.encode_unit_length + len(self.control_bits_pos)\n\n @staticmethod\n def chars_to_bin(input_message):\n return ''.join([bin(ord(c))[2:].zfill(8) for c in input_message])\n\n @staticmethod\n def unit_iterator(binary_message, unit_length):\n \"\"\"\n Берем строку из набора битов и разделяем по заданной длине юнита\n Может работать с закодированным и раскодированным сообщениями (в конструкторе класса есть занчения)\n \"\"\"\n for i in range(len(binary_message)):\n if not i % unit_length:\n yield binary_message[i:i + unit_length]\n\n @property\n def encode_message(self):\n encoded_message = str()\n for item in self.unit_iterator(self.message_bin_array, self.encode_unit_length):\n encoded_message += self.set_control_bits(item, self.control_bits_pos)\n return encoded_message\n\n @property\n def decode_message(self):\n encoded_message = self.encode_message\n decoded_message = str()\n for i, unit in enumerate(self.unit_iterator(encoded_message, self.decode_unit_length)):\n unit_control_bits: dict = self.__get_control_bits(unit)\n decoded_unit = ''.join([item for i, item in enumerate(unit) if i not in unit_control_bits])\n #####################################\n if i == 3:\n decoded_unit = list(decoded_unit)\n if decoded_unit[2] == 1:\n decoded_unit[2] = '0'\n decoded_unit = ''.join(decoded_unit)\n else:\n decoded_unit[2] = '1'\n decoded_unit = ''.join(decoded_unit)\n #####################################\n if self.__find_error(decoded_unit, unit_control_bits):\n # сори за лапшу\n encode_decoded_unit_control_bits = self.__get_control_bits(self.set_control_bits(decoded_unit, self.control_bits_pos))\n decoded_message = self.fix_error(unit_control_bits, encode_decoded_unit_control_bits)\n else:\n pass\n decoded_message += decoded_unit\n\n return decoded_message\n\n @staticmethod\n def __get_control_bit(message_unit_part):\n return '0' if (message_unit_part.count('1') % 2) == 0 else '1'\n\n @staticmethod\n def __get_control_bits(encoded_message_unit):\n control_bits = dict()\n for i, item in enumerate(encoded_message_unit):\n if not (i+1) & i:\n control_bits[int(i)] = item\n return control_bits\n\n def __find_error(self, decoded_unit, check_bits):\n encode_decoded_unit = self.set_control_bits(decoded_unit, self.control_bits_pos)\n encode_decoded_unit_control_bits = self.__get_control_bits(encode_decoded_unit)\n\n return True if (check_bits != encode_decoded_unit_control_bits) else False\n\n @staticmethod\n def set_control_bits(message_unit, control_bits_pos):\n temp_var = message_unit\n for value in range(len(message_unit)):\n if value in control_bits_pos:\n control_bit = Hemming.__get_control_bit(message_unit[value:])\n temp_var = temp_var[:value] + control_bit + temp_var[value:]\n return temp_var\n\n @staticmethod\n def fix_error(unit_control_bits, encode_decoded_unit_control_bits):\n encoded_unit = str()\n if encode_decoded_unit_control_bits != unit_control_bits:\n invalid_bits = []\n for encode_decoded_unit_control_bits, value in encode_decoded_unit_control_bits.items():\n if unit_control_bits[encode_decoded_unit_control_bits] != value:\n invalid_bits.append(encode_decoded_unit_control_bits)\n num_bit = sum(invalid_bits)\n encoded_unit = '{0}{1}{2}'.format(\n unit_control_bits[:num_bit - 1],\n int(unit_control_bits[num_bit - 1]) ^ 1,\n unit_control_bits[num_bit:])\n return encoded_unit\n\n\nif __name__ == '__main__':\n x = Hemming('Pep', 8)\n print(f'Начальный набор бит: {x.message_bin_array}')\n print(f'Закодированное сообщение: {x.encode_message}')\n print(f'Раскодированное сообщение: {x.decode_message}')\n print(f'Равенство исходного и раскодированного сообщения: {(x.message_bin_array == x.decode_message)}')\n message = int(x.decode_message, 2)\n message = binascii.unhexlify('%x' % message)\n print(f'Сообщение: {message}')\n","sub_path":"oleg.py","file_name":"oleg.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"555418697","text":"from typing import Optional, List, Tuple\nfrom threading import Thread\nfrom feedparser import parse\nimport xml.etree.ElementTree as ET\nfrom requests import Response\nfrom data import LastEntry\nfrom .discord import Discord\nfrom config import HentaiHavenConfig\n\n\nclass HentaiHaven(Thread):\n def __init__(self, discord: Discord, config: HentaiHavenConfig, last_entry: LastEntry) -> None:\n self.discord = discord\n self.config = config\n self.last_entry = last_entry\n Thread.__init__(self, name=\"HentaiHaven\")\n\n def run(self):\n go(\n discord=self.discord,\n config=self.config,\n last_entry=self.last_entry\n )\n\n\ndef go(discord: Discord, config: HentaiHavenConfig, last_entry: LastEntry):\n # Get items from the RSS feed\n items = parse(\"http://hentaihaven.org/feed\").entries\n new_items = []\n counter: int = 0\n first_name_hh: Optional[int] = None\n for item in items:\n id_: int = int(item['id'].replace(\"http://hentaihaven.org/?p=\", \"\"))\n if (id_ == last_entry.hh) or (counter == config.posts):\n break\n elif tag_filter(config.black_list, item.summary):\n new_items.append(item)\n counter += 1\n if first_name_hh is None:\n first_name_hh = id_\n if first_name_hh is not None:\n last_entry.hh = first_name_hh\n\n # Turn RSS items into embed objects\n embs: List = []\n for item in new_items:\n desc, image = get_from_summary(item.summary)\n emb_obj = {\n \"title\": item.title,\n \"description\": desc,\n \"url\": item.link,\n \"color\": config.embed_colour,\n \"image\": {\n \"url\": image\n }\n }\n embs.append(emb_obj)\n\n if len(embs) == 0:\n print(\"Info No New HentaiHaven Entries\")\n\n for e in embs:\n for ch in config.channels:\n response: Response = discord.send_msg(\n channel=ch,\n content=config.message,\n embed=e\n )\n output: str = f\"To Channel: {ch}, Sent \\'{e['title']}\\'\"\n if response.ok:\n print(\"Success!\", output)\n else:\n print(\"Error!\", output)\n print(response.text)\n\n\ndef tag_filter(tags: List[str], summary: str) -> bool:\n summary = summary.lower()\n for t in tags:\n tag = t.lower()\n if tag in summary:\n return False\n return True\n\n\ndef get_from_summary(summary: str) -> Tuple[str, str]:\n root = ET.fromstring(f\"{summary}\")\n d = f\"{root[1].text}\\n\\n{root[2].text}\"\n i = root[0][0].attrib[\"src\"]\n return d, i\n","sub_path":"src/hentai_haven.py","file_name":"hentai_haven.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"137008204","text":"# -*- coding: utf-8 -*-\nimport pyalps\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport pyalps.plot\nimport numpy as np\n#prepare the input parameters\n\n\n\ndata = pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm1a'), 'Connected Susceptibility')\nsusc = pyalps.collectXY(data,x='T',y='Connected Susceptibility',foreach=['L'])\n\nred=susc\n\nfor d in red:\n d.x=np.around(d.x,3)\n\nfh=open('susc_rounded_t_3D_Ising_SC.txt','w')\nfh.write(pyalps.plot.convertToText(red))\nfh.close()\n\nlvrednost=np.array([q.props['L'] for q in red])\nsel=np.argsort(lvrednost)\nred=np.array(red)\nred=red[sel]\n\ns=open('susc_rounded_t_redosled_3D_Ising_SC.txt','w')\ns.write(pyalps.plot.convertToText(red))\ns.close()\n\nTc=4.52\na=1.519\n\nnumeratorfig=1\n\n#make a data collapse of the |magnetization| as a function of (T-Tc)/Tc\nfor two_minus_eta in np.linspace(0.0,3.0,31):\n susc = pyalps.collectXY(data,x='T',y='Connected Susceptibility',foreach=['L'])\n for d in susc:\n d.x -= Tc\n d.x = d.x/Tc\n l = d.props['L']\n d.x = d.x * pow(float(l),a)\n d.y = d.y/pow(float(l),two_minus_eta) \n plt.figure()\n pyalps.plot.plot(susc)\n plt.xlabel('$L^{a}(T-T_{C})/T_{C}$')\n plt.ylabel(r'$L^{2-\\eta}\\chi,2-\\eta=\\gamma/\\nu=$ %.6s' % two_minus_eta)\n plt.title(u'3D Izingov model na prostoj kubnoj rešetki')\n plt.savefig('figure_SC_eta_procena%d.eps'%(numeratorfig),dpi=300)\n numeratorfig+=1\n\n","sub_path":"Simple_cubic_lattice_Ising_model/eta_procena_SC_1.py","file_name":"eta_procena_SC_1.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569368200","text":"alphabet={x: ord(x)-64 for x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}\r\nwith open ('p042_words.txt','r') as f:\r\n data = f.read()\r\ndata=data.replace('\"','')\r\nlist=data.split(',')\r\n\r\np=[]\r\nfor x in list:\r\n sum=0\r\n for c in x:\r\n sum+=alphabet[c]\r\n p.append(int(sum))\r\n\r\ntriangle_nums=[int((x*(x+1))/2) for x in range(1,30)]\r\n\r\ncount=0\r\nfor x in p:\r\n for y in triangle_nums:\r\n if (x==y): count+=1\r\nprint(count)\r\n","sub_path":"euler_42.py","file_name":"euler_42.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"109366009","text":"# Copyright 2019 Open Source Robotics Foundation, Inc.\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\"\"\"Test parsing a group action.\"\"\"\n\nimport io\nimport textwrap\n\nfrom launch.actions import SetLaunchConfiguration\nfrom launch.frontend import Parser\n\n\ndef test_group():\n yaml_file = \\\n \"\"\"\\\n launch:\n - group:\n scoped: False\n children:\n - let:\n name: 'var1'\n value: 'asd'\n - let:\n name: 'var2'\n value: 'asd'\n \"\"\" # noqa: E501\n yaml_file = textwrap.dedent(yaml_file)\n root_entity, parser = Parser.load(io.StringIO(yaml_file))\n ld = parser.parse_description(root_entity)\n group = ld.entities[0]\n actions = group.execute(None)\n assert 2 == len(actions)\n assert isinstance(actions[0], SetLaunchConfiguration)\n assert isinstance(actions[1], SetLaunchConfiguration)\n\n\nif __name__ == '__main__':\n test_group()\n","sub_path":"launch_yaml/test/launch_yaml/test_group.py","file_name":"test_group.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"190185519","text":"\"\"\"Signature module for crypto-cookie package\n\"\"\"\n__author__ = \"@philipkershaw\"\n__date__ = \"09/07/15\"\n__copyright__ = \"(C) 2015 Science and Technology Facilities Council\"\n__license__ = \"BSD - see LICENSE file in top-level directory\"\n__contact__ = \"Philip.Kershaw@stfc.ac.uk\"\n__revision__ = '$Id$'\nimport hmac\nimport hashlib\n\n\nclass VerificationError(Exception):\n \"\"\"Raise if signature verification failed\"\"\"\n \n \nclass Signature(object):\n \"\"\"Class for handling HMAC signature of messages\"\"\"\n DEFAULT_HASH_ALGORITHM = hashlib.sha256\n \n def __init__(self, hash_algorithm=DEFAULT_HASH_ALGORITHM):\n '''Set hash algorithm and encoding method'''\n self.hash_algorithm = hash_algorithm\n \n def sign(self, msg, key):\n \"\"\"Calculate digest for input message using the given key\"\"\"\n signature = hmac.new(key, msg, self.hash_algorithm)\n digest = signature.digest()\n\n return digest\n\n def verify_signature(self, msg, digest, key):\n \"\"\"Verify digest for input message\"\"\"\n calculated_digest = self.sign(msg, key)\n \n if calculated_digest != digest:\n raise VerificationError(\"Signature verification failed: \"\n \"the calculated digest (%r) doesn't \"\n \"match the input value %r\" % \n (calculated_digest, digest))","sub_path":"crypto_cookie/signature.py","file_name":"signature.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"576777436","text":"from django.urls import path, include\nfrom . import views\nfrom django.views.generic.base import TemplateView\n\nurlpatterns = [\n #path('', views.post_list, name='post_list'),\n #path('', views.login, name='login'),\n path('page_logout/',views.logout, name='page_logout'),\n\t#path('', TemplateView.as_view(template_name='home.html'), name='home'), #IMPORTANTE home quando nao existe view, só a pagina html :)\n\tpath('', include('django.contrib.auth.urls')), #entra com endereco site/login, qualquer coisa incluir accounts/ no url e no site fica site /accounts/login\n\t#path('signup/', views.SignUp.as_view(), name='signup'),\n path('', TemplateView.as_view(template_name='welcome.html'), name='welcome'),\n path('home/', views.home, name='home'),\n\tpath('signup/', views.signup, name='signup'),\n path('customer_registration/', views.customer_registration, name='customer_registration'),\n path('product_registration/', views.product_registration, name='product_registration'),\n path('payment_type_registration/', views.payment_registration, name='payment_type_registration'),\n\tpath('report_daily/', views.report_daily, name='report_daily'),\n\tpath('income_outcome_registration/', views.income_outcome_registration, name='income_outcome_registration'),\n path('export/xls/', views.export_xls, name='export_xls'),\n\tpath('report_customer/', views.report_customer, name='report_customer'),\n\tpath('report_income_outcome_registration/', views.report_income_outcome_registration, name='report_income_outcome_registration'),\n\tpath('report_customer_comparation/', views.report_customer_comparation, name='report_customer_comparation'),\n\tpath('report_comparation/', views.report_comparation, name='report_comparation'),\n\n\n]\n","sub_path":"tienda_admin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"515996553","text":"import matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport matplotlib.ticker as ticker\nfrom matplotlib.font_manager import fontManager\nimport codecs\nimport numpy as np\nimport os\nimport random\nfrom sklearn.metrics import auc\n\n\ndef draw_curve(data, params, name):\n plt.cla()\n plt.figure(figsize=(14, 9))\n\n # axes.set_title('p-r curve')\n for i in range(len(data)):\n points_list = np.array(data[i])\n\n recall, precision = [float(d[0]) for d in points_list], [float(d[1]) for d in points_list]\n plt.plot(\n recall, precision, label=params[i][0], color=params[i][1], linestyle=params[i][2],\n marker=params[i][3], ms=10, markevery=params[i][4]\n )\n\n plt.legend(loc='upper right', prop={'size': 17})\n plt.xlabel('Recall', fontsize=18)\n plt.ylabel('Precision', fontsize=18)\n plt.tick_params(labelsize=18)\n plt.xlim(0, None)\n plt.ylim(0.4, None)\n # , bbox_inches = 'tight'\n plt.rcParams['savefig.dpi'] = 1000\n # plt.show()\n plt.savefig('{}.png'.format(name), bbox_inches='tight')\n\n\nif __name__ == '__main__':\n params = {\n # 'fl_att_11': ('fl_att_11', 'blue', '--'),\n # 'fl_att_21': ('fl_att_21', 'dimgrey', '-'),\n # 'fl_att_31': ('fl_att_31', 'dimgrey', '-.'),\n # 'fl_max_21': ('fl_max_21', 'olive', '-.'),\n # 'fl_max_31': ('fl_max_31', 'green', '--'),\n # 'extract_max': ('en_max_11', 'dimgrey', '-.'),\n # 'extract_att': ('att_new_11', 'olive', '-'),\n # 'attentive-matching': ('Attentive-Matching', 'blue', '--'),\n # 'combine2max': ('combine2max', 'green', '-'),\n # 'combine3max': ('combine3max', 'olive', '-.'),\n # 'combine4max': ('combine4max', 'red', '--'),\n # 'weighted6max': ('weighted6max', 'blue', '--'),\n # 'weighted6max2': ('weighted6max2', 'red', '-'),\n # 'weighted8max3': ('weighted8max3', 'magenta', '-.'),\n # 'boosted_7': ('boosted_7', 'green', '-'),\n # 'max20latest': ('BMM', 'red', '-'),\n 'PRCurve_copa_dev_PMI': ('PRCurve_copa_dev_PMI', 'c', '-', '^', 0.1),\n 'PRCurve_copa_test_PMI': ('PRCurve_copa_test_PMI', 'steelblue', '-.', 's', 0.1),\n 'PRCurve_copa_dev_cause_effect_embedding': ('PRCurve_copa_dev_embedding', 'coral', '--', 'X', (0.2, 0.05)),\n 'PRCurve_copa_test_cause_effect_embedding': ('PRCurve_copa_test_embedding', 'green', '-.', 'o', 0.1),\n 'PRCurve_concepnet_PMI': ('PRCurve_concepnet_PMI', 'teal', '-.', '>', (0.0, 0.05)),\n 'PRCurve_semeval_PMI': ('PRCurve_semeval_PMI', 'goldenrod', '-.', 'd', (0.45, 0.1)),\n #\n # 'en_sota': ('BMM', 'black', '--', '^', 0.1),\n # 'att-new': ('Att-Matching', 'black', ':', 'x', (0.45, 0.05)),\n # 'max-matching': ('Max', 'red', '-'),\n # 'pairwise-matching': ('Pairwise-Matching', 'dimgrey', '-.'),\n # 'Lookup_baseline': ('Look-up', 'olive', '-.'),\n # # 'pairwise-matching': ('Pairwise-Matching', 'dimgrey', '-.'),\n # # 'Lookup_baseline': ('Look-up', 'olive', '-.'),\n # 'Vanilla': ('vEmbed', 'black', '--', '*', 0.1),\n 'PRCurve_copa_dev_PMI_dir': ('PRCurve_copa_dev_PMI_dir', 'coral', '--', 'X', (0.2, 0.05)),\n 'PRCurve_copa_test_PMI_dir': ('PRCurve_copa_test_PMI_dir', 'green', '-.', 'o', 0.1),\n 'PRCurve_copa_dev_PMI_dir1': ('PRCurve_copa_dev_PMI_dir1', 'teal', '-.', '>', (0.0, 0.05)),\n 'PRCurve_copa_test_PMI_dir1': ('PRCurve_copa_test_PMI_dir1', 'goldenrod', '-.', 'd', (0.45, 0.1)),\n # 'Causal_bidir_pmi': ('cEmbedBiNoise', 'black', '--', 'o', 0.1),\n\n # 'extract_max': ('extract_max', 'blue', '-'),\n # 'extract_att': ('extract_att', 'dimgrey', '-.'),\n\n }\n\n points_data, parameters = [], []\n project_source_path = ['PRCurve_copa_dev_PMI.txt', 'PRCurve_copa_test_PMI.txt',\n 'PRCurve_copa_dev_cause_effect_embedding.txt',\n 'PRCurve_copa_test_cause_effect_embedding.txt',\n 'PRCurve_concepnet_PMI.txt', 'PRCurve_semeval_PMI.txt']\n project_source_path_dir = ['PRCurve_copa_dev_PMI.txt', 'PRCurve_copa_test_PMI.txt',\n 'PRCurve_copa_dev_PMI_dir.txt', 'PRCurve_copa_test_PMI_dir.txt',\n 'PRCurve_copa_dev_PMI_dir1.txt', 'PRCurve_copa_test_PMI_dir1.txt']\n # path = os.path.join(project_source_path, 'prcurve/')\n # files = os.listdir(path)\n # names = [f.strip().split('.')[1] for f in files]\n ordered_file = [\n 'PRCurve_icw_ourmethods', 'PRCurve_icw_causalNET', 'PRCurve_icw_PMI',\n 'PRCurve_bok_ourmethods', 'PRCurve_bok_causalNET', 'PRCurve_bok_PMI',\n 'PRCurve_gut_ourmethods', 'PRCurve_gut_causalNET', 'PRCurve_gut_PMI']\n\n # for f in ordered_file:\n # if f not in params:\n # continue\n # print(f)\n for path in project_source_path_dir[:]:\n f = path[:-4]\n lines = codecs.open(path, 'r', 'utf-8').readlines()\n points = [line.strip().split(' ') for line in lines]\n points_data.append(points)\n parameters.append(params[str(f)])\n\n draw_curve(points_data, parameters, 'PRCurve_dir1')\n # \"\"\"\n # pr图重画 OK\n # auc计算 ok\n # example(en, cn分析)\n # architecture重画\n # 激发性模板 对照优缺点\n # \"\"\"\n # for f in ordered_file:\n # if f not in params:\n # continue\n # lines = codecs.open(os.path.join(path, 'points.{}'.format(f)), 'r', 'utf-8').readlines()\n # points = [list(map(float, line.strip().split('\\t'))) for line in lines]\n # recall, precision = zip(*points)\n # auc_val = auc(recall, precision)\n # print(f, auc_val)\n","sub_path":"code/test/semeval/draw_code/draw_ori.py","file_name":"draw_ori.py","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"424358569","text":"import json\nimport re\nimport requests\n\nfrom django.core.urlresolvers import reverse\nfrom django.http import Http404, HttpResponse, HttpResponseRedirect\nfrom dvutils.replica_set import get_replica_set\n\nfrom inventory.app_settings import INV_INIT_URL, INV_SCAN_URL\nfrom inventory.app_settings import INV_EXP_URL, INV_COM_URL, INV_SUMM_URL\nfrom inventory.app_settings import NSL_INV_AUDIT_MISSING_LOCK\nfrom inventory.app_settings import LOST_PKG_API_REMARK, UKN_PKG_API_REMARK\nfrom inventory.app_settings import EXP_PKG_STATUS_LIST, EXP_BAG_STATUS_LIST\nfrom inventory.app_settings import INV_ERROR_MSG, NO_PERMISSION_RMK\nfrom inventory.forms import InventorySearchForm\n\nfrom inventory.tasks import package_audit_missing\nfrom inventory.tasks import push_expected_item_nums\nfrom inventory.utils import instance_identifier\nfrom inventory.utils import segregate_items\nfrom inventory.utils import has_permission\n\nfrom rest_framework import status\nfrom rest_framework.authentication import SessionAuthentication, \\\n TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\nfrom package.models import find_by_wbns\nfrom package.app_settings import WAYBILL_PATTERN\nfrom bag.settings import BAG_SEAL_PATTERN\nfrom package.models import find_by_wbn\nfrom bag.models import find_by_bs\n\nclass CsrfExemptSessionAuthentication(SessionAuthentication):\n\n def enforce_csrf(self, request):\n return None\n\nclass AuditHandler(APIView):\n '''\n class responsible for providing audit process\n '''\n def post(self, request):\n response = []\n conn = get_replica_set()\n cn = request.POST.get('center', None)\n if cn:\n q = conn.packages.find({\n 'cs.sl': u'{}'.format(cn),\n 'cs.ss': {'$in': EXP_PKG_STATUS_LIST},\n 'pid': None,\n 'date.cpd': {'$ne': None, '$exists': True},\n 'ivd': {'$ne': None, '$exists': True},\n 'dd.id': None,}, {'wbn': 1, '_id': 0})\n\n b = conn.bags.find({\n 'cs.sl': u'{}'.format(cn),\n 'cs.ss': {'$in': EXP_BAG_STATUS_LIST},\n 'cs.pid': None,\n 'dd.id': None,}, {'bs': 1, '_id': 0})\n\n pkgs = [pkg.get('wbn') for pkg in q]\n bags = [bag.get('bs') for bag in b]\n response = pkgs + bags\n return Response(response)\n\nclass AuditInitViewSet(APIView):\n '''\n class responsible for initiating inventory\n calls 'inventory service' to create a new inventory\n triggers 'push_expected_item_nums' tasks which pushes-\n expected items nums to inventory\n '''\n authentication_classes = (SessionAuthentication, TokenAuthentication)\n permission_classes = (IsAuthenticated,)\n\n renderer_classes = (JSONRenderer, TemplateHTMLRenderer)\n\n def get(self, request, format=None):\n response = {\n 'success' : True,\n 'error' : None,\n 'data' : {}\n }\n if not has_permission(request.user):\n response['success'] = False\n response['error'] = NO_PERMISSION_RMK\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_new.html')\n\n user = request.user.username\n if not user:\n response['success'] = False\n response['error'] = 'user not specified'\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_new.html')\n\n center = request.session.get('center') or request.GET.get('center')\n if not center:\n response['success'] = False\n response['error'] = 'center not specified'\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_new.html')\n\n payload = {'center': center, 'user': user}\n try:\n res = requests.post(INV_INIT_URL, data=payload).content\n res = json.loads(res)\n except:\n response['success'] = False\n response['error'] = INV_ERROR_MSG\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_new.html')\n response['data'] = res.get('data')\n\n # ask inventory to fetch expected pkgs/bags\n uniqueid = response.get('data', {}).get('uniqueid')\n if uniqueid:\n push_expected_item_nums(url=INV_EXP_URL, uniqueid=uniqueid)\n else:\n response['success'] = False\n response['error'] = INV_ERROR_MSG\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_new.html')\n\nclass ScanViewSet(APIView):\n '''\n class responsible for scanning pkg/bags\n requires uniqueid of the inventory\n '''\n authentication_classes = (CsrfExemptSessionAuthentication, TokenAuthentication)\n permission_classes = (IsAuthenticated,)\n\n renderer_classes = (JSONRenderer, TemplateHTMLRenderer)\n def get(self, request, uniqueid, format=None):\n\n if not has_permission(request.user):\n response = {\n 'success': False,\n 'error': NO_PERMISSION_RMK\n }\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_scan.html')\n\n try:\n verbose = request.DATA.get('verbose', 1)\n except ValueError:\n verbose = 1\n payload = {'_id': uniqueid, 'verbose': verbose}\n try:\n res = requests.get(INV_SUMM_URL, data=payload).content\n res = json.loads(res)\n except:\n response = {\n 'success': False,\n 'error': INV_ERROR_MSG,\n 'uniqueid': uniqueid\n }\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_scan.html')\n\n if request.accepted_renderer.format == 'html':\n # check for error code in response\n # error code 3 - for invalid objectId\n if not res.get('success') and res.get('error', {}).get('code')==3:\n raise Http404\n if res.get('data', {}).get('cpl'):\n return HttpResponseRedirect(\n reverse('summary_inventory', args=[uniqueid]))\n\n data = res.get('data')\n fnd_items = [{'refnum': item, 'exp': True} for\\\n item in data.get('fnd_items', [])]\n uexp_items = [{'refnum': item, 'exp': False} for\\\n item in data.get('uexp_items')+data.get('ukn_items')]\n # prepare response\n response = {\n 'scanned_items': fnd_items+uexp_items,\n 'total_count': data.get('total_count'),\n 'uexp_items': len(uexp_items),\n 'uniqueid': uniqueid,\n 'center': data.get('cn'),\n 'status': 'Initiated',\n 'success': True\n }\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_scan.html')\n\n def post(self, request, uniqueid, format=None):\n response = {\n 'success': True,\n 'error': None,\n 'data': {}\n }\n\n if not has_permission(request.user):\n response['success'] = False\n response['error'] = NO_PERMISSION_RMK\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_scan.html')\n\n ref_num = request.DATA.get('ref_num')\n if not ref_num:\n response['success'] = False\n response['error'] = 'wbn not provided'\n response['data'] = {'uniqueid': uniqueid}\n return Response(response, template_name='inventory_scan.html')\n user = request.user.username\n if not user:\n response['success'] = False\n response['error'] = 'user name not provided'\n response['data'] = {'uniqueid': uniqueid}\n return Response(response, template_name='inventory_scan.html')\n\n # check for valid instance\n ukn, remark = False, ''\n exist = instance_identifier(ref_num)\n if not exist:\n ukn = True\n remark = UKN_PKG_API_REMARK\n\n payload = {'wbn': ref_num, '_id': uniqueid, 'ukn': ukn, 'u': user}\n try:\n res = requests.post(INV_SCAN_URL, data=payload).content\n res = json.loads(res)\n except:\n response['success'] = False\n response['error'] = INV_ERROR_MSG\n return Response(response, template_name='inventory_scan.html')\n if res.get('success'):\n # check for lost item\n lost = False\n result = find_by_wbns([ref_num], ['cs.nsl'])\n pkg = result.get(ref_num, {})\n if pkg.get('cs.nsl') == NSL_INV_AUDIT_MISSING_LOCK:\n lost = True\n remark = LOST_PKG_API_REMARK\n # update ukn & lost in res\n data = res.get('data')\n extra_info = {'ukn': ukn, 'lost': lost, 'remark': remark}\n data.update(extra_info)\n response['data'] = data\n else:\n response['success'] = False\n response['error'] = res.get('error', {}).get('rmk')\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_scan.html')\n\nclass AuditCompleteViewSet(APIView):\n '''\n class responsible for completing inventory\n requires inventory's uniqueid\n '''\n authentication_classes = (SessionAuthentication, TokenAuthentication)\n permission_classes = (IsAuthenticated,)\n\n renderer_classes = (JSONRenderer, TemplateHTMLRenderer)\n\n def get(self, request, uniqueid=None, format=None):\n response = {\n 'success': True,\n 'error': None,\n 'data': {}\n }\n\n if not has_permission(request.user):\n response['success'] = False\n response['error'] = NO_PERMISSION_RMK\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_complete.html')\n\n try:\n verbose = int(request.GET.get('verbose', 1))\n except ValueError as e:\n verbose = 1\n payload = {'_id': uniqueid, 'verbose': verbose}\n try:\n res = requests.post(INV_COM_URL, data=payload).content\n res = json.loads(res)\n except:\n response['success'] = False\n response['error'] = INV_ERROR_MSG\n return Response(response, template_name='inventory_complete.html')\n data = res.get('data')\n\n if res.get('success'):\n # audit lock missed items\n mis_items = res.get('data', {}).get('mis_items')\n pkg_wbns = [wbn for wbn in mis_items if not wbn.startswith('BAG')]\n package_audit_missing.delay(pkg_wbns)\n\n if request.accepted_renderer.format == 'html':\n if not res.get('success'):\n raise Http404\n return HttpResponseRedirect(\n reverse('summary_inventory', args=[uniqueid]))\n else:\n if res.get('success'):\n mis_items = data.get('mis_items')\n mis_pkgs, mis_bags = segregate_items(mis_items)\n result = {\n 'uniqueid': uniqueid,\n 'adt_count': data.get('adt'),\n 'exp_count': data.get('exp'),\n 'mis_pkgs_count': len(mis_pkgs),\n 'mis_bags_count': len(mis_bags),\n 'mis_pkgs': mis_pkgs,\n 'mis_bags': mis_bags,\n }\n response['data'] = result\n else:\n response['success'] = False\n response['error'] = res.get('error', {}).get('rmk')\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_complete.html')\n\nclass AuditSummaryViewSet(APIView):\n '''\n inventory's summary\n '''\n authentication_classes = (SessionAuthentication, TokenAuthentication)\n permission_classes = (IsAuthenticated,)\n\n renderer_classes = (JSONRenderer, TemplateHTMLRenderer)\n\n def get(self, request, uniqueid=None, format=None):\n response = {\n 'success': True,\n 'error': None,\n 'data':{}\n }\n\n if not has_permission(request.user):\n response['success'] = False\n response['error'] = NO_PERMISSION_RMK\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_summary.html')\n\n try:\n verbose = int(request.GET.get('verbose', 1))\n except ValueError:\n verbose = 1\n\n payload = {'_id': uniqueid, 'verbose': verbose}\n try:\n res = requests.get(INV_SUMM_URL, data=payload).content\n res = json.loads(res)\n except:\n response['success'] = False\n response['error'] = INV_ERROR_MSG\n return Response(response, template_name='inventory_summary.html')\n if res.get('success'):\n data = res.get('data')\n fnd_items = data.get('fnd_items', [])\n ukn_items = data.get('ukn_items', [])\n uexp_items = data.get('uexp_items', [])\n mis_items = data.get('mis_items', [])\n fnd_pkgs, fnd_bags = segregate_items(fnd_items)\n mis_pkgs, mis_bags = segregate_items(mis_items)\n extra_info = {\n 'fnd_pkgs': fnd_pkgs, 'fnd_bags': fnd_bags,\n 'mis_pkgs': mis_pkgs, 'mis_bags': mis_bags,\n 'fnd': len(fnd_items), 'uniqueid': uniqueid,\n 'users': data.get('u', [])\n }\n data.update(extra_info)\n response['data'] = data\n else:\n response['success'] = False\n response['error'] = res.get('error')\n\n return Response(response, status.HTTP_200_OK,\n template_name='inventory_summary.html')\n","sub_path":"inventory/rest_views.py","file_name":"rest_views.py","file_ext":"py","file_size_in_byte":14166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"582560788","text":"import numpy as np\nimport random\n\ndef makeA(randOr1): #coefficients of the entries of the yukawa-matrix\n\tnp.random.seed()\n\taij = np.zeros((3,3),dtype=complex)\n\tif(randOr1==0):\n\t\tfor i in range(0,3):\n\t\t\tfor j in range(0,3):\n\t\t\t\tr, phi = np.random.uniform(0.9,1.1), np.random.uniform(0,2*np.pi)\n\t\t\t\taij[i][j] = r*np.exp(phi*1j)\n\tif(randOr1==1):\n\t\tfor i in range(0,3):\n\t\t\tfor j in range(0,3):\n\t\t\t\taij[i][j] = np.random.uniform(0.9,1.1)\n\tif(randOr1==2):\n\t\tfor i in range(0,3):\n\t\t\tfor j in range(0,3):\n\t\t\t\taij[i][j] = 1\n\treturn aij\n\t\ndef makeN(di, si): #exponents of the yukawa entries\n\tnExp = np.zeros((3,3))\n\tfor i in range(0,3):\n\t\tfor j in range(0,3):\n\t\t\tnExp[i][j] = qi[i] + si[j]\t\n\treturn nExp\n\ndef makeYs(aij, di, si, eps): #producing yukawa matricies by coefficients a and charges n\n\tnExp = makeN(qi,ui)\n\tY = aij*eps**nExp \n\treturn Y\n\ndef makeVs_NumUnitary(Y): #the rotation matricies should be unitary, here computed by the recipe of the paper\n\tV_L, V_R = np.zeros((3,3),dtype=complex), np.zeros((3,3),dtype=complex)\n\tfor i in range(0,3):\n\t\tfor j in range(0,3):\n\t\t\tif(j>=i):\n\t\t\t\tV_L[i][j] = Y[i][j]/Y[j][j]\n\t\t\t\tV_R[i][j] = Y[j][i]/Y[j][j]\n\t#unitarity conditions\n\tV_L[1][0] = -np.conjugate(V_L[0][1]) - V_L[1][2]*np.conjugate(V_L[0][2])\n\tV_L[2][0] = (np.conjugate(V_L[1][2])*np.conjugate(V_L[0][1])+np.conjugate(V_L[0][2])) / (1-np.conjugate(V_L[1][0]*V_L[0][1]))\n\tV_L[2][1] = -V_L[2][0]*np.conjugate(V_L[1][0]) - np.conjugate(V_L[1][2])\n\n\tV_R[1][0] = -np.conjugate(V_R[0][1]) - V_R[1][2]*np.conjugate(V_R[0][2])\n\tV_R[2][0] = (np.conjugate(V_R[1][2])*np.conjugate(V_R[0][1])+np.conjugate(V_R[0][2])) / (1-np.conjugate(V_R[1][0]*V_R[0][1]))\n\tV_R[2][1] = -V_R[2][0]*np.conjugate(V_R[1][0]) - np.conjugate(V_R[1][2])\n\n#\tV_L, V_R = normaliseVCols(V_L), normaliseVCols(V_R)\n\treturn V_L, V_R\n\ndef makeVs_AnaBidiag(Y): #the rotation matricies should be unitary, here computed analytically by bidiagonalisation (U* MM* U = M2diag)\n\tV_L, V_R = np.zeros((3,3),dtype=complex), np.zeros((3,3),dtype=complex)\n\tYnt = Y.dot(Y.transpose().conjugate()) #used for V_L\n\tYtn = Y.transpose().conjugate().dot(Y) #used for V_R\n\tevYnt, evYtn = np.linalg.eig(Ynt)[1], np.linalg.eig(Ytn)[1]\n\tfor i in range(0,3): #swap columns to get the O(1) entries at the diagonal\n\t\tV_L[i][0] = evYnt[i][1]\n\t\tV_L[i][1] = evYnt[i][2]\n\t\tV_L[i][2] = evYnt[i][0]\n\t\tV_R[i][0] = evYtn[i][1]\n\t\tV_R[i][1] = evYtn[i][2]\n\t\tV_R[i][2] = evYtn[i][0]\n\treturn V_L, V_R\n\ndef make_AnaDiag(m):\n\tP = np.zeros((3,3))\n\tev = np.linalg.eig(m)[1]\n\tfor i in range(0,3):\n\t\tP[i][0] = ev[i][1]\n\t\tP[i][1] = ev[i][2]\n\t\tP[i][2] = ev[i][0]\n\treturn P\n\ndef checkDiag(V_L, Y, V_R):\n\treturn np.transpose(V_L).dot(Y).dot(V_R) #should return an (almost) diagonal yukawa matrix\n\ndef det(V): #determinant to prove another property of unitary matricies\n\tprint(np.absolute(np.linalg.det(V)))\n\ndef normaliseVCols(V): #in case of degenerate charges (as for Vd_R here) the columns have to be normalised so that V becomes unitary\n\tnorm = np.zeros((3))\n\tfor j in range(0,3):\n\t\tfor i in range(0,3):\n\t\t\tnorm[j] += V[i][j]**2\n\tnorm = np.sqrt(norm)\n\tfor j in range(0,3):\t\n\t\tfor i in range(0,3):\n\t\t\tV[i][j] = 1/norm[j] * V[i][j]\n\tprint(norm)\n\treturn V\n\t\ndef printVs(Vu_L, Vu_R, Vd_L, Vd_R, Vl_L, Vl_R, nOra):\n\tprint(\"#######Rotmatrices######\")\n\tprint(\"######%s#######\") % (nOra)\n\tprint(np.absolute(Vu_L))\n\tprint(np.absolute(Vu_R))\n\tprint(np.absolute(Vd_L))\n\tprint(np.absolute(Vd_R))\n\tprint(np.absolute(Vl_L))\n\tprint(np.absolute(Vl_R))\n\tprint(\"************************\")\n\ndef printYnorm(Yu, Yd, Yl, nOra):\n\tprint(\"#######Ynorm######\")\n\tprint(\"######%s#######\") % (nOra)\n\tprint(np.absolute(Yu))\n\tprint(np.absolute(Yd))\n\tprint(np.absolute(Yl))\n\tprint(\"************************\")\n\ndef printVdet(vul,vur,vdl,vdr,vll,vlr,nOra):\n\tprint(\"######Determinants####\")\n\tprint(\"######%s#######\") % (nOra)\n\tdet(vul),det(vur),det(vdl),det(vdr),det(vll),det(vlr)\n\tprint(\"************************\")\n\ndef func(A_ass, eps, qi, ui, di, li, ei): #main function\n\taiju, aijd, aijl = makeA(A_ass), makeA(A_ass), makeA(A_ass)\n\tYu, Yd, Yl = makeYs(aiju,qi,ui,eps),makeYs(aijd,qi,di,eps),makeYs(aijl,li,ei,eps)\n\n\t####paper####\n\tVu_Lnum, Vu_Rnum = makeVs_NumUnitary(Yu)\n\tVd_Lnum, Vd_Rnum = makeVs_NumUnitary(Yd)\n\tVl_Lnum, Vl_Rnum = makeVs_NumUnitary(Yl)\n\tYuNorm_num = checkDiag(Vu_Lnum, Yu, Vu_Rnum)\n\tYdNorm_num = checkDiag(Vd_Lnum, Yd, Vd_Rnum)\n\tYlNorm_num = checkDiag(Vl_Lnum, Yl, Vl_Rnum)\n\t\t\n\t####mathematics####\n\tVu_Lana, Vu_Rana = makeVs_AnaBidiag(Yu)\n\tVd_Lana, Vd_Rana = makeVs_AnaBidiag(Yd)\n\tVl_Lana, Vl_Rana = makeVs_AnaBidiag(Yl)\n\tYuNorm_ana = checkDiag(Vu_Lana, Yu, Vu_Rana)\n\tYdNorm_ana = checkDiag(Vd_Lana, Yd, Vd_Rana)\n\tYlNorm_ana = checkDiag(Vl_Lana, Yl, Vl_Rana)\n\n\t####printresults####\n\tprint(\"always uL, uR, dL, dR\")\n\tprintVdet(Vu_Lana,Vu_Rana,Vd_Lana,Vd_Rana,Vl_Lana,Vl_Lana,\"ana\")\n\tprintVdet(Vu_Lnum,Vu_Rnum,Vd_Lnum,Vd_Rnum,Vl_Lnum,Vl_Rnum,'num')\n\tprintVs(Vu_Lana,Vu_Rana,Vd_Lana,Vd_Rana,Vl_Lana,Vl_Rana,'ana')\n\tprintVs(Vu_Lnum,Vu_Rnum,Vd_Lnum,Vd_Rnum,Vl_Lnum,Vl_Rnum,'num')\n\tprintYnorm(YuNorm_ana, YdNorm_ana,YlNorm_ana, 'ana')\n\tprintYnorm(YuNorm_num, YdNorm_num,YlNorm_num, 'num')\n\n##############################\n######## assignments #########\n##############################\nqi = np.array([3,2,0]) #charges under the U(1)_F symmetry for quark doublets\nui = np.array([3,2,0]) #up-type singlets\ndi = np.array([4,2,2]) #down-type singlets\nli = np.array([3,1,0]) #lepton doublets\nei = np.array([5,4,3]) #charged lepton singlets\n\nYukPrefactor = 0 #0complex(generic), 1real, 2unity\nexpansion = 0.2 #Cabibbo parameter\n\n######\nxi, m = np.zeros((3,3)), np.zeros((3,3))\nm[0][0] = 8\nm[0][1] = 5\nm[0][2] = 6\nm[1][0] = 5\nm[1][1] = 4\nm[1][2] = 4\nm[2][0] = 6\nm[2][1] = 4\nm[2][2] = 2\nm = expansion**m\n\nxi[0][1] =1\nxi[1][0] =1\n\n\nprint(m)\np = make_AnaDiag(m)\nVl, Vr = makeVs_AnaBidiag(m)\nprint(np.linalg.eig(m)[0])\nprint(Vl)\nprint(Vr)\nprint(checkDiag(Vl, m, Vr))\nprint(xi)\nprint(Vl.dot(xi).dot(Vr.transpose()))\nprint(Vl.transpose().dot(xi).dot(Vr))\n\n\n\n\n\n#func(YukPrefactor, expansion, qi, ui, di, li, ei) \n\n#EOP\n","sub_path":"calc/pythoncalc/yukawaFINAL.py","file_name":"yukawaFINAL.py","file_ext":"py","file_size_in_byte":5994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"512256580","text":"from django import template\nfrom familytree.models import FamilyMember, Marriage\n\nregister = template.Library()\n\n\n@register.filter\ndef nested_to_flat(nodes):\n if isinstance(nodes, list):\n yield {'start_nodes': True}\n for node in nodes:\n yield {'start_node': True}\n for i in nested_to_flat(node):\n yield i\n yield {'end_node': True}\n yield {'end_nodes': True}\n else:\n yield {'data': nodes, 'is_data': True}","sub_path":"familytree/templatetags/familytree_tags.py","file_name":"familytree_tags.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"236560008","text":"# import smtplib as smtp\n#\n# my_email = \"someoneanonymous475@gmail.com\"\n#\n# with smtp.SMTP_SSL(\"smtp.gmail.com\", 465) as connection:\n# connection.login(user=my_email, password=\"Sp1d#rweb\")\n# connection.sendmail(\n# from_addr=my_email,\n# to_addrs=\"rodermus@yahoo.com\",\n# msg=\"Subject:Hello\\n\\nThis is the body of the email\")\n\n\nimport datetime as dt\n\nnow = dt.datetime.now()\nyear = now.year\nprint(now.weekday())\n\ndate_of_birth = dt.datetime(year=1991, month=2, day=26, hour=17, minute=30)\nprint(date_of_birth)\n","sub_path":"Day32/day-32-start/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"348239780","text":"\"\"\"Reads line score data.\n\nThis gives us the scores and possession status for every game at once, se we can\ndecide which box scores to refresh next.\n\"\"\"\n\nimport collections\nimport datetime\nimport json\nimport sys\nimport urllib.request\n\n\n_SCORES_URL = 'https://feeds.nfl.com/feeds-rs/scores.json'\n\n\nGame = collections.namedtuple(\n 'Game',\n ('id', 'home', 'hscore', 'away', 'ascore', 'poss', 'start_time', 'clock',\n 'alert', 'is_over'))\nGame.__doc__ = \"\"\"The score and schedule for a game.\n\nAttributes:\n id: The game ID.\n home: The home team abbreviation, e.g., 'ATL'.\n away: The away team abbreviation, e.g., 'NE'.\n hscore: The home team's score. None if the game hasn't started.\n Otherwise, an integer, such as 28.\n ascore: The away team's score. None if the game hasn't started.\n Otherwise, an integer, such as 3.\n poss: The team that currently has possession. This is either the home team,\n the away team, or the empty string if nobody has possession (the game is\n over, it's halftime, etc.).\n start_time: The start time of the game, as a datetime.datetime.\n clock: Number of seconds elapsed on the game clock since the start of the\n game. 0 if the game hasn't started. This value is not well-defined if\n the game is over. Check is_over instead.\n alert: A \"big play\" that just happened. Usually the empty string, but is\n populated for a few minutes after a major event. Known values include:\n FG, FOURTH_FAIL, FUM_LOST, INT, PAT, TD\n is_over: Whether this game is over.\n\"\"\"\n\n\ndef parse_game_json(json_obj):\n sched = json_obj.get('gameSchedule')\n score = json_obj.get('score')\n game_id = str(sched['gameId'])\n home_team = sched['homeTeamAbbr']\n away_team = sched['visitorTeamAbbr']\n if score:\n home_score = score['homeTeamScore']['pointTotal']\n away_score = score['visitorTeamScore']['pointTotal']\n poss = score['possessionTeamAbbr'] or ''\n clock = parse_game_clock(score['phase'], score['time'])\n alert = score['alertPlayType'] or ''\n is_over = score['phase'].upper() == 'FINAL'\n else:\n home_score = None\n away_score = None\n poss = ''\n clock = 0\n alert = ''\n is_over = False\n start_time = datetime.datetime.fromtimestamp(sched['isoTime'] / 1000)\n return Game(id=game_id,\n home=home_team,\n away=away_team,\n hscore=home_score,\n ascore=away_score,\n poss=poss,\n start_time=start_time,\n clock=clock,\n alert=alert,\n is_over=is_over)\n\n\ndef parse_game_clock(phase, clock):\n \"\"\"Parses the game clock.\n\n Args:\n phase: The phase of the game, e.g., 'Q1', 'Q3', 'FINAL'. Not sure what\n overtime is, but it's probably 'OT'.\n clock: The current game clock, as a string, e.g., '03:28'.\n Returns:\n The number of seconds elapsed on the game clock since the start of the\n game. For example, 920 means the clock shows 14:40 in the 2nd quarter.\n If the game is over, returns some large value.\n \"\"\"\n if not clock:\n return 0\n # TODO: Find out what the phase is for overtime. Also, whether overtime\n # finals are shown differently ('F/OT'?)\n if phase.upper() == 'FINAL':\n # Larger than any regulation game (5 quarters at most).\n return 5 * 900 + 1\n if phase.upper() == 'HALFTIME':\n return 1800\n if phase.upper() in ('Q1', 'Q2', 'Q3', 'Q4'):\n qnum = int(phase[1])\n elif phase.upper() == 'OT':\n qnum = 5\n else:\n # Unknown phase.\n return 0\n if ':' not in clock:\n # Unknown clock format.\n return 0\n try:\n mm_str, ss_str = clock.split(':')\n mm = int(mm_str)\n ss = int(ss_str)\n except ValueError:\n return 0\n clock_secs = 60 * mm + ss\n return qnum * 900 - clock_secs\n\n\ndef fetch(url=_SCORES_URL):\n \"\"\"Get line scores for whatever the current week is.\n\n Returns:\n (season, week, games)\n games is a dict mapping game IDs to Games. Each game's ID is unique, and\n is constant between fetches, so you can compare Games fetched at\n different times.\n \"\"\"\n raw = urllib.request.urlopen(url).read()\n data = json.loads(str(raw, 'utf-8'))\n scores = data.get('gameScores')\n if not scores:\n return {}\n games = {}\n for obj in scores:\n game = parse_game_json(obj)\n games[game.id] = game\n week = data['week']\n if data['seasonType'] == 'PRE':\n week = 'P{0}'.format(week)\n return data['season'], week, games\n","sub_path":"nfl_scraper/linescore.py","file_name":"linescore.py","file_ext":"py","file_size_in_byte":4689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"116382538","text":"from expdj.apps.turk.views import edit_hit, delete_hit, expire_hit, serve_hit, \\\n multiple_new_hit, sync, end_assignment, finished_view\nfrom django.views.generic.base import TemplateView\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns('',\n # HITS\n url(r'^hits/(?P\\d+|[A-Z]{8})/new$',edit_hit,name='new_hit'),\n url(r'^hits/(?P\\d+|[A-Z]{8})/multiple$',multiple_new_hit,name='multiple_new_hit'),\n url(r'^hits/(?P\\d+|[A-Z]{8})/(?P\\d+|[A-Z]{8})/edit$',edit_hit,name='edit_hit'),\n url(r'^hits/(?P\\d+|[A-Z]{8})/delete$',delete_hit,name='delete_hit'),\n url(r'^hits/(?P\\d+|[A-Z]{8})/expire$',expire_hit,name='expire_hit'),\n\n # Turk Deployments\n url(r'^turk/(?P\\d+|[A-Z]{8})',serve_hit,name='serve_hit'),\n url(r'^turk/end/(?P\\d+|[A-Z]{8})',end_assignment,name='end_assignment'),\n url(r'^sync/(?P\\d+|[A-Z]{8})/$',sync,name='sync_data'),\n url(r'^sync/$',sync,name='sync_data'),\n url(r'^finished$', finished_view, name=\"finished_view\")\n)\n","sub_path":"expdj/apps/turk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"649052821","text":"#! /usr/bin/env python\n\nimport os, sys\n\ntry:\n\tfrom setuptools import setup\n\textra_kwargs = {\n\t\t\"test_suite\": \"ufoLib.test\"\n\t}\nexcept ImportError:\n\tfrom distutils.core import setup\n\textra_kwargs = {}\n\ntry:\n\timport fontTools\nexcept ImportError:\n\tprint(\"*** Warning: ufoLib needs FontTools for some operations, see:\")\n\tprint(\" https://github.com/behdad/fonttools\")\n\n\nlong_description = \"\"\"\\\nufoLib reads and writes Unified Font Object (UFO) files. UFO is a file format\nthat stores fonts source files.\n\"\"\"\n\nsetup(\n\t\tname = \"ufoLib\",\n\t\tversion = \"1.2\",\n\t\tdescription = \"A low-level UFO reader and writer.\",\n\t\tauthor = \"Just van Rossum, Tal Leming, Erik van Blokland, others\",\n\t\tauthor_email = \"info@robofab.com\",\n\t\tmaintainer = \"Just van Rossum, Tal Leming, Erik van Blokland\",\n\t\tmaintainer_email = \"info@robofab.com\",\n\t\turl = \"http://unifiedfontobject.org\",\n\t\tlicense = \"OpenSource, BSD-style\",\n\t\tplatforms = [\"Any\"],\n\t\tlong_description = long_description,\n\n\t\tpackages = [\n\t\t\t\"ufoLib\",\n\t\t],\n\t\tpackage_dir = {'': 'Lib'},\n\t\tclassifiers = [\n\t\t\t\"Development Status :: 4 - Beta\",\n\t\t\t\"Environment :: Console\",\n\t\t\t\"Environment :: Other Environment\",\n\t\t\t\"Intended Audience :: Developers\",\n\t\t\t\"Intended Audience :: End Users/Desktop\",\n\t\t\t\"License :: OSI Approved :: BSD License\",\n\t\t\t\"Natural Language :: English\",\n\t\t\t\"Operating System :: OS Independent\",\n\t\t\t\"Programming Language :: Python\",\n\t\t\t\"Topic :: Multimedia :: Graphics\",\n\t\t\t\"Topic :: Multimedia :: Graphics :: Graphics Conversion\",\n\t\t],\n\t\t**extra_kwargs\n\t)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"314769442","text":"import sys, pygame\nimport random\nimport numpy as np\nrandom.seed = 42\n\n\nclass Lifegame ():\n \n def __init__(self, screen_width = 800, screen_height=600, cell_size = 10, alive_color = (255,0,0), fps = 30):\n \"\"\"init Lifegame Class\n\n Args:\n screen_width (int, optional): Defaults to 800.\n screen_height (int, optional): Defaults to 600.\n cell_size (int, optional): Circle diameter. Defaults to 10.\n alive_color (tuple, optional): Color of alive cells. Defaults to (255,0,0).\n fps (int, optional): frames per seconds. Defaults to 30.\n \"\"\"\n self.game_over = False\n self.FPS = fps\n self.BOARDER_SIZE = self.WIDTH, self.HEIGHT = screen_width, screen_width\n self.CELL_SIZE = cell_size\n self.DEAD_COLOR = 0, 0, 0\n self.ALIVE_COLOR = alive_color\n self.COLORS = {0 : self.DEAD_COLOR, 1: self.ALIVE_COLOR}\n pygame.init()\n self.screen = pygame.display.set_mode(self.BOARDER_SIZE)\n self.init_grids()\n self.clear_screen()\n self.clock = pygame.time.Clock()\n self.paused = False\n pygame.display.flip()\n\n def init_grids(self):\n \"\"\"initilize the defalut grid to inactive cells\n \"\"\"\n self.num_cols = self.WIDTH // self.CELL_SIZE\n self.num_rows = self.HEIGHT // self.CELL_SIZE\n print (f'Columns: {self.num_cols}, Rows: {self.num_rows}')\n self.grids = ([[0 for x in range(self.num_cols)] for y in range (self.num_rows)],\n [[0 for x in range(self.num_cols)] for y in range (self.num_rows)])\n self.active_grid = 0\n self.game_grid_inactive = []\n self.set_grid()\n\n \n def set_grid (self,value = None):\n \"\"\"\n set an entire grid at once, wither single value or random 0/1\n example : \n set_grid(0) - All dead\n set_grid(1) - All alive\n set_grid() - all random\n\n Args:\n value ([int], optional): [set the value of the grid]. Defaults to None.\n \"\"\" \n for col in range(self.num_cols):\n for row in range(self.num_rows):\n if value == None :\n cell_value = random.choice([0,1])\n else :\n cell_value = value\n self.grids[self.active_grid][row][col] = cell_value\n def clear_screen (self):\n \"\"\"Clear current screen\n \"\"\"\n self.screen.fill(self.DEAD_COLOR) \n \n def check_cell_neighbors (self,row,col,grid):\n \"\"\"Check the status of nearby cells.\n\n Args:\n row ([int]): [index of current row]\n col ([int]): [index of current col]\n grid ([list]): [current active grid]\n\n Returns:\n [int]: [number of alive nighbors]\n \"\"\"\n x_min = max (0,col-1)\n x_max = min (self.num_cols-1,col+1)\n y_min = max (0,row-1)\n y_max = min (self.num_rows-1,row+1)\n return (np.sum([grid[a][x_min:x_max+1] for a in range (y_min,y_max+1)]) - grid[row][col])\n \n def update_generation(self):\n '''\n Inspect the current active generation\n Update the inactive grid to store the next gen\n swap out the active grid\n '''\n # Inspect the current active generation, prepare the next generation\n for row in range(self.num_rows):\n for col in range(self.num_cols):\n nighbors = self.check_cell_neighbors (row,col,self.grids[self.active_grid])\n status = 0 if nighbors < 2 or nighbors >3 else 1\n if self.grids[self.active_grid][row][col]==0 and nighbors == 2: status = 0\n self.grids[self.inactive_grid()][row][col] = status\n self.active_grid= self.inactive_grid()\n \n def inactive_grid(self):\n \"\"\"inactive current grid\n\n Returns:\n [int]: [index of the current inactive grid (0,1)]\n \"\"\"\n return (self.active_grid+1) %2\n\n def draw_grid(self):\n \"\"\"Draw the grid by grids status\n \"\"\"\n for c in range (self.num_cols):\n for r in range (self.num_rows): \n pygame.draw.circle(self.screen, \n self.COLORS[self.grids[self.active_grid][r][c]], \n (c* self.CELL_SIZE + self.CELL_SIZE//2, r * self.CELL_SIZE + self.CELL_SIZE//2), \n self.CELL_SIZE//2, \n 0)\n pygame.display.flip()\n\n\n def handle_events(self):\n \"\"\"handle games events\n \"\"\"\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.unicode == 'p':\n if self.paused:\n self.paused=False\n else:\n self.paused=True\n \n elif event.unicode =='r':\n self.set_grid()\n elif event.unicode =='q':\n self.game_over = True\n \n #if event is keypressed of \"p\" then toggle game pause\n #if event is keypressed of \"r\" then randomize grid\n #if event is keypressed of \"q\" then quit\n\n if event.type == pygame.QUIT: \n self.game_over = True\n # sys.exit()\n\n self.screen.fill(self.DEAD_COLOR)\n # screen.blit(ball, ballrect)\n \n def run(self):\n \"\"\"Run the game\n \"\"\"\n\n while True:\n if self.game_over: return\n self.clock.tick(self.FPS)\n self.handle_events()\n if self.paused : continue\n self.draw_grid()\n self.update_generation()\n # print (self.grids[self.active_grid][0][:30])\n\n\n\nif __name__==\"__main__\":\n game = Lifegame()\n game.run()\n\n","sub_path":"pygameoflife/LifeGame.py","file_name":"LifeGame.py","file_ext":"py","file_size_in_byte":5908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"450985433","text":"# coding: utf-8\n\n\"\"\"\n Talon.One API\n\n Use the Talon.One API to integrate with your application and to manage applications and campaigns: - Use the operations in the [Integration API section](#integration-api) are used to integrate with our platform - Use the operation in the [Management API section](#management-api) to manage applications and campaigns. ## Determining the base URL of the endpoints The API is available at the same hostname as your Campaign Manager deployment. For example, if you access the Campaign Manager at `https://yourbaseurl.talon.one/`, the URL for the [updateCustomerSessionV2](https://docs.talon.one/integration-api#operation/updateCustomerSessionV2) endpoint is `https://yourbaseurl.talon.one/v2/customer_sessions/{Id}` # noqa: E501\n\n The version of the OpenAPI document: \n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom talon_one.configuration import Configuration\n\n\nclass InventoryCoupon(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'id': 'int',\n 'created': 'datetime',\n 'campaign_id': 'int',\n 'value': 'str',\n 'usage_limit': 'int',\n 'discount_limit': 'float',\n 'reservation_limit': 'int',\n 'start_date': 'datetime',\n 'expiry_date': 'datetime',\n 'limits': 'list[LimitConfig]',\n 'usage_counter': 'int',\n 'discount_counter': 'float',\n 'discount_remainder': 'float',\n 'reservation_counter': 'float',\n 'attributes': 'object',\n 'referral_id': 'int',\n 'recipient_integration_id': 'str',\n 'import_id': 'int',\n 'reservation': 'bool',\n 'batch_id': 'str',\n 'is_reservation_mandatory': 'bool',\n 'profile_redemption_count': 'int',\n 'state': 'str'\n }\n\n attribute_map = {\n 'id': 'id',\n 'created': 'created',\n 'campaign_id': 'campaignId',\n 'value': 'value',\n 'usage_limit': 'usageLimit',\n 'discount_limit': 'discountLimit',\n 'reservation_limit': 'reservationLimit',\n 'start_date': 'startDate',\n 'expiry_date': 'expiryDate',\n 'limits': 'limits',\n 'usage_counter': 'usageCounter',\n 'discount_counter': 'discountCounter',\n 'discount_remainder': 'discountRemainder',\n 'reservation_counter': 'reservationCounter',\n 'attributes': 'attributes',\n 'referral_id': 'referralId',\n 'recipient_integration_id': 'recipientIntegrationId',\n 'import_id': 'importId',\n 'reservation': 'reservation',\n 'batch_id': 'batchId',\n 'is_reservation_mandatory': 'isReservationMandatory',\n 'profile_redemption_count': 'profileRedemptionCount',\n 'state': 'state'\n }\n\n def __init__(self, id=None, created=None, campaign_id=None, value=None, usage_limit=None, discount_limit=None, reservation_limit=None, start_date=None, expiry_date=None, limits=None, usage_counter=None, discount_counter=None, discount_remainder=None, reservation_counter=None, attributes=None, referral_id=None, recipient_integration_id=None, import_id=None, reservation=True, batch_id=None, is_reservation_mandatory=True, profile_redemption_count=None, state=None, local_vars_configuration=None): # noqa: E501\n \"\"\"InventoryCoupon - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._id = None\n self._created = None\n self._campaign_id = None\n self._value = None\n self._usage_limit = None\n self._discount_limit = None\n self._reservation_limit = None\n self._start_date = None\n self._expiry_date = None\n self._limits = None\n self._usage_counter = None\n self._discount_counter = None\n self._discount_remainder = None\n self._reservation_counter = None\n self._attributes = None\n self._referral_id = None\n self._recipient_integration_id = None\n self._import_id = None\n self._reservation = None\n self._batch_id = None\n self._is_reservation_mandatory = None\n self._profile_redemption_count = None\n self._state = None\n self.discriminator = None\n\n self.id = id\n self.created = created\n self.campaign_id = campaign_id\n self.value = value\n self.usage_limit = usage_limit\n if discount_limit is not None:\n self.discount_limit = discount_limit\n if reservation_limit is not None:\n self.reservation_limit = reservation_limit\n if start_date is not None:\n self.start_date = start_date\n if expiry_date is not None:\n self.expiry_date = expiry_date\n if limits is not None:\n self.limits = limits\n self.usage_counter = usage_counter\n if discount_counter is not None:\n self.discount_counter = discount_counter\n if discount_remainder is not None:\n self.discount_remainder = discount_remainder\n if reservation_counter is not None:\n self.reservation_counter = reservation_counter\n if attributes is not None:\n self.attributes = attributes\n if referral_id is not None:\n self.referral_id = referral_id\n if recipient_integration_id is not None:\n self.recipient_integration_id = recipient_integration_id\n if import_id is not None:\n self.import_id = import_id\n if reservation is not None:\n self.reservation = reservation\n if batch_id is not None:\n self.batch_id = batch_id\n if is_reservation_mandatory is not None:\n self.is_reservation_mandatory = is_reservation_mandatory\n self.profile_redemption_count = profile_redemption_count\n self.state = state\n\n @property\n def id(self):\n \"\"\"Gets the id of this InventoryCoupon. # noqa: E501\n\n Internal ID of this entity. # noqa: E501\n\n :return: The id of this InventoryCoupon. # noqa: E501\n :rtype: int\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this InventoryCoupon.\n\n Internal ID of this entity. # noqa: E501\n\n :param id: The id of this InventoryCoupon. # noqa: E501\n :type: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and id is None: # noqa: E501\n raise ValueError(\"Invalid value for `id`, must not be `None`\") # noqa: E501\n\n self._id = id\n\n @property\n def created(self):\n \"\"\"Gets the created of this InventoryCoupon. # noqa: E501\n\n The time this entity was created. # noqa: E501\n\n :return: The created of this InventoryCoupon. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._created\n\n @created.setter\n def created(self, created):\n \"\"\"Sets the created of this InventoryCoupon.\n\n The time this entity was created. # noqa: E501\n\n :param created: The created of this InventoryCoupon. # noqa: E501\n :type: datetime\n \"\"\"\n if self.local_vars_configuration.client_side_validation and created is None: # noqa: E501\n raise ValueError(\"Invalid value for `created`, must not be `None`\") # noqa: E501\n\n self._created = created\n\n @property\n def campaign_id(self):\n \"\"\"Gets the campaign_id of this InventoryCoupon. # noqa: E501\n\n The ID of the campaign that owns this entity. # noqa: E501\n\n :return: The campaign_id of this InventoryCoupon. # noqa: E501\n :rtype: int\n \"\"\"\n return self._campaign_id\n\n @campaign_id.setter\n def campaign_id(self, campaign_id):\n \"\"\"Sets the campaign_id of this InventoryCoupon.\n\n The ID of the campaign that owns this entity. # noqa: E501\n\n :param campaign_id: The campaign_id of this InventoryCoupon. # noqa: E501\n :type: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and campaign_id is None: # noqa: E501\n raise ValueError(\"Invalid value for `campaign_id`, must not be `None`\") # noqa: E501\n\n self._campaign_id = campaign_id\n\n @property\n def value(self):\n \"\"\"Gets the value of this InventoryCoupon. # noqa: E501\n\n The coupon code. # noqa: E501\n\n :return: The value of this InventoryCoupon. # noqa: E501\n :rtype: str\n \"\"\"\n return self._value\n\n @value.setter\n def value(self, value):\n \"\"\"Sets the value of this InventoryCoupon.\n\n The coupon code. # noqa: E501\n\n :param value: The value of this InventoryCoupon. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and value is None: # noqa: E501\n raise ValueError(\"Invalid value for `value`, must not be `None`\") # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n value is not None and len(value) < 4):\n raise ValueError(\"Invalid value for `value`, length must be greater than or equal to `4`\") # noqa: E501\n\n self._value = value\n\n @property\n def usage_limit(self):\n \"\"\"Gets the usage_limit of this InventoryCoupon. # noqa: E501\n\n The number of times the coupon code can be redeemed. `0` means unlimited redemptions but any campaign usage limits will still apply. # noqa: E501\n\n :return: The usage_limit of this InventoryCoupon. # noqa: E501\n :rtype: int\n \"\"\"\n return self._usage_limit\n\n @usage_limit.setter\n def usage_limit(self, usage_limit):\n \"\"\"Sets the usage_limit of this InventoryCoupon.\n\n The number of times the coupon code can be redeemed. `0` means unlimited redemptions but any campaign usage limits will still apply. # noqa: E501\n\n :param usage_limit: The usage_limit of this InventoryCoupon. # noqa: E501\n :type: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and usage_limit is None: # noqa: E501\n raise ValueError(\"Invalid value for `usage_limit`, must not be `None`\") # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n usage_limit is not None and usage_limit > 999999): # noqa: E501\n raise ValueError(\"Invalid value for `usage_limit`, must be a value less than or equal to `999999`\") # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n usage_limit is not None and usage_limit < 0): # noqa: E501\n raise ValueError(\"Invalid value for `usage_limit`, must be a value greater than or equal to `0`\") # noqa: E501\n\n self._usage_limit = usage_limit\n\n @property\n def discount_limit(self):\n \"\"\"Gets the discount_limit of this InventoryCoupon. # noqa: E501\n\n The total discount value that the code can give. Typically used to represent a gift card value. # noqa: E501\n\n :return: The discount_limit of this InventoryCoupon. # noqa: E501\n :rtype: float\n \"\"\"\n return self._discount_limit\n\n @discount_limit.setter\n def discount_limit(self, discount_limit):\n \"\"\"Sets the discount_limit of this InventoryCoupon.\n\n The total discount value that the code can give. Typically used to represent a gift card value. # noqa: E501\n\n :param discount_limit: The discount_limit of this InventoryCoupon. # noqa: E501\n :type: float\n \"\"\"\n if (self.local_vars_configuration.client_side_validation and\n discount_limit is not None and discount_limit > 999999): # noqa: E501\n raise ValueError(\"Invalid value for `discount_limit`, must be a value less than or equal to `999999`\") # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n discount_limit is not None and discount_limit < 0): # noqa: E501\n raise ValueError(\"Invalid value for `discount_limit`, must be a value greater than or equal to `0`\") # noqa: E501\n\n self._discount_limit = discount_limit\n\n @property\n def reservation_limit(self):\n \"\"\"Gets the reservation_limit of this InventoryCoupon. # noqa: E501\n\n The number of reservations that can be made with this coupon code. # noqa: E501\n\n :return: The reservation_limit of this InventoryCoupon. # noqa: E501\n :rtype: int\n \"\"\"\n return self._reservation_limit\n\n @reservation_limit.setter\n def reservation_limit(self, reservation_limit):\n \"\"\"Sets the reservation_limit of this InventoryCoupon.\n\n The number of reservations that can be made with this coupon code. # noqa: E501\n\n :param reservation_limit: The reservation_limit of this InventoryCoupon. # noqa: E501\n :type: int\n \"\"\"\n if (self.local_vars_configuration.client_side_validation and\n reservation_limit is not None and reservation_limit > 999999): # noqa: E501\n raise ValueError(\"Invalid value for `reservation_limit`, must be a value less than or equal to `999999`\") # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n reservation_limit is not None and reservation_limit < 0): # noqa: E501\n raise ValueError(\"Invalid value for `reservation_limit`, must be a value greater than or equal to `0`\") # noqa: E501\n\n self._reservation_limit = reservation_limit\n\n @property\n def start_date(self):\n \"\"\"Gets the start_date of this InventoryCoupon. # noqa: E501\n\n Timestamp at which point the coupon becomes valid. # noqa: E501\n\n :return: The start_date of this InventoryCoupon. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._start_date\n\n @start_date.setter\n def start_date(self, start_date):\n \"\"\"Sets the start_date of this InventoryCoupon.\n\n Timestamp at which point the coupon becomes valid. # noqa: E501\n\n :param start_date: The start_date of this InventoryCoupon. # noqa: E501\n :type: datetime\n \"\"\"\n\n self._start_date = start_date\n\n @property\n def expiry_date(self):\n \"\"\"Gets the expiry_date of this InventoryCoupon. # noqa: E501\n\n Expiration date of the coupon. Coupon never expires if this is omitted, zero, or negative. # noqa: E501\n\n :return: The expiry_date of this InventoryCoupon. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._expiry_date\n\n @expiry_date.setter\n def expiry_date(self, expiry_date):\n \"\"\"Sets the expiry_date of this InventoryCoupon.\n\n Expiration date of the coupon. Coupon never expires if this is omitted, zero, or negative. # noqa: E501\n\n :param expiry_date: The expiry_date of this InventoryCoupon. # noqa: E501\n :type: datetime\n \"\"\"\n\n self._expiry_date = expiry_date\n\n @property\n def limits(self):\n \"\"\"Gets the limits of this InventoryCoupon. # noqa: E501\n\n Limits configuration for a coupon. These limits will override the limits set from the campaign. **Note:** Only usable when creating a single coupon which is not tied to a specific recipient. Only per-profile limits are allowed to be configured. # noqa: E501\n\n :return: The limits of this InventoryCoupon. # noqa: E501\n :rtype: list[LimitConfig]\n \"\"\"\n return self._limits\n\n @limits.setter\n def limits(self, limits):\n \"\"\"Sets the limits of this InventoryCoupon.\n\n Limits configuration for a coupon. These limits will override the limits set from the campaign. **Note:** Only usable when creating a single coupon which is not tied to a specific recipient. Only per-profile limits are allowed to be configured. # noqa: E501\n\n :param limits: The limits of this InventoryCoupon. # noqa: E501\n :type: list[LimitConfig]\n \"\"\"\n\n self._limits = limits\n\n @property\n def usage_counter(self):\n \"\"\"Gets the usage_counter of this InventoryCoupon. # noqa: E501\n\n The number of times the coupon has been successfully redeemed. # noqa: E501\n\n :return: The usage_counter of this InventoryCoupon. # noqa: E501\n :rtype: int\n \"\"\"\n return self._usage_counter\n\n @usage_counter.setter\n def usage_counter(self, usage_counter):\n \"\"\"Sets the usage_counter of this InventoryCoupon.\n\n The number of times the coupon has been successfully redeemed. # noqa: E501\n\n :param usage_counter: The usage_counter of this InventoryCoupon. # noqa: E501\n :type: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and usage_counter is None: # noqa: E501\n raise ValueError(\"Invalid value for `usage_counter`, must not be `None`\") # noqa: E501\n\n self._usage_counter = usage_counter\n\n @property\n def discount_counter(self):\n \"\"\"Gets the discount_counter of this InventoryCoupon. # noqa: E501\n\n The amount of discounts given on rules redeeming this coupon. Only usable if a coupon discount budget was set for this coupon. # noqa: E501\n\n :return: The discount_counter of this InventoryCoupon. # noqa: E501\n :rtype: float\n \"\"\"\n return self._discount_counter\n\n @discount_counter.setter\n def discount_counter(self, discount_counter):\n \"\"\"Sets the discount_counter of this InventoryCoupon.\n\n The amount of discounts given on rules redeeming this coupon. Only usable if a coupon discount budget was set for this coupon. # noqa: E501\n\n :param discount_counter: The discount_counter of this InventoryCoupon. # noqa: E501\n :type: float\n \"\"\"\n\n self._discount_counter = discount_counter\n\n @property\n def discount_remainder(self):\n \"\"\"Gets the discount_remainder of this InventoryCoupon. # noqa: E501\n\n The remaining discount this coupon can give. # noqa: E501\n\n :return: The discount_remainder of this InventoryCoupon. # noqa: E501\n :rtype: float\n \"\"\"\n return self._discount_remainder\n\n @discount_remainder.setter\n def discount_remainder(self, discount_remainder):\n \"\"\"Sets the discount_remainder of this InventoryCoupon.\n\n The remaining discount this coupon can give. # noqa: E501\n\n :param discount_remainder: The discount_remainder of this InventoryCoupon. # noqa: E501\n :type: float\n \"\"\"\n\n self._discount_remainder = discount_remainder\n\n @property\n def reservation_counter(self):\n \"\"\"Gets the reservation_counter of this InventoryCoupon. # noqa: E501\n\n The number of times this coupon has been reserved. # noqa: E501\n\n :return: The reservation_counter of this InventoryCoupon. # noqa: E501\n :rtype: float\n \"\"\"\n return self._reservation_counter\n\n @reservation_counter.setter\n def reservation_counter(self, reservation_counter):\n \"\"\"Sets the reservation_counter of this InventoryCoupon.\n\n The number of times this coupon has been reserved. # noqa: E501\n\n :param reservation_counter: The reservation_counter of this InventoryCoupon. # noqa: E501\n :type: float\n \"\"\"\n\n self._reservation_counter = reservation_counter\n\n @property\n def attributes(self):\n \"\"\"Gets the attributes of this InventoryCoupon. # noqa: E501\n\n Custom attributes associated with this coupon. # noqa: E501\n\n :return: The attributes of this InventoryCoupon. # noqa: E501\n :rtype: object\n \"\"\"\n return self._attributes\n\n @attributes.setter\n def attributes(self, attributes):\n \"\"\"Sets the attributes of this InventoryCoupon.\n\n Custom attributes associated with this coupon. # noqa: E501\n\n :param attributes: The attributes of this InventoryCoupon. # noqa: E501\n :type: object\n \"\"\"\n\n self._attributes = attributes\n\n @property\n def referral_id(self):\n \"\"\"Gets the referral_id of this InventoryCoupon. # noqa: E501\n\n The integration ID of the referring customer (if any) for whom this coupon was created as an effect. # noqa: E501\n\n :return: The referral_id of this InventoryCoupon. # noqa: E501\n :rtype: int\n \"\"\"\n return self._referral_id\n\n @referral_id.setter\n def referral_id(self, referral_id):\n \"\"\"Sets the referral_id of this InventoryCoupon.\n\n The integration ID of the referring customer (if any) for whom this coupon was created as an effect. # noqa: E501\n\n :param referral_id: The referral_id of this InventoryCoupon. # noqa: E501\n :type: int\n \"\"\"\n\n self._referral_id = referral_id\n\n @property\n def recipient_integration_id(self):\n \"\"\"Gets the recipient_integration_id of this InventoryCoupon. # noqa: E501\n\n The Integration ID of the customer that is allowed to redeem this coupon. # noqa: E501\n\n :return: The recipient_integration_id of this InventoryCoupon. # noqa: E501\n :rtype: str\n \"\"\"\n return self._recipient_integration_id\n\n @recipient_integration_id.setter\n def recipient_integration_id(self, recipient_integration_id):\n \"\"\"Sets the recipient_integration_id of this InventoryCoupon.\n\n The Integration ID of the customer that is allowed to redeem this coupon. # noqa: E501\n\n :param recipient_integration_id: The recipient_integration_id of this InventoryCoupon. # noqa: E501\n :type: str\n \"\"\"\n if (self.local_vars_configuration.client_side_validation and\n recipient_integration_id is not None and len(recipient_integration_id) > 1000):\n raise ValueError(\"Invalid value for `recipient_integration_id`, length must be less than or equal to `1000`\") # noqa: E501\n\n self._recipient_integration_id = recipient_integration_id\n\n @property\n def import_id(self):\n \"\"\"Gets the import_id of this InventoryCoupon. # noqa: E501\n\n The ID of the Import which created this coupon. # noqa: E501\n\n :return: The import_id of this InventoryCoupon. # noqa: E501\n :rtype: int\n \"\"\"\n return self._import_id\n\n @import_id.setter\n def import_id(self, import_id):\n \"\"\"Sets the import_id of this InventoryCoupon.\n\n The ID of the Import which created this coupon. # noqa: E501\n\n :param import_id: The import_id of this InventoryCoupon. # noqa: E501\n :type: int\n \"\"\"\n\n self._import_id = import_id\n\n @property\n def reservation(self):\n \"\"\"Gets the reservation of this InventoryCoupon. # noqa: E501\n\n Defines the type of reservation: - `true`: The reservation is a soft reservation. Any customer can use the coupon. This is done via the [Create coupon reservation](https://docs.talon.one/integration-api#operation/createCouponReservation) endpoint. - `false`: The reservation is a hard reservation. Only the associated customer (`recipientIntegrationId`) can use the coupon. This is done via the Campaign Manager when you create a coupon for a given `recipientIntegrationId`, the [Create coupons](https://docs.talon.one/management-api#operation/createCoupons) endpoint or [Create coupons for multiple recipients](https://docs.talon.one/management-api#operation/createCouponsForMultipleRecipients) endpoint. # noqa: E501\n\n :return: The reservation of this InventoryCoupon. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._reservation\n\n @reservation.setter\n def reservation(self, reservation):\n \"\"\"Sets the reservation of this InventoryCoupon.\n\n Defines the type of reservation: - `true`: The reservation is a soft reservation. Any customer can use the coupon. This is done via the [Create coupon reservation](https://docs.talon.one/integration-api#operation/createCouponReservation) endpoint. - `false`: The reservation is a hard reservation. Only the associated customer (`recipientIntegrationId`) can use the coupon. This is done via the Campaign Manager when you create a coupon for a given `recipientIntegrationId`, the [Create coupons](https://docs.talon.one/management-api#operation/createCoupons) endpoint or [Create coupons for multiple recipients](https://docs.talon.one/management-api#operation/createCouponsForMultipleRecipients) endpoint. # noqa: E501\n\n :param reservation: The reservation of this InventoryCoupon. # noqa: E501\n :type: bool\n \"\"\"\n\n self._reservation = reservation\n\n @property\n def batch_id(self):\n \"\"\"Gets the batch_id of this InventoryCoupon. # noqa: E501\n\n The id of the batch the coupon belongs to. # noqa: E501\n\n :return: The batch_id of this InventoryCoupon. # noqa: E501\n :rtype: str\n \"\"\"\n return self._batch_id\n\n @batch_id.setter\n def batch_id(self, batch_id):\n \"\"\"Sets the batch_id of this InventoryCoupon.\n\n The id of the batch the coupon belongs to. # noqa: E501\n\n :param batch_id: The batch_id of this InventoryCoupon. # noqa: E501\n :type: str\n \"\"\"\n\n self._batch_id = batch_id\n\n @property\n def is_reservation_mandatory(self):\n \"\"\"Gets the is_reservation_mandatory of this InventoryCoupon. # noqa: E501\n\n Whether the reservation effect actually created a new reservation. # noqa: E501\n\n :return: The is_reservation_mandatory of this InventoryCoupon. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._is_reservation_mandatory\n\n @is_reservation_mandatory.setter\n def is_reservation_mandatory(self, is_reservation_mandatory):\n \"\"\"Sets the is_reservation_mandatory of this InventoryCoupon.\n\n Whether the reservation effect actually created a new reservation. # noqa: E501\n\n :param is_reservation_mandatory: The is_reservation_mandatory of this InventoryCoupon. # noqa: E501\n :type: bool\n \"\"\"\n\n self._is_reservation_mandatory = is_reservation_mandatory\n\n @property\n def profile_redemption_count(self):\n \"\"\"Gets the profile_redemption_count of this InventoryCoupon. # noqa: E501\n\n The number of times the coupon was redeemed by the profile. # noqa: E501\n\n :return: The profile_redemption_count of this InventoryCoupon. # noqa: E501\n :rtype: int\n \"\"\"\n return self._profile_redemption_count\n\n @profile_redemption_count.setter\n def profile_redemption_count(self, profile_redemption_count):\n \"\"\"Sets the profile_redemption_count of this InventoryCoupon.\n\n The number of times the coupon was redeemed by the profile. # noqa: E501\n\n :param profile_redemption_count: The profile_redemption_count of this InventoryCoupon. # noqa: E501\n :type: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and profile_redemption_count is None: # noqa: E501\n raise ValueError(\"Invalid value for `profile_redemption_count`, must not be `None`\") # noqa: E501\n\n self._profile_redemption_count = profile_redemption_count\n\n @property\n def state(self):\n \"\"\"Gets the state of this InventoryCoupon. # noqa: E501\n\n Can be: - `active`: The coupon can be used. It is a reserved coupon that is neither pending, used nor expired, and has a non-exhausted limit counter. - `used`: The coupon has been redeemed and cannot be used again. It is not pending and has reached its redemption limit or was redeemed by the profile before expiration. - `expired`: The coupon was never redeemed and it is now expired. It is non-pending, non-active and non-used by the profile. - `pending`: The coupon will be usable in the future. - `disabled`: The coupon is part of a non-active campaign. # noqa: E501\n\n :return: The state of this InventoryCoupon. # noqa: E501\n :rtype: str\n \"\"\"\n return self._state\n\n @state.setter\n def state(self, state):\n \"\"\"Sets the state of this InventoryCoupon.\n\n Can be: - `active`: The coupon can be used. It is a reserved coupon that is neither pending, used nor expired, and has a non-exhausted limit counter. - `used`: The coupon has been redeemed and cannot be used again. It is not pending and has reached its redemption limit or was redeemed by the profile before expiration. - `expired`: The coupon was never redeemed and it is now expired. It is non-pending, non-active and non-used by the profile. - `pending`: The coupon will be usable in the future. - `disabled`: The coupon is part of a non-active campaign. # noqa: E501\n\n :param state: The state of this InventoryCoupon. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and state is None: # noqa: E501\n raise ValueError(\"Invalid value for `state`, must not be `None`\") # noqa: E501\n\n self._state = state\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, InventoryCoupon):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, InventoryCoupon):\n return True\n\n return self.to_dict() != other.to_dict()\n","sub_path":"talon_one/models/inventory_coupon.py","file_name":"inventory_coupon.py","file_ext":"py","file_size_in_byte":30963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"485142353","text":"import re\nf = open(\"day3input.txt\")\ndataset=[]\nxcount =0\npoints =set()\noverlappoints=set()\n\n#Get data in workable set\nfor cordinates in f:\n data = re.split(\"[#@,:x\\n\\s]\",cordinates)\n while '' in data:\n data.remove('')\n dataset.append(data)\n\n#create a 1100x1100 2d list\nourMap = [['~'] * 10 for i in range(1400)]\n\n\n#For each cord, map it and check for overlaps in the map\nfor piece in dataset:\n overlapflag = False\n cordID= int(piece[0])\n cordY = int(piece[2])\n cordX = int(piece[1])\n sizeY = int(piece[4])\n sizeX = int(piece[3])\n for cord in range(cordY, cordY+sizeY):\n for cordi in range(cordX, cordX +sizeX):\n cordinate = str(cord)+\",\"+str(cordi)\n if cordinate in points:\n overlappoints.add(cordinate)\n else:\n points.add(cordinate)\nprint(len(overlappoints))\n \n\n\nfor piece in dataset:\n overlapflag = False\n cordID= int(piece[0])\n cordY = int(piece[2])\n cordX = int(piece[1])\n sizeY = int(piece[4])\n sizeX = int(piece[3])\n for cord in range(cordY, cordY+sizeY):\n for cordi in range(cordX, cordX +sizeX):\n cordinate = str(cord)+\",\"+str(cordi)\n if cordinate in overlappoints:\n overlapflag = True\n \n if overlapflag == False:\n print(cordID)\n\n\n \n\n","sub_path":"day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"521918425","text":"\"\"\"\nぐるなびAPI\n\"\"\"\n# -*- coding: utf-8 -*-\nfrom requests.exceptions import RequestException\nfrom plugins.restapi import RestApi\n\nclass GnaviApi(RestApi):\n \"\"\"\n ぐるなびAPI用クラス\n \"\"\"\n def __init__(self, url, key):\n super().__init__(url)\n self.key = key\n self.garea_s = None\n\n def url_list(self):\n \"\"\"\n ResponseからレストランURLのリストを作って返す。\n \"\"\"\n json_data = self.response_data.json()\n if 'error' in json_data:\n raise Exception('そのキーワードじゃ見つかんなかった・・・(´・ω・`)')\n\n if json_data['total_hit_count'] == '1':\n return [(json_data['rest'])['url']]\n else:\n return [rest_data['url'] for rest_data in json_data['rest']]\n\n def garea_middle_fech(self):\n \"\"\"\n ぐるなびAPIからエリアMマスタを取得する。\n \"\"\"\n garea = RestApi('https://api.gnavi.co.jp/master/GAreaMiddleSearchAPI/20150630/')\n params = {\n 'keyid': self.key,\n 'format': 'json',\n 'lang': 'ja'\n }\n try:\n garea.api_request(params)\n self.garea_s = garea.response_data.json()\n if 'error' in self.garea_s:\n raise Exception('その場所知らない・・・(´・ω・`)')\n except RequestException:\n raise RequestException()\n\n def garea_middle_search(self, area_name):\n \"\"\"\n エリアMマスタ内から、area_nameに一致する値を取得する。\n (完全一致だと厳しいので、部分一致。)\n \"\"\"\n result_dict = {}\n for area_s in self.garea_s['garea_middle']:\n if area_s['areaname_m'].find(area_name) >= 0:\n result_dict = {'areacode_m': area_s['areacode_m']}\n break\n\n return result_dict\n","sub_path":"plugins/gnaviapi.py","file_name":"gnaviapi.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"408949730","text":"import pytest\nimport config\nfrom base.BaseAppiumServer import AppiumServer\nfrom base.mobile_core import new_driver\n\n\ndef pytest_addoption(parser):\n parser.addoption(\"--cmdopt\", action='store', help=\"devices info\")\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef cmdopt(request):\n return request.config.getoption(\"--cmdopt\")\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef start_test(cmdopt):\n\n \"\"\"\n 生成driver实例需要条件:\n 1.设备池:设备信息\n 2.appium server:对应启动appium server端\n 3.driver实例信息:配置信息、连接地址\n :return:\n \"\"\"\n device_info = eval(cmdopt)\n # # 启动appium server\n appium_server = AppiumServer()\n\n driver_address = device_info.pop('driver_address')\n # 生成driver实例\n driver = new_driver(address=driver_address, capabilities=device_info)\n config.driver = driver\n driver.implicitly_wait(5)\n yield\n driver.quit()\n # appium_server.stop_server()","sub_path":"conftest_弃用.py","file_name":"conftest_弃用.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"192505397","text":"#!ENV/bin/python\n\n'''Provide a WSGI under the name 'application' when this module is improted.\n\nRun a Bottle development server when this module is run as a program.\n\nStart with Dreamhost's python, use execl to switch to the virtual environment\npython.\n\n'''\n\n# import from stdlib\nimport os\nimport sys\nimport datetime\nimport traceback\n\n\ntry:\n # describe the environment\n ROOT = os.path.dirname(os.path.abspath(__file__))\n INTERP = os.path.join(ROOT, 'ENV/bin/python')\n\n # fix sys.path; change interpreter; enter the virtualenv\n sys.path.insert(1, ROOT)\n if sys.executable != INTERP:\n os.execl(INTERP, INTERP, *sys.argv)\n\n # import from 3rd party\n import bottle\n # import from local\n import lib.config\n import lib.wsgi\n\n # launch dev or prod\n if __name__ == '__main__':\n # dev server\n application = lib.wsgi.start(lib.config.DB_PATH, lib.config.HTML_PATH,\n dev={'docroot': './public'})\n bottle.debug(True)\n bottle.run(app=application, host='localhost', port=65080)\n else:\n # prod app\n application = lib.wsgi.start(lib.config.DB_PATH, lib.config.HTML_PATH)\n\nexcept:\n if __name__ == '__main__':\n # raise exceptions that occur in development\n print('[Exception caught]')\n raise\n else:\n # log exceptions that occur in production\n with open(os.path.join(ROOT, 'public/error.passenger_wsgi.txt'), 'a') as fd:\n fd.write('=== %s ===\\n' % datetime.datetime.now())\n traceback.print_exc(file=fd)\n exit()\n\n","sub_path":"passenger_wsgi.py","file_name":"passenger_wsgi.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"57898633","text":"import os\nimport numpy as np\nimport pickle\nimport re\nimport matplotlib.pyplot as plt\n\nimport cddm_data_simulation as cd\nimport boundary_functions as bf\n\nmethod = \"full\"\n\nif method == \"ddm\":\n dgp = cd.ddm_flexbound_simulate\n boundary = bf.constant\n params=[\"v\", \"a\", \"w\"]\n data_folder = \"/users/afengler/data/tony/kde/ddm/method_comparison/\"\nelif method == \"ornstein\":\n dgp = cd.ornstein_uhlenbeck\n boundary = bf.constant\n params = [\"v\", \"a\", \"w\", \"g\"]\n data_folder = \"/users/afengler/data/tony/kde/ornstein_uhlenbeck/method_comparison/\"\nelif method == \"full\":\n dgp = cd.full_ddm\n boundary = bf.constant\n params = [\"v\", \"a\", \"w\", \"dw\", \"sdv\"]\n data_folder = \"/users/afengler/data/tony/kde/full_ddm/method_comparison/\"\n\nfiles = os.listdir(data_folder)\nfiles = [f for f in files if re.match(\"kde_sim_random.*\", f)]\n\ntrue_params, data, samples = pickle.load(open(data_folder + files[0], \"rb\"))\nfor f in files[1:]:\n param_tmp, data_tmp, samples_tmp = pickle.load(open(data_folder + f, \"rb\"))\n true_params = np.concatenate([true_params, param_tmp])\n data = np.concatenate([data, data_tmp])\n samples = np.concatenate([samples, samples_tmp])\n\neap = np.zeros((true_params.shape[0], len(params)))\nfor i in range(samples.shape[0]):\n eap[i] = samples[i][500:].mean(axis=0)\n\nix = np.random.choice(true_params.shape[0], size=9)\nppc_params = true_params[ix]\nppc_samples = eap[ix]\n\nfig, ax = plt.subplots(3, 3)\n\nfor i in range(3):\n for j in range(3):\n sim_data = dgp(*ppc_params[i*3 + j], n_samples=2000, boundary_fun=boundary)\n sim_data = sim_data[0][sim_data[1] == 1]\n ax[i][j].hist(sim_data, color=\"blue\", bins=30)\n ppc_data = dgp(*ppc_samples[i*3 + j], n_samples=2000, boundary_fun=boundary)\n ppc_data = ppc_data[0][ppc_data[1] == 1]\n ax[i][j].hist(ppc_data, color=\"red\", bins=30)\n\nfig.savefig(data_folder + \"ppc.png\")\n","sub_path":"posterior_predictive_checks.py","file_name":"posterior_predictive_checks.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"295822651","text":"'''\n/*\n * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\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 * A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n '''\n\nimport sys\nsys.path.append(\"../util/\")\nsys.path.append(\"../exception/\")\nimport commuteServer\nimport logManager\nimport AWSIoTExceptions\nimport Queue\nimport signal\n\nclass serialCommuteServer(commuteServer.commuteServer):\n _messageQueue = None\n _txBuf = None\n _log = None\n _acceptTimeout = 0 # Never timeout\n _chunkSize = 50 # Biggest chunk of data that can be sent over serial\n _returnList = []\n\n def __init__(self, srcLogManager):\n self._log = srcLogManager\n self._messageQueue = Queue.Queue(0)\n self._txBuf = \"\"\n # Register timeout signal handler\n signal.signal(signal.SIGALRM, self._timeoutHandler)\n signal.alarm(0) # disable SIGALRM\n self._log.writeLog(\"Register timeout signal handler.\")\n self._log.writeLog(\"serialCommuteServer init.\")\n \n\n def _timeoutHandler(self, signal, frame):\n self._log.writeLog(\"Raise a custom exception for accept timeout.\")\n raise AWSIoTExceptions.acceptTimeoutException()\n\n def _basicInput(self):\n return raw_input()\n\n def _basicOutput(self, srcContent):\n print(srcContent)\n\n def setAcceptTimeout(self, srcTimeout):\n self._acceptTimeout = srcTimeout\n self._log.writeLog(\"serialCommuteServer set accept timeout to \" + str(self._acceptTimeout))\n\n def setChunkSize(self, srcChunkSize):\n self._chunkSize = srcChunkSize\n self._log.writeLog(\"serialCommuteServer set chunk size to \" + str(self._chunkSize))\n\n def accept(self):\n # Messages are passed from remote client to server line by line\n # A number representing the number of lines to receive will be passed first\n # Then serialCommuteServer should loop the exact time to receive the following lines\n # All these reads add up tp ONE timeout: acceptTimeout. Once exceeded, this timeout will trigger a callback raising an exception\n # Throw acceptTimeoutException, ValueError\n # Store the incoming parameters into an internal data structure\n self._returnList = []\n self._log.writeLog(\"Clear internal list. Size: \" + str(len(self._returnList)))\n signal.alarm(self._acceptTimeout) # Enable SIGALRM\n self._log.writeLog(\"Accept-timer starts, with acceptTimeout: \" + str(self._acceptTimeout) + \" second(s).\")\n numLines = int(self._basicInput()) # Get number of lines to receive\n self._log.writeLog(str(numLines) + \" lines to be received. Loop begins.\")\n loopCount = 1\n while(loopCount <= numLines):\n currElementIn = self._basicInput()\n self._returnList.append(currElementIn)\n self._log.writeLog(\"Received: \" + str(loopCount) + \"/\" + str(numLines) + \" Message is: \" + currElementIn)\n loopCount += 1\n signal.alarm(0) # Finish reading from remote client, disable SIGALRM\n self._log.writeLog(\"Finish reading from remote client. Accept-timer ends.\")\n return self._returnList\n\n def writeToInternal(self, srcContent):\n self._messageQueue.put(srcContent)\n self._log.writeLog(\"Updated serialCommuteServer internal messageQueue by inserting a new message. Size: \" + str(self._messageQueue.qsize()))\n\n def writeToExternal(self):\n # Pick one complete message from the internal messageQueue and write to the remote client in chunks\n # Messages in the internal messageQueue should be well-formated for yield messages, serialCommuteServer will do nothing to format it\n while(not self._messageQueue.empty()):\n currElementOut = self._messageQueue.get()\n self._log.writeLog(\"Start sending message to remote client: \" + currElementOut)\n while(len(currElementOut) != 0):\n self._txBuf = currElementOut[0:self._chunkSize]\n self._basicOutput(self._txBuf)\n self._log.writeLog(\"Send through serial to remote client. Chunk: \" + self._txBuf + \" Size: \" + str(len(self._txBuf)))\n currElementOut = currElementOut[self._chunkSize:]\n self._log.writeLog(\"End sending this message.\")\n self._log.writeLog(\"No more messages. Exiting writeToExternal.\")\n","sub_path":"ExampleAppScript/ThermostatSimulatorApp/lib/comm/serialCommuteServer.py","file_name":"serialCommuteServer.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"433887581","text":"import cgl.plugins.smart_task as smart_task\nfrom cgl.ui.widgets.dialog import InputDialog\nfrom cgl.core.path import PathObject\nfrom cgl.core.utils.general import load_json\nfrom cgl.plugins.maya.alchemy import scene_object, reference_file\nfrom cgl.plugins.maya.utils import get_namespace, load_plugin\nimport pymel.core as pm\nimport maya.cmds as cmds\nimport glob\nimport os\n\n\nclass Task(smart_task.SmartTask):\n\n def __init__(self, path_object=None):\n if not path_object:\n from cgl.plugins.maya.alchemy import scene_object\n self.path_object = scene_object()\n\n def build(self):\n task = 'mdl'\n pm.select(cl=True)\n if pm.objExists(task):\n print('mdl already exists')\n pass\n else:\n create_material_groups()\n\n def get_msd_info(self, mdl):\n \"\"\"\n returns the msd dict for the given task.\n :return:\n \"\"\"\n\n dict_ = {}\n meshes = []\n groups = get_mtl_groups(mdl)\n so = scene_object()\n if groups:\n for child in groups:\n clean_name = str(child)\n meshes.append(clean_name)\n dict_['attrs'] = {'mtl_groups': meshes}\n dict_['source_file'] = so.path\n dict_['name'] = so.shot\n # find all the model exports:\n render_object = so.copy(context='render', set_proper_filename=True, ext='*')\n files = glob.glob(render_object.path_root)\n if files:\n for f in files:\n file_, ext_ = os.path.splitext(f)\n dict_['attrs'][ext_] = PathObject(f).path\n return dict_\n\n\ndef get_mtl_groups(mdl, res='high'):\n sel = '{}|{}'.format(mdl, res)\n mtl_groups = pm.listRelatives(sel, children=True)\n return mtl_groups\n\n\ndef msd_import(msd_path):\n from cgl.core.path import add_root\n namespace = get_namespace(msd_path)\n if os.path.exists(msd_path):\n msd_dict = load_json(msd_path)\n ref = reference_file(add_root(msd_dict['attrs']['mb']), namespace)\n return ref\n else:\n mb_path = msd_path.replace('.msd', '.mb')\n namespace = get_namespace(mb_path)\n ref = reference_file(mb_path, namespace)\n return ref\n\n\ndef create_high_group(materials):\n pm.select(cl=True)\n for m in materials:\n pm.select(m, tgl=True)\n pm.group(name='high')\n\n\ndef create_mdl_group(res='high'):\n pm.select(cl=True)\n pm.select(res)\n pm.group(name='mdl')\n\n\ndef create_material_groups(do_high=True, do_mdl=True):\n dialog_ = InputDialog(title='Create Material Groups',\n message='list materials needed in this object (comma seperated)', line_edit=True,\n regex='^([a-z]{3,}, *)*[a-z]{3,}', name_example='ex: wood, metal')\n dialog_.exec_()\n\n if dialog_.button == 'Ok':\n list_ = dialog_.line_edit.text().split(',')\n cleaned_list = []\n for each in list_:\n each = each.replace(' ', '')\n each = '%s_mtl' % each\n cleaned_list.append(each)\n for c in cleaned_list:\n pm.select(cl=True)\n pm.group(name=c)\n if do_high:\n create_high_group(cleaned_list)\n if do_mdl:\n create_mdl_group()\n pm.select(cl=True)\n dialog2 = InputDialog(title='Success!', message='Your model hierarchy has been created\\n'\n 'please move all objects into their proper *_mtl groups')\n dialog2.exec_()\n\n\ndef snap_to_origin(sel=None):\n if not sel:\n sel = pm.ls(sl=True)[0]\n loc = pm.spaceLocator()\n snap_to(sel, loc)\n pm.delete(loc)\n\n\ndef snap_to(a=None, b=None, pretransform=None, prerotation=None):\n \"\"\"\n snaps object a to object b\n :return:\n \"\"\"\n if not b:\n sel = pm.ls(sl=True)\n if len(sel) != 2:\n pm.windows.confirmDialog(title='Select Error',\n message='Please select 2 asset',\n button=['Ok'])\n else:\n b = sel[1]\n a = sel[0]\n point = pm.pointConstraint(b, a)\n orient = pm.orientConstraint(b, a)\n pm.delete(point)\n pm.delete(orient)\n\n if prerotation:\n axi = ['X', 'Y', 'Z']\n for rval, axis in enumerate(axi):\n rcurrent = pm.getAttr('%s.rotate%s' % (a, axis))\n pm.setAttr('%s.rotate%s' % (a, axis), (rcurrent-prerotation[rval]))\n tcurrent = pm.getAttr('%s.translate%s' % (a, axis))\n pm.setAttr('%s.translate%s' % (a, axis), (tcurrent - pretransform[rval]))\n\n\ndef delete_history(name=None):\n if name:\n pm.select(name)\n else:\n name = pm.ls(sl=True)\n if not name:\n print('Nothing Selected, and no object given, skipping Delete History')\n return\n pm.delete(all=True, constructionHistory=True)\n\n\ndef freeze_transforms(name=None):\n if name:\n pm.select(name)\n else:\n name = pm.ls(sl=True)\n if not name:\n print('Nothing Selected, and no object given, skipping Delete History')\n return\n pm.runtime.FreezeTransformations()\n\n\ndef create_bounding_box_cube(obj):\n \"\"\"\n creates a cube int he same proportions as the bounding box of the object.\n :return:\n \"\"\"\n if ':' in obj:\n name = obj.split(':')[0]\n else:\n name = obj\n name = '{}_proxy_anim'.format(name)\n pm.select(obj)\n sel = pm.ls(sl=True)\n x1, y1, z1, x2, y2, z2 = cmds.exactWorldBoundingBox(sel, calculateExactly=True)\n cube = cmds.polyCube(name=name)[0]\n snap_to(cube, obj)\n cmds.move(x1, '%s.f[5]' % cube, x=True)\n cmds.move(y1, '%s.f[3]' % cube, y=True)\n cmds.move(z1, '%s.f[2]' % cube, z=True)\n cmds.move(x2, '%s.f[4]' % cube, x=True)\n cmds.move(y2, '%s.f[1]' % cube, y=True)\n cmds.move(z2, '%s.f[0]' % cube, z=True)\n pm.select(d=True)\n return cube\n\n\ndef disconnect_attrs(obj, tx=False, ty=False, tz=False, rx=False, ry=False, rz=False, sx=False, sy=False, sz=False):\n \"\"\"\n if you only give this function the object, it will disconnect ALL attributes. otherwise it will disconnect\n the attrs set to True.\n :param obj:\n :param tx:\n :param ty:\n :param tz:\n :param rx:\n :param ry:\n :param rz:\n :param sx:\n :param sy:\n :param sz:\n :return:\n \"\"\"\n if not tx and not ty and not tz and not rx and not ry and not rz and not sx and not sy and not sz:\n tx = True\n ty = True\n tz = True\n rx = True\n ry = True\n rz = True\n sx = True\n sy = True\n sz = True\n if tx:\n pm.disconnectAttr('{}.tx'.format(obj))\n if ty:\n pm.disconnectAttr('{}.ty'.format(obj))\n if tz:\n pm.disconnectAttr('{}.tz'.format(obj))\n if rx:\n pm.disconnectAttr('{}.rx'.format(obj))\n if ry:\n pm.disconnectAttr('{}.ry'.format(obj))\n if rz:\n pm.disconnectAttr('{}.rz'.format(obj))\n if sx:\n pm.disconnectAttr('{}.sx'.format(obj))\n if sy:\n pm.disconnectAttr('{}.sy'.format(obj))\n if sz:\n pm.disconnectAttr('{}.sz'.format(obj))\n\n\ndef get_transform_arrays(mesh):\n \"\"\"\n returns translate, rotate, scale arrays.\n :param mesh:\n :return:\n \"\"\"\n translate = pm.getAttr('%s.t' % mesh)\n scale = pm.getAttr('%s.s' % mesh)\n rotate = pm.getAttr('%s.r' % mesh)\n t_array = [translate[0], translate[1], translate[2]]\n r_array = [rotate[0], rotate[1], rotate[2]]\n s_array = [scale[0], scale[1], scale[2]]\n return t_array, r_array, s_array\n\n\ndef get_matrix(obj, query=False):\n \"\"\"\n Returns a matrix of values relating to translate, scale, rotate.\n :param obj:\n :param query:\n :return:\n \"\"\"\n\n if not query:\n if pm.objExists(obj):\n if 'rig' in obj:\n translate = '%s:translate' % obj.split(':')[0]\n scale = '%s:scale' % obj.split(':')[0]\n rotate = '%s:rotate' % obj.split(':')[0]\n relatives = pm.listRelatives(obj)\n if translate and scale in relatives:\n if rotate in pm.listRelatives(translate):\n matrix_rotate = pm.getAttr('%s.matrix' % rotate)[0:3]\n matrix_scale = pm.getAttr('%s.matrix' % scale)[0:3]\n matrix = matrix_scale * matrix_rotate\n matrix.append(pm.getAttr('%s.matrix' % translate)[3])\n else:\n attr = \"%s.%s\" % (obj, 'matrix')\n if pm.attributeQuery('matrix', n=obj, ex=True):\n matrix = pm.getAttr(attr)\n else:\n matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0],\n [0.0, 0.0, 0.0, 1.0]]\n else:\n attr = \"%s.%s\" % (obj, 'matrix')\n if pm.attributeQuery('matrix', n=obj, ex=True):\n matrix = pm.getAttr(attr)\n else:\n matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]\n else:\n attr = \"%s.%s\" % (obj, 'matrix')\n if pm.attributeQuery('matrix', n=obj, ex=True):\n matrix = pm.getAttr(attr)\n else:\n matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0],\n [0.0, 0.0, 0.0, 1.0]]\n else:\n matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]\n return matrix\n else:\n return [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]\n\n\ndef get_msd_info(mesh):\n \"\"\"\n gets the .msd info for a given mesh\n :param mesh:\n :return:\n \"\"\"\n try:\n ref_path = pm.referenceQuery(mesh, filename=True, wcn=True)\n path_object = PathObject(ref_path)\n matrix = get_matrix(mesh)\n matrix = str(matrix).replace('[', '').replace(']', '').replace(',', '')\n translate, rotate, scale = get_transform_arrays(mesh)\n mdl_dict = {}\n mdl_dict['msd_path'] = path_object.relative_msd_path\n mdl_dict['name'] = '{}_{}'.format(path_object.seq, path_object.shot)\n mdl_dict['transform'] = {'matrix': matrix,\n 'scale': scale,\n 'rotate': rotate,\n 'translate': translate\n }\n return mdl_dict\n except RuntimeError:\n return {}\n\n\ndef assign_lambert_to_material_groups(model='mdl|high'):\n \"\"\"\n Assigns a lambert shader \"material_name\" to geo, and allows the user to pick a color for it.\n This expects a properly named model.\n :return:\n \"\"\"\n material_groups = pm.listRelatives(model, children=True)\n for mat in material_groups:\n pm.select(d=True)\n if '|' in mat:\n mat_ = mat.split('|')[-1]\n else:\n mat_ = mat\n shd = mat_.replace('_mtl', '')\n if pm.objExists(shd):\n print('found {}'.format(shd))\n node = pm.PyNode(shd)\n print(node.nodeType())\n if node.nodeType() == 'transform':\n print('renaming')\n pm.rename(shd, '{}_a'.format(shd))\n sg = '%sSG' % shd\n surface_shader = '%s.surfaceShader' % sg\n _ = pm.nodetypes.Lambert(name=shd)\n out_color = '%s.outColor' % shd\n pm.sets(renderable=True, noSurfaceShader=True, empty=True, name=sg)\n pm.connectAttr(out_color, surface_shader, force=True)\n pm.select(d=True)\n if pm.objExists('mdl|low'):\n pm.select(mat, mat.replace('high', 'low'))\n else:\n pm.select(mat)\n pm.sets(sg, forceElement=True)\n\n\ndef export_mdl(mesh='mdl', ext='obj', path_object=None):\n typ_dict = {'obj': 'OBJexport',\n 'mb': 'mayaBinary',\n 'fbx': 'FBX export'}\n if not path_object:\n export_path = scene_object().copy(context='render', ext=ext).path_root\n else:\n print('{} export outside of mdl context not yet defined'.format(ext))\n pm.select(d=True)\n if pm.objExists(mesh):\n print('Exporting {}'.format(mesh))\n pm.select(mesh)\n pm.exportSelected(export_path, typ=typ_dict[ext], force=True)\n print('MB exported: {}'.format(export_path))\n else:\n print('No mesh {} in scene'.format(mesh))\n\n\ndef export_fbx(mesh='mdl', path_object=None):\n # TODO - replace this with export_mdl()\n load_plugin('fbxmaya')\n if not path_object:\n fbx_export = scene_object().copy(context='render', ext='fbx').path_root\n else:\n print('fbx export outside of mdl context not yet defined')\n pm.select(d=True)\n if pm.objExists(mesh):\n print('Exporting {}'.format(mesh))\n pm.select(mesh)\n pm.exportSelected(fbx_export, typ='FBX export', force=True)\n print('FBX exported: {}'.format(fbx_export))\n else:\n print('No mesh {} in scene'.format(mesh))\n\n\ndef get_bad_faces(top_node='mdl'):\n pm.select(top_node)\n children = pm.listRelatives(children=True, ad=True, type='mesh')\n dict = {}\n for c in children:\n pm.select(d=True)\n pm.select(c.f, r=True)\n pm.polySelectConstraint(m=2, t=8, sz=2)\n pm.polySelectConstraint(m=0)\n mel.eval('InvertSelection;')\n sel = pm.ls(sl=True)\n if sel:\n dict[c] = sel\n pm.select(dict.keys())\n return dict.keys()\n\n\ndef select_bad_faces(mesh):\n pmesh = pm.PyNode(mesh)\n pm.select(d=True)\n pm.select(pmesh.f, r=True)\n pm.polySelectConstraint(m=2, t=8, sz=2)\n pm.polySelectConstraint(m=0)\n mel.eval('InvertSelection;')\n sel = pm.ls(sl=True)\n if sel:\n print('BAD FECES: ----->>>>>\\t', sel)\n return True\n else:\n return False\n\n\n\n\n","sub_path":"cgl/plugins/maya/tasks/mdl.py","file_name":"mdl.py","file_ext":"py","file_size_in_byte":14091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"133836642","text":"from abc import ABC, abstractmethod\nfrom typing import Iterator, List, Optional, Set, Tuple\n\nfrom parallelpipe import stage\n\nfrom gfw_pixetl import get_module_logger\nfrom gfw_pixetl.layers import Layer\nfrom gfw_pixetl.settings.globals import GLOBALS\nfrom gfw_pixetl.tiles.tile import Tile\nfrom gfw_pixetl.utils import upload_geometries\nfrom gfw_pixetl.utils.gdal import get_metadata\n\nLOGGER = get_module_logger(__name__)\n\n\nclass Pipe(ABC):\n \"\"\"Base Pipe including all the basic stages to seed, filter, delete and\n upload tiles.\n\n Create a subclass and override create_tiles() method to create your\n own pipe.\n \"\"\"\n\n def __init__(self, layer: Layer, subset: Optional[List[str]] = None) -> None:\n self.grid = layer.grid\n self.layer = layer\n self.subset = subset\n self.tiles_to_process = 0\n\n def collect_tiles(self, overwrite: bool) -> List[Tile]:\n pipe = (\n self.get_grid_tiles()\n | self.filter_subset_tiles(self.subset)\n | self.filter_src_tiles\n | self.filter_target_tiles(overwrite=overwrite)\n )\n tiles = list()\n\n for tile in pipe.results():\n if tile.status == \"pending\":\n self.tiles_to_process += 1\n tiles.append(tile)\n\n LOGGER.info(f\"{self.tiles_to_process} tiles to process\")\n\n return tiles\n\n @abstractmethod\n def create_tiles(\n self, overwrite\n ) -> Tuple[List[Tile], List[Tile], List[Tile], List[Tile]]:\n \"\"\"Override this method when implementing pipes.\"\"\"\n ...\n\n @abstractmethod\n def get_grid_tiles(self) -> Set[Tile]:\n \"\"\"Seed all available tiles within given grid.\n\n Use 1x1 degree tiles covering all land area as starting point.\n Then see in which target grid cell it would fall. Remove\n duplicated grid cells.\n \"\"\"\n ...\n\n @abstractmethod\n def _get_grid_tile(self, tile_id: str) -> Tile:\n \"\"\"Override this method when implementing pipes.\"\"\"\n ...\n\n @staticmethod\n @stage(workers=GLOBALS.num_processes)\n @abstractmethod\n def filter_src_tiles():\n \"\"\"Override this method when implementing pipes.\"\"\"\n ...\n\n @staticmethod\n @stage(workers=GLOBALS.num_processes)\n def filter_subset_tiles(tiles: Iterator[Tile], subset) -> Iterator[Tile]:\n \"\"\"Apply filter in case user only wants to process a subset.\n\n Useful for testing.\n \"\"\"\n for tile in tiles:\n if subset and tile.status == \"pending\" and tile.tile_id not in subset:\n LOGGER.debug(f\"Tile {tile} not in subset. Skip.\")\n tile.status = \"skipped (not in subset)\"\n yield tile\n\n @staticmethod\n @stage(workers=GLOBALS.num_processes)\n def filter_target_tiles(tiles: Iterator[Tile], overwrite: bool) -> Iterator[Tile]:\n \"\"\"Don't process tiles if they already exist in target location,\n unless overwrite is set to True.\"\"\"\n for tile in tiles:\n if (\n not overwrite\n and tile.status == \"pending\"\n and all([tile.dst[fmt].exists() for fmt in tile.dst.keys()])\n ):\n for dst_format in tile.dst.keys():\n tile.metadata[dst_format] = get_metadata(\n tile.dst[tile.default_format].url,\n tile.layer.compute_stats,\n tile.layer.compute_histogram,\n ).dict()\n tile.status = \"existing\"\n LOGGER.debug(f\"Tile {tile} already in destination. Skip processing.\")\n yield tile\n\n @staticmethod\n @stage(workers=GLOBALS.num_processes)\n def create_gdal_geotiff(tiles: Iterator[Tile]) -> Iterator[Tile]:\n \"\"\"Copy local file to geotiff format.\"\"\"\n for tile in tiles:\n if tile.status == \"pending\":\n tile.create_gdal_geotiff()\n yield tile\n\n @staticmethod\n @stage(workers=GLOBALS.num_processes)\n def upload_file(tiles: Iterator[Tile]) -> Iterator[Tile]:\n \"\"\"Upload tile to target location.\"\"\"\n for tile in tiles:\n if tile.status == \"pending\":\n tile.upload()\n yield tile\n\n @staticmethod\n @stage(workers=GLOBALS.num_processes)\n def delete_work_dir(tiles: Iterator[Tile]) -> Iterator[Tile]:\n \"\"\"Delete local files.\"\"\"\n for tile in tiles:\n tile.remove_work_dir()\n yield tile\n\n def _process_pipe(\n self, pipe\n ) -> Tuple[List[Tile], List[Tile], List[Tile], List[Tile]]:\n \"\"\"Fetching all tiles which ran through the pipe.\n\n Check and sort by status.\n \"\"\"\n\n processed_tiles: List[Tile] = list()\n skipped_tiles: List[Tile] = list()\n failed_tiles: List[Tile] = list()\n existing_tiles: List[Tile] = list()\n\n for tile in pipe.results():\n\n # Sort tiles based on their final status\n if tile.status == \"pending\":\n tile.status = \"processed\"\n processed_tiles.append(tile)\n elif tile.status.startswith(\"failed\"):\n failed_tiles.append(tile)\n elif tile.status == \"existing\":\n existing_tiles.append(tile)\n else:\n skipped_tiles.append(tile)\n\n if not failed_tiles:\n upload_geometries.upload_geojsons(\n processed_tiles, existing_tiles, self.layer.prefix\n )\n\n return processed_tiles, skipped_tiles, failed_tiles, existing_tiles\n","sub_path":"gfw_pixetl/pipes/pipe.py","file_name":"pipe.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"289427728","text":"import numpy as np\nimport os\nimport random as rn\nimport time\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.linear_model import PassiveAggressiveClassifier\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.pipeline import FeatureUnion, Pipeline\n\ndef get_filepaths_labels(dirpath):\n # 1) find all possible filepaths (and the respective labels)\n filepaths_labels = list()\n for label in CLASSES:\n classpath = os.path.join(dirpath, label)\n for filename in os.listdir(classpath):\n if filename.endswith('.txt'):\n filepaths_labels.append(\n (os.path.join(classpath, filename), CLASSES[label])\n )\n # 2) shuffle the filepaths (and the respective labels) to have the\n # two classes in the training and test sets\n rn.shuffle(filepaths_labels)\n return filepaths_labels\n\n\ndef split_filepaths_labels(filepaths_labels):\n filepaths = list()\n labels = list()\n for filepath, label in filepaths_labels:\n filepaths.append(filepath)\n labels.append(label)\n return filepaths, labels\n\nabsolutist_words = ['absolutely','all','always','complete','completely','constant','constantly','definitely','entire','ever','every','everyone','everything','full','must','never','nothing','totally','whole']\n\nself_related_words = ['i', 'my', 'mine', 'myself', 'me']\n\ndef count_abs(filepath):\n \n abs_count = 0\n self_count = 0\n l = 0\n fo = open(filepath, 'r', encoding='utf-8')\n file_content = fo.read()\n split_content = file_content.split(\" \")\n for word in split_content:\n if word.lower() in absolutist_words:\n abs_count += 1\n else:\n if word.lower() in self_related_words:\n self_count += 1\n l = len(split_content)\n fo.close()\n \n return abs_count, self_count, l\n\n\nclass TextStats(BaseEstimator, TransformerMixin):\n \"\"\"Extract features from each document for DictVectorizer\"\"\"\n\n def fit(self, x, y=None):\n return self\n\n def transform(self, filepaths):\n return [{'abs': count_abs(filepath)[0] if count_abs(filepath)[0] > 700 else 0,\n 'self': count_abs(filepath)[1] if count_abs(filepath)[1] > 2700 else 0,\n 'length': count_abs(filepath)[2] if count_abs(filepath)[0] > 65000 else 0} \n for filepath in filepaths]\n\nSEED = 0\nrn.seed(SEED)\nnp.random.seed(SEED)\n\nSTOPPATH = '/home/alinatrifan/SOCA/github/stopwords_nltk.txt'\nDIRPATH = '/home/alinatrifan/SOCA/datasets/cleaned/ra/dataset/data/'\nDIRPATH_TEST = '/home/alinatrifan/SOCA/datasets/cleaned/ra/dataset/testing/'\nCLASSES = {'control': 0, 'depression': 1}\n\n#get stopwords without self-related words\nwith open(STOPPATH) as f:\n stopwords_list = f.readlines()\nstopwords_list = [word.strip() for word in stopwords_list]\n\n\n# get all the filepaths of the dataset\nfilepaths_labels = get_filepaths_labels(DIRPATH)\nfilepaths_labels_test = get_filepaths_labels(DIRPATH_TEST)\n\n# total number of documents\nn_total = len(filepaths_labels)\nn_test = len(filepaths_labels_test)\nprint('Total number of samples: {}'.format(n_total))\n\nprint('Training samples: {}'.format(n_total))\nprint('Test samples: {}'.format(n_test))\n\n# get train filepaths and respective labels\ntrain_filepaths, train_labels = split_filepaths_labels(filepaths_labels)\n# get test filepaths and respective labels\ntest_filepaths, test_labels = split_filepaths_labels(filepaths_labels_test)\n\n# the number of documents to use in partial_fit\nbatch_size = 500\n#print('Batch size: {}'.format(batch_size))\n\n# declare classifier\n#clf = SGDClassifier(max_iter=1000, tol=1e-3, random_state=SEED, class_weight='balanced')\n#clf = MultinomialNB(alpha=0.01)\nclf = PassiveAggressiveClassifier(tol=1e-3)\n#clf = Perceptron()\n\nprint('Fitting TfidfVectorizer using training samples...')\n# training filepaths to fit the TfidfVectorizer\n\nts = TextStats()\n\ntrain_dict = ts.transform(train_filepaths)\nprint(\"List of dicts of ad-hoc features\", train_dict)\n\ndv = DictVectorizer(sparse = False)\nx_train = dv.fit_transform(train_dict)\ny_train = train_labels\nn = len(y_train)\nprint('Training with {} samples.'.format(n)) \n_ = clf.fit(x_train, y_train)\n \n# predict test samples (again through batches of `batch_size`)\nprint('Predicting test samples using batches...')\nstart = 0\nend = batch_size\ni = 1\ny_true = list()\ny_pred = list()\nwhile start < n_test:\n x_test = dv.transform(ts.transform(test_filepaths[start:end]))\n y_test = test_labels[start:end]\n n = len(y_test)\n print('Predicting batch #{} with {} samples.'.format(i, n))\n i += 1\n y_true += y_test\n y_pred += list(clf.predict(x_test))\n start += batch_size\n end += batch_size\n\ntn, fp, fn, tp = confusion_matrix(y_true=y_true, y_pred=y_pred).ravel()\nacc = accuracy_score(y_true=y_true, y_pred=y_pred)\nprecision = precision_score(y_true=y_true, y_pred=y_pred)\nrecall = recall_score(y_true=y_true, y_pred=y_pred)\nf1 = f1_score(y_true=y_true, y_pred=y_pred)\n\nprint('TP: {:d}'.format(tp))\nprint('TN: {:d}'.format(tn))\nprint('FP: {:d}'.format(fp))\nprint('FN: {:d}'.format(fn))\nprint('Precision: {:.4f}'.format(precision))\nprint('Recall: {:.4f}'.format(recall))\nprint('F1-score: {:.4f}'.format(f1))\nprint('Accuracy: {:.4f}'.format(acc))\n\n","sub_path":"code/adhoc_features.py","file_name":"adhoc_features.py","file_ext":"py","file_size_in_byte":5685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"447110920","text":"def findlongestvalue(data):\n key = \"\"\n key = (len(v) for k,v in data.items())\n return max(list(key))\n\ndef order_values(data):\n Range = findlongestvalue(data)\n lis = []\n for i in range(Range):\n nlis=[]\n for k,v in data.items():\n try:\n nlis.append(v[i])\n except IndexError:\n nlis.append(None)\n lis.append(nlis)\n return lis\n\n\ndef get_key(val,dic):\n print('hy!!!!!!')\n print(dic)\n for key, value in dic.items(): \n print(value)\n if val == value: \n return key \n return \"yooooo\"\n \n \ndit = {'hey':[1,2,3,4],'work':[1,2],3:[1,2,3,4,5,6,7,8],'damm':[1,2,3,4,5,6,7]}\nhey = [1,2,3,4]\n(a,(v,b,c,d))='h',hey\nprint(a)","sub_path":"flasker/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"460675251","text":"import os\nimport json\nimport threading\nimport uuid\nfrom twisted.internet import threads\n\nfrom ShuttleConfig import ShuttleConfig\nimport ShuttleJob\nfrom ShuttleGit import GitBuilder\nfrom ShuttleJob import JobStatus, UploadStatus\nfrom ShuttleLog import ShuttleLog\nimport glob\nfrom datetime import datetime\n\ncfg = ShuttleConfig()\nShuttleLog()\n\nlock = threading.Lock()\n\nclass PackageConfig():\n def __init__(self, pkgname, reponame='defaults'):\n _default = os.path.join(cfg.get('build','configdir'), 'package', reponame)\n if not os.path.exists(_default):\n _default = os.path.join(cfg.get('build','configdir'), 'package', 'defaults')\n default_config = os.path.join(_default, 'default.json')\n if os.path.exists(default_config):\n self.config = json.load(open(default_config))\n else:\n self.config = {}\n\n package_config = os.path.join(_default, '%s.json' % pkgname)\n if os.path.exists(package_config):\n self.config.update(json.load(open(package_config)))\n\n\nclass Repo():\n def __init__(self, name):\n self.name = name \n self.configdir = os.path.join(cfg.get('build', 'configdir'), 'repo')\n self.json_config = os.path.join(self.configdir, '%s.json' % name)\n if not os.path.exists(self.json_config):\n raise IOError(\"config not exists\")\n self.config = json.load(open(self.json_config))\n\n def packages(self, pkgs):\n result = []\n for pkg in pkgs:\n s_pkg = ShuttleJob.Package.selectBy(reponame=self.name, pkgname=pkg).orderBy(\"-id\")\n if s_pkg.count():\n result.append(s_pkg[0])\n else:\n result.append({'pkgname': pkg, 'pkgver': '-', 'upload_status': '-'})\n return result\n\n @property\n def dists(self):\n return self.config.get('dists', [])\n\n def arches(self, dist=None):\n if dist is None:\n return self.config.get('arches', [])\n else:\n arches = self.config.get('%s-arches' % dist, None)\n if arches is not None:\n return arches\n else:\n return self.config.get('arches', [])\n\n @property\n def description(self):\n _description = \"Description not filled in by author\"\n return self.config.get(\"description\", _description)\n\nclass Package():\n @staticmethod\n #def add(package, reponame, action, arches=None, sha=None, version=None):\n def add(package, reponame, action, arches, dist, sha=None, version=None, force=False):\n def _callback(result, dist, arches, division=None):\n version = result.get('version', None)\n if version is None:\n return {'status': 'failed', 'message': result.get('message', 'dummy')}\n if ShuttleJob.Package.selectBy(pkgname=pkgname, reponame=reponame, pkgver=version, action=action).count() != 0:\n os.system(\"rm -rf %s\" % result['path'])\n pkg = ShuttleJob.Package.selectBy(pkgname=pkgname, reponame=reponame, pkgver=version, action=action).orderBy(\"-id\")[0]\n #if job has builded, then skip rebuild\n if pkg.upload_status != UploadStatus.UNKNOWN:\n return {'id': pkg.id, 'status': 'failed', 'messsage': 'same version has alread built - status: %d' % pkg.upload_status} \n else:\n for job in pkg.jobs:\n job.status = JobStatus.WAIT\n return {'status': 'successful', 'messsage': 'rebuild version has alread built'} \n\n hashsum = result.get('hashsum', None)\n with lock:\n package = ShuttleJob.Package(pkgname=pkgname, reponame=reponame, pkgver=version, action=action, hashsum=hashsum)\n try:\n source_cache = os.path.join(cfg.get('build', 'cachedir'), 'debian-package', str(package.id), 'source')\n if not os.path.exists(source_cache):\n os.makedirs(source_cache)\n for _file in result['files']:\n os.system(\"install -Dm644 %s %s\" % (os.path.join(result['path'], _file), os.path.join(source_cache, _file)))\n\n info = {'build': datetime.now().strftime(\"%Y-%m-%d %H:%M\"),\n 'pkgname': pkgname,\n 'dist': dist,\n 'arches': arches,\n 'reponame': reponame,\n 'pkgver': version\n }\n if division is not None:\n info['division'] = division\n with open(os.path.join(source_cache, \"source.info\"), \"w\") as fp:\n fp.write(json.dumps(info, indent=4))\n\n finally:\n os.system(\"rm -rf %s\" % result['path'])\n\n for arch in arches:\n ShuttleJob.Job(package=package, arch=arch, dist=dist, status=JobStatus.WAIT)\n ShuttleLog.info(\"Add %s %s to %s\" % (pkgname, version, reponame))\n if action == \"tag\":\n rebuild_packages = config.get(\"rebuild\", [])\n for rebuild_name in rebuild_packages:\n if ShuttleJob.Package.selectBy(pkgname=rebuild_name, reponame=reponame, action=\"tag\").count() == 0:\n continue\n with lock:\n rebuild_package = ShuttleJob.Package.selectBy(pkgname=rebuild_name, reponame=reponame, action=\"tag\").orderBy(\"-id\")[0]\n if ShuttleJob.Package.selectBy(pkgname=rebuild_name, pkgver=rebuild_package.pkgver, reponame=reponame, action=\"rebuild\").count() == 0:\n binnmu = 1\n else:\n last_rebuild = ShuttleJob.Package.selectBy(pkgname=rebuild_name, pkgver=rebuild_package.pkgver, reponame=reponame, action=\"rebuild\").orderBy(\"-id\")[0]\n binnmu = int(last_rebuild.binnmu) + 1\n with lock:\n save_rebuild = ShuttleJob.Package(pkgname=rebuild_name, reponame=reponame, pkgver=rebuild_package.pkgver, hashsum=rebuild_package.hashsum, action=\"rebuild\", binnmu=binnmu)\n\n _cache_dir = cfg.get('build', 'cachedir')\n save_rebuild_cache = os.path.join('debian-package', str(save_rebuild.id)) \n rebuild_source_cache = os.path.join('debian-package', str(rebuild_package.id), 'source')\n if os.path.exists(os.path.join(_cache_dir, save_rebuild_cache)):\n os.system(\"rm -rf %s\" % os.path.join(_cache_dir, save_rebuild_cache))\n os.makedirs(os.path.join(_cache_dir, save_rebuild_cache))\n os.system(\"cd %s && ln -rsf %s %s\" % (_cache_dir, rebuild_source_cache, save_rebuild_cache))\n\n save_rebuild.add_dep(package)\n for arch in arches:\n ShuttleJob.Job(package=save_rebuild, arch=arch, dist=dist, status=JobStatus.WAIT)\n\n return {'id': package.id, 'status': 'successful', 'version': version, 'pkgname': pkgname, 'reponame': reponame}\n\n try:\n if isinstance(package, dict):\n pkgname = package.get('pkgname')\n config = package\n else:\n pkgname = package\n config = PackageConfig(pkgname, reponame).config\n except Exception as e:\n return {'status': 'failed', 'message': 'package config can not loaded: %s' % json_config}\n\n builder = GitBuilder(pkgname=pkgname, config=config)\n\n if reponame is None:\n reponame = config.get('ppa', None)\n\n if reponame is None:\n return {'status': 'failed', 'message': 'reponame should specify'}\n\n if action in ['commit', 'nightly']:\n if dist is None:\n dist = 'experimental'\n t = threads.deferToThread(builder.archive, action, sha, \"low\", force)\n elif action == 'tag':\n #dist = 'unstable'\n t = threads.deferToThread(builder.tag, version, None, reponame)\n\n division = None\n try:\n divisions = config.get('divisions', None)\n if divisions is not None:\n division = divisions.get(dist, None)\n except Exception as e:\n pass\n\n t.addCallback(_callback, dist, arches, division)\n return t\n\n @staticmethod\n def delete(pkgid):\n pkgs = shuttle.get_all_packages(id=pkg)\n if len(pkgs) != 0:\n pkg = pkgs[0]\n jobs = shuttle.get_all_jobs(packageID=pkg.id)\n for job in jobs:\n job.destroySelf()\n pkg.destroySelf()\n ShuttleLog.info(\"Delete %s %s\" % (pkg.pkgname, pkg.pkgver))\n return {'status': 'successful'}\n else:\n return {'status': 'failed'}\n\n @staticmethod\n def requeue_upload(pkgid):\n if ShuttleJob.Package.selectBy(id=pkgid).count() == 0:\n return {'status': 'skip'}\n\n pkg = ShuttleJob.Package.selectBy(id=pkgid)[0]\n if pkg.upload_status > UploadStatus.UPLOADING:\n ShuttleLog.info(\"Requeue %s %s from %s to WAIT\" % (pkg.pkgname, pkg.pkgver, UploadStatus.whatis(pkg.upload_status)))\n pkg.upload_status = UploadStatus.WAIT\n else:\n ShuttleLog.info(\"Skip requeue %s %s with %s\" % (pkg.pkgname, pkg.pkgver, UploadStatus.whatis(pkg.upload_status)))\n return {'status': 'successful'}\n\nclass LoopAddPackage():\n def __init__(self, reponame):\n self.packages = []\n self.configdir=cfg.get('build', 'configdir')\n self.reponame = reponame\n self.package_config = os.path.join(self.configdir, 'package', reponame)\n if not os.path.exists(self.package_config):\n print(\"W: %s is not exists.Set as defaults\" % self.package_config)\n self.package_config = os.path.join(self.configdir, 'package', 'defaults')\n\n for _json in glob.glob(os.path.join(self.package_config, '*.json')):\n package = os.path.basename(_json)[:-5]\n if package not in ['default']:\n self.packages.append(package)\n\n def get_version(self, pkgname, ref=None):\n if pkgname not in self.packages:\n return None\n pkgconfig = os.path.join(self.package_config, '%s.json' % pkgname)\n config = json.load(open(pkgconfig, \"r\"))\n package = GitBuilder(pkgname, config)\n package.initial()\n if ref is None:\n version = package.get_release_version(url=package.source, ref=package.source_ref, cwd=package.source_cache)\n else:\n version = package.get_release_version(url=package.source, ref=ref, cwd=package.source_cache)\n\n return version\n\n def loop(self, ignore_commit=True, arches=['amd64', 'i386']):\n for package in self.packages:\n try:\n pkgver = self.get_version(package)\n except Exception as e:\n print(\"%s Error: %s\" % (package, e))\n pkgver = None\n if pkgver is None:\n continue\n if pkgver['fallback'] is False:\n hashsum = self.get_version(package, pkgver['ver'])['sha']\n if ShuttleJob.Package.selectBy(pkgname=package, reponame=self.reponame, action='tag', hashsum=hashsum).count() == 0:\n Package().add(package=package, reponame=self.reponame, sha=pkgver['sha'], action=\"tag\", arches=arches)\n\n if not ignore_commit:\n comver = \"%(ver)s+r%(rev)s~%(sha)s\" % pkgver\n if ShuttleJob.Package.selectBy(pkgname=package, reponame=self.reponame, pkgver=comver).count() == 0:\n with lock:\n Package().add(package=package, reponame=self.reponame, sha=pkgver.get('sha', None), action=\"commit\")\n","sub_path":"shuttle/ShuttleStore.py","file_name":"ShuttleStore.py","file_ext":"py","file_size_in_byte":11852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"229295095","text":"__author__ = 'zhufeng'\n\nimport csv\n\nimport pymysql\n\n\nconn = pymysql.connect(host=\"localhost\", user=\"root\", database=\"ocenter_datapush\")\n\ncursor = conn.cursor()\n\ncursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS app_msg_stat(\n id BIGINT(20) NOT NULL AUTO_INCREMENT,\n app_key VARCHAR(32),\n type VARCHAR(10),\n msg_num INT(11),\n PRIMARY KEY (id)\n ) ENGINE =InnoDB DEFAULT CHARSET=UTF8\"\"\")\n\nconn.commit()\n\n# with open(\"/fls/3.27.csv\", encoding=\"gbk\") as csvfile:\n# reader = csv.reader(csvfile)\n# jump_first = True\n# for row in reader:\n# if jump_first:\n# jump_first = False\n# continue\n#\n# sql = \"INSERT INTO rds_db_type(rds_name, msg_num) VALUES ('\" + row[2] + \"\\',\" + row[6] + \")\"\n# print(sql)\n# cursor.execute(sql)\n# conn.commit()\n\n\nwith open(\"/fls/70594349.csv\", encoding='gbk') as csvfile:\n reader = csv.reader(csvfile)\n is_first = True\n for row in reader:\n if is_first:\n is_first = False\n continue\n sql = \"INSERT INTO app_msg_stat (app_key, type, msg_num) VALUES (%s, '%s', %s)\" % (row[1], row[2], row[4])\n\n cursor.execute(sql)\n conn.commit()\n\n","sub_path":"AnalyzeRDS/analyze_rds_type.py","file_name":"analyze_rds_type.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"405218277","text":"'''\nReinforcement Learning by Sutton and Barto\n5. Monte Carlo Methods\n5.4 On-Policy Monte Carlo Control\nExample 5.3: Solving Blackjack\n'''\nimport numpy as np\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\nHIT = 0\nSTICK = 1\nACTIONS = (HIT, STICK)\n\n\ndef generate_episode(policy):\n dealer_showing = min(np.random.randint(1, 14), 10)\n dealer_hidden = min(np.random.randint(1, 14), 10)\n dealer_sum = 0\n dealer_usable_ace = False\n dealer_sum += dealer_showing\n if dealer_showing == 1:\n dealer_sum += 10\n dealer_usable_ace = True\n dealer_sum += dealer_hidden\n if dealer_sum > 21 and dealer_usable_ace:\n dealer_sum -= 10\n dealer_usable_ace = False\n if dealer_hidden == 1 and dealer_sum <= 11:\n dealer_sum += 10\n dealer_usable_ace = True\n\n states = []\n actions = []\n player_sum = 0\n player_cards_num = 0\n usable_ace = False\n action = HIT\n while action == HIT:\n player_card = min(np.random.randint(1, 14), 10)\n player_cards_num += 1\n player_sum += player_card\n if player_sum > 21 and usable_ace:\n player_sum -= 10\n usable_ace = False\n if player_card == 1 and player_sum <= 11:\n player_sum += 10\n usable_ace = True\n if player_sum <= 11:\n continue\n if player_sum > 21:\n break\n s = (player_sum, dealer_showing, usable_ace)\n action = np.random.choice(ACTIONS, p=policy[s])\n states.append(s)\n actions.append(action)\n \n reward = 0\n if player_sum == 21 and player_cards_num == 2:\n if dealer_sum == 21:\n reward = 0\n else:\n reward = 1\n elif player_sum > 21:\n reward = -1\n else:\n while dealer_sum < 17:\n dealer_card = min(np.random.randint(1, 14), 10)\n dealer_sum += dealer_card\n if dealer_sum > 21 and dealer_usable_ace:\n dealer_sum -= 10\n dealer_usable_ace = False\n if dealer_card == 1 and dealer_sum <= 11:\n dealer_sum += 10\n dealer_usable_ace = True\n if dealer_sum > 21:\n reward = 1\n else:\n if player_sum > dealer_sum:\n reward = 1\n elif player_sum < dealer_sum:\n reward = -1\n else:\n reward = 0\n return reward, states, actions\n\n\ndef plot_policy(policy, usable_ace, ax):\n policy_arr = []\n for player_sum in range(22):\n policy_arr.append([])\n for dealer_showing in range(11):\n s = (player_sum, dealer_showing, usable_ace)\n greedy_action = np.argmax(policy[s])\n policy_arr[-1].append(greedy_action)\n ax.matshow(policy_arr, cmap=cm.coolwarm)\n ax.xaxis.set_ticks_position('bottom')\n ax.invert_yaxis()\n ax.set_xlim(0.5, 10.5)\n ax.set_ylim(10.5, 21.5)\n\n\ndef plot_V(V, usable_ace, ax):\n z = np.zeros((10, 10))\n for player_sum in range(12, 22):\n for dealer_showing in range(1, 11):\n z[player_sum - 12][dealer_showing - 1] = V[player_sum, dealer_showing, usable_ace]\n \n x = range(1, 11)\n y = range(12, 22)\n x, y = np.meshgrid(x, y)\n \n ax.plot_surface(x, y, z, cmap=cm.coolwarm)\n ax.set_xlim(1, 11)\n ax.set_ylim(11, 21)\n ax.set_zlim(-1, 1)\n\n\ndef plot_policy_and_V(policy, V):\n fig = plt.figure()\n \n ax1 = fig.add_subplot(221)\n ax1.set_title('π*\\nUsable Ace')\n plot_policy(policy, True, ax1)\n ax2 = fig.add_subplot(223)\n ax2.set_title('No Usable Ace')\n ax2.set_xlabel('Dealer Showing')\n ax2.set_ylabel('Player Sum')\n plot_policy(policy, False, ax2)\n \n ax3 = fig.add_subplot(222, projection='3d')\n ax3.set_title('V*\\nUsable Ace')\n plot_V(V, True, ax3)\n ax4 = fig.add_subplot(224, projection='3d')\n ax4.set_title('No Usable Ace')\n ax4.set_xlabel('Dealer Showing')\n ax4.set_ylabel('Player Sum')\n plot_V(V, False, ax4)\n \n plt.subplots_adjust(hspace=0.5)\n plt.show()\n\n\nclass Agent(object):\n def __init__(self, actions, eps):\n actions_num = len(actions)\n self.actions = actions\n self.eps = eps\n self.Q = defaultdict(lambda: np.zeros(actions_num))\n self.cnt_Q = defaultdict(lambda: np.zeros(actions_num))\n self.V = defaultdict(float)\n self.cnt_V = defaultdict(int)\n self.policy = defaultdict(lambda: np.ones(actions_num)/actions_num)\n \n \n def evaluate_policy(self, reward, states, actions):\n for s, a in zip(states, actions):\n self.cnt_Q[s][a] += 1\n self.Q[s][a] += (reward - self.Q[s][a])/self.cnt_Q[s][a]\n for s in states:\n self.cnt_V[s] += 1\n self.V[s] += (reward - self.V[s])/self.cnt_V[s]\n\n \n def improve_policy(self, states):\n actions_num = len(self.actions)\n for s in states:\n greedy_action = np.argmax(self.Q[s])\n for a in self.actions:\n if a == greedy_action:\n self.policy[s][a] = 1 - self.eps + self.eps/actions_num\n else:\n self.policy[s][a] = self.eps/actions_num\n\n\ndef main():\n np.random.seed(0)\n episodes_num = 2000000\n agent = Agent(ACTIONS, eps=0.2)\n \n for i in range(episodes_num):\n reward, states, actions = generate_episode(agent.policy)\n agent.evaluate_policy(reward, states, actions)\n agent.improve_policy(states)\n\n plot_policy_and_V(agent.policy, agent.V)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"5_monte_carlo_methods/blackjack_on_policy.py","file_name":"blackjack_on_policy.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"367465278","text":"from pokemon_class import Pokemon\nfrom pokemon_class import Attack\nfrom character_class import Trainer\nfrom character_class import Enemy\nfrom validate import Validate\nfrom battle import Battle\nfrom location_class import Location\nfrom ascii import *\n\n\n\nflamethrower = Attack(\"Flamethrower\", 40)\nfire_blast = Attack(\"Fire Blast\", 50)\nwaterfall = Attack(\"Waterfall\", 40)\nhydro_pump = Attack(\"Hydro Pump\", 50)\ngiga_drain = Attack(\"Giga Drain\", 40)\nsolar_beam = Attack(\"Solar Beam\", 50)\nwing_attack = Attack(\"Wing Attack\", 35)\ndrill_peck = Attack(\"Drill Peck\", 40)\nfly = Attack(\"Fly\", 50)\ntackle = Attack(\"Tackle\", 30)\nscratch = Attack(\"Scratch\", 35)\nrapid_spin = Attack(\"Rapid Spin\", 35)\nslash = Attack(\"Slash\", 35)\nmega_punch = Attack(\"Mega Punch\", 35)\ntri_attack = Attack(\"Tri Attack\", 40)\nhyperbeam = Attack(\"Hyperbeam\", 55)\nfeint_attack = Attack(\"Feint Attack\", 35)\npay_back = Attack(\"Pay Back\", 40)\ncrunch = Attack(\"Crunch\", 40)\nthunder_bolt = Attack(\"Thunder Bolt\", 35)\nthunder = Attack(\"Thunder\", 50)\nhigh_jump_kick = Attack(\"High Jump Kick\", 50)\nconfusion = Attack(\"Confusion\", 40)\npsychic = Attack(\"Psychic\", 60)\npsybeam = Attack(\"Psybeam\", 50)\nsludge_bomb = Attack(\"Sludge Bomb\", 40)\nacid = Attack(\"Acid\", 40)\nice_punch = Attack(\"Ice Punch\", 35)\nice_beam = Attack(\"Ice Beam\", 50)\nplay_rough = Attack(\"Play Rough\", 40)\n\n\n#\npersian_attacks = [scratch, play_rough, feint_attack, pay_back]\nmewtwo_attacks = [psychic, confusion, tri_attack, ice_beam]\nkoffing_attacks = [sludge_bomb, pay_back, acid, tackle]\nhoundoom_attacks = [fire_blast, crunch, feint_attack, flamethrower]\nmurkrow_attacks = [wing_attack, drill_peck, tackle, pay_back]\narbok_attacks = [sludge_bomb, crunch, acid, feint_attack]\ngrimer_attacks = [acid, feint_attack, tackle, scratch]\nraticate_attacks = [slash, feint_attack, tackle, scratch]\n\n# Pokemon attack list\ncharizard_attacks = [flamethrower, wing_attack, slash, fire_blast]\nblastoise_attacks = [hydro_pump, waterfall, rapid_spin, crunch]\nvenusaur_attacks = [solar_beam, sludge_bomb, acid, giga_drain]\nalakazam_attacks = [confusion, psybeam, tri_attack, flamethrower]\nsnorlax_attacks = [hyperbeam, mega_punch, ice_punch, crunch]\ngyarados_attacks = [hydro_pump, waterfall, drill_peck, crunch]\nmachamp_attacks = [high_jump_kick, mega_punch, pay_back, ice_punch]\nelectabuzz_attacks = [thunder, thunder_bolt, slash, play_rough]\npidgeot_attacks = [wing_attack, drill_peck, slash, fly]\n\n# Enemy Pokemon\npersian = Pokemon(\"Persian\", 130, 130, persian_attacks)\nmewtwo = Pokemon(\"Mewtwo\", 150, 140, mewtwo_attacks)\nkoffing = Pokemon(\"Koffing\", 120, 120, koffing_attacks)\nhoundoom = Pokemon(\"Houndoom\", 130, 130, houndoom_attacks)\nmurkrow = Pokemon(\"Murkrow\", 120, 120, murkrow_attacks)\narbok = Pokemon(\"Arbok\", 130, 130, arbok_attacks)\ngrimer = Pokemon(\"Grimer\", 110, 110, grimer_attacks)\nraticate = Pokemon(\"Raticate\", 120, 120, raticate_attacks)\n\n# User Pokemon\ncharizard = Pokemon(\"Charizard\", 110, 110, charizard_attacks)\nblastoise = Pokemon(\"Blastoise\", 125, 125, blastoise_attacks)\nvenusaur = Pokemon(\"Venusaur\", 125, 125, venusaur_attacks)\nalakazam = Pokemon(\"Alakazam\", 110, 110, alakazam_attacks)\nsnorlax = Pokemon(\"Snorlax\", 170, 170, snorlax_attacks)\ngyarados = Pokemon(\"Gyarados\", 120, 120, gyarados_attacks)\nmachamp = Pokemon(\"Machamp\", 120, 120, machamp_attacks)\nelectabuzz = Pokemon(\"Electabuzz\", 120, 120, electabuzz_attacks)\npidgeot = Pokemon(\"Pidgeot\", 120, 120, pidgeot_attacks)\n\n\npokemon_party = []\noptions = [charizard, blastoise, venusaur, alakazam, snorlax, gyarados, machamp, electabuzz, pidgeot]\n\n\n\n# Location Options\nunion_cave_options = [1]\necruteak_city_options = [2, 4, 5, 3]\npokemon_center_options = [1]\nold_man_options = [1]\nroute_34_options = [1]\nslowpoke_well_options = [6, 1]\nmain_room_options = [7, 8, 9, 5]\ngrunt_office_options = [5]\ncracked_wall_options = [5]\nsean_office_options = [1]\n\n\n# Locations\nunion_cave = Location(\"Union Cave\", union_cave_options, \"After several hours of wandering about, you finally navigate your way out of the dark, tricky cave. Ahead of you is a sign: Ecruteak City - 500 feet\")\necruteak_city = Location(\"Ecruteak City\", ecruteak_city_options, \"You're in Ecruteak City. Birds are chirping and life is good.\")\npokemon_center = Location(\"Pokemon Center\", pokemon_center_options, \"You walk into the Pokemon Center. Nurse Joy greets you\")\nroute_34 = Location(\"Route 34\", route_34_options, \"You leave the city and are now on Route 34. There are trainers all around you battling\")\nold_man = Location(\"House with garden\", old_man_options, \"Old man: Hello youngster. Are you new to town? Keep a close eye on your pokemon, strange things have been happening around town lately.\")\nslowpoke_well = Location(\"Inside Slowpoke Well\", slowpoke_well_options, \"You are now inside the slowpoke well. The inside is a lot larger than you imagined. It has dim lighting and feels humid\")\nmain_room = Location(\"Deep Inside Slowpoke Well\", main_room_options, \"You are deep inside the well. You notice a ladder to your right leading down, and a fairly large crack in the wall to your left.\")\ngrunt_office = Location(\"Grunt Office\", grunt_office_options, \"You descend down the ladder and find yourself inside a room that looks like an office. There are slowpokes in the corner, each missing their tails. You spot a Team Rocket member at the end of the room, but he has yet to spot you.\")\ncracked_wall = Location(\"Crack in the wall\", cracked_wall_options, \"You crawl through the crack in the wall and emerge into a large area. There are dozens of slowpoke hanging by a small body of water. You notice a Team Rocket member pushing a large cart.\")\nsean_office = Location(\"Sean's office\", sean_office_options, \"You enter the room. Inside, you find the man in charge of the entire operation. He notices you, but does not react.\")\nlocations = [union_cave, ecruteak_city, pokemon_center, old_man, route_34, slowpoke_well, main_room, grunt_office, cracked_wall, sean_office]\n\n\ntrainer_name = input(\"Enter a name \")\nsean = Enemy(\"Team Rocket Leader Sean\", \"Sean: Spelling isn't your only nemesis today.\", [persian, mewtwo])\nsampai = Enemy(\"Rocket Grunt Sam-pai\", \"Sam-pai: You're going nowhere! I've got you for 3 minutes.\", [murkrow, arbok])\nzachary = Enemy(\"Rocket Grunt Zachary\", \"Zachary: Finally, something to do.\", [koffing, houndoom])\n# joey = Enemy(\"Younger Joey\", \"I just lost, so I'm trying to find more Pokemon. Wait! You look weak! Come on, lets battle!\")\n# abe = Enemy(\"Birdkeeper Abe\", \"You're not as fly as me!\")\ntrainer = Trainer(trainer_name, pokemon_party, union_cave)\n\n\n\n\ndef choose_pokemon(trainer, choices):\n count = 0\n while len(choices) > count:\n print(f'{count + 1}. {choices[count].name}')\n count += 1\n user_input = Validate().range(1, len(choices), \"please enter a valid option. \", \"Select a pokemon you would like to add to your party. \")\n trainer.pokemon_party.append(choices[user_input - 1])\n print(f'You chose {choices[user_input - 1].name}!')\n choices.remove(choices[user_input - 1])\n input(\"Press enter to continue\")\n print(\"\\033c\")\n\n\nrunning = True\n\ndef play_game(trainer):\n logo_img()\n while running:\n print(f'Current Location: {trainer.location.name}\\n')\n print(f'{trainer.location.description}\\n\\n')\n count = 0\n while count < len(trainer.location.options):\n print(f'{count + 1}. {locations[trainer.location.options[count]].name}')\n count += 1\n location_choice = Validate().range(1, len(trainer.location.options), \"Please choose a valid option\", \"Where would you like to go? \")\n trainer.location = locations[trainer.location.options[location_choice - 1]]\n print(\"\\033c\")\n\nplay_game(trainer)\n\n# def play_game():\n# logo_img()\n# input(\"Press enter to continue\")\n# print(\"\\033c\")\n# choose_pokemon(trainer,options)\n# choose_pokemon(trainer,options)\n# choose_pokemon(trainer,options)\n# while True:\n# if trainer.location == 'Union Cave':\n# current_location(union_cave)\n\n# elif trainer.location == 'Ecruteak City':\n# current_location(ecruteak_city)\n\n# elif trainer.location == 'Pokemon Center':\n# current_location(pokemon_center)\n\n# elif trainer.location == \"Enter house with garden\":\n# current_location(old_man)\n\n# elif trainer.location == 'Route 34':\n# current_location(route_34)\n \n# elif trainer.location == 'Battle youngster trainer':\n# joey_battle.battle()\n# current_location(route_34)\n\n# elif trainer.location == 'Battle birdkeeper trainer':\n# abe_battle.battle()\n# current_location(route_34)\n\n# elif trainer.location == 'Slowpoke Well':\n# current_location(slowpoke_well)\n\n# elif trainer.location == \"Back to Slowpoke Well Entrance\":\n# current_location(main_room)\n \n# elif trainer.location == \"Walk deeper into well\":\n# current_location(main_room)\n \n# elif trainer.location == \"Explore down the ladder\":\n# current_location(grunt_office)\n \n# elif trainer.location == \"Explore crack in the wall\":\n# current_location(cracked_wall)\n\n# elif trainer.location == \"Try the large metal door\":\n# current_location(sean_office)\n\n# elif trainer.location == \"Battle Team Rocket Leader\":\n# sean_battle.battle()\n# current_location(sean_office)\n \n# elif trainer.location == \"Ladder leading out to Ecruteak City\":\n# current_location(ecruteak_city)\n\n\n# sean_battle = Battle(trainer, sean)\n# joey_battle = Battle(trainer, joey)\n# abe_battle = Battle(trainer, abe)\n# zachary_battle = Battle(trainer, zachary)\n# sam_battle = Battle(trainer, sampai)\n# play_game()\n\n\n# current_location(location)\n# # Player chooses 3 pokemon\n# choose_pokemon(trainer, options)\n# choose_pokemon(trainer, options)\n# choose_pokemon(trainer, options)\n\n# sean_battle = Battle(trainer, sean)\n# sean_battle.battle()\n\n","sub_path":"body.py","file_name":"body.py","file_ext":"py","file_size_in_byte":9792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"415816810","text":"from wtforms import Form, BooleanField, StringField, IntegerField, SelectField\nfrom wtforms.validators import DataRequired\n\n\nclass NewEngagement(Form):\n name = StringField(u'* Name', validators=[DataRequired()])\n client = StringField(u'* Client', validators=[DataRequired()])\n sowlink = StringField(u'* Statement of Works Link', validators=[DataRequired()])\n probability = SelectField(\n u'* Probability',\n choices=[('0.0', '0%'), ('0.1', '10%'), ('0.2', '20%'),\n ('0.3', '30%'), ('0.4', '40%'), ('0.5', '50%'),\n ('0.6', '60%'), ('0.7', '70%'), ('0.8', '80%'),\n ('0.9', '90%'), ('1.0', '100%')],\n coerce=str,\n validators=[DataRequired()])\n sustainability = SelectField(\n u'* Sustainability',\n choices=[('0.1', '10%'), ('0.2', '20%'), ('0.3', '30%'),\n ('0.4', '40%'), ('0.5', '50%'), ('0.6', '60%'),\n ('0.7', '70%'), ('0.8', '80%'), ('0.9', '90%'),\n ('1.0', '100%')],\n coerce=str,\n validators=[DataRequired()])\n alignment = SelectField(\n u'* Alignment',\n choices=[('0.0', '0%'), ('0.1', '10%'), ('0.2', '20%'),\n ('0.3', '30%'), ('0.4', '40%'), ('0.5', '50%'),\n ('0.6', '60%'), ('0.7', '70%'), ('0.8', '80%'),\n ('0.9', '90%'), ('1.0', '100%')],\n coerce=str,\n validators=[DataRequired()])\n revenue = IntegerField(u'Revenue Per Iteration')\n status = SelectField(\n u'* Status',\n choices=[(u'Complete', u'Complete'), (u'Sold', u'Sold'), (u'Negotiation', u'Negotiation'), (u'Approach', u'Approach'), (u'Lost', u'Lost')],\n coerce=str,\n validators=[DataRequired()])\n complexity = SelectField(\n u'* Complexity',\n choices=[('0.1', u'Tiny'), ('0.5', u'Small'), ('1.0', u'Medium'), ('2.0', u'Large')],\n coerce=str,\n validators=[DataRequired()])\n isrnd = BooleanField(u'Tick if eligable for research and development tax credits')\n\n","sub_path":"planner/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"482179704","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom . import views\n\napp_name= 'home'\n\nurlpatterns = [\n url(r'^$', views.index , name='index'),\n\n#Actor:\n\n url(r'^actor/$', views.actor , name='actor'),\n url(r'^actor/(?P\\d+)/$', views.actor_detail, name='actor_detail'),\n url(r'^actors/(?P.+?)/$', views.actors_select, name='actors_select'),\n\n#Actress:\n\n url(r'^actress/$', views.actress , name='actress'),\n url(r'^actress/(?P\\d+)/$', views.actress_detail, name='actress_detail'),\n url(r'^actoresses/(?P.+?)/$', views.actress_select, name='actress_select'),\n\n#Directors:\n\n url(r'^directors/$', views.directors , name='directors'),\n url(r'^directors/(?P\\d+)/$', views.directors_detail, name='directors_detail'),\n url(r'^director/(?P.+?)/$', views.directors_select, name='directors_select'),\n\n#Movieslist:\n\n url(r'^movieslist/$', views.movieslist , name='movieslist'),\n url(r'^movieslist/(?P\\d+)/$', views.movieslist_detail, name='movieslist_detail'),\n url(r'^movieslists/(?P.+?)/$', views.movieslist_select, name='movieslist_select'),\n\n#Genres:\n\n url(r'^genres/$', views.genres , name='genres'),\n url(r'^genres/(?P\\d+)/$', views.genres_detail, name='genres_detail'),\n url(r'^genre/(?P.+?)/$', views.genres_select, name='genres_select'),\n\n#Rating:\n\n url(r'^rating/$', views.rating , name='rating'),\n url(r'^rating/(?P\\d+)/$', views.rating_detail, name='rating_detail'),\n url(r'^ratings/(?P.+)/$', views.rating_select, name='rating_select'),\n url(r'^rating/(?P.+)/(?P.+)/$', views.rating_betw, name='rating_betw'),\n\n\n#Plots:\n \n url(r'^plots/$', views.plots , name='plots'),\n url(r'^plots/(?P\\d+)/$', views.plots_detail, name='plots_detail'),\n url(r'^plot/(?P.+?)/$', views.plot_select, name='plot_select'),\n]","sub_path":"imdb/home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"577675309","text":"#from collections.abc import MutableMapping\nfrom typing import AbstractSet, Dict, Iterator, TypeVar, Mapping, Set, MutableMapping, Generic\nimport typing\n\nKT = TypeVar('KT')\nVT = TypeVar('VT')\n\n\nclass JournaledMapping(MutableMapping[KT, VT], Generic[KT, VT]):\n def __init__(self, lower: Mapping[KT, VT]):\n self.lower = lower\n self.top: Dict[KT, VT] = dict()\n self.deleted: Set[KT] = set()\n\n def keys(self) -> AbstractSet[KT]:\n return (self.lower.keys() | self.top.keys()) - self.deleted\n\n def __getitem__(self, k) -> VT:\n if k in self.deleted:\n raise KeyError(k)\n if k in self.top:\n return self.top[k]\n return self.lower[k]\n\n def __setitem__(self, k: KT, v: VT):\n self.deleted.discard(k)\n self.top[k] = v\n\n def __delitem__(self, k: KT) -> None:\n if k in self.deleted:\n raise KeyError(k)\n found = False\n if k in self.lower:\n self.deleted.add(k)\n found = True\n if k in self.top:\n del self.top[k]\n found = True\n if not found:\n raise KeyError(k)\n\n def __iter__(self) -> Iterator[KT]:\n return self.keys().__iter__()\n\n def __len__(self) -> int:\n return len(self.keys())\n\n# TESTS\n\n_base_dict = {\"lower\": True, \"deleted\" : False, \"overwrite\" : False}\n_base_dict_copy = _base_dict.copy()\n\ndef jm():\n jm = JournaledMapping(_base_dict)\n del jm[\"deleted\"]\n jm[\"overwrite\"] = True\n jm[\"top\"] = True\n return jm\n\n\ndef test_basic(jm):\n assert jm[\"lower\"]\n assert jm[\"top\"]\n assert jm[\"overwrite\"]\n assert \"deleted\" not in jm\n\ndef _test_delete(jm, key):\n del jm[key]\n assert key not in jm, \"failed to delete\" \n try:\n del jm[key]\n except KeyError:\n pass\n else:\n raise Exception(\"double delete should fail\")\n\ndef test_iter(jm: JournaledMapping):\n for k,v in jm.items():\n print(k,v)\n\ndef test_keys(jm: JournaledMapping):\n keys = jm.keys()\n assert keys == {'lower', 'top', 'overwrite'}\n\ndef test_delete_top(jm):\n return _test_delete(jm, \"top\")\n\ndef test_delete_lower(jm):\n return _test_delete(jm, \"lower\")\n\ntest_delete_top(jm())\ntest_delete_lower(jm())\ntest_iter(jm())\ntest_keys(jm())\n\nfor x in _base_dict.__iter__():\n print(x)","sub_path":"src/ucel/journaled.py","file_name":"journaled.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"441644705","text":"import ctypes\n\nfrom PyQt5.QtGui import QFont, QIcon\nfrom PyQt5.QtWidgets import QMainWindow\n\nfrom paste_printer.gui.central_widget import Central_Widget\nfrom paste_printer.gui.customization.load_font import load_font\nfrom paste_printer.util.file_handler import File_Handler\n\n\nclass Main_Screen(QMainWindow):\n\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n self.file_handler = File_Handler()\n\n # Create program name\n program_name = \"G-Code Modifier \"\n program_version = \"1.0\"\n\n # Set Name Of Program\n self.setWindowTitle(program_name + program_version)\n\n # change program icon\n self.setWindowIcon(QIcon(str(self.file_handler.icon_png_path)))\n\n # change Font\n load_font(self.file_handler.used_font_path)\n self.setFont(QFont(\"Eurostile LT Std\", 18))\n heading_font = QFont(\"Eurostile LT Std\", 18, weight=QFont.Bold)\n\n # change taskbar icon\n myappid = program_name + program_version # arbitrary string\n ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)\n\n # Set name of Window (Starting x, starting y, width, height\n #self.setGeometry(180, 180, 720, 720)\n\n # Add left hand side\n central_widget = Central_Widget()\n self.setCentralWidget(central_widget)\n","sub_path":"src/paste_printer/gui/main_screen.py","file_name":"main_screen.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"171959056","text":"'''\n Find the number intermedaite(non-leaf) Nodes in a given Binary tree\n Exapmle :\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n\n intermedaite(Non-Leaf) Nodes : 3 (i.e. 1,2,3)\n'''\n\n\nfrom TreeNode import Node\n\n\ndef non_leaf(root):\n \"\"\"\n Function to Find the number intermedaite Nodes(Non-Leaf) in a given Binary tree\n Syntax: non_leaf(root) \n Time Complexity: O(n) \n Recurrence Relation :\n Best Case : T(n)=2T(n/2)+C (C represents constant) \n Worst Case : T(n)=T(n-1)+C (C represents constant) \n \"\"\"\n # if Tree is empty\n if not root:\n return 0 \n\n #if leaf node \n if root.left==None and root.right==None:\n return 0\n\n #recursively compute intermediate nodes in left and right subtree \n left_subtree_non_leaf=non_leaf(root.left)\n right_subtree_non_leaf=non_leaf(root.right)\n\n #compute the total intermediates node by considering current intermediate node , left_subtree_non_leaf node and right_subtree_non_leaf node\n total_non_leaf=left_subtree_non_leaf+right_subtree_non_leaf+1\n \n return total_non_leaf\n \n \n \n\na=Node(1)\nb=Node(2)\nc=Node(3)\nd=Node(4)\ne=Node(5)\nf=Node(6)\ng=Node(7)\na.left=b\na.right=c\nb.left=d\nb.right=e\nc.left=f\nc.right=g\n\nresult=non_leaf(a)\nprint(result)","sub_path":"Trees/Intermediate Nodes.py","file_name":"Intermediate Nodes.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"614493631","text":"# -*- coding: utf-8 -*-\nfrom aip import AipSpeech\nimport os\n\nAPP_ID = '18139977'\nAPI_KEY = 'G8LLOmt8fivpBX0RPQNzQKwc'\nSECRET_KEY = 'x2LbbQFHepdaI3fnxsk7LBbEYh9KlH7S'\n\nclient = AipSpeech(APP_ID, API_KEY, SECRET_KEY)\n\n# 读取文件\ndef get_file_content(filePath):\n os.system(f\"ffmpeg -y -i {filePath} -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.pcm\")\n with open(f\"{filePath}.pcm\", 'rb') as fp:\n return fp.read()\n\n# 识别本地文件\nret = client.asr(get_file_content('1.m4a'), 'pcm', 16000, {\n 'dev_pid': 1536,\n})\n\nprint(ret)","sub_path":"s2.py","file_name":"s2.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"74077750","text":"# Authors:\n# Loic Gouarin \n# Benjamin Graille \n# Thibaut Van Hoof \n#\n# License: BSD 3 clause\n\nimport ipyvuetify as v\n\nfrom .pylbmwidget import out\n\nimport sympy as sp\nfrom traitlets import Unicode, Float, List, Bool\n\nfrom schema.utils import SchemeVelocity, RelaxationParameterFinal\n\nfrom .debug import debug\nfrom .dialog_form import Form, Item, Dialog, add_rule\nfrom ..utils import required_fields, FloatField, RelaxField\n\n@debug\nclass DesignForm(Form):\n def __init__(self, test_case_widget, lb_scheme_widget, discret_widget, **kwargs):\n self.test_case_widget = test_case_widget\n self.lb_scheme_widget = lb_scheme_widget\n self.discret_widget = discret_widget\n self.params, self.relax_params = None, None\n\n self.select_param = v.Select(label='Parameters', v_model=None, items=[])\n self.select_relax = v.Select(label='Relaxation parameters', v_model=[], items=[], multiple=True, class_='d-none')\n self.srt_relax = v.Switch(label='Single relaxation time', v_model=True, class_='d-none')\n self.sigma = v.Switch(label='Using sigma', v_model=False, class_='d-none')\n self.in_log = v.Switch(label='Using log10', v_model=False, class_='d-none')\n self.minmax = v.Layout()\n\n self.update_select_fields(None)\n\n test_case_widget.select_case.observe(self.update_select_fields, 'v_model')\n lb_scheme_widget.select_case.observe(self.update_select_fields, 'v_model')\n discret_widget['dx'].observe(self.update_select_fields, 'v_model')\n\n self.select_param.observe(self.select_param_changed, 'v_model')\n self.select_relax.observe(self.select_relax_rules, 'v_model')\n self.select_relax.observe(self.select_relax_all, 'v_model')\n\n self.fields = [self.select_param, self.select_relax, self.srt_relax, self.sigma, self.in_log, self.minmax]\n\n super().__init__(v_model='valid', children=self.fields)\n\n def update_select_fields(self, change):\n fields = required_fields(self.test_case_widget.get_case())\n fields.update(required_fields(self.lb_scheme_widget.get_case()))\n fields.update({'dx': {'value': self.discret_widget['dx'].value,\n 'type': 'number'}})\n\n params = {'relaxation parameters': None}\n params.update({f: v['value'] for f, v in fields.items() if v['type'] != 'relaxation parameter'})\n relax_params = {f: v['value'] for f, v in fields.items() if v['type'] == 'relaxation parameter'}\n\n self.params = {k: params[k] for k in sorted(params)}\n self.relax_params = {k: relax_params[k] for k in sorted(relax_params)}\n\n self.select_param.items = list(self.params.keys())\n self.select_relax.items = ['all'] + list(self.relax_params.keys())\n\n def select_param_changed(self, change):\n if self.select_param.v_model:\n if self.select_param.v_model == 'relaxation parameters':\n self.minmax.children = [\n FloatField(label='Enter the minimum', v_model=1),\n FloatField(label='Enter the maximum', v_model=1)\n ]\n self.select_relax.class_ = ''\n self.srt_relax.class_ = ''\n self.sigma.class_ = ''\n self.in_log.class_ = ''\n else:\n value = self.params[self.select_param.v_model]\n self.minmax.children = [\n FloatField(label='Enter the minimum', v_model=value),\n FloatField(label='Enter the maximum', v_model=value)\n ]\n self.select_relax.class_ = 'd-none'\n self.srt_relax.class_ = 'd-none'\n self.sigma.class_ = 'd-none'\n self.in_log.class_ = 'd-none'\n self.select_relax.v_model = []\n\n for c in self.minmax.children:\n c.observe(self.minmax_rules, 'v_model')\n c.observe(self.minmax_rules, 'v_model')\n\n def select_relax_all(self, change):\n if 'all' in self.select_relax.v_model:\n self.select_relax.v_model = list(self.relax_params.keys())\n\n @add_rule\n def select_relax_rules(self, change):\n if self.select_param.v_model == 'relaxation parameters':\n if self.select_relax.v_model == []:\n self.select_relax.rules = ['You must select at least one relaxation parameter']\n self.select_relax.error = True\n return\n else:\n self.select_relax.rules = []\n self.select_relax.error = False\n\n @add_rule\n def minmax_rules(self, change):\n min_widget, max_widget = self.minmax.children\n min, max = min_widget.value, max_widget.value\n if min == max:\n min_widget.rules = ['Min must be different from Max']\n min_widget.error = True\n max_widget.rules = ['Max must be different from Min']\n max_widget.error = True\n self.minmax.error = True\n return\n elif min > max:\n min_widget.rules = ['Min must be lower than Max']\n min_widget.error = True\n max_widget.rules = ['Max must be greater than Min']\n max_widget.error = True\n self.minmax.error = True\n return\n else:\n min_widget.check(None)\n max_widget.check(None)\n self.minmax.error = min_widget.error | max_widget.error\n\n def reset_form(self):\n super().reset_form()\n self.select_relax.class_ = 'd-none'\n self.srt_relax.class_ = 'd-none'\n self.srt_relax.v_model = True\n self.sigma.class_ = 'd-none'\n self.sigma.v_model = False\n self.in_log.class_ = 'd-none'\n self.in_log.v_model = False\n self.minmax.children = []\n\n@debug\nclass DesignItem(Item):\n form_class = DesignForm\n update_text = 'Update field range configuration'\n\n param = Unicode()\n relax = List()\n srt = Bool()\n sigma = Bool()\n in_log = Bool()\n min = Float()\n max = Float()\n\n def __init__(self, test_case_widget, lb_scheme_widget, discret_widget, **kwargs):\n super().__init__(test_case_widget, lb_scheme_widget, discret_widget, **kwargs)\n self.content.children = [f'{self}']\n\n def form2field(self):\n self.param = self.form.select_param.v_model\n self.relax = self.form.select_relax.v_model\n self.srt = self.form.srt_relax.v_model\n self.sigma = self.form.sigma.v_model\n self.in_log = self.form.in_log.v_model\n self.min = self.form.minmax.children[0].value\n self.max = self.form.minmax.children[1].value\n\n def field2form(self):\n self.form.select_param.v_model = self.param\n self.form.select_relax.v_model = self.relax\n self.form.srt_relax.v_model = self.srt\n self.form.sigma.v_model = self.sigma\n self.form.in_log.v_model = self.in_log\n self.form.minmax.children[0].value = self.min\n self.form.minmax.children[1].value = self.max\n\n def __str__(self):\n if self.param == 'relaxation parameters':\n return ', '.join(self.relax) + f' (srt: {self.srt}, sigma: {self.sigma}, log: {self.in_log}, min: {self.min}, max: {self.max})'\n else:\n return f'{self.param} (min: {self.min}, max: {self.max})'\n\n@debug\nclass DesignWidget(Dialog):\n item_class = DesignItem\n new_text = \"New field range configuration\"\n\n def __init__(self, test_case_widget, lb_scheme_widget, discret_widget):\n self.test_case_widget = test_case_widget\n self.lb_scheme_widget = lb_scheme_widget\n self.discret_widget = discret_widget\n super().__init__(test_case_widget, lb_scheme_widget, discret_widget)\n\n def create_item(self):\n return DesignItem(self.test_case_widget,\n self.lb_scheme_widget,\n self.discret_widget,\n param = self.form.select_param.v_model,\n relax = self.form.select_relax.v_model,\n srt = self.form.srt_relax.v_model,\n sigma = self.form.sigma.v_model,\n in_log = self.form.in_log.v_model,\n min = self.form.minmax.children[0].value,\n max = self.form.minmax.children[1].value,\n class_='ma-1',\n style_='background-color: #F8F8F8;'\n )\n\n def design_space(self):\n test_case = self.test_case_widget.get_case()\n lb_scheme = self.lb_scheme_widget.get_case()\n discret = self.discret_widget\n\n output = {}\n for c in self.item_list.children:\n if c.relax:\n attrs = [getattr(lb_scheme, r).symb for r in c.relax]\n\n smin, smax = c.min, c.max\n if c.in_log:\n smin = 10**smin\n smax = 10**smax\n\n if c.sigma:\n smin, smax = 2/(2*smax + 1), 2/(2*smin + 1)\n\n if c.srt:\n output.update({tuple(attrs): (smin, smax)})\n else:\n output.update({a: (smin, smax) for a in attrs})\n else:\n if c.param == 'dx':\n output.update({'dx': (c.min, c.max)})\n else:\n if hasattr(test_case, c.param):\n attr = getattr(test_case, c.param)\n elif hasattr(lb_scheme, c.param):\n attr = getattr(lb_scheme, c.param)\n if isinstance(attr, SchemeVelocity):\n attr = attr.symb\n if not isinstance(attr, sp.Symbol):\n attr = c.param\n output.update({attr: (c.min, c.max)})\n print(output)\n return output","sub_path":"pylbm_ui/widgets/design_space.py","file_name":"design_space.py","file_ext":"py","file_size_in_byte":9915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"141094339","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport zipfile\nimport os\n\nfrom nature import get_dss\n\n\n\ndate_begin = '2020-07-20'\ndate_end = '2020-08-10'\n\nfn = get_dss() + 'fut/bar/min5_IF2008.csv'\ndf = pd.read_csv(fn)\ndf = df[df.time == '09:34:00']\ndf = df[(df.date >= date_begin) & (df.date <= date_end)]\n\ndate_list = sorted(list(df.date))\n# print(df)\n# gap = 50\ngap = 100\nfor date in date_list:\n df1 = df[df.date == date]\n rec = df1.iloc[0,:]\n obj = rec.close\n atm = int(round(round(obj*(100/gap)/1E4,2) * 1E4/(100/gap), 0)) # 获得平值\n print(date, obj, atm)\n\n fn = get_dss() + 'fut/bar/min5_IO2008-C-' + str(atm) + '.csv'\n df_m0_c = pd.read_csv(fn)\n df_m0_c = df_m0_c[df_m0_c.date == date]\n\n fn = get_dss() + 'fut/bar/min5_IO2008-P-' + str(atm) + '.csv'\n df_m0_p = pd.read_csv(fn)\n df_m0_p = df_m0_p[df_m0_p.date == date]\n\n fn = get_dss() + 'fut/bar/min5_IO2009-C-' + str(atm) + '.csv'\n df_m1_c = pd.read_csv(fn)\n df_m1_c = df_m1_c[df_m1_c.date == date]\n\n fn = get_dss() + 'fut/bar/min5_IO2009-P-' + str(atm) + '.csv'\n df_m1_p = pd.read_csv(fn)\n df_m1_p = df_m1_p[df_m1_p.date == date]\n\n # print(len(df_m0_c), len(df_m0_p),len(df_m1_c), len(df_m1_p))\n # print(df_m1_c.head())\n # print(df_m1_p .head())\n base_m1 = df_m1_c.iat[0,5] + df_m1_p.iat[0,5]\n base_m0 = df_m0_c.iat[0,5] + df_m0_p.iat[0,5]\n\n\n df_m1_c['diff_m1'] = df_m1_c.close + df_m1_p.close - base_m1\n df_m0_c['diff_m0'] = df_m0_c.close + df_m0_p.close - base_m0\n df_m1_c['diff'] = df_m1_c.diff_m1 - df_m0_c.diff_m0\n # # print(df_m1_c.head())\n #\n df2 = df_m1_c[['date', 'time', 'diff']]\n # print(df2.head())\n fn = get_dss() + 'opt/straddle_diff.csv'\n if os.path.exists(fn):\n df2.to_csv(fn, index=False, mode='a', header=False)\n else:\n df2.to_csv(fn, index=False)\n\n # break\n","sub_path":"engine/fut/rd/IO/straddle_diff1.py","file_name":"straddle_diff1.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"219942318","text":"#!/usr/bin/env python\n\nimport rospy\nimport numpy as np\n\nfrom std_msgs.msg import Float64\nfrom std_msgs.msg import String\nfrom std_msgs.msg import Float64MultiArray\nfrom control_msgs.msg import JointControllerState\n\nimport matplotlib.pyplot as plt\nimport time\n\nfrom aml_robot.sawyer_robot import SawyerArm\n\nprint('Please wait 5 seconds')\nrospy.init_node('test')\n\nrobot = SawyerArm('right')\n# initial position\n# robot.move_to_joint_position([-7.28164062e-02 , 6.17187500e-04, -1.78447266e-02, 1.64414062e-02,\n# 4.15722656e-03, 9.50683594e-03, 3.31331445e+00])\n# the one i need to change = 9.50683594e-03 for up/down\n# the one i need to change = 4.15722656e-03 for right/left\n\n\npos_cmd_lr=4.15722656e-03\npos_cmd_ud=9.50683594e-03\n\n#####################\n\n#joint 2\n# not publishing anymore but use another type of command, if you want to edit\n# pub2= rospy.Publisher('/robot/right_joint_position_controller/joints/right_j4_controller/command', Float64, queue_size=100)\n\nlimit_pos_j4=1.57 #xacro file\nlimit_vel_j4=3.485 #xacro file\n\nposition_des2=list()\n# position_des2.append(0.0)\n# position_des2.append(0.0)\nposition_act2=list()\n# position_act2.append(0.0)\n# position_act2.append(0.0)\n# position_act2.append(0.0)\n# vel_des2=list()\n# vel_des2.append(0.0)\n# vel_act2=list()\n# vel_act2.append(0.0)\n\n\n#joint 1\n# pub1= rospy.Publisher('/robot/right_joint_position_controller/joints/right_j5_controller/command', Float64, queue_size=100)\n\nlimit_vel_j5=3.059 #xacro file\nlimit_pos_j5=2.9761 #xacro file\n\nposition_des1=list()\n# position_des1.append(0.0)\n# position_des1.append(0.0)\nposition_act1=list()\n# position_act1.append(0.0)\n# position_act1.append(0.0)\n# position_act1.append(0.0)\n# vel_des1=list()\n# vel_des1.append(0.0)\n# vel_act1=list()\n# vel_act1.append(0.0)\n\n#####################\n#plot of all the sensors \ns_1=list()\ns_2=list()\ns_3=list()\ns_4=list()\ns_5=list()\ns_6=list()\ns_7=list()\ns_8=list()\n\n\nlist_of_emg=list()\ndt=0.02\n\n\ndef avg_list_emg(l):\n\taverage_list_of_emg=[0,0,0,0,0,0,0,0]\n\tfor i in range (0,8): #8 datas in each emg\n\t\tsomme=0\n\t\tfor j in range (0,len(l)):\t\n\t\t\tsomme=somme+int(l[j][i])\n\t\taverage_list_of_emg[i]=somme/len(l)\t\n\n\t#to plot the contribution of each sensors \n\ts_1.append(average_list_of_emg[0])\n\ts_2.append(average_list_of_emg[1])\n\ts_3.append(average_list_of_emg[2])\n\ts_4.append(average_list_of_emg[3])\n\ts_5.append(average_list_of_emg[4])\n\ts_6.append(average_list_of_emg[5])\n\ts_7.append(average_list_of_emg[6])\n\ts_8.append(average_list_of_emg[7])\n\n\t\n\t#there are 4 groups of sensors\n\tgroup1 = list()\n\tgroup2 = list()\n\tgroup3 = list()\n\tgroup4 = list()\n\t\t\n\t#Group1 - when I lower my hand\n\tgroup1.append(average_list_of_emg[0])\n\tgroup1.append(average_list_of_emg[1])\n\tgroup1.append(average_list_of_emg[7])\n\t#print('group1 is ', group1)\n\t\n\t#Group2 - when I raise my hand\n\tgroup2.append(average_list_of_emg[4])\n\tgroup2.append(average_list_of_emg[3])\n\tgroup2.append(average_list_of_emg[5])\n\t#print('group2 is ', group2)\n\t\t\n\t#Group3 - left\n\tgroup3.append(average_list_of_emg[0])\n\t# group3.append(average_list_of_emg[2])\n\tgroup3.append(average_list_of_emg[1])\n\tgroup3.append(average_list_of_emg[3])\n\t#print('group3 is ', group3)\n\n\t#Group4 - right\n\tgroup4.append(average_list_of_emg[6])\n\tgroup4.append(average_list_of_emg[7])\n\tgroup4.append(average_list_of_emg[5])\n\t#print('group4 is ', group4)\n\n\treturn group1,group2,group3,group4\n\ndef avg_group(group):\n\tavg=float(group[0]*0.5+group[1]*0.25+group[2]*0.25)\n\treturn avg \n\n\ndef callback(data):\n\n\t#we want to have an array of integer, so we keep only the integer coming from the myoband\n\t#my_data=data.data[1:-1].split(', ') #if string here type = Float64MultiArray\n\t#rospy.loginfo(rospy.get_caller_id() + \" I heard for %s\", data.data)\n\tlist_of_emg.append(data.data)\n\tpos_cmd_lr=4.15722656e-03\n\tpos_cmd_ud=9.50683594e-03\n\n\tpos=robot.state()['position']\n\tposition_act2.append(pos[5])\n\tposition_act1.append(pos[4])\n\n\n\tif len(list_of_emg) == 8: \n\t\t#number of emg we want to use to smooth by computing the average\n\t\t(gp1,gp2,gp3,gp4) = avg_list_emg(list_of_emg)\n\n\t\t'''\n\t\tTo make it smoother, compute the average of the several values\n\t\t'''\n\t\taverage_group1_values=-avg_group(gp1)*0.20*limit_pos_j4/1000.0 #i can go until 1000 when i lower my hand\n\t\taverage_group2_values=avg_group(gp2)*0.20*limit_pos_j4/950.0 \n\t\taverage_group3_values=-avg_group(gp3)*0.20*limit_pos_j5/600.0 # can only go until 600\n\t\taverage_group4_values=avg_group(gp4)*0.20*limit_pos_j5/600.0 \n\t\t#scale = i saw on internet that the maximum torque for an human hand is 900 N\n\t\t# while sending to the real robot, send only 20% by security\n\t\t\n\t\tif abs(average_group1_values + average_group2_values) > 0.15 or abs(average_group3_values + average_group4_values) > 0.15 :\n\t\t\t#we have to be careful, I cam increase the stiffness without moving-> need to keep the previous position\n\t\t\t#I did some tests, by printing average_group1_values and average_group2_values, only 0.15 of difference while increasing the stiffness\n\t\t\t\n\t\t\tmaximum_ud=max(abs(average_group1_values),average_group2_values)\n\t\t\tmaximum_lr=max(abs(average_group3_values),average_group4_values)\n\t\t\tif max(avg_group(gp1),avg_group(gp2))> max(avg_group(gp3),avg_group(gp4)) + 0.10:\n\t\t\t\tif maximum_ud==abs(average_group1_values):\n\t\t\t\t\tpos_cmd_ud=min(maximum_ud,limit_pos_j4)\n\t\t\t\telse:\n\t\t\t\t\tpos_cmd_ud=-min(maximum_ud,limit_pos_j4)\n\t\t\t\t# velocity_ud=min((((position_des2[-1]-position_des2[-3])/(2*dt))*limit_vel_j4/50),limit_vel_j4)\n\t\t\t\t# vel_des2.append(velocity_ud)\n\t\t\telif max(avg_group(gp3),avg_group(gp4))> max(avg_group(gp1),avg_group(gp2)) + 0.10:\n\t\t\t\tif maximum_lr==abs(average_group3_values):\n\t\t\t\t\tpos_cmd_lr=-min(maximum_lr,limit_pos_j5)\n\t\t\t\telse:\n\t\t\t\t\tpos_cmd_lr=min(maximum_lr,limit_pos_j5)\n\t\t\t\t# velocity_lr=min((((position_des1[-1]-position_des1[-3])/(2*dt))*limit_vel_j5/50),limit_vel_j5)\n\t\t\t\t# vel_des1.append(velocity_lr)\n\t\t\t\t\n\t\tposition_des1.append(pos_cmd_lr)\n\t\tposition_des2.append(pos_cmd_ud)\n\n\n\t\trobot.move_to_joint_position([-7.28164062e-02 , 6.17187500e-04, -1.78447266e-02, 1.64414062e-02,\n pos_cmd_lr, pos_cmd_ud, 3.31331445e+00], timeout = 0.0001)\n\t\tdel list_of_emg[0] #delete the first to add the next raw at the end of the list \n\t\t\n\n\n\ndef listener_myo():\n\t# rospy.init_node('listener', anonymous=True)\n\trospy.Subscriber(\"myo_emg\", Float64MultiArray, callback)\n\trospy.spin()\n\t# spin() simply keeps python from exiting until this node is stopped\n\t\n\nif __name__ == '__main__':\t\n\tpos_cmd_lr=4.15722656e-03\n\tpos_cmd_ud=9.50683594e-03\n\trobot.move_to_joint_position([-7.28164062e-02 , 6.17187500e-04, -1.78447266e-02, 1.64414062e-02,\n 4.15722656e-03, 9.50683594e-03, 3.31331445e+00], timeout = 5.0)\n\traw_input('press enter to continue and wait 5 seconds')\n\n\tlistener_myo()\n\tplt.figure()\n\tplt.subplot(2, 1, 1)\n\tplt.title('joint position up/down - average method')\n\tplt.plot(position_des2, 'b', label='desired position')\n\tplt.plot(position_act2, 'r', label='actual position')\n\tplt.legend()\n\tplt.subplot(2, 1,2)\n\t# plt.title('joint velocity up/down - average method')\n\t# plt.plot(vel_des2,'b',label='velocity send')\n\t# plt.plot(vel_act2, 'r', label='actual velocity')\n\t# plt.show()\n\t#savemat(\"position.mat\",{\"A\":position_des2}) #to save position_des2 in the directory chosen\n\t# plt.figure()\n\t# plt.subplot(2, 1, 1)\n\tplt.title('joint position right/left - average method')\n\tplt.plot(position_des1, 'b', label='desired position')\n\tplt.plot(position_act1, 'r', label='actual position')\n\tplt.legend()\n\t# plt.subplot(2, 1,2)\n\t# plt.title('joint velocity right/left - average method')\n\t# plt.plot(vel_des1,'b',label='velocity send')\n\t# plt.plot(vel_act1, 'r', label='actual velocity')\n\tplt.show()\n\n# determination of the most stressed sensors \n\t# plt.figure()\n\t# plt.title('use of the different sensors')\n\t# plt.plot(s_1, 'b',label='sensor 0')\n\t# plt.plot(s_2, 'r', label='sensor 1')\n\t# plt.plot(s_3,'g', label='sensor 2')\n\t# plt.plot(s_4,'c',label='sensor 3')\n\t# plt.plot(s_5,'m',label='sensor 4')\n\t# plt.plot(s_6,'y',label='sensor 5')\n\t# plt.plot(s_7, 'k',label='sensor 6')\n\t# plt.plot(s_8, 'g-.', label='sensor 7')\n\t# plt.legend()\n\t# plt.show()\n\n","sub_path":"sawyer_control.py","file_name":"sawyer_control.py","file_ext":"py","file_size_in_byte":8053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"202048587","text":"import os\nimport socket\nimport subprocess\nimport argparse\nimport logging\nimport tempfile\nimport shutil\nimport xml.etree.ElementTree as ET\n\nlog_stdout = open(\"/root/stdout-add-worker.txt\", \"a\")\nlog_stderr = open(\"/root/stderr-add-worker.txt\", \"a\")\ndef basic_env_setup():\n \"\"\"\n Install the required packages on the user machine\n :return:\n \"\"\"\n commands = [\n # ['apt-get', 'update'],\n # ['apt-get', '-y', 'dist-upgrade'],\n # ['apt-get', 'install', 'openjdk-8-jdk', 'openssh-server', 'openssh-client', 'python3-pip', 'zip', '-y'],\n # # TODO Check if keys have already existed:\n ['ssh-keygen', '-t', 'rsa', '-N', '', '-f', '/root/.ssh/id_rsa'],\n ['service', 'ssh', 'start'],\n # ['pip3', 'install', 'psutil', 'requests'],\n ]\n for command in commands:\n subprocess.Popen(command, stdout=log_stdout, stderr=log_stderr).wait()\n logging.info(\"Finish basic_env_setup\")\n\n\ndef cluster_setup():\n \"\"\"\n Set up the environment variables required for the cluster including Hadoop, Spark, Yarn, Tensorflow, and TensorflowOnSpark\n :return:\n \"\"\"\n scp_commands = [\n ['scp', '-o', 'StrictHostKeyChecking=no', '-r', 'master:/usr/local/hadoop', '/usr/local/hadoop'],\n ['scp', '-o', 'StrictHostKeyChecking=no', '-r', 'master:/usr/local/spark', '/usr/local/spark'],\n ]\n for command in scp_commands:\n subprocess.Popen(command, stdout=log_stdout, stderr=log_stderr).wait()\n\n logging.info(\"Finish scp\")\n\n envs = {\n 'PATH': '{0}:/usr/local/hadoop/bin:/usr/local/hadoop/sbin:/usr/local/spark/bin'.format(os.environ['PATH']),\n 'HADOOP_HOME': '/usr/local/hadoop',\n 'JAVA_HOME': '/usr/lib/jvm/java-8-openjdk-amd64',\n 'SPARK_HOME': '/usr/local/spark',\n 'PYSPARK_PYTHON': '/usr/bin/python3.6',\n 'SPARK_YARN_USER_ENV': 'PYSPARK_PYTHON=/usr/bin/python3.6',\n 'LIB_HDFS': '/usr/local/hadoop/lib/native',\n 'LIB_JVM': '$JAVA_HOME/jre/lib/amd64/server',\n }\n for key in envs:\n os.environ[key] = envs[key]\n extra_envs = {\n 'HADOOP_CONF_DIR': '{0}/etc/hadoop'.format(os.environ['HADOOP_HOME']),\n 'LD_LIBRARY_PATH': '{0}:{1}'.format(os.environ['LIB_HDFS'], os.environ['LIB_JVM']),\n }\n for key in extra_envs:\n os.environ[key] = extra_envs[key]\n\n os.environ['CLASSPATH'] = subprocess.check_output(['hadoop', 'classpath', '--glob']).decode().strip('\\n')\n envs['CLASSPATH'] = os.environ['CLASSPATH']\n logging.info(\"Finish python env setup\")\n\n\n shutil.rmtree(os.path.join(os.environ['HADOOP_HOME'], 'data/nameNode/'), True)\n shutil.rmtree(os.path.join(os.environ['HADOOP_HOME'], 'data/dataNode/'), True)\n shutil.rmtree(os.path.join(os.environ['HADOOP_HOME'], 'logs'), True)\n\n logging.info(\"Finish remove the logs, old dataNode and namenode directory\")\n\n with open('/root/.bashrc', 'a') as f:\n for key in envs:\n f.write('{0}={1}\\n'.format(key, envs[key]))\n with open('/root/.bash_profile', 'a') as f:\n for key in envs:\n f.write('{0}={1}\\n'.format(key, envs[key]))\n logging.info(\"Finish bash env setup\")\n\n\ndef config_yarn_resources(cpu_cores_limit, memory_limit):\n \"\"\"\n :param int cpu_cores_limit:\n :param int memory_limit: In MB\n :return:\n \"\"\"\n # https://docs.python.org/3.7/library/xml.etree.elementtree.html#module-xml.etree.ElementTree\n # begin\n yarn_config_path = os.path.join(os.environ['HADOOP_CONF_DIR'], 'yarn-site.xml')\n yarn_config = ET.parse(yarn_config_path)\n root = yarn_config.getroot()\n # [TBD] Check if the memory & cpu limit values have already existed\n memory_config = ET.Element('property')\n memory_config_name = ET.SubElement(memory_config, 'name')\n memory_config_name.text = 'yarn.nodemanager.resource.memory-mb'\n memory_config_value = ET.SubElement(memory_config, 'value')\n memory_config_value.text = str(memory_limit)\n root.append(memory_config)\n cpu_config = ET.Element('property')\n cpu_config_name = ET.SubElement(cpu_config, 'name')\n cpu_config_name.text = 'yarn.nodemanager.resource.cpu-vcores'\n cpu_config_value = ET.SubElement(cpu_config, 'value')\n cpu_config_value.text = str(cpu_cores_limit)\n root.append(cpu_config)\n yarn_config.write(yarn_config_path)\n logging.info(\"Finish the yarn config setup\")\n hadoop_commands = [\n ['yarn', '--daemon', 'start', 'nodemanager'],\n ['hdfs', '--daemon', 'start', 'datanode'],\n ]\n for command in hadoop_commands:\n subprocess.Popen(command, stdout=log_stdout, stderr=log_stderr).wait()\n logging.info(\"Finish the daemon launching\")\n # end\n\n\ndef tensorflow_setup():\n commands = [\n ['pip3', 'install', 'tensorflow', 'tensorflowonspark==1.4.4'],\n ]\n for command in commands:\n subprocess.Popen(command, stdout=log_stdout, stderr=log_stderr).wait()\n logging.info(\"Finish the tensorflow setup\")\n\n\ndef register_machine(core_num, memory_size, time_period, public_key, authorized_key_path, sessionid, csrftoken, master, start_time, end_time):\n \"\"\"\n Register the user machine on the existing cluster.\n :param core_num:\n :param memory_size:\n :param time_period:\n :param public_key:\n :param authorized_key_path:\n :return:\n \"\"\"\n logging.info('Register_machine')\n import psutil\n import requests\n # The ways to access the machine data is cited from\n # https://www.pythoncircle.com/post/535/python-script-9-getting-system-information-in-linux-using-python-script/\n # https://stackoverflow.com/questions/1006289/how-to-find-out-the-number-of-cpus-using-python\n # https://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python/28161352\n # begin\n core_limit = os.cpu_count()\n memory_limit = psutil.virtual_memory().total # in Bytes\n logging.info('contribute cpu cores {0} with limit {1}'.format(core_num, core_limit))\n logging.info('contribute memory {0} with limit {1}'.format(memory_size, memory_limit))\n assert core_num <= core_limit and core_num >= 1\n assert memory_size*1024 <= memory_limit and memory_size >= 1024\n\n # https://stackoverflow.com/questions/22567306/python-requests-file-upload\n # https://stackoverflow.com/questions/13567507/passing-csrftoken-with-python-requests\n # https://www.geeksforgeeks.org/display-hostname-ip-address-python/\n # begin\n url = master + '/services/machine/submit/' #'http://192.168.1.12:8000/services/machine/submit/'\n client = requests.session()\n# tf = tempfile.TemporaryFile()\n# tf.write(public_key.encode('utf-8')\n files = {\n 'public_key': open('/root/.ssh/id_rsa.pub', 'r'),\n }\n # The way to get the ip address of the user machine is cited from https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib\n # begin\n my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n my_socket.connect((\"8.8.8.8\", 80))\n ip_address = my_socket.getsockname()[0]\n my_socket.close()\n # end\n data = {\n 'ip_address': ip_address,\n 'core_num': core_num,\n 'memory_size': memory_size,\n 'time_period': time_period,\n 'csrfmiddlewaretoken': csrftoken,\n 'start_time': start_time,\n 'end_time': end_time,\n }\n cookies = requests.cookies.RequestsCookieJar()\n cookies.set('sessionid', sessionid)\n cookies.set('csrftoken', csrftoken)\n logging.info('Before submit machine request')\n response = client.post(url, data=data, files=files, headers=dict(Referer=url), cookies=cookies)\n logging.info('After submit machine request')\n public_keys = response.json()['public_keys']\n with open(authorized_key_path, 'a') as f:\n for public_key in public_keys:\n f.write(public_key)\n host_ip_mapping = response.json()['host_ip_mapping']\n with open('/etc/hosts', 'a') as f:\n for host in host_ip_mapping:\n f.write('{0}\\t{1}\\n'.format(host_ip_mapping[host], host))\n # end\n # end\n\ndef only_join_cluster():\n basic_env_setup()\n cluster_setup()\n tensorflow_setup()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Initialize the worker server.')\n parser.add_argument('--only-join-cluster', type=int, help='only join cluster or not', default=0)\n parser.add_argument('--authorized-key-path', type=str, help='The path to the authorized keys path.', default='/root/.ssh/authorized_keys')\n parser.add_argument('--cpu-cores', type=int, help='The number of cpu cores to be contributed to the cluster.',\n required=True)\n parser.add_argument('--memory-size', type=int, help='The memory size to be contributed to the cluster.',\n required=True)\n parser.add_argument('--start-time', type=str, help='The start time for machine to be contributed to the cluster.',\n required=False, default='')\n parser.add_argument('--end-time', type=str, help='The end time for machine to be contributed to the cluster.',\n required=False, default='')\n# parser.add_argument('--public-key', type=str, help='The public key of the user machine.')\n parser.add_argument('--sessionid', type=str, help='The id of the current user session.',\n required=True)\n parser.add_argument('--csrftoken', type=str, help='The csrf_token for the purpose of security.',\n required=True)\n parser.add_argument('--master-url', type=str, help='The url of master server',\n required=True)\n args = vars(parser.parse_args())\n logging.basicConfig(filename='init_worker.log', level=logging.INFO)\n\n if args[\"only_join_cluster\"]:\n only_join_cluster()\n logging.info('only_join_cluster')\n else:\n import time\n start_time = time.time()\n basic_env_setup()\n logging.info('basic_env_setup--- {} seconds ---'.format(time.time() - start_time))\n start_time = time.time()\n register_machine(args['cpu_cores'], args['memory_size'], 10, '/root/.ssh/id_rsa.pub', args['authorized_key_path'],\n args['sessionid'], args['csrftoken'], args['master_url'], args['start_time'], args['end_time'])\n logging.info('register_machine--- {} seconds ---'.format(time.time() - start_time))\n start_time = time.time()\n cluster_setup()\n logging.info('cluster_setup--- {} seconds ---'.format(time.time() - start_time))\n\n start_time = time.time()\n config_yarn_resources(args['cpu_cores'], args['memory_size'])\n logging.info('config_yarn_resources--- {} seconds ---'.format(time.time() - start_time))\n\n tensorflow_setup()\n log_stdout.close()\n log_stderr.close()\n","sub_path":"src/main/resources/init_worker.py","file_name":"init_worker.py","file_ext":"py","file_size_in_byte":10774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"90201834","text":"energieTotal = int(input())\nnbAste = int(input())\n\njaune = []\nbleu = []\n\nfor i in range (nbAste):\n asteroide = [int(x) for x in input().split()]\n if(asteroide[0] == 1):\n jaune.append(asteroide[1])\n else:\n bleu.append(asteroide[1])\n #endif\n#endfor\n\nasteroideOk = \"\"\nmaxi = 0\nfor i in range (len(jaune)):\n for j in range (len(bleu)):\n if (jaune[i] + bleu[j] <= energieTotal and jaune[i] + bleu[j] > maxi):\n asteroideOk = str(i) + str(j)\n maxi = jaune[i] + bleu[j]\n #endfor\n#endif\n\nif (asteroideOk != \"\"):\n print(int(jaune[int(asteroideOk[0])])+int(bleu[int(asteroideOk[1])]))\nelse:\n print(0)","sub_path":"Concours développement/Coding Battle - Octobre 2019/exo4.py","file_name":"exo4.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"24533570","text":"#! /home/project/siftr/env/bin/python\n\nimport sys, json, os\n\nimport SqlConst\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.sql import text\n\n\n# consts?\nARTISTS_JSON_FILE = \\\n os.path.join(os.environ['HOME'], 'siftr/artists/included_artists.json')\n\neng = create_engine('sqlite:////home/project/siftr/db/test_db.sqlite')\n\n\ndef make_concerts_table():\n \"\"\"Make a fresh concerts table\"\"\"\n\n with eng.connect() as con:\n\n con.execute(text(\"\"\"DROP TABLE IF EXISTS concerts \"\"\"))\n\n con.execute(text(SqlConst.CREATE_CONCERTS))\n\n\ndef make_venues_table():\n \"\"\"Make a fresh venues table from \"\"\"\n\n with eng.connect() as con:\n\n con.execute(text(\"\"\"DROP TABLE IF EXISTS venues\"\"\"))\n\n con.execute(text(SqlConst.CREATE_VENUES))\n\n\ndef make_artists_table():\n \"\"\"Make a fresh artists table, using \"\"\"\n\n with eng.connect() as con:\n\n con.execute(text(\"\"\"DROP TABLE IF EXISTS artists\"\"\"))\n\n con.execute(text(SqlConst.CREATE_ARTISTS))\n\n\ndef make_links_artists_concerts():\n \"\"\"Create *empty* links_artists_concerts table\"\"\"\n\n with eng.connect() as con:\n\n con.execute(text(\"DROP TABLE IF EXISTS links_artists_concerts\"))\n\n con.execute(text(SqlConst.CREATE_LINKS_ARTISTS_CONCERTS))\n\n\ndef populate_artists():\n\n with open(ARTISTS_JSON_FILE) as fhand:\n\n artists = json.load(fhand)['artists']\n\n with eng.connect() as con:\n\n for a in artists:\n\n con.execute(text(SqlConst.ARTISTS_INSERT), **a)\n\n\nif __name__ == \"__main__\":\n\n #while True:\n # response = input(\"Create new DB '{}?': \".format(eng))\n # sys.exit(\"TOO BAD\")\n\n pass\n","sub_path":"siftr/db_handlers/db_init.py","file_name":"db_init.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"202956032","text":"# -*- coding: utf-8 -*-\nimport torch, torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\n\nfrom pathlib import Path\nimport datetime\nimport argparse\nimport sys\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm\n\nfrom unet_elem import DConv, Down, Up, OutConv\n\nsys.path.append(\"./../\")\nimport dataset\n\n# Training algorithm is a modified of Anders Taskens codebase: https://github.com/Anderstask1/TEE_MAPSE/blob/master/dl_cardiac-view-classification/Code/train.py\n\nclass unet(nn.Module):\n def __init__(self, config=None):\n super(unet, self).__init__()\n self.config = config\n self.n_channels = 1\n self.n_classes = 4\n\n #Network architecture: (inspired by https://github.com/milesial/Pytorch-UNet/tree/6aa14cbbc445672d97190fec06d5568a0a004740)\n self.inc = DConv(self.n_channels, 64)\n self.down1 = Down(64, 128)\n self.down2 = Down(128, 256)\n self.down3 = Down(256, 512)\n self.down4 = Down(512, 1024)\n self.up1 = Up(1024, 512)\n self.up2 = Up(512, 256)\n self.up3 = Up(256, 128)\n self.up4 = Up(128, 64)\n self.outc = OutConv(64, self.n_classes)\n\n def forward(self, x):\n x1 = self.inc(x)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n x4 = self.down3(x3)\n x5 = self.down4(x4)\n x = self.up1(x5, x4)\n x = self.up2(x, x3)\n x = self.up3(x, x2)\n x = self.up4(x, x1)\n logits = self.outc(x)\n return logits\n\n def train_model(self, dataloaders, loss, optimizer, num_epochs=25):\n '''\n Training algorithm\n '''\n device = torch.device(self.config.device)\n\n # Generate folder\n folder_path = _generate_folders(self.config.output)\n\n # Metadata names\n training_info_path = folder_path + \"training_info.pth\"\n weights_path = folder_path + \"weights_\"+ str(opt.dim) + \"x\" + str(opt.dim) +\".pth\"\n\n print(\"Training info path: \", training_info_path)\n print(\"Weights path: \", weights_path)\n\n criterion = nn.CrossEntropyLoss()\n\n train_info = {'epoch': [], 'loss': [], 'all_loss': []}\n val_info = {'epoch': [], 'loss': [], 'all_loss': []}\n best_loss = 1e10\n\n for epoch in range(num_epochs):\n\n print(\"Epoch {}/{}\".format(epoch + 1, num_epochs))\n print(\"-\" * 40)\n\n for phase in ['train', 'val']:\n\n print(\"Phase: \", phase)\n if phase == 'train':\n self.train()\n else:\n self.eval()\n\n running_loss = 0.0\n \n for _, sample_batch in tqdm(enumerate(dataloaders[phase]), \n total=len(dataloaders[phase])):\n\n sample_batch['image'] = sample_batch['image'].to(device)\n\n optimizer.zero_grad()\n\n with torch.set_grad_enabled(phase == 'train'):\n out = self(sample_batch['image'])\n target = torch.LongTensor(sample_batch['cardiac_view'].long()).to(device)\n loss = criterion(out, target)\n\n all_loss = loss.item()\n running_loss += all_loss\n\n if phase == 'train':\n loss.backward()\n optimizer.step()\n train_info['all_loss'].append(all_loss)\n\n epoch_loss = running_loss / len(dataloaders[phase].dataset)\n\n if phase == 'train':\n print('{{\"metric\": \"loss\", \"value\": {}, \"epoch\": {}}}'.format(\n epoch_loss, epoch + 1))\n else:\n print('{{\"metric\": \"Validation loss\", \"value\": {}, \"epoch\": {}}}'.format(\n epoch_loss, epoch + 1))\n \n if phase == 'train':\n train_info['epoch'].append(epoch + 1)\n train_info['loss'].append(epoch_loss)\n else:\n val_info['epoch'].append(epoch + 1)\n val_info['loss'].append(epoch_loss)\n\n torch.save({\n 'epoch': epoch,\n 'train_info': train_info,\n 'val_info': val_info}, training_info_path)\n\n if phase == 'val' and epoch_loss <= best_loss:\n torch.save({\n 'epoch': epoch,\n 'model_state_dict': self.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict()}, weights_path)\n best_loss = epoch_loss\n print(\"Weights saved\")\n print()\n\n \ndef _options():\n \"\"\"Function for taking in arguments from user\n Returns:\n Arguments from user\n \"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\"--train\", \n required=False, \n action=\"store_true\", \n help=\"Train model\")\n parser.add_argument('--device', \n type=str, \n default=\"cpu\", \n help='Which device to run on')\n parser.add_argument(\"--input\", \n type=str, \n required=False,\n default=\"datasets/training/\", \n help=\"Path to dataset\")\n parser.add_argument(\"--output\", \n type=str, \n required=False, \n default=\"trained_models/\",\n help=\"Path to output\")\n parser.add_argument(\"--dim\", \n type=int, \n required=False, \n default=256, \n help=\"Dimension to be used in training, dim x dim image\")\n parser.add_argument(\"--batch_size\", \n type=int, \n required=False, \n default=5, \n help=\"Batch size used during training phase\")\n parser.add_argument(\"--epochs\", \n type=int, \n required=False, \n default=25, \n help=\"Number of training epochs\")\n\n return parser.parse_args() \n\n\n\ndef _generate_folders(start_path):\n \"\"\"Generate folder where dataset weill be stored\n Returns:\n Directory to where data will be saved\n \"\"\"\n\n location_dir = Path(start_path + datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\n\n if not location_dir.is_dir():\n location_dir.mkdir(parents=True)\n\n return str(location_dir) + \"/\"\n\nif __name__ == \"__main__\":\n opt = _options()\n \n opt.input = opt.input if (\"/\" == opt.input[-1]) else opt.input + \"/\"\n opt.output = opt.output if (\"/\" == opt.output[-1]) else opt.output + \"/\"\n\n if opt.train:\n \n data_transforms = {\n 'train':transforms.Compose([dataset.Rescale(opt.dim),\n dataset.Standardize(),\n dataset.Zero_pad_and_center(),\n dataset.ToTensor()\n ]),\n 'val':transforms.Compose([ dataset.Rescale(opt.dim),\n dataset.Standardize(),\n dataset.Zero_pad_and_center(),\n dataset.ToTensor()\n ]),\n 'aug':transforms.Compose([ dataset.RandomCrop(crop_ratio=0.1),\n dataset.RandomRotation(degrees=15),\n dataset.Blackout_data(100), \n dataset.Gamma(gamma_ratio=0.35),\n dataset.Noise_injection()\n ])\n }\n\n datasets = {\n 'train':dataset.UltrasoundData(opt.input, transform=data_transforms['train'], augment_transform=data_transforms['aug']),\n 'val':dataset.UltrasoundData(opt.input, transform=data_transforms['val'], val=True)\n }\n \n print(\"Number of training samples: \" + str(len(datasets['train'])))\n print(\"Number of validation samples: \" + str(len(datasets['val'])))\n\n dataloaders = {\n 'train':DataLoader(datasets['train'], batch_size=opt.batch_size, shuffle=True, num_workers=4),\n 'val':DataLoader(datasets['val'], batch_size=1, shuffle=False, num_workers=4)\n }\n\n print()\n print(\" + Batch size:\\t\\t\\t{}\".format(opt.batch_size))\n print(\" + Number of epochs:\\t\\t{}\".format(opt.epochs))\n print()\n\n print(datasets['train'])\n model = unet(opt)\n print(\"Model architecture: U-Net\")\n\n model = model.to(opt.device)\n\n optimizer = optim.Adam(model.parameters())\t\n\n loss = nn.L1Loss()\n\n print(\"Training model...\")\n \n model.train_model(\n dataloaders=dataloaders, \n loss=loss, \n optimizer=optimizer, \n num_epochs=opt.epochs\n )\n ","sub_path":"src/models/unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":9789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"341932250","text":"from gym_yamax.forward_walker import ForwardWalker\nfrom roboschool.gym_urdf_robot_env import RoboschoolUrdfEnv\nfrom roboschool.scene_abstract import cpp_household\nfrom roboschool.scene_stadium import SinglePlayerStadiumScene\nimport numpy as np\n\n\nclass RoboschoolYamaXForwardWalk(ForwardWalker, RoboschoolUrdfEnv):\n random_yaw = False\n foot_list = [\"foot_right\", \"foot_left\"]\n right_leg = \"leg_right_2\"\n left_leg = \"leg_left_2\"\n hip_part = \"hip\"\n num_joints = 19\n\n def __init__(self):\n ForwardWalker.__init__(self)\n RoboschoolUrdfEnv.__init__(self,\n \"robot_models/yamax.urdf\",\n \"YamaX\",\n action_dim=self.num_joints, obs_dim=self.num_joints + 3,\n fixed_base=False,\n self_collision=True)\n\n def create_single_player_scene(self):\n # 8 instead of 4 here\n return SinglePlayerStadiumScene(gravity=9.8, timestep=0.0165/8, frame_skip=8)\n\n def robot_specific_reset(self):\n ForwardWalker.robot_specific_reset(self)\n self.set_initial_orientation(yaw_center=0, yaw_random_spread=np.pi)\n self.head = self.parts[\"head\"]\n\n random_yaw = False\n\n def set_initial_orientation(self, yaw_center, yaw_random_spread):\n cpose = cpp_household.Pose()\n if not self.random_yaw:\n yaw = yaw_center\n else:\n yaw = yaw_center + \\\n self.np_random.uniform(\n low=-yaw_random_spread, high=yaw_random_spread)\n\n cpose.set_xyz(self.start_pos_x, self.start_pos_y,\n self.start_pos_z + 1.0)\n # just face random direction, but stay straight otherwise\n cpose.set_rpy(0, 0, yaw)\n self.cpp_robot.set_pose_and_speed(cpose, 0, 0, 0)\n self.initial_z = 1.5\n","sub_path":"gym_yamax/yamax_forward_walk.py","file_name":"yamax_forward_walk.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"538564988","text":"# %load q03_t_test/build.py\n# Default imports\nimport scipy.stats as stats\nimport pandas as pd\nimport numpy as np\n\ndf = pd.read_csv('data/house_pricing.csv')\n\n\n# Enter Code Here\n\ndef t_statistic(df):\n population = df['GrLivArea']\n sample = df[df['Neighborhood'] == 'OldTown']['GrLivArea']\n \n statistic, p_value = stats.ttest_1samp(sample, popmean= population.mean())\n\n nullHypothesisIsCorrect = np.greater(p_value, 0.9)\n \n return p_value, nullHypothesisIsCorrect\nt_statistic(df)\n\n\n","sub_path":"q03_t_test/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"310156637","text":"import numpy as np\nfrom config import Config\nfrom collections import deque\nimport keras\nfrom keras.layers import *\nfrom keras.regularizers import l2, l1_l2\nfrom keras import Model\nfrom keras.optimizers import *\nfrom keras.losses import *\nfrom env import StockEnv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nimport tensorflow as tf\nfrom numpy.random import choice\n# from sklearn.utils.random import choice\nfrom collections import OrderedDict\nimport os\nfrom keras.models import load_model, save_model, model_from_json\nfrom util import plot_regression_test\n\n\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\n\n\n\nclass QAgent:\n def __init__(self, mode='q'):\n self.config = Config()\n self.fund = self.config.init_fund\n self.memory_pool = []\n self.agent_mode = mode\n self.agent_model = self.build_q_model()\n self.env = StockEnv(mode)\n self.true_history = self.env.prepare_supervision_data()\n self.agent_model.summary()\n self.t = 0\n json = self.agent_model.to_json()\n with open(self.config.q_json, 'w') as f:\n f.write(json)\n self.check = keras.callbacks.ModelCheckpoint(self.config.q_weights,\n monitor='loss', verbose=1,\n save_best_only=False, save_weights_only=True, mode='auto', period=1)\n\n def build_q_model(self):\n state = Input((self.config.T, self.config.feature_size))\n conv_outs = []\n for fsize in self.config.filter_sizes:\n bn = BatchNormalization()(state)\n conv = Conv1D(self.config.n_filter, fsize, activation='relu')\n conv_out = conv(bn)\n conv_outs.append(conv_out)\n \n lstm_outs = []\n for feature in [state] + conv_outs:\n bn = BatchNormalization()(feature)\n lstm = LSTM(self.config.lstm_dim, recurrent_dropout=self.config.dropout)\n lstm_out = lstm(bn)\n lstm_outs.append(lstm_out)\n \n concat_features = Concatenate()(lstm_outs)\n prelu1 = PReLU()(concat_features)\n dense1 = Dense(300)(prelu1)\n drop1 = Dropout(self.config.dropout)(dense1)\n out = Dense(self.config.action_size, activation='linear', kernel_regularizer=l2(self.config.l2_rate),\n bias_regularizer=l2(self.config.l2_rate), activity_regularizer=l2(self.config.l2_rate))(drop1)\n model = Model(inputs=[state], outputs=[out])\n # model.compile(optimizer=Nadam(lr=self.config.lr), loss=binary_crossentropy, metrics=['accuracy'])\n model.compile(optimizer=Nadam(lr=self.config.lr), loss=mean_squared_error)\n return model\n \n def add_to_pool(self, state, action, reward, next_state):\n self.memory_pool.append((state, action, reward, next_state))\n self.t += 1\n \n def epsilon_greedy(self, state):\n self.config.epsilon = self.config.epsilon * self.config.decay\n is_random = choice([0,1], 1, p=[1-self.config.epsilon, self.config.epsilon])\n if is_random:\n random_action = choice(range(self.config.action_size))\n return random_action\n action = self.agent_model.predict(np.array([state]))\n # print(action)\n greedy_action = np.argmax(action)\n # print(greedy_action)\n return greedy_action\n \n def train_by_replay(self):\n indices = range(len(self.memory_pool))\n chosen_indices = choice(indices, size=self.config.batch_size, replace=False)\n memory_batch = np.array(self.memory_pool)[chosen_indices]\n # print(memory_batch[0])\n states, targets = [], []\n tmp_model = keras.models.clone_model(self.agent_model)\n tmp_model.set_weights(self.agent_model.get_weights())\n for mem in memory_batch:\n state = mem[0]\n action = mem[1]\n reward = mem[2]\n next_state = mem[3]\n # print(next_state, next_state.shape)\n value = reward + (self.config.gamma*np.max(tmp_model.predict(np.array([next_state]))[0]))\n target = self.agent_model.predict(np.array([state]))[0]\n target[action] = value\n states.append(state)\n targets.append(target)\n states = np.array(states)\n targets = np.array(targets)\n # print(states.shape, targets.shape)\n self.agent_model.fit(states, targets, batch_size=self.config.batch_size, verbose=0, callbacks=[self.check])\n \n def train(self):\n for i in range(self.config.epochs):\n state = self.env.get_initial_state()\n print(\"epochs: {}/{}\".format(i, self.config.epochs))\n for t in range(len(self.env.history)-1):\n if t%10 == 0:\n print(\"\\tstep: {}/{}\".format(t, len(self.env.history)-1))\n action_ind = self.epsilon_greedy(state)\n next_state, reward = self.env.step(action_ind, t)\n self.add_to_pool(state, action_ind, reward, next_state)\n if len(self.memory_pool)>self.config.MAX_POOL_SIZE:\n self.memory_pool = self.memory_pool[-self.config.MAX_POOL_SIZE:]\n state = next_state\n if len(self.memory_pool) > self.config.MIN_POOL_SIZE and t%self.config.batch_size==0:\n self.train_by_replay()\n \n def evaluate(self, agent=True, baseline=True, random=True):\n self.load_trained_agent_model(self.config.q_json, self.config.q_weights)\n FUND = 100000\n\n baseline_fund = 100000\n random_fund = 100000\n agent_fund = 100000\n \n baseline_trace = []\n random_trace = []\n agent_trace = []\n states = self.env.history[:-1]\n action_probs = self.agent_model.predict(np.array(states), batch_size=128, verbose=1)\n print(action_probs.shape)\n actions = np.argmax(action_probs, axis=-1)\n for t in range(len(self.env.history)-1):\n change = self.env.index_change[t]\n # print(change)\n print(\"Step : {}/{}, change: {}%\".format(t, len(self.env.history)-1, change))\n \n if agent:\n action = self.config.actions[actions[t]]\n buy = action*min(FUND, agent_fund)\n buy_return = (1.0+change/100) * buy\n remain = agent_fund - buy\n agent_fund = remain + buy_return\n agent_trace.append(agent_fund)\n print(\"\\tagent chose action: {}, agent fund: {}\".format(action, agent_fund))\n if random:\n random_act = choice(self.config.actions)\n random_buy = random_act * random_fund\n random_buy_return = (1.0+change/100) * random_buy\n random_remain = random_fund - random_buy\n random_fund = random_remain + random_buy_return\n random_trace.append(random_fund)\n print(\"\\tidiot random agent fund: {}\".format(random_fund))\n if baseline:\n baseline_fund *= (1.0+change/100)\n baseline_trace.append(baseline_fund)\n print(\"\\tbaseline func: {}\".format(baseline_fund))\n print()\n Y = []\n x = range(len(self.env.history)-1)\n if baseline_trace:\n Y.append(baseline_trace)\n if random_trace:\n Y.append(random_trace)\n if agent_trace:\n Y.append(agent_trace)\n \n plot_regression_test(x, Y)\n \n def load_trained_agent_model(self, json_path, weights_path):\n with open(json_path, 'r', encoding='utf-8') as f:\n json = f.read()\n self.agent_model = model_from_json(json)\n self.agent_model.load_weights(weights_path)\n \n \n \nclass SupervisedAgent:\n def __init__(self, mode='classification'):\n self.config = Config()\n self.agent_mode = mode\n if self.agent_mode == 'classification':\n self.agent_model = self.build_classification_model()\n else:\n self.agent_model = self.build_regression_model()\n self.agent_model.summary()\n self.env = StockEnv(mode)\n self.get_data_for_supervision()\n \n def get_data_for_supervision(self):\n self.X, self.dates, self.Y = self.env.prepare_supervision_data()\n \n \n def build_regression_model(self):\n state = Input((self.config.T, self.config.feature_size))\n conv_outs = []\n for fsize in self.config.filter_sizes:\n bn = BatchNormalization()(state)\n conv = Conv1D(self.config.n_filter, fsize, activation='relu')\n conv_out = conv(bn)\n conv_outs.append(conv_out)\n \n lstm_outs = []\n for feature in [state]+conv_outs:\n bn = BatchNormalization()(feature)\n lstm = LSTM(self.config.lstm_dim, recurrent_dropout=self.config.dropout)\n lstm_out = lstm(bn)\n lstm_outs.append(lstm_out)\n \n concat_features = Concatenate(lstm_outs)\n prelu1 = PReLU()(concat_features)\n dense1 = Dense(300)(prelu1)\n drop1 = Dropout(self.config.dropout)(dense1)\n out = Dense(1, activation='linear', kernel_regularizer=l2(self.config.l2_rate), bias_regularizer=l2(self.config.l2_rate), activity_regularizer=l2(self.config.l2_rate))(drop1)\n model = Model(inputs=[state], outputs=[out])\n # model.compile(optimizer=Nadam(lr=self.config.lr), loss=binary_crossentropy, metrics=['accuracy'])\n model.compile(optimizer=Nadam(lr=self.config.lr), loss=mean_squared_logarithmic_error)\n return model\n \n def build_classification_model(self):\n state = Input((self.config.T, self.config.feature_size))\n conv_outs = []\n for fsize in self.config.filter_sizes:\n bn = BatchNormalization()(state)\n conv = Conv1D(self.config.n_filter, fsize, activation='relu')\n conv_out = conv(bn)\n conv_outs.append(conv_out)\n \n lstm_outs = []\n for feature in [state] + conv_outs:\n bn = BatchNormalization()(feature)\n lstm = LSTM(self.config.lstm_dim, recurrent_dropout=self.config.dropout)\n lstm_out = lstm(bn)\n lstm_outs.append(lstm_out)\n \n concat_features = Concatenate()(lstm_outs)\n prelu1 = PReLU()(concat_features)\n drop1 = Dropout(self.config.dropout)(prelu1)\n dense1 = Dense(300)(drop1)\n drop2 = Dropout(self.config.dropout)(dense1)\n # out = Dense(1, activation='sigmoid', kernel_regularizer=l2(self.config.l2_rate),\n # bias_regularizer=l2(self.config.l2_rate), activity_regularizer=l2(self.config.l2_rate))(drop2)\n out = Dense(1, activation='sigmoid')(drop2)\n model = Model(inputs=[state], outputs=[out])\n model.compile(optimizer=Nadam(lr=self.config.lr), loss=binary_crossentropy, metrics=['accuracy'])\n return model\n \n def train(self, mode='regression'):\n json = self.agent_model.to_json()\n with open('./model/'+mode+'.json', 'w') as f:\n f.write(json)\n check = keras.callbacks.ModelCheckpoint('./model/'+mode+'.h5',\n monitor='val_acc', verbose=1,\n save_best_only=True, save_weights_only=True, mode='auto', period=1)\n self.agent_model.fit([self.X], [self.Y],\n batch_size=self.config.batch_size,\n epochs=self.config.epochs,\n verbose=1,\n callbacks=[check], validation_split=0.1)\n \n \nif __name__ == '__main__':\n agent = SupervisedAgent()\n agent.get_data_for_supervision()\n agent.train()","sub_path":"supervised_agent.py","file_name":"supervised_agent.py","file_ext":"py","file_size_in_byte":11817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"379947279","text":"from django.contrib import admin\nfrom mptt.admin import MPTTModelAdmin\nfrom datetime import date\n\n\nfrom .models import Idea,Category\n\nclass CustomMPTTModelAdmin(MPTTModelAdmin):\n mptt_level_indent = 30\n\nadmin.site.register(Category, CustomMPTTModelAdmin)\n\nclass YearIdeaFilter(admin.SimpleListFilter):\n # name of the filter to display\n title = \"Year created\"\n # name for what we a filtering \n parameter_name = \"year\"\n def lookups(self, request, modeladmin):\n \"\"\"create a clickable link on the right side\"\"\"\n # one goes to the url,another appears in the sidebar\n # url = parameter_name + [0] from the lookups\n return (\n (2019,2019),\n (2018,2018)\n )\n def queryset(self,request,queryset):\n if self.value() == '2019':\n return queryset.filter(created_at__gte=date(2019,1,1),\n created_at__lte = date(2019,12,31)\n ) \n if self.value() == '2018':\n return queryset.filter(created_at__gte=date(2018,1,1),\n created_at__lte = date(2018,12,31)\n ) \n\ndef make_published(modeladmin,request,queryset):\n \"\"\"make possbile to mark idea as published in admin bar checkbox\"\"\"\n queryset.update(status=2)\n\nmake_published.short_description = 'Mark idea as published' \n\n\n\n# group fields in fieldsets\nclass IdeaAdmin(admin.ModelAdmin):\n search_fields = ('title','lead_text','main_text')\n list_filter = ('created_at','is_public',YearIdeaFilter,'tags')\n list_display = ['id','title','author','status','is_public','created_at']\n list_editable = ['status']\n list_display_links = ['title']\n fieldsets = (\n # I don't need it\n (None,{'fields':('author','title','categ',\n 'lead_text','main_text','status')}),\n # should be present for clearity\n ('Not required Fields',\n {\n 'fields':('featured','view_count','likes','dislikes','is_public','thumbnail','tags'),\n 'classes':('collapse',)\n },\n )\n )\n radio_fields = {'categ':admin.HORIZONTAL}\n actions = [make_published]\n\nadmin.site.register(Idea,IdeaAdmin)\n\n\n# check it (below) out\n# @admin.register(Comment)\n# class IdeaAdmin(admin.ModelAdmin):\n# list_display = ('title', 'id', 'status', 'slug', 'author')\n# prepopulated_fields = {'slug': ('title',), }\n\n","sub_path":"ideas/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"526139166","text":"\ndef lms(v,w_teorico, mu):\n lms_error = []\n w_lms = np.array([[0],[0]])\n w_all_values = [[],[]]\n\n for n in range(0, len(v)):\n sample_signal = [[ v[n - 1]], [v[n - 2]]] #Se toma una muestra del vector de entrada\n w1_error = math.pow( (w_teorico[0] - w_lms[0][0]) / w1, 2)\n w2_error = math.pow( (w_teorico[1] - w_lms[1][0]) / w2, 2)\n lms_error.append(math.sqrt(w1_error + w2_error))\n w_lms = w_lms + np.multiply(mu, sample_signal * np.transpose( v[n] - np.dot(np.transpose(w_lms), sample_signal))) #Actualizamos los pesos\n w_all_values[0].append(w_lms[0][0])\n w_all_values[1].append(w_lms[1][0])\n\n return w_lms, lms_error, w_all_values\n\ndef graphLMS(mu):\n\n w_lms_experimental_1 , error_lms_1, w_all_values = lms(signal_vector, [w1,w2], mu)\n w1_all_values = w_all_values[0]\n w2_all_values = w_all_values[1]\n w1_arange = np.arange(0,len(w1_all_values),1)\n w2_arange = np.arange(0,len(w2_all_values),1)\n print(\"For mu = \",mu)\n fig1, ax1 = plt.subplots()\n ax1.plot(w1_arange,w1_all_values)\n ax1.set_title(\"W1\")\n fig2, ax2 = plt.subplots()\n ax2.plot(w2_arange,w2_all_values)\n ax2.set_title(\"W2\")\n\n error_lms_arange = np.arange(0,len(error_lms_1),1)\n fig3, ax3 = plt.subplots()\n\n ax3.plot(error_lms_arange,error_lms_1)\n ax3.set_title(\"Error\")\n print(\"W1: \",w_lms_experimental_1[0][0])\n print(\"W2: \",w_lms_experimental_1[1][0])\n","sub_path":"lms.py","file_name":"lms.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"633902868","text":"from tkinter import *\n\n\n# Funções\n\n# o meu widget\nclass FrameNome(Frame): # indica o que fazer com os frames\n def __init__(self, ajanela):\n super().__init__() # inicia a função de cima\n self['height'] = 150 # define a altura\n self['width'] = 200 # define a largura\n self['bd'] = 2 # borda e tamanho dela\n self['relief'] = 'solid' # tipo da borda\n\n label_nome = Label(self, text='nome: ')\n text_nome = Entry(self)\n label_nome.grid(row=0, column=0)\n text_nome.grid(row=0, column=1)\n\n\n# GUI\njanela = Tk()\njanela.title('022')\n\n# WIDGETS\n\n# LAYOUT\n\nframe1_nome_1 = FrameNome(janela).grid()\nframe1_nome_2 = FrameNome(janela).grid()\nframe1_nome_3 = FrameNome(janela).grid()\nframe1_nome_4 = FrameNome(janela).grid()\n\n\njanela.mainloop()\n","sub_path":"Bibliotecas-Python/tkinter - João ribeiro/027 - criar nosso proprio widget.py","file_name":"027 - criar nosso proprio widget.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"650679575","text":"import random\nimport gym\nimport numpy as np\nfrom bisect import bisect_left\nimport statistics\nimport make_plot\nrandom.seed(0)\nnp.random.seed(0)\n\n\ndef get_distribution(first, last, step):\n ans = []\n while first <= last:\n ans.append(first)\n first += step\n return ans\n\n\nclass QParameters:\n def __init__(self, e=0.5, a=0.3, g=0.6):\n self.eps = e\n self.alpha = a\n self.gamma = g\n\n\nclass QTwoDimFunctionSampling:\n def __init__(self, first, second, acts):\n self.first_dim = first\n self.second_dim = second\n self.actions = acts\n self.q_function = np.zeros([len(self.first_dim) + 1, len(self.second_dim) + 1, len(self.actions) + 1])\n\n def get_parameters_index(self, state):\n i = bisect_left(self.first_dim, state[0], 0, len(self.first_dim))\n j = bisect_left(self.second_dim, state[1], 0, len(self.second_dim))\n return i, j\n\n def get_action_index(self, action):\n return bisect_left(self.actions, action, 0, len(self.actions))\n\n\nclass Car:\n def __init__(self, parameters, sampling, environment):\n self.q_parameters = parameters\n self.q_sampling = sampling\n self.env = environment\n self.env.seed(0)\n\n def get_action(self, state):\n if self.q_parameters.eps > random.uniform(0, 1):\n action = self.q_sampling.get_action_index(self.env.action_space.sample())\n else:\n action = np.argmax(self.q_sampling.q_function[state[0], state[1]])\n return action\n\n def max_delta(self, next_state, state, action):\n return np.max(self.q_sampling.q_function[next_state[0], next_state[1]])\\\n - self.q_sampling.q_function[state[0], state[1], action]\n\n def learn(self, epoch, rendering):\n scores = []\n for i in range(epoch):\n flag = False\n self.q_parameters.eps -= self.q_parameters.eps / epoch\n obs = self.env.reset()\n state = self.q_sampling.get_parameters_index(obs)\n total_score = 0\n while not flag:\n\n if rendering:\n self.env.render()\n\n action = self.get_action(state)\n next_obs, reward, flag, information = self.env.step([self.q_sampling.actions[action]])\n new_reward = reward + 100 * self.q_parameters.gamma * (abs(next_obs[1]) - abs(obs[1]))\n next_state = self.q_sampling.get_parameters_index(next_obs)\n s_f, s_s = state\n delta = new_reward + self.q_parameters.gamma * self.max_delta(next_state, state, action)\n last_delta = (1 - self.q_parameters.alpha) * self.q_sampling.q_function[s_f, s_s, action]\n self.q_sampling.q_function[s_f, s_s, action] = last_delta + self.q_parameters.alpha * delta\n state = next_state\n total_score += reward\n scores.append(total_score)\n self.env.close()\n return scores\n\n\nepoch_number = 10000\neps = 0.2\nalpha = 0.5\ngamma = 0.8\n\nq_parameters = QParameters(eps, alpha, gamma)\n\nvelocity = get_distribution(-0.701, 0.701, 0.001)\nposition = get_distribution(0, 0.51, 0.01)\nactions = get_distribution(-1, 1.01, 0.01)\n\nq_two_dim_func_sampling = QTwoDimFunctionSampling(position, velocity, actions)\n\nenv = gym.make('MountainCarContinuous-v0').env\n\ncar = Car(q_parameters, q_two_dim_func_sampling, env)\n\nscores = car.learn(epoch_number, False)\n\nmake_plot.make_plot(scores, epoch_number)\n","sub_path":"car_continuous.py","file_name":"car_continuous.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"8848299","text":"from django.template.defaultfilters import slugify\nfrom django import template\n\nregister = template.Library()\n\n@register.simple_tag\ndef get_template_profile_link(username, job):\n\tprofile = None\n\tif job == 'M':\n\t\tprofile = \"/employees/upper-management/\" + username\n\telif job == 'P':\n\t\tprofile = \"/employees/production-managers/\" + username\n\telif job == 'D':\n\t\tprofile = \"/employees/draftsmen/\" + username\n\telif job == 'T':\n\t\tprofile = \"/employees/machine-technicians/\" + username\n\telif job == 'B':\n\t\tprofile = \"/employees/model-builders/\" + username\n\tif profile != None:\n\t\treturn profile\n\n","sub_path":"employee/templatetags/extra_tags.py","file_name":"extra_tags.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"73413612","text":"from collections import deque, defaultdict\n\n\nclass Cell:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n\n def __eq__(self, cell):\n return self.key_equal(cell.key)\n\n def key_equal(self, key):\n return self.key == key\n\n\nclass HashMap:\n def __init__(self):\n self.__storage = defaultdict(deque)\n\n @staticmethod\n def _hash(key):\n return 0 # To simulate collide\n # return hash(key)\n\n def insert(self, key, value):\n '''Insert or Update exist key.\n\n If True returned, new pair inserted, else old pair updated.\n '''\n hash_key = self._hash(key)\n for cell in self.__storage[hash_key]:\n if cell.key_equal(key):\n cell.value = value\n return False\n cell = Cell(key, value)\n self.__storage[hash_key].append(cell)\n return True\n\n def lookup(self, key):\n hash_key = self._hash(key)\n for cell in self.__storage[hash_key]:\n if cell.key_equal(key):\n return cell.value\n return None\n\n def erase(self, key):\n '''Remove key in map.\n\n If True returned, pair deleted, else no pair found.\n '''\n hash_key = self._hash(key)\n target_cell = None\n for cell in self.__storage[hash_key]:\n if cell.key_equal(key):\n target_cell = cell\n break\n if target_cell is None:\n return False\n self.__storage[hash_key].remove(target_cell)\n return True\n","sub_path":"OOD/HashMap/hashmap.py","file_name":"hashmap.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"562748974","text":"import openpyxl\nfrom Models.stock_exchange_information import StockExchangeInformation\n\n\ndef read_sp500_stock_exchange_information(path, sheet, ticker_column, exchange_column, row_start):\n wb = openpyxl.load_workbook(path, data_only=True, read_only=True)\n sheet = wb[sheet]\n max_row = sheet.max_row\n data = []\n for i in range(row_start, max_row + 1):\n ticker_obj = sheet.cell(row=i, column=ticker_column)\n exchange_obj = sheet.cell(row=i, column=exchange_column)\n stock = StockExchangeInformation(ticker_obj.value, exchange_obj.value)\n data.append(stock)\n return data\n\n","sub_path":"excel_data_reader.py","file_name":"excel_data_reader.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"432431609","text":"#CreateVMWVMfromTemplate.py\n\nfrom VMWConfigFile import *\nfrom pyVim import connect\nfrom pyVim.connect import SmartConnect, Disconnect\nfrom pyVmomi import vim, vmodl\nimport atexit\nimport os\nimport ssl\nimport requests\nimport argparse\nimport time\nimport getpass\n\n\n# Disabling urllib3 ssl warnings\nrequests.packages.urllib3.disable_warnings()\n \n# Disabling SSL certificate verification\ncontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)\ncontext.verify_mode = ssl.CERT_NONE\n\n\n\ndef find_disk(vm,index):\n \"\"\"Return the disk of the given index in the vm\"\"\"\n i=0\n for device in vm.config.hardware.device:\n if hasattr(device.backing,\"fileName\"):\n if i==index:\n return device\n else:\n i +=1\n\ndef disk_controller(vm):\n \"\"\"Return the first disk controller for the given vm\"\"\"\n for device in vm.config.hardware.device:\n if isinstance(device,vim.vm.device.VirtualSCSIController):\n return device\n\n\n\ndef get_vim_objects(content, vim_type):\n '''Get vim objects of a given type.'''\n return [item for item in content.viewManager.CreateContainerView(\n content.rootFolder, [vim_type], recursive=True\n ).view]\n\n\n\ndef get_args():\n \"\"\" Get arguments from CLI \"\"\"\n parser = argparse.ArgumentParser(description='Create VMW VM from template')\n parser.add_argument('-u', '--user', help='VC User', required=True)\n parser.add_argument('-p', '--passw', help='VC User Pass', required=False)\n parser.add_argument('-v', '--vm-name', required=True, help='Name of the VM')\n parser.add_argument('-t','--template', required=True, help='Name of the template')\n parser.add_argument('-f','--vm-folder', required=False, default=None, help='Name of the VMFolder') \n parser.add_argument('-d','--datastore', required=False, default=None, help='Datastore you wish the VM to end up on\\\n \t\t\t\t\tIf left blank, VM will be put on the same \\\n \t\t\t\t\tdatastore as the template')\n\n parser.add_argument('-r','--resource-pool', required=False, default=None, help='Resource Pool to use. If left blank the first\\\n \t\t\t\t\tresource pool found will be used')\n\n parser.add_argument('--power-on', dest='power_on', required=False, action='store_true', help='power on the VM after creation')\n parser.add_argument('--no-power-on', dest='power_on', required=False, action='store_false', help='do not power on the VM after creation')\n parser.add_argument('-c', '--cpus', type=int, help='Number of CPUs, default: 1 vCPU', default=1)\n parser.add_argument('-m', '--mem', type=int, help='Memory in GB, default: 2 Gb', default=2)\n parser.add_argument('--nic0', help='NIC0 portgroup to use', required=False, nargs='?')\n parser.add_argument('--nic1', help='NIC1 portgroup to use', required=False, nargs='?')\n parser.add_argument('--nic2', help='NIC2 portgroup to use', required=False, nargs='?')\n parser.add_argument('--iops', type=int, help='IOPS limit to use, by default 100 is used', required=False, default=100)\n parser.add_argument('--disk', type=int, help='Disk size to use, by default the template size is used', required=False)\n\n\n args = parser.parse_args()\n\n if not args.passw:\n args.passw = getpass.getpass(\n prompt='Enter password')\n\n return args\n\n\ndef wait_for_task(task):\n \"\"\" wait for a vCenter task to finish \"\"\"\n task_done = False\n while not task_done:\n if task.info.state == 'success':\n print(\"ok\")\n return task.info.result\n\n if task.info.state == 'error':\n print(\"error\")\n task_done = True\n\n\ndef get_obj(content, vimtype, name):\n \"\"\"\n Return an object by name, if name is None the\n first found object is returned\n \"\"\"\n obj = None\n container = content.viewManager.CreateContainerView(\n content.rootFolder, vimtype, True)\n for c in container.view:\n if name:\n if c.name == name:\n obj = c\n break\n else:\n obj = c\n break\n\n return obj\n\n\ndef clone_vm(\n content, template, vm_name, si,\n datacenter_name, vm_folder, datastore,\n cluster_name, resource_pool, power_on, nic0, nic1, nic2, \n cpus, mem, iops, disk_size ):\n \"\"\"\n Clone a VM from a template/VM, datacenter_name, vm_folder, datastore\n cluster_name, resource_pool, and power_on are all optional.\n \"\"\"\n\n # if none git the first one\n datacenter = get_obj(content, [vim.Datacenter], datacenter_name)\n\n if vm_folder:\n destfolder = get_obj(content, [vim.Folder], vm_folder)\n else:\n destfolder = datacenter.vmFolder\n\n if datastore:\n datastore = get_obj(content, [vim.Datastore], datastore)\n else:\n datastore = get_obj(\n content, [vim.Datastore], template.datastore[0].info.name)\n\n # if None, get the first one\n cluster = get_obj(content, [vim.ClusterComputeResource], cluster_name)\n\n if resource_pool:\n resource_pool = get_obj(content, [vim.ResourcePool], resource_pool)\n else:\n resource_pool = cluster.resourcePool\n\n # set relospec\n relospec = vim.vm.RelocateSpec()\n relospec.datastore = datastore\n relospec.pool = resource_pool\n\n devices = []\n\n if nic0:\n # VM device\n nic = vim.vm.device.VirtualDeviceSpec()\n nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add # or edit if a device exists\n nic.device = vim.vm.device.VirtualVmxnet3()\n nic.device.wakeOnLanEnabled = True\n nic.device.addressType = 'assigned'\n nic.device.key = 4000 # 4000 seems to be the value to use for a vmxnet3 device\n nic.device.deviceInfo = vim.Description()\n nic.device.deviceInfo.summary = nic0\n nic.device.deviceInfo.label = \"Network Adapter 1\"\n\n pg_obj = get_obj(content, [vim.dvs.DistributedVirtualPortgroup], nic0)\n dvs_port_connection = vim.dvs.PortConnection()\n dvs_port_connection.portgroupKey= pg_obj.key\n dvs_port_connection.switchUuid= pg_obj.config.distributedVirtualSwitch.uuid\n\n nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()\n nic.device.backing.port = dvs_port_connection\n\n nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()\n nic.device.connectable.startConnected = True\n nic.device.connectable.allowGuestControl = True\n devices.append(nic)\n\n if nic1:\n # VM device\n nic = vim.vm.device.VirtualDeviceSpec()\n nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add # or edit if a device exists\n nic.device = vim.vm.device.VirtualVmxnet3()\n nic.device.wakeOnLanEnabled = True\n nic.device.addressType = 'assigned'\n nic.device.key = 4000 # 4000 seems to be the value to use for a vmxnet3 device\n nic.device.deviceInfo = vim.Description()\n nic.device.deviceInfo.summary = nic1\n nic.device.deviceInfo.label = \"Network Adapter 2\"\n\n pg_obj = get_obj(content, [vim.dvs.DistributedVirtualPortgroup], nic1)\n dvs_port_connection = vim.dvs.PortConnection()\n dvs_port_connection.portgroupKey= pg_obj.key\n dvs_port_connection.switchUuid= pg_obj.config.distributedVirtualSwitch.uuid\n\n nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()\n nic.device.backing.port = dvs_port_connection\n\n nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()\n nic.device.connectable.startConnected = True\n nic.device.connectable.allowGuestControl = True\n devices.append(nic)\n\n if nic2:\n # VM device\n nic = vim.vm.device.VirtualDeviceSpec()\n nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add # or edit if a device exists\n nic.device = vim.vm.device.VirtualVmxnet3()\n nic.device.wakeOnLanEnabled = True\n nic.device.addressType = 'assigned'\n nic.device.key = 4000 # 4000 seems to be the value to use for a vmxnet3 device\n nic.device.deviceInfo = vim.Description()\n nic.device.deviceInfo.summary = nic2\n nic.device.deviceInfo.label = \"Network Adapter 3\"\n\n pg_obj = get_obj(content, [vim.dvs.DistributedVirtualPortgroup], nic2)\n dvs_port_connection = vim.dvs.PortConnection()\n dvs_port_connection.portgroupKey= pg_obj.key\n dvs_port_connection.switchUuid= pg_obj.config.distributedVirtualSwitch.uuid\n\n nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()\n nic.device.backing.port = dvs_port_connection\n\n nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()\n nic.device.connectable.startConnected = True\n nic.device.connectable.allowGuestControl = True\n devices.append(nic)\n\n\n disk=find_disk(template,0)\n controller=disk_controller(template)\n disk_spec=vim.vm.device.VirtualDeviceSpec()\n disk_spec.operation=vim.vm.device.VirtualDeviceSpec.Operation.edit\n disk_spec.device=disk\n disk_spec.device.controllerKey=controller.key\n if disk_size > 50:\n disk_spec.device.capacityInKB=disk_size*1024*1024\n #disk_spec.device.backing.thinProvisioned=True\n disk_spec.device.storageIOAllocation.limit = iops\n devices.append(disk_spec)\n\n\n # VM config spec\n vmconf = vim.vm.ConfigSpec()\n vmconf.numCPUs = cpus\n vmconf.memoryMB = mem * 1024\n vmconf.cpuHotAddEnabled = True\n vmconf.memoryHotAddEnabled = True\n vmconf.deviceChange = devices\n\n clonespec = vim.vm.CloneSpec()\n\n clonespec.location = relospec\n clonespec.config = vmconf\n clonespec.powerOn = power_on\n\n\n #print \"cloning VM...\"\n task = template.Clone(folder=destfolder, name=vm_name, spec=clonespec)\n #wait_for_task(task)\n print(task.info.key)\n\ndef VMfromTemplate(**kwargs):\n try:\n si = None\n try:\n #si = Service Instance of vCenter\n si = connect.SmartConnect(host=vc_settings[\"vcenter\"],\n user=kwargs['user'],\n pwd=kwargs['passw'],\n port=443,\n sslContext=context)\n\n\n except IOError as e:\n pass\n atexit.register(Disconnect, si)\n content = si.RetrieveContent()\n template = None\n\n\n template = get_obj(content, [vim.VirtualMachine], kwargs['template_name'])\n\n if template:\n clone_vm(content, template, kwargs['vm_name'], si,vc_settings[\"datacenter\"],\n kwargs['vm_folder'], kwargs['datastore'], vc_settings[\"cluster\"],\n kwargs['resource_pool'], kwargs['power_on'], kwargs['nic0'], kwargs['nic1'],\n kwargs['nic2'], kwargs['cpus'], kwargs['mem'],\n kwargs['iops'], kwargs['disk'])\n\n else:\n print(\"template not found\")\n\n except vmodl.MethodFault as e:\n print(\"Caught vmodl fault: %s\" % e.msg)\n return 1\n\n except Exception as e:\n print(\"Caught exception: %s\" % str(e))\n return 1","sub_path":"worker/worker/lib/vcenter/vms.py","file_name":"vms.py","file_ext":"py","file_size_in_byte":11122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"214668056","text":"from django.contrib.contenttypes.models import ContentType\nfrom django.db.models.fields import BLANK_CHOICE_DASH\n\nfrom glitter.models import Version\n\nfrom .models import PublishAction\n\n\ndef object_version_choices(obj):\n \"\"\"\n Return a list of form choices for versions of this object which can be published.\n \"\"\"\n choices = BLANK_CHOICE_DASH + [(PublishAction.UNPUBLISH_CHOICE, 'Unpublish current version')]\n\n # When creating a new object in the Django admin - obj will be None\n if obj is not None:\n saved_versions = Version.objects.filter(\n content_type=ContentType.objects.get_for_model(obj),\n object_id=obj.pk,\n ).exclude(\n version_number=None,\n )\n\n for version in saved_versions:\n choices.append((version.version_number, version))\n\n return choices\n","sub_path":"glitter/publisher/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"80697595","text":"# ECDeise\n\nfrom mapper.NodeMap import *\nfrom base.Heuristics import *\nfrom math import sqrt\nfrom itertools import product\n\nclass Search_Algorithms(object):\n\n def __init__(self, nodemap):\n self.nodeMap = nodemap\n self.heuristic_code = 1\n\n def a_star(self, heuristic_code):\n self.heuristic_code = heuristic_code\n open_nodeset = set()\n closed_nodeset = set()\n #get the start node\n starter = self.nodeMap.node_dictionary[self.nodeMap.start[0],self.nodeMap.start[1] ]\n current = Node(starter.x, starter.y)\n current.h = 0\n current.g = 0\n current.parent = None\n open_nodeset.add(current)\n while open_nodeset:\n #get the min in set\n current = min(open_nodeset, key=lambda nd:nd.g + nd.h)\n #All Done ... found the Goal..\n if self.end_location_test(current):\n print('Path Found! a_star operation complete ...')\n return current\n open_nodeset.remove(current)\n closed_nodeset.add(current)\n #get the adjacent nodes( cardinal and diagonals)\n for nextnode in self.get_adjacent_nodes_full(current):\n #been there\n if nextnode in closed_nodeset:\n continue\n #update node data\n if nextnode in open_nodeset:\n new_g = current.g + current.move_cost(nextnode)\n if nextnode.g > new_g:\n nextnode.g = new_g\n nextnode.parent = current\n #apply heuristic and project guess - add to the open_nodeset\n else:\n nextnode.g = current.g + current.move_cost(nextnode)\n if self.heuristic_code == 1:\n nextnode.h = manhattan_distance(nextnode, self.nodeMap.end)\n elif self.heuristic_code == 2:\n nextnode.h = euclid_distance(nextnode, self.nodeMap.end)\n elif self.heuristic_code == 3:\n nextnode.h = tchebychev_distance(nextnode, self.nodeMap.end)\n else:\n nextnode.h = manhattan_distance(nextnode, self.nodeMap.end)\n nextnode.parent = current\n\n open_nodeset.add(nextnode)\n\n # No Path to the goal in that map\n print('a_star operation completed. No path found....')\n return None\n\n\n def end_location_test(self, current):\n \"\"\"Return if current Node is the target.\n Args:\n current: the current Node.\n Returns:\n Boolean.\n Raises:\n e: exception\n \"\"\"\n try:\n return (current.x == self.nodeMap.end[0] and current.y == self.nodeMap.end[1])\n except Exception as e:\n raise e\n\n\n # Retrieve node from dictionary by location/coords\n def get_node_at_location(self, x, y):\n \"\"\"Return Node with coordinates provided.\n Args:\n x, y: x and y coords of Node in map.\n Returns:\n Node.\n Raises:\n e: exception.\n \"\"\"\n try:\n return self.nodeMap.node_dictionary[x, y]\n except Exception as e:\n raise e\n\n # Get the set of all legal moves from the current node (cardinals and diagonals)\n def get_adjacent_nodes_full(self, node):\n \"\"\"Return array of Nodes adjacent to current node.\n Args:\n node: the current Node.\n Returns:\n adjacent_nodes an array of Nodes.\n Raises:\n e: exception.\n \"\"\"\n try:\n adjacent_nodes = set()\n # generate adjacents in 8 possible directions...\n for i, j in product([-1, 0, 1], [-1, 0, 1]):\n #out of bounds?\n if not (0 <= node.x + i < self.nodeMap.width):\n continue\n #out of bounds?\n if not (0 <= node.y + j < self.nodeMap.height):\n continue\n #is this an obstacle? - if so, ignore it\n if self.get_node_at_location(node.x+i, node.y+j).accessible == False:\n continue\n #get the relavant info\n newNode = Node(node.x+i, node.y+j)\n newNode.h = node.h\n newNode.g = node.g\n if (i == j == 0):\n newNode.parent = None\n else:\n newNode.parent = node\n #add node for consideration\n adjacent_nodes.add(newNode)\n return adjacent_nodes\n except Exception as e:\n raise e\n\n\n # display the path, write to file\n def report_trip_path(self, pathnode, outputfile):\n \"\"\"Return path Nodes of final path.\n Args:\n pathnode: the current Node in the path.\n outputfile: path to output file for result writing\n Returns:\n string display to console.\n writen output to outputfile\n Raises:\n e: IOError.\n \"\"\"\n pathlist = []\n count = 0\n totalCost = 0\n while True:\n count += 1\n if not pathnode:\n break\n pathlist.append(pathnode.retdisplay())\n if pathnode.g > totalCost:\n totalCost = pathnode.g\n pathnode = pathnode.parent\n #reverse the list\n pathlist.reverse()\n\n #display to console\n print ('Start: (%d, %d)' % (self.nodeMap.start[0], self.nodeMap.start[1]))\n print ('\\n'.join(map(str, pathlist)))\n print ('End: (%d, %d)' % (self.nodeMap.end[0], self.nodeMap.end[1]))\n print ('Nodes in path %s Total Cost: %d ' % (count, totalCost))\n\n if outputfile is not None:\n #write to file ....\n try:\n f = open(outputfile, \"a\")\n try:\n f.write('Start: (%d, %d)\\n' % (self.nodeMap.start[0], self.nodeMap.start[1]))\n if len(pathlist) >= 2:\n f.write(str('\\n'.join(map(str, pathlist))))\n else:\n f.write('\\n*** NO PATH FOUND ***')\n f.write(\"\\nEnd: (%d, %d)\" % (self.nodeMap.end[0], self.nodeMap.end[1]))\n f.write(\"\\nNodes in path %s Total Cost: %d \" % (count, totalCost))\n finally:\n f.close()\n except IOError as e:\n print (\"I/O error({0}): {1}\".format(e.errno, e.strerror))\n\n\n","sub_path":"searchalgorithms/SearchAlgorithms.py","file_name":"SearchAlgorithms.py","file_ext":"py","file_size_in_byte":6643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"565088799","text":"# -*- coding: utf-8 -*-\nfrom openerp import api, fields, models\nfrom openerp.exceptions import except_orm\n\n\nclass ProductSaleClaim(models.Model):\n _name = 'sale.claim'\n _description = 'Claim'\n _order = 'name desc'\n _inherit = ['mail.thread']\n\n name = fields.Char('Claim ID #', default='/', readonly=True)\n claim_sub = fields.Char('Claim Subject')\n saleorder_id = fields.Many2one('sale.order', string='Sale Order')\n state = fields.Selection([('new', 'New'),\n ('progress', 'In-Progress'),\n ('done', 'Done')],\n compute='_get_claim_state', store=True, default='new')\n\n @api.depends('replace_delivery_picking_id.state', 'return_picking_id.state', 'confirmed', 'paid')\n def _get_claim_state(self):\n for claim in self:\n claim.state = 'new'\n if claim.return_type == 'credit_return':\n if claim.paid:\n claim.state = 'done'\n elif claim.confirmed:\n claim.state = 'progress'\n else:\n if claim.delivered:\n claim.state = 'done'\n elif claim.confirmed:\n claim.state = 'progress'\n\n group_id = fields.Many2one('procurement.group', compute='_get_procurement_group', store=True)\n\n @api.depends('saleorder_id')\n def _get_procurement_group(self):\n for claim in self:\n claim.group_id = claim.saleorder_id.procurement_group_id\n\n return_type = fields.Selection([('repair', 'Repair'),\n ('exchange', 'Exchange'),\n ('credit_return', 'Credit Return')], string='Return Type')\n partner_id = fields.Many2one('res.partner', string='Customer')\n return_picking_id = fields.Many2one('stock.picking')\n picking_ids = fields.One2many('stock.picking', 'claim_id')\n damage_location = fields.Many2one('stock.location', string='Damage Location',\n default=lambda self: self._get_default_damage_location())\n confirmed = fields.Boolean('Confirmed')\n received = fields.Boolean('Received')\n invoiced = fields.Boolean('Invoiced')\n paid = fields.Boolean('Paid', compute='_get_refund_invoice_state', store=True)\n\n @api.depends('invoice_ids.state')\n def _get_refund_invoice_state(self):\n for claim in self:\n claim.paid = False\n if claim.invoice_ids:\n invoice_paid = True\n for invoice in claim.invoice_ids:\n if invoice.state != 'paid':\n invoice_paid = False\n if invoice_paid:\n claim.paid = True\n\n delivered = fields.Boolean('Delivered', compute='_get_delivered_state', store=True)\n\n @api.depends('replace_delivery_picking_id.state')\n def _get_delivered_state(self):\n for claim in self:\n if claim.replace_delivery_picking_id and \\\n claim.replace_delivery_picking_id.state == 'done':\n claim.delivered = True\n #Incoming Return from Customer\n if claim.return_type =='exchange':\n return_total = sum(each_move.product_id.lst_price * each_move.quantity_done for each_move in claim.return_picking_id.move_lines)\n # Outgoing Shipment to Customer\n replace_total = sum(each_move.product_id.lst_price * each_move.quantity_done for each_move in claim.replace_delivery_picking_id.move_lines)\n if return_total == replace_total:\n break\n return_sign = -1 if replace_total > return_total else 1\n replace_sign = 1 if replace_total > return_total else -1\n type = 'out_invoice' if replace_total > return_total else 'out_refund'\n invoice_line_ids = []\n order_inv = claim.saleorder_id.order_line.mapped('invoice_lines').mapped('invoice_id')\n for each_move in claim.return_picking_id.move_lines:\n invoice_line_ids.append((0, 0, {'name': each_move.product_id.name, 'product_id': each_move.product_id.id,\n 'quantity': each_move.quantity_done, 'uom_id': each_move.product_id.uom_id.id,\n 'price_unit': each_move.product_id.lst_price * return_sign,\n 'account_id': each_move.product_id.categ_id.property_account_income_categ_id.id}))\n for each_move in claim.replace_delivery_picking_id.move_lines:\n invoice_line_ids.append((0, 0, {'name': each_move.product_id.name, 'product_id': each_move.product_id.id,\n 'quantity': each_move.quantity_done, 'uom_id': each_move.product_id.uom_id.id,\n 'price_unit': each_move.product_id.lst_price * replace_sign,\n 'account_id': each_move.product_id.categ_id.property_account_income_categ_id.id}))\n invoice_vals = {\n 'name': '',\n 'type': type,\n 'partner_id': claim.partner_id.id,\n 'invoice_line_ids':invoice_line_ids,\n 'account_id': order_inv.account_id.id,\n 'journal_id': order_inv.journal_id.id,\n 'currency_id': order_inv.currency_id.id,\n 'claim_id': claim.id\n }\n self.env['account.invoice'].create(invoice_vals)\n\n replace_delivery_picking_id = fields.Many2one('stock.picking')\n claim_desc = fields.Text('Description')\n line_ids = fields.One2many('sale.claim.line', 'claim_id')\n picking_count = fields.Integer('Picking Count', compute='_calc_picking_count')\n\n @api.depends('picking_ids')\n def _calc_picking_count(self):\n for claim in self:\n claim.picking_count = claim.picking_ids and len(claim.picking_ids) or 0\n\n invoice_ids = fields.One2many('account.invoice', 'claim_id')\n total_invoices = fields.Float('Invoice Count', compute='_calc_invoice_count')\n\n @api.depends('invoice_ids')\n def _calc_invoice_count(self):\n for claim in self:\n claim.total_invoices = claim.invoice_ids and len(claim.invoice_ids) or 0\n\n # Constraints\n @api.constrains('saleorder_id')\n def _check_saleorder_duplication(self):\n for claim in self:\n claim_exists = claim.search([('saleorder_id', '=', claim.saleorder_id.id), ('id', '!=', claim.id)], limit=1)\n if claim_exists:\n raise except_orm('Claim already created for ' + claim.saleorder_id.name, claim_exists.name)\n\n def _get_default_damage_location(self):\n return self.env.ref('sale_product_exchange_drc.stock_location_damaged').id\n\n @api.multi\n def action_view_picking(self):\n for claim in self:\n return {\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'stock.picking',\n 'type': 'ir.actions.act_window',\n 'context': self._context,\n 'domain': [('id', 'in', claim.picking_ids.ids)]\n }\n\n @api.onchange('saleorder_id')\n def _onchange_sale_order(self):\n self.partner_id = self.saleorder_id.partner_id.id\n\n @api.onchange('partner_id')\n def _onchange_partner_id(self):\n if self.partner_id.id != self.saleorder_id.partner_id.id:\n self.saleorder_id = False\n\n # @api.onchange('saleorder_id')\n # def _onchange_sale_order(self):\n # for claim in self:\n # if claim.saleorder_id:\n # res = []\n # for line in claim.saleorder_id.order_line:\n # res.append((0, 0, {\n # 'product_id': line.product_id.id,\n # 'claim_id': claim.id,\n # 'ordered_qty': line.product_uom_qty,\n # 'uom_id': line.product_uom.id,\n # }\n # ))\n # if res:\n # claim.line_ids = res\n\n @api.multi\n def fetch_products(self):\n for claim in self:\n claim.line_ids = False\n if claim.saleorder_id:\n res = []\n for line in claim.saleorder_id.order_line:\n res.append((0, 0, {\n 'product_id': line.product_id.id,\n 'claim_id': claim.id,\n 'ordered_qty': line.product_uom_qty,\n 'uom_id': line.product_uom.id,\n }\n ))\n if res:\n claim.line_ids = res\n\n @api.model\n def create(self, vals):\n if vals.get('name', '/') == '/':\n vals['name'] = self.env['ir.sequence'].get('sale.claim') or '/'\n res = super(ProductSaleClaim, self).create(vals)\n return res\n\n @api.multi\n def claim_confirm(self):\n for claim in self:\n for line in self.line_ids:\n if line.return_qty <= 0:\n raise except_orm(\"Error!\", \"Can not return zero/negative quantity\")\n if line.ordered_qty < line.return_qty:\n raise except_orm(\"Error!\", \"Can not return quantity more then ordered quantity\")\n claim.confirmed = True\n claim.saleorder_id.is_claim_created = True\n\n @api.multi\n def create_in_shipment(self):\n StockMove = self.env['stock.move']\n for claim in self:\n if claim.return_picking_id:\n raise except_orm('Incoming Shipment is Already created for this claim',\n 'Shipment id is ' + claim.return_picking_id.name)\n pick_type_id = claim.saleorder_id.picking_ids and self.saleorder_id.picking_ids[0].picking_type_id and \\\n claim.saleorder_id.picking_ids[0].picking_type_id.return_picking_type_id.id\n destination_location = claim.saleorder_id.picking_ids[0].location_dest_id.id\n new_picking = claim.saleorder_id.picking_ids[0].copy({\n 'move_lines': [],\n 'picking_type_id': pick_type_id,\n 'state': 'draft',\n 'origin': claim.saleorder_id.name + ' - ' + claim.name,\n 'claim_id': claim.id\n })\n\n claim.return_picking_id = new_picking.id\n for line in claim.line_ids:\n StockMove.create({\n 'name': line.product_id.product_tmpl_id.name,\n 'product_id': line.product_id.id,\n 'product_uom_qty': line.return_qty,\n 'product_uom': line.uom_id.id,\n 'picking_id': new_picking.id,\n 'state': 'draft',\n 'location_id': destination_location,\n 'location_dest_id': claim.damage_location.id,\n 'picking_type_id': pick_type_id,\n 'warehouse_id': claim.saleorder_id.warehouse_id.id,\n 'procure_method': 'make_to_stock',\n })\n\n if claim.return_type == 'credit_return':\n new_picking.invoice_state = '2binvoiced'\n else:\n new_picking.invoice_state = 'none'\n claim.received = True\n return {\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'stock.picking',\n 'type': 'ir.actions.act_window',\n 'res_id': new_picking.id,\n 'context': self._context,\n 'target': 'new',\n 'flags': {'action_buttons': True}\n }\n\n @api.multi\n def open_refund_invoice(self):\n action_id = self.env.ref('account.action_invoice_tree2')\n if action_id:\n action = action_id.read()\n action = action[0] or action\n action['domain'] = \"[('id','in', [\" + ','.join(map(str, self.invoice_ids.ids)) + \"])]\"\n return action\n\n @api.multi\n def create_claim_refund_invoice(self):\n for claim in self:\n order_inv = claim.saleorder_id.order_line.mapped('invoice_lines').mapped('invoice_id')\n order_inv_lines = claim.saleorder_id.order_line.mapped('invoice_lines')\n invoice_vals = {\n 'name': '',\n 'type': 'out_refund',\n 'partner_id': claim.partner_id.id,\n 'invoice_line_ids': [(0, 0, {'name': line.product_id.name, 'product_id': line.product_id.id,\n 'quantity': line.return_qty, 'uom_id': line.product_id.uom_id.id,\n 'price_unit': line.product_id.standard_price,\n 'account_id': order_inv.account_id.id}) for line in claim.line_ids],\n 'account_id': order_inv.account_id.id,\n 'journal_id': order_inv.journal_id.id,\n 'currency_id': order_inv.currency_id.id,\n 'claim_id': claim.id\n }\n inv = self.env['account.invoice'].create(invoice_vals)\n return {\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'account.invoice',\n 'type': 'ir.actions.act_window',\n 'res_id': inv.id,\n 'target': 'self',\n }\n\n @api.multi\n def create_out_shipment(self):\n for claim in self:\n if claim.replace_delivery_picking_id:\n raise except_orm('Delivery Order is Already created for this claim',\n 'Delivery Order is ' + claim.replace_delivery_picking_id.name)\n pick_type_id = claim.return_picking_id.picking_type_id.return_picking_type_id and claim.return_picking_id.picking_type_id.return_picking_type_id.id or claim.return_picking_id.picking_type_id.id\n new_picking = claim.return_picking_id.copy({\n 'move_lines': [],\n 'picking_type_id': pick_type_id,\n 'state': 'draft',\n 'origin': claim.return_picking_id.name + ' - ' + claim.name,\n 'claim_id': claim.id\n })\n claim.replace_delivery_picking_id = new_picking.id\n for move in claim.return_picking_id.move_lines:\n move.copy({\n 'product_uom_qty': move.product_uom_qty,\n 'picking_id': new_picking.id,\n 'state': 'draft',\n 'location_id': claim.saleorder_id.picking_ids[0].location_id.id,\n 'location_dest_id': move.location_id.id,\n 'picking_type_id': pick_type_id,\n 'warehouse_id': claim.saleorder_id.warehouse_id.id,\n 'origin_returned_move_id': move.id,\n 'procure_method': 'make_to_stock',\n })\n return {\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'stock.picking',\n 'type': 'ir.actions.act_window',\n 'res_id': new_picking.id,\n 'context': self._context,\n 'target': 'new',\n 'flags': {'action_buttons': True}\n }\n\n\nclass ProductSaleClaimLine(models.Model):\n _name = 'sale.claim.line'\n\n product_id = fields.Many2one('product.product', string='Product', readonly=True)\n uom_id = fields.Many2one('product.uom', string='UOM', readonly=True)\n claim_id = fields.Many2one('sale.claim', string='Claim')\n ordered_qty = fields.Float('Ordered Quantity', readonly=True)\n return_qty = fields.Float('Return Quantity')\n claim_desc = fields.Text('Note')\n","sub_path":"sale_product_exchange_drc/models/sale_product_claim.py","file_name":"sale_product_claim.py","file_ext":"py","file_size_in_byte":16223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"430937820","text":"import torch\nimport torchvision\nimport tqdm\nimport numpy as np\nfrom torch.utils.data import random_split\nfrom tqdm import tqdm\nfrom torchvision import transforms\nimport matplotlib.pyplot as plt\nfrom model import Model\nimport torch.nn.functional as F\nfrom matplotlib import cm, colors\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef plot(embeds, labels):\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111, projection='3d')\n\n # Create a sphere\n r = 1\n pi = np.pi\n cos = np.cos\n sin = np.sin\n phi, theta = np.mgrid[0.0:pi:100j, 0.0:2.0*pi:100j]\n x = r*sin(phi)*cos(theta)\n y = r*sin(phi)*sin(theta)\n z = r*cos(phi)\n ax.plot_surface(\n x, y, z, rstride=1, cstride=1, color='w', alpha=0.3, linewidth=0)\n\n embeds = np.stack(embeds)\n ax.scatter(embeds[:, 0], embeds[:, 1], embeds[:, 2], c=labels, s=20)\n\n ax.set_xlim([-1, 1])\n ax.set_ylim([-1, 1])\n ax.set_zlim([-1, 1])\n plt.tight_layout()\n plt.savefig('output/result.png')\n\n\ndef test(test_loader, model):\n all_embeds = []\n all_labels = []\n with torch.no_grad():\n for data, label in tqdm(test_loader):\n embed = model(data)\n embed = F.normalize(embed, p=2, dim=1).squeeze().cpu().numpy()\n all_embeds.append(embed)\n all_labels.append(label)\n\n all_embeds = np.array(all_embeds)\n all_labels = np.array(all_labels)\n\n plot(all_embeds, all_labels)\n\n\nif __name__ == '__main__':\n transform = transforms.Compose([transforms.ToTensor()])\n testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)\n test_loader = torch.utils.data.DataLoader(testset, batch_size=1, shuffle=True)\n\n model = Model()\n model.eval()\n model.load_state_dict(torch.load('output/weight.pth'))\n\n test(test_loader, model)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"244229846","text":"# -*- coding: utf-8 -*-\n# @Author: Vincent Xu\n# @E-mail: wenhong0815@qq.com\n# For my Graduation Design about RS\n'''\n这里用来存cookie\n'''\n\nCOOKIES_V4 = [\n{\n \"domain\": \".zhihu.com\",\n \"expirationDate\": 1630387980.450661,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"_xsrf\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"YczvFtZpIyg6P7TxbJggEXrD430otDeL\",\n \"id\": 1\n},\n{\n \"domain\": \".zhihu.com\",\n \"expirationDate\": 1615699980.45062,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"_zap\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"cc19b63a-d67f-401d-a44f-8f229e788aed\",\n \"id\": 2\n},\n{\n \"domain\": \".zhihu.com\",\n \"expirationDate\": 1555220200.413068,\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"capsion_ticket\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"\\\"2|1:0|10:1552628199|14:capsion_ticket|44:NjcyMDIwYjQ5YTY0NDlkN2EwNGFiMWE0NGMwM2JjNDg=|0ac84002be5a9d4344d6e24dd9f6770b3ffdeb650c0e7c68cc698303e0579306\\\"\",\n \"id\": 3\n},\n{\n \"domain\": \".zhihu.com\",\n \"expirationDate\": 1647236194.684021,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"d_c0\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"\\\"ABDk7jEKIA-PTk_IbMnlzbf35AG0yqgTEB0=|1552628193\\\"\",\n \"id\": 4\n},\n{\n \"domain\": \".zhihu.com\",\n \"expirationDate\": 1647237578.342158,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"q_c1\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"f901aa6e48384ff9855d4b3c593447f5|1552629577000|1552629577000\",\n \"id\": 5\n},\n{\n \"domain\": \".zhihu.com\",\n \"expirationDate\": 1555221541,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"tst\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"r\",\n \"id\": 6\n},\n{\n \"domain\": \".zhihu.com\",\n \"expirationDate\": 1568180204.44267,\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"z_c0\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"\\\"2|1:0|10:1552628203|4:z_c0|92:Mi4xZHZZZ0FnQUFBQUFBRU9UdU1Rb2dEeVlBQUFCZ0FsVk42NGQ0WFFEVnM5bkNTMnJ3Q0diOEJzYTZJS2wwd04tZmxR|94430f8810de2b2ca2d56f90a5c4cfa79cbadbc656402944bdd35dde0b3e9b1e\\\"\",\n \"id\": 7\n}]\n# {\n# \"domain\": \"www.zhihu.com\",\n# \"expirationDate\": 1552630439.229063,\n# \"hostOnly\": True,\n# \"httpOnly\": False,\n# \"name\": \"tgw_l7_route\",\n# \"path\": \"/\",\n# \"sameSite\": \"no_restriction\",\n# \"secure\": False,\n# \"session\": False,\n# \"storeId\": \"0\",\n# \"value\": \"80f350dcd7c650b07bd7b485fcab5bf7\",\n# \"id\": 8\n# }\n","sub_path":"functiontool/constant_cookies.py","file_name":"constant_cookies.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"385162411","text":"from pathlib import Path\nfrom typing import Union, Any, List, Tuple, Optional, IO\n\ndef dump(\n value: Any,\n filename: Union[str, Path, IO[bytes]],\n compress: Union[int, bool, Tuple[str, int]] = False,\n protocol: Optional[int] = None,\n cache_size: Optional[int] = None\n) -> List[str]:\n ...\n\ndef load(\n filename: Union[str, Path, IO[bytes]],\n mmap_mode: Optional[str] = None\n) -> Any:\n ...\n","sub_path":"stubs/sklearn/externals/joblib.pyi","file_name":"joblib.pyi","file_ext":"pyi","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"633861768","text":"#!/usr/bin/python3\nimport smtplib\nimport socket\nimport sys\nfrom smtplib import SMTPException\n\nsender = 'testSender@testdomain.com'\nreceivers = ['testReceiver@testdomain.com']\n\n#structured mail\nmailContent = \"\"\"From: testSender@testdomain.com\nTo: testReceiver@testdomain.com\nSubject: Hello from python code\n\nYou have been chosen by the python gods !\n\n\"\"\"\n\n# messages can be without any format like plainMessage below but these messages are usually caught by spam filters\nplainMessage = \"\"\" \nThis is a message without To , From and subject \n\"\"\"\n\n\ntry:\n # Set timeout to a minute to force stop the connection , change this if necessary\n socket.setdefaulttimeout(1 * 60)\n\n # # without SSL\n # smtpObj = smtplib.SMTP('enter smtp server ip')\n # smtpObj.sendmail(sender, receivers, plainMessage)\n # print (\"Your Mail has been delivered !\")\n\n #with SSL and auth\n \"\"\" For gmail , there is a security feature which might throw an error saying -\n mtplib.SMTPAuthenticationError: Please log in via your web browser and then try again. Learn more at https://support.google.com/mail/answer/78754 \n To resolve this , enable \"Allow less secure apps\" option in gmail. Check references section at the end of the code for further info.\n \"\"\"\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server.login(\"gmailId\", \"gmailPassword\")\n server.sendmail(\n \"From address\",\n \"To address\",\n mailContent)\n server.quit()\n\nexcept SMTPException:\n lineNo = sys.exc_info()[-1].tb_lineno\n print(\"Error: SMTP exception , Check line {0}\".format(lineNo))\n\nexcept BaseException as e:\n lineNo = sys.exc_info()[-1].tb_lineno\n print(\"Error: {0} at line {1}\".format(e, lineNo))\n\n\n# References -\n# 1. https://www.afternerd.com/blog/how-to-send-an-email-using-python-and-smtplib/\n# 2. https://docs.python.org/3/library/smtplib.html\n","sub_path":"DeliverMyMail/mailSender.py","file_name":"mailSender.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"604453421","text":"def knuthMorrisPrattAlgorithm(string, substring):\n # Write your code here.\n\tpattern = getPattern(substring)\n\treturn knp(string, substring, pattern)\n\n\ndef knp(string, substring, pattern):\n\tj = 0\n\ti = 0\n\twhile i + len(substring) - j <= len(string):\n\t\tif string[i] == substring[j]:\n\t\t\tif j == len(substring) -1:\n\t\t\t\treturn True\n\t\t\ti += 1\n\t\t\tj += 1\n\t\telif j > 0:\n\t\t\tj = pattern[j-1] + 1\n\t\telse:\n\t\t\ti += 1\n\treturn False\n\ndef getPattern(substring):\n\tpattern = [-1 for _ in substring]\n\tj = 0\n\ti = 1\n\twhile i < len(substring):\n\t\tif substring[i] == substring[j]:\n\t\t\tpattern[i] = j\n\t\t\ti += 1\n\t\t\tj += 1\n\t\telif j > 0:\n\t\t\tj = pattern[j-1] + 1 # the previously indexed item + 1\n\t\telse:\n\t\t\ti += 1\n\treturn pattern\n","sub_path":"python/KnuthMorrisPratt.py","file_name":"KnuthMorrisPratt.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569955488","text":"import pickle\nimport string\nimport re\nfrom nltk.corpus import stopwords \nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import TweetTokenizer\nfrom nltk import classify\nfrom nltk import NaiveBayesClassifier\nimport json\nimport random\nimport pandas as pd\n\noverall_df = pd.read_csv('overall_counts.csv')\nneg_tweets = pd.read_csv('negative_tweets.csv')\npos_tweets = pd.read_csv('positive_tweets.csv')\n\nfull_tweets = neg_tweets.append(pos_tweets, sort=True)\n\napp3 = full_tweets\n\ndf_sent1 = pd.read_csv('pre_debate_candidate_sentiment.csv')\ndf_sent1['scenario'] = 'pre_debate'\ndf_sent2 = pd.read_csv('post_debate_candidate_sentiment.csv')\ndf_sent3 = pd.read_csv('pre_election_candidate_sentiment.csv')\ndf_sent4 = pd.read_csv('post_election_candidate_sentiment.csv')\n\ndf_sent1 = df_sent1[['Name','Negative Probability','Positive Probability','Results','scenario']]\ndf_sent2 = df_sent2[['Name','Negative Probability','Positive Probability','Results','scenario']]\ndf_sent3 = df_sent3[['Name','Negative Probability','Positive Probability','Results','scenario']]\ndf_sent4 = df_sent4[['Name','Negative Probability','Positive Probability','Results','scenario']]\n\nsent_app1 = df_sent1.append(df_sent2)\n\nsent_app2 = sent_app1.append(df_sent3)\n\nsent_app3 = sent_app2.append(df_sent4)\n\nsent_app3['Staging'] = sent_app3['Negative Probability'] + sent_app3['Positive Probability']\nsent_app3['General_Probability'] = 1 - sent_app3['Staging']\n\nsent_app3['General_Probability'] = sent_app3['General_Probability']*100\nsent_app3['Negative Probability'] = sent_app3['Negative Probability']*100\nsent_app3['Positive Probability'] = sent_app3['Positive Probability']*100\n\navg_group = sent_app3.groupby('Name').mean().reset_index()\n \n\ndef clean_tweets(tweet):\n stopwords_english = stopwords.words('english')\n\n stopwords_english = stopwords.words('english')\n tweet = re.sub(r'\\$\\w*', '', tweet)\n \n ## Cleaing up RTs\n tweet = re.sub(r'^RT[\\s]+', '', tweet)\n \n ## Removing hyperlinks\n tweet = re.sub(r'https?:\\/\\/.*[\\r\\n]*', '', tweet)\n \n ## Removing hastags\n tweet = re.sub(r'#', '', tweet)\n \n # tokenize tweets\n tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True, reduce_len=True)\n tweet_tokens = tokenizer.tokenize(tweet)\n \n tweets_clean = [] \n for word in tweet_tokens:\n if (word not in stopwords_english and # remove stopwords\n word not in string.punctuation): # remove punctuation\n ##stem_word = stemmer.stem(word) # stemming word\n tweets_clean.append(word)\n \n return tweets_clean\n\ndef bag_of_words(tweet):\n words = clean_tweets(tweet)\n words_dictionary = dict([word, True] for word in words) \n return words_dictionary\n\ndef run(tweet):\n filename = 'pre_debate_model.sav'\n loaded_model = pickle.load(open(filename, 'rb'))\n user_input = tweet\n custom_tweet_set = bag_of_words(user_input)\n prob_result = loaded_model.prob_classify(custom_tweet_set)\n \n final_result = str(prob_result.max())\n negative_percent = round(((prob_result.prob(\"neg\"))*100),2)\n positive_percent = round(((prob_result.prob(\"pos\"))*100),2)\n general_percent = round(((prob_result.prob(\"gen\"))*100),2)\n jsondata = {}\n json_final = {}\n json_final['Tweet'] = user_input\n json_final['Overall_Sentiment'] = final_result\n json_final['Negative_Percent'] = negative_percent\n json_final['Positive_Percent'] = positive_percent\n json_final['General_Percent'] = general_percent\n\n jsondata['Sentiment'] = json_final\n\n myjson = json.dumps(jsondata)\n\n return myjson\n\ndef random_tweets(name,col,time):\n \n save_tweets = []\n time_df = app3[app3['time_period']==time]\n name_df = time_df[time_df['candidate']==name]\n get_df = name_df[name_df['sentiment']==col].reset_index()\n\n \n for x in range(5):\n date = get_df['date'].iloc[random.randint(1,20)]\n username = get_df['username'].iloc[random.randint(1,20)]\n tweet = get_df['tweet_text'].iloc[random.randint(1,20)]\n\n save = {'date' : date, 'username': username, 'tweet': tweet}\n save_tweets.append(save)\n \n return save_tweets\n\ndef get_elements(name, col, scenario):\n df_cand = sent_app3[sent_app3['scenario']==scenario]\n df_sent = df_cand[df_cand['Name']==name]\n \n for i in df_sent[col]:\n return i\n\ndef get_avg(name,col):\n avg_group = sent_app3.groupby('Name').mean().reset_index()\n df_sent = avg_group[avg_group['Name']==name]\n for i in df_sent[col]:\n return i\n\ndef get_agg(name,period):\n name_agg = overall_df[overall_df['Name']==name]\n per_agg = name_agg[period]\n for i in per_agg:\n return i\n\ndef create_dash_api():\n\n jsondata = {}\n candidate_1 = {}\n electoral_data = {}\n\n ## Create Bernie Candidate \n candidate_1 = 'Bernie Sanders'\n\n ## Create electoral data\n\n electoral_data['period4'] = 'Overall'\n electoral_data['positive_sentitment_score_4'] = get_avg('Sanders','Positive Probability')\n electoral_data['negative_sentiment_score_4'] = get_avg('Sanders','Negative Probability')\n electoral_data['general_sentitment_score_4'] = get_avg('Sanders','General_Probability')\n electoral_data['tweet_count_4'] = get_agg('Sanders','Overall')\n positive_tweets = random_tweets('Sanders','positive','Pre-Debate')\n negative_tweets = random_tweets('Sanders','negative','Pre-Debate')\n electoral_data['positive_tweets_4'] = [positive_tweets]\n electoral_data['negative_tweets_4'] = [negative_tweets]\n\n electoral_data['period1'] = 'pre_debate'\n electoral_data['positive_sentitment_score_1'] = get_elements('Sanders','Positive Probability','pre_debate')\n electoral_data['negative_sentiment_score_1'] = get_elements('Sanders','Negative Probability','pre_debate')\n electoral_data['general_sentitment_score_1'] = get_elements('Sanders','General_Probability','pre_debate')\n electoral_data['tweet_count_1'] = get_agg('Sanders','Pre-Debate')\n positive_tweets = random_tweets('Sanders','positive','Pre-Debate')\n negative_tweets = random_tweets('Sanders','negative','Pre-Debate')\n electoral_data['positive_tweets_1'] = [positive_tweets]\n electoral_data['negative_tweets_1'] = [negative_tweets]\n\n\n electoral_data['period2'] = 'post_debate'\n electoral_data['positive_sentitment_score_2'] = get_elements('Sanders','Positive Probability','post_debate')\n electoral_data['negative_sentiment_score_2'] = get_elements('Sanders','Negative Probability','post_debate')\n electoral_data['general_sentitment_score_2'] = get_elements('Sanders','General_Probability','post_debate')\n electoral_data['tweet_count_2'] = get_agg('Sanders','Post-Debate')\n positive_tweets = random_tweets('Sanders','positive','Post-Debate')\n negative_tweets = random_tweets('Sanders','negative','Post-Debate')\n electoral_data['positive_tweets_2'] = [positive_tweets]\n electoral_data['negative_tweets_2'] = [negative_tweets]\n\n electoral_data['period3'] = 'post_election'\n electoral_data['positive_sentitment_score_3'] = get_elements('Sanders','Positive Probability','post_election')\n electoral_data['negative_sentiment_score_3'] = get_elements('Sanders','Negative Probability','post_election')\n electoral_data['general_sentitment_score_3'] = get_elements('Sanders','General_Probability','post_election')\n electoral_data['tweet_count_3'] = get_agg('Sanders','Post-Caucus')\n positive_tweets = random_tweets('Sanders','positive','Post-Caucus')\n negative_tweets = random_tweets('Sanders','negative','Post-Caucus')\n electoral_data['positive_tweets_3'] = [positive_tweets]\n electoral_data['negative_tweets_3'] = [negative_tweets]\n\n\n\n\n\n\n\n\n ## Liz Warren JSON\n\n candidate_2 = {}\n electoral_data_2 = {}\n\n ## Create Candidate\n candidate_2 = 'Elizabeth Warren'\n\n ## Create electoral data for Liz Warren \n\n electoral_data_2['period4'] = 'Overall'\n electoral_data_2['positive_sentitment_score_4'] = get_avg('Warren','Positive Probability')\n electoral_data_2['negative_sentiment_score_4'] = get_avg('Warren','Negative Probability')\n electoral_data_2['general_sentitment_score_4'] = get_avg('Warren','General_Probability')\n electoral_data_2['tweet_count_4'] = get_agg('Warren','Overall')\n positive_tweets = random_tweets('Warren','positive','Post-Caucus')\n negative_tweets = random_tweets('Warren','negative','Post-Caucus')\n electoral_data_2['positive_tweets_4'] = [positive_tweets]\n electoral_data_2['negative_tweets_4'] = [negative_tweets]\n\n\n electoral_data_2['period1'] = 'pre_debate'\n electoral_data_2['positive_sentitment_score_1'] = get_elements('Warren','Positive Probability','pre_debate')\n electoral_data_2['negative_sentiment_score_1'] = get_elements('Warren','Negative Probability','pre_debate')\n electoral_data_2['general_sentitment_score_1'] = get_elements('Warren','General_Probability','pre_debate')\n electoral_data_2['tweet_count_1'] = get_agg('Warren','Pre-Debate')\n positive_tweets = random_tweets('Warren','positive','Pre-Debate')\n negative_tweets = random_tweets('Warren','negative','Pre-Debate')\n electoral_data_2['positive_tweets_1'] = [positive_tweets]\n electoral_data_2['negative_tweets_1'] = [negative_tweets]\n\n\n electoral_data_2['period2'] = 'post_debate'\n electoral_data_2['positive_sentitment_score_2'] = get_elements('Warren','Positive Probability','post_debate')\n electoral_data_2['negative_sentiment_score_2'] = get_elements('Warren','Negative Probability','post_debate')\n electoral_data_2['general_sentitment_score_2'] = get_elements('Warren','General_Probability','post_debate')\n electoral_data_2['tweet_count_2'] = get_agg('Warren','Post-Debate')\n positive_tweets = random_tweets('Warren','positive','Post-Debate')\n negative_tweets = random_tweets('Warren','negative','Post-Debate')\n electoral_data_2['positive_tweets_2'] = [positive_tweets]\n electoral_data_2['negative_tweets_2'] = [negative_tweets]\n\n\n electoral_data_2['period3'] = 'post_election'\n electoral_data_2['positive_sentitment_score_3'] = get_elements('Warren','Positive Probability','post_election')\n electoral_data_2['negative_sentiment_score_3'] = get_elements('Warren','Negative Probability','post_election')\n electoral_data_2['general_sentitment_score_3'] = get_elements('Warren','General_Probability','post_election')\n electoral_data_2['tweet_count_3'] = get_agg('Warren','Post-Caucus')\n positive_tweets = random_tweets('Warren','positive','Post-Caucus')\n negative_tweets = random_tweets('Warren','negative','Post-Caucus')\n electoral_data_2['positive_tweets_3'] = [positive_tweets]\n electoral_data_2['negative_tweets_3'] = [negative_tweets]\n\n\n ## Kloobuchar build\n\n candidate_3 = {}\n electoral_data_3 = {}\n\n candidate_3 = 'Amy Klobuchar'\n\n ## Create for Amy\n\n electoral_data_3['period4'] = 'Overall'\n electoral_data_3['positive_sentitment_score_4'] = get_avg('Klobuchar','Positive Probability')\n electoral_data_3['negative_sentiment_score_4'] = get_avg('Klobuchar','Negative Probability')\n electoral_data_3['general_sentitment_score_4'] = get_avg('Klobuchar','General_Probability')\n electoral_data_3['tweet_count_4'] = get_agg('Klobuchar','Overall')\n positive_tweets = random_tweets('Klobuchar','positive','Post-Caucus')\n negative_tweets = random_tweets('Klobuchar','negative','Post-Caucus')\n electoral_data_3['positive_tweets_4'] = [positive_tweets]\n electoral_data_3['negative_tweets_4'] = [negative_tweets]\n\n electoral_data_3['period1'] = 'pre_debate'\n electoral_data_3['positive_sentitment_score_1'] = get_elements('Klobuchar','Positive Probability','pre_debate')\n electoral_data_3['negative_sentiment_score_1'] = get_elements('Klobuchar','Negative Probability','pre_debate')\n electoral_data_3['general_sentitment_score_1'] = get_elements('Klobuchar','General_Probability','pre_debate')\n electoral_data_3['tweet_count_1'] = get_agg('Klobuchar','Pre-Debate')\n positive_tweets = random_tweets('Klobuchar','positive','Pre-Debate')\n negative_tweets = random_tweets('Klobuchar','negative','Pre-Debate')\n electoral_data_3['positive_tweets_1'] = [positive_tweets]\n electoral_data_3['negative_tweets_1'] = [negative_tweets]\n\n electoral_data_3['period2'] = 'post_debate'\n electoral_data_3['positive_sentitment_score_2'] = get_elements('Klobuchar','Positive Probability','post_debate')\n electoral_data_3['negative_sentiment_score_2'] = get_elements('Klobuchar','Negative Probability','post_debate')\n electoral_data_3['general_sentitment_score_2'] = get_elements('Klobuchar','General_Probability','post_debate')\n electoral_data_3['tweet_count_2'] = get_agg('Klobuchar','Post-Debate')\n positive_tweets = random_tweets('Klobuchar','positive','Post-Debate')\n negative_tweets = random_tweets('Klobuchar','negative','Post-Debate')\n electoral_data_3['positive_tweets_2'] = [positive_tweets]\n electoral_data_3['negative_tweets_2'] = [negative_tweets]\n\n\n electoral_data_3['period3'] = 'post_election'\n electoral_data_3['positive_sentitment_score_3'] = get_elements('Klobuchar','Positive Probability','post_election')\n electoral_data_3['negative_sentiment_score_3'] = get_elements('Klobuchar','Negative Probability','post_election')\n electoral_data_3['general_sentitment_score_3'] = get_elements('Klobuchar','General_Probability','post_election')\n electoral_data_3['tweet_count_3'] = get_agg('Klobuchar','Post-Caucus')\n positive_tweets = random_tweets('Klobuchar','positive','Post-Caucus')\n negative_tweets = random_tweets('Klobuchar','negative','Post-Caucus')\n electoral_data_3['positive_tweets_3'] = [positive_tweets]\n electoral_data_3['negative_tweets_3'] = [negative_tweets]\n\n\n ## Buttigieg Build\n\n candidate_4 = {}\n electoral_data_4 = {}\n\n candidate_4 = 'Pete Buttigieg'\n\n ## Create for Pete\n\n electoral_data_4['period4'] = 'Overall'\n electoral_data_4['positive_sentitment_score_4'] = get_avg('Buttigieg','Positive Probability')\n electoral_data_4['negative_sentiment_score_4'] = get_avg('Buttigieg','Negative Probability')\n electoral_data_4['general_sentitment_score_4'] = get_avg('Buttigieg','General_Probability')\n electoral_data_4['tweet_count_4'] = get_agg('Buttigieg','Overall')\n positive_tweets = random_tweets('Buttigieg','positive','Post-Caucus')\n negative_tweets = random_tweets('Buttigieg','negative','Post-Caucus')\n electoral_data_4['positive_tweets_4'] = [positive_tweets]\n electoral_data_4['negative_tweets_4'] = [negative_tweets]\n\n electoral_data_4['period1'] = 'pre_debate'\n electoral_data_4['positive_sentitment_score_1'] = get_elements('Buttigieg','Positive Probability','pre_debate')\n electoral_data_4['negative_sentiment_score_1'] = get_elements('Buttigieg','Negative Probability','pre_debate')\n electoral_data_4['general_sentitment_score_1'] = get_elements('Buttigieg','General_Probability','pre_debate')\n electoral_data_4['tweet_count_1'] = get_agg('Buttigieg','Pre-Debate')\n positive_tweets = random_tweets('Buttigieg','positive','Pre-Debate')\n negative_tweets = random_tweets('Buttigieg','negative','Pre-Debate')\n electoral_data_4['positive_tweets_1'] = [positive_tweets]\n electoral_data_4['negative_tweets_1'] = [negative_tweets]\n\n electoral_data_4['period2'] = 'post_debate'\n electoral_data_4['positive_sentitment_score_2'] = get_elements('Buttigieg','Positive Probability','post_debate')\n electoral_data_4['negative_sentiment_score_2'] = get_elements('Buttigieg','Negative Probability','post_debate')\n electoral_data_4['general_sentitment_score_2'] = get_elements('Buttigieg','General_Probability','post_debate')\n electoral_data_4['tweet_count_2'] = get_agg('Buttigieg','Post-Debate')\n positive_tweets = random_tweets('Buttigieg','positive','Post-Debate')\n negative_tweets = random_tweets('Buttigieg','negative','Post-Debate')\n electoral_data_4['positive_tweets_2'] = [positive_tweets]\n electoral_data_4['negative_tweets_2'] = [negative_tweets]\n\n electoral_data_4['period3'] = 'post_election'\n electoral_data_4['positive_sentitment_score_3'] = get_elements('Buttigieg','Positive Probability','post_election')\n electoral_data_4['negative_sentiment_score_3'] = get_elements('Buttigieg','Negative Probability','post_election')\n electoral_data_4['general_sentitment_score_3'] = get_elements('Buttigieg','General_Probability','post_election')\n electoral_data_4['tweet_count_3'] = get_agg('Buttigieg','Post-Caucus')\n positive_tweets = random_tweets('Buttigieg','positive','Post-Caucus')\n negative_tweets = random_tweets('Buttigieg','negative','Post-Caucus')\n electoral_data_4['positive_tweets_3'] = [positive_tweets]\n electoral_data_4['negative_tweets_3'] = [negative_tweets]\n\n\n ## Biden Build\n\n candidate_5 = {}\n electoral_data_5 = {}\n\n candidate_5 = 'Joe Biden'\n\n ## Create for Biden\n\n electoral_data_5['period4'] = 'Overall'\n electoral_data_5['positive_sentitment_score_4'] = get_avg('Biden','Positive Probability')\n electoral_data_5['negative_sentiment_score_4'] = get_avg('Biden','Negative Probability')\n electoral_data_5['general_sentitment_score_4'] = get_avg('Biden','General_Probability')\n electoral_data_5['tweet_count_4'] = get_agg('Biden','Overall')\n positive_tweets = random_tweets('Biden','positive','Post-Caucus')\n negative_tweets = random_tweets('Biden','negative','Post-Caucus')\n electoral_data_5['positive_tweets_4'] = [positive_tweets]\n electoral_data_5['negative_tweets_4'] = [negative_tweets]\n\n electoral_data_5['period1'] = 'pre_debate'\n electoral_data_5['positive_sentitment_score_1'] = get_elements('Biden','Positive Probability','pre_debate')\n electoral_data_5['negative_sentiment_score_1'] = get_elements('Biden','Negative Probability','pre_debate')\n electoral_data_5['general_sentitment_score_1'] = get_elements('Biden','General_Probability','pre_debate')\n electoral_data_5['tweet_count_1'] = get_agg('Biden','Pre-Debate')\n positive_tweets = random_tweets('Biden','positive','Pre-Debate')\n negative_tweets = random_tweets('Biden','negative','Pre-Debate')\n electoral_data_5['positive_tweets_1'] = [positive_tweets]\n electoral_data_5['negative_tweets_1'] = [negative_tweets]\n\n electoral_data_5['period2'] = 'post_debate'\n electoral_data_5['positive_sentitment_score_2'] = get_elements('Biden','Positive Probability','post_debate')\n electoral_data_5['negative_sentiment_score_2'] = get_elements('Biden','Negative Probability','post_debate')\n electoral_data_5['general_sentitment_score_2'] = get_elements('Biden','General_Probability','post_debate')\n electoral_data_5['tweet_count_2'] = get_agg('Biden','Post-Debate')\n positive_tweets = random_tweets('Biden','positive','Post-Debate')\n negative_tweets = random_tweets('Biden','negative','Post-Debate')\n electoral_data_5['positive_tweets_2'] = [positive_tweets]\n electoral_data_5['negative_tweets_2'] = [negative_tweets]\n\n electoral_data_5['period3'] = 'post_election'\n electoral_data_5['positive_sentitment_score_3'] = get_elements('Biden','Positive Probability','post_election')\n electoral_data_5['negative_sentiment_score_3'] = get_elements('Biden','Negative Probability','post_election')\n electoral_data_5['general_sentitment_score_3'] = get_elements('Biden','General_Probability','post_election')\n electoral_data_5['tweet_count_3'] = get_agg('Biden','Post-Caucus')\n positive_tweets = random_tweets('Biden','positive','Post-Caucus')\n negative_tweets = random_tweets('Biden','negative','Post-Caucus')\n electoral_data_5['positive_tweets_3'] = [positive_tweets]\n electoral_data_5['negative_tweets_3'] = [negative_tweets]\n\n\n ## Bloomberg Build\n\n candidate_6 = {}\n electoral_data_6 = {}\n\n candidate_6 = 'Michael Bloomberg'\n\n ## Build for Bloomberg\n\n electoral_data_6['period4'] = 'Overall'\n electoral_data_6['positive_sentitment_score_4'] = get_avg('Bloomberg','Positive Probability')\n electoral_data_6['negative_sentiment_score_4'] = get_avg('Bloomberg','Negative Probability')\n electoral_data_6['general_sentitment_score_4'] = get_avg('Bloomberg','General_Probability')\n electoral_data_6['tweet_count_4'] = get_agg('Bloomberg','Overall')\n positive_tweets = random_tweets('Bloomberg','positive','Post-Caucus')\n negative_tweets = random_tweets('Bloomberg','negative','Post-Caucus')\n electoral_data_6['positive_tweets_4'] = [positive_tweets]\n electoral_data_6['negative_tweets_4'] = [negative_tweets]\n\n electoral_data_6['period1'] = 'pre_debate'\n electoral_data_6['positive_sentitment_score_1'] = get_elements('Bloomberg','Positive Probability','pre_debate')\n electoral_data_6['negative_sentiment_score_1'] = get_elements('Bloomberg','Negative Probability','pre_debate')\n electoral_data_6['general_sentitment_score_1'] = get_elements('Bloomberg','General_Probability','pre_debate')\n electoral_data_6['tweet_count_1'] = get_agg('Bloomberg','Pre-Debate')\n positive_tweets = random_tweets('Bloomberg','positive','Pre-Debate')\n negative_tweets = random_tweets('Bloomberg','negative','Pre-Debate')\n electoral_data_6['positive_tweets_1'] = [positive_tweets]\n electoral_data_6['negative_tweets_1'] = [negative_tweets]\n\n electoral_data_6['period2'] = 'post_debate'\n electoral_data_6['positive_sentitment_score_2'] = get_elements('Bloomberg','Positive Probability','post_debate')\n electoral_data_6['negative_sentiment_score_2'] = get_elements('Bloomberg','Negative Probability','post_debate')\n electoral_data_6['general_sentitment_score_2'] = get_elements('Bloomberg','General_Probability','post_debate')\n electoral_data_6['tweet_count_2'] = get_agg('Bloomberg','Post-Debate')\n positive_tweets = random_tweets('Bloomberg','positive','Post-Debate')\n negative_tweets = random_tweets('Bloomberg','negative','Post-Debate')\n electoral_data_6['positive_tweets_2'] = [positive_tweets]\n electoral_data_6['negative_tweets_2'] = [negative_tweets]\n\n electoral_data_6['period3'] = 'post_election'\n electoral_data_6['positive_sentitment_score_3'] = get_elements('Bloomberg','Positive Probability','post_election')\n electoral_data_6['negative_sentiment_score_3'] = get_elements('Bloomberg','Negative Probability','post_election')\n electoral_data_6['general_sentitment_score_3'] = get_elements('Bloomberg','General_Probability','post_election')\n electoral_data_6['tweet_count_3'] = get_agg('Bloomberg','Post-Caucus')\n positive_tweets = random_tweets('Bloomberg','positive','Post-Caucus')\n negative_tweets = random_tweets('Bloomberg','negative','Post-Caucus')\n electoral_data_6['positive_tweets_3'] = [positive_tweets]\n electoral_data_6['negative_tweets_3'] = [negative_tweets]\n\n\n ## Bernie - done\n jsondata['candidate1'] = candidate_1\n jsondata['electoral_data'] = electoral_data\n\n ##Warren - done\n jsondata['candidate2'] = candidate_2\n jsondata['electoral_data_2'] = electoral_data_2\n\n ##Klobuchar - done\n jsondata['candidate3'] = candidate_3\n jsondata['electoral_data_3'] = electoral_data_3\n\n ##Buttigieg - done\n jsondata['candidate4'] = candidate_4\n jsondata['electoral_data_4'] = electoral_data_4\n\n ##Biden\n jsondata['candidate5'] = candidate_5\n jsondata['electoral_data_5'] = electoral_data_5\n\n ##Bloomberg\n jsondata['candidate6'] = candidate_6\n jsondata['electoral_data_6'] = electoral_data_6\n\n final_json = json.dumps(jsondata)\n return final_json","sub_path":"nevada-caucus-sentiment-master/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":23520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"562602953","text":"# https://www.codewars.com/kata/59decdf40863c76ae3000080\ndef max_consec_zeros(n):\n n = bin(int(n))[2:]\n s = ''\n for el in n:\n if el==\"1\": s+=' '\n else: s+=\"0\"\n s = s.split()\n if s == []: return \"Zero\"\n s = max([len(el) for el in s])\n digits =['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen']\n return digits[s]","sub_path":"Most Consecutive Zeros of a Binary Number.py","file_name":"Most Consecutive Zeros of a Binary Number.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"301159710","text":"''' when a remote user changes their profile '''\nimport json\nimport pathlib\nfrom django.test import TestCase\n\nfrom bookwyrm import models, incoming\n\n\nclass UpdateUser(TestCase):\n def setUp(self):\n self.user = models.User.objects.create_user(\n 'mouse', 'mouse@mouse.com', 'mouseword',\n remote_id='https://example.com/user/mouse',\n local=False,\n localname='mouse'\n )\n\n datafile = pathlib.Path(__file__).parent.joinpath(\n '../data/ap_user.json'\n )\n self.user_data = json.loads(datafile.read_bytes())\n\n def test_handle_update_user(self):\n self.assertIsNone(self.user.name)\n self.assertEqual(self.user.localname, 'mouse')\n\n incoming.handle_update_user({'object': self.user_data})\n self.user = models.User.objects.get(id=self.user.id)\n\n self.assertEqual(self.user.name, 'MOUSE?? MOUSE!!')\n self.assertEqual(self.user.localname, 'mouse')\n","sub_path":"bookwyrm/tests/incoming/test_update_user.py","file_name":"test_update_user.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"218589409","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom numpy import genfromtxt\nfrom scipy.stats import gamma\nfrom scipy.stats import geom\nfrom scipy.optimize import fsolve\n\n################################\n################################ path\n################################\n\nos.chdir(os.path.realpath(''))\n\n################################\n################################ Import Data \n################################\ntime = []\nsize = []\n\nmy_data = genfromtxt('size_time.txt', delimiter=',')\n#my_data = genfromtxt('size_time_poisson.txt', delimiter=',')\nfor i in range(len(my_data)):\n size.append(float(my_data[i][1]))\n time.append(float(my_data[i][0]))\n\ntime = np.array(time)\nsize = np.array(size)\n\n################################\n################################ theory\n################################\n########## parameters\np_hosp = 0.029\n\n####### Infection distribution\nshape_inf = 6.6\nscale_inf = 0.833\n\n########## Hospitalization time distribution - Gamma\nshape_hosp = 31.0\nscale_hosp = 0.463\n\n########## secondary infections\nR0 = 1.3\n\n########## auxiliary\ndt = 0.01\nda = dt\ntfin = 200.\nt = np.arange(0,tfin+dt,dt)\ntfin_hosp = 200\n\n################################ prediction\n###### extinction probability - Poisson\ndef ext(x):\n return(x-np.exp(R0*(x-1)))\n\np_ext = fsolve(ext,0.5)[0]\np_surv = 1 - p_ext\n\n####### epidemic size prediction - asymptotic limit\nalpha = 0.0486829 # Mathematica solution!\nbeta = 5.28354 # Mathematica solution!\n\n\n############### McKendrick-von Foerster approach\npext = [p_ext]\nx = dt\nfor i in range(int(tfin/dt)-1):\n pext.append(p_ext*np.exp((1-p_ext)*R0*gamma.cdf(x,shape_inf,scale=scale_inf)))\n x += dt\n\npext = np.asarray(pext)\n\n##### Solve pde\n\nfx = np.zeros((int(tfin/dt),int(tfin/dt)))\n\ntot = [1]\n\n# initialize with 1 individual at time 0 with age 0\nfx[0,0] = 1\nk = 2\nmu_adj = (1+pext[0])\ninf_times = [0]\n\n# infectiousness vector\nmu = []\nx = 0\nfor i in range(int(tfin/dt)):\n mu.append(R0*(gamma.pdf(x+dt/2, shape_inf, scale=scale_inf)))\n x = x + dt\n\nmu = np.asarray(mu)\n\nfor i in range(int(tfin/dt)-1):\n # move up age\n fx[i+1,1:] = fx[i,0:-1]\n \n # add infections\n # adjusted mu\n if (tot[-1] >= k):\n prod = 1\n for j in range(len(inf_times)):\n prod = pext[i-inf_times[j]]*prod\n \n inf_times.append(i)\n mu_adj = (1- pext[0] * prod)/(1-prod)\n k += 1 \n \n fx[i+1,0] = np.sum(da*mu*mu_adj*fx[i,:])\n tot.append(np.sum(fx[i+1,:]))\n\ntot = np.asarray(tot)\n\n######## hospitalization times\nhosp_time_dist = np.zeros(len(t))\nhosp_time_dist2 = np.zeros(len(t))\n\n#################### computation\nfor k in range(200): ### sum over geometric distribution\n # determine deterministic hitting time of k infected individuals\n tdet = np.log((k+1)*alpha*beta*p_surv)/alpha\n #\n if (tdet <= 0): \n tdet = 0\n \n index = int(tdet/dt)\n index2 = np.min(np.where(tot >=k+1))\n \n # add hospitalisation time distribution to tdet\n hosp_time_dist[index:] += geom.pmf(k+1,p_hosp) * gamma.pdf(t[0:(len(t)-index)],shape_hosp,scale = scale_hosp)\n hosp_time_dist2[index2:] += geom.pmf(k+1,p_hosp) * gamma.pdf(t[0:(len(t)-index2)],shape_hosp,scale = scale_hosp)\n \n\n################################\n################################ Plot\n################################\n\nplt.hist(time, bins=np.arange(0,np.max(time),5),density=True,alpha=0.5,color='C0')\nplt.plot(t,hosp_time_dist,color='C0',linewidth=3)\nplt.plot(t,hosp_time_dist2,color='black',linewidth=3)\nplt.axvline(np.mean(time),color='C0',linewidth=3,linestyle='dotted')\nplt.axvline(np.sum(dt*t*hosp_time_dist),color='C0',linewidth=3,linestyle='dashed')\nplt.axvline(np.sum(dt*t*hosp_time_dist2),color='black',linewidth=3,linestyle='dashed')\nplt.xlim((0,150))\nplt.tick_params(axis='both', which='major', labelsize=15, width=1, length=10)\nplt.tick_params(axis='both', which='minor', labelsize=10, width=1, length=5)\nplt.show()\n\n\n################################\n################################ Mean and SD of data\n################################\nprint(np.mean(time))\nprint(np.sqrt(np.var(time)))\n\n","sub_path":"SI/FigS2/a/figS2a.py","file_name":"figS2a.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"470630748","text":"from pandas import DataFrame\nfrom time import time\n\nfrom ..explainers.explainer_functions import explain_model\nfrom ..utils.data_loading_utils import load_data_from_csv\nfrom ..utils.model_utils import generate_trained_model\n\n\ndef compute_time_vs_lime_params(data_file_name, target_name,\n num_neighbours_list,\n num_features_list,\n num_samples):\n \"\"\"\n Computes how long it takes to run n=num_samples LIME explanations for varying num_neighbours and\n num_features\n :param data_file_name:\n :param target_name:\n :param num_neighbours_list: list of integers specifying the num_neighbours to be used in LIME\n explainer\n :param num_features_list: list of integers specifying the num_features to be used in LIME\n explainer\n :param num_samples: integer specifying the number of samples to be explained\n :return:\n pandas DataFrame containing time it took to generate the explanations\n \"\"\"\n x, x_test, y, y_test, categorical_idx = load_data_from_csv(\n file_name=data_file_name, target_name=target_name,\n max_levels=100, test_size=0.2, skiprows=False,\n multiples_of_rows_to_skip=100)\n model, is_classification = generate_trained_model('rf', x, x_test, y, y_test)\n tdeltas = DataFrame(index=num_features_list, columns=num_neighbours_list)\n\n for i, num_features in enumerate(num_features_list):\n for j, num_neighbours in enumerate(num_neighbours_list):\n ts = time()\n _, _ = explain_model(model, x, categorical_idx,\n is_classification=is_classification,\n explainer_type='lime',\n num_samples=num_samples,\n num_features=num_features,\n num_neighbours=num_neighbours)\n tdeltas.iloc[i, j] = time() - ts\n print(\"\\nExperiment took {:.2f} s.\".format(tdeltas.iloc[i, j]))\n return tdeltas\n\n\ndef compute_time_vs_shap(data_file_name, target_name, num_samples_list):\n \"\"\"\n Computes how long it takes to run n=num_samples SHAP explanations for varying num_samples\n :param data_file_name:\n :param target_name:\n :param num_samples_list: integers specifying the number of samples to be explained\n :return:\n pandas DataFrame containing time it took to generate the explanations\n \"\"\"\n x, x_test, y, y_test, categorical_idx = load_data_from_csv(file_name=data_file_name,\n target_name=target_name,\n max_levels=100, test_size=0.2,\n skiprows=False,\n multiples_of_rows_to_skip=100)\n model, is_classification = generate_trained_model('rf', x, x_test, y, y_test)\n tdeltas = DataFrame(columns=num_samples_list)\n\n for i, num_samples in enumerate(num_samples_list):\n ts = time()\n _, _ = explain_model(model, x, categorical_idx, explainer_type='shap',\n num_samples=num_samples, is_classification=is_classification)\n tdeltas.loc[0, num_samples] = time() - ts\n print(\"\\nExperiment took {:.2f} s.\".format(tdeltas.loc[0, num_samples]))\n return tdeltas\n","sub_path":"asset-xai-feature-first-commit/xai/performance_benchmarking/compute_time.py","file_name":"compute_time.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"247669244","text":"from tkinter import *\r\nfrom functions import *\r\nfrom PIL import ImageTk, Image\r\nfrom threading import Thread\r\n\r\nclass Description:\r\n def __init__(self,win,name,author,isbn,id,picFolder,settings):\r\n self.window = win\r\n self.setBgColor(win,'black')\r\n self.addTitle(name,author)\r\n self.createMainCanvas()\r\n self.addPic(picFolder,id)\r\n self.addDescription()\r\n fetchDescriptionThread = Thread(target = lambda: self.updateDescription(getBookDescription(isbn,settings)))\r\n fetchDescriptionThread.daemon = True\r\n fetchDescriptionThread.start()\r\n\r\n\r\n def updateDescription(self,desc):\r\n self.descriptionLabel['text'] = desc if desc else 'Nothing Found...'\r\n #to handle the dissapearing pictures bug\r\n self.picLabel.pack_forget()\r\n self.picLabel.pack()\r\n\r\n\r\n\r\n\r\n\r\n def addTitle(self,bookName,bookAuthor):\r\n Label(self.window,\r\n text = f'''{bookName} by {bookAuthor}''',\r\n font=('Arial', 20),\r\n background='black',\r\n foreground='white'\r\n ).pack(pady=20)\r\n\r\n def addPic(self,folderPath,id):\r\n path = getExtensionIfExist(folderPath + str(id))\r\n self.img = Image.open(path)\r\n self.img = self.img.resize((300,360))\r\n self.img = ImageTk.PhotoImage(self.img)\r\n self.picFrame = Label(self.body,background='black',foreground='white')\r\n self.picLabel = Label(self.picFrame, image = self.img,anchor='c',background='black',foreground='white',borderwidth=2, relief=\"raised\")\r\n self.picLabel.image = self.img # keep a reference!\r\n self.picLabel.pack()\r\n self.picFrame.pack()#dont pack here- pack in travelers function\r\n\r\n\r\n def addDescription(self):\r\n self.descriptionLabel = Label(self.body,\r\n background='black',\r\n foreground='white',\r\n text = \"Fetching...\",\r\n font=('Arial', 14),\r\n wraplengt = 500,\r\n anchor='w'\r\n )\r\n self.descriptionLabel.pack()\r\n\r\n\r\n def createMainCanvas(self):\r\n self.canvas = Canvas(self.window,bg='black',highlightthickness=0, highlightbackground='black')\r\n self.body = Label(self.canvas)\r\n self.scroll = Scrollbar(self.window, orient=\"vertical\", command=self.canvas.yview)\r\n self.canvas.configure(yscrollcommand=self.scroll.set)\r\n self.scroll.pack(side=\"right\", fill=\"y\")\r\n self.canvas.pack(side=\"left\", fill=\"both\", expand=True)\r\n self.canvas.create_window((4,4), window=self.body, anchor=\"nw\",tags='ff')\r\n self.canvas.bind(\"\", self.setCanvasSize)\r\n self.body.bind(\"\", self.onFrameConfigure)\r\n self.setBgColor(self.body,'black')\r\n self.setFgColor(self.body,'white')\r\n\r\n\r\n def setCanvasSize(self,event):\r\n self.canvas.itemconfig('ff', width=self.canvas.winfo_width())\r\n\r\n\r\n def onFrameConfigure(self, event):\r\n self.canvas.configure(scrollregion=self.canvas.bbox(\"all\"))\r\n\r\n\r\n def setBgColor(self,widget,clr):\r\n if not isArray(widget):\r\n widget = [widget]\r\n\r\n for wid in widget:\r\n try:\r\n wid.configure(background=clr)\r\n except:\r\n try:\r\n wid.configure(bg=clr)\r\n except:\r\n continue\r\n\r\n\r\n def setFgColor(self,widget,clr):\r\n if not isArray(widget):\r\n widget = [widget]\r\n for wid in widget:\r\n try:\r\n wid.configure(foreground=clr)\r\n except:\r\n try:\r\n wid.configure(fg=clr)\r\n except:\r\n continue\r\n","sub_path":"src/classes/displayDescription.pyw","file_name":"displayDescription.pyw","file_ext":"pyw","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"184844870","text":"import pygame\r\nimport shelve\r\nimport math, random\r\nfrom pygamegame import PygameGame\r\nfrom MainCharacter import MainCharacter\r\nfrom Map import Map\r\nfrom Tree import Tree\r\nfrom Rock import Rock\r\nfrom Button import Button\r\n\r\n# all fonts from fontsquirrel.com\r\n# Seaside.ttf property of Nick's Fonts\r\n\r\nclass Game(PygameGame):\r\n maps = []\r\n bestScore = 0\r\n bestDistance = 0\r\n\r\n def init(self):\r\n MainCharacter.init()\r\n Tree.init()\r\n Rock.init()\r\n Button.init()\r\n \r\n pygame.font.init()\r\n\r\n self.trees = pygame.sprite.Group()\r\n self.mainCharacter = MainCharacter(-1, -1, self)\r\n\r\n self.loadButtons()\r\n self.loadGame()\r\n self.restartGame()\r\n\r\n def loadButtons(self):\r\n left = self.width/9\r\n right = 8*self.width/9\r\n top = self.height/9\r\n bottom = 8*self.height/9\r\n\r\n # initialize all buttons\r\n self.mapCreationButtons = pygame.sprite.Group()\r\n self.saveMapButton = Button(left, bottom, 'Save Map')\r\n self.discardMapButton = Button(right, bottom, 'Discard Map')\r\n self.newMapButton = Button(right, top, 'New Map')\r\n self.returnButton = Button(left, top, 'Back')\r\n self.mapCreationButtons.add(self.saveMapButton)\r\n self.mapCreationButtons.add(self.discardMapButton)\r\n self.mapCreationButtons.add(self.newMapButton)\r\n self.mapCreationButtons.add(self.returnButton)\r\n\r\n self.startScreenButtons = pygame.sprite.Group()\r\n self.saveGameButton = Button(right, bottom, 'Save Game')\r\n self.mapModeButton = Button(self.width/2, self.height/3, 'Map Creation Mode')\r\n self.endlessMapButton = Button(self.width/2, 2*self.height/3, 'Endless Terrain Mode')\r\n # self.mapModeButton = Button(left, bottom, 'Maps')\r\n self.startScreenButtons.add(self.saveGameButton)\r\n self.startScreenButtons.add(self.mapModeButton)\r\n self.startScreenButtons.add(self.endlessMapButton)\r\n\r\n self.mapListButtons = pygame.sprite.Group()\r\n self.createButton = Button(right, top, 'Create')\r\n self.homeButton = Button(left, top, 'Back')\r\n self.mapListButtons.add(self.createButton)\r\n self.mapListButtons.add(self.homeButton)\r\n\r\n self.mapListButtonX = self.width/3\r\n self.mapListButtonY = self.height/4\r\n\r\n def restartGame(self):\r\n # always start in start screen mode\r\n print('len', len(Game.maps))\r\n self.startScreenMode = True\r\n self.mapListMode = False\r\n self.mapCreationMode = False\r\n self.helpScreenMode = False\r\n self.gameMode = False\r\n self.endlessMapMode = False\r\n\r\n # self.scrolling = False\r\n self.rotateAngle = 0\r\n\r\n self.recordName = False\r\n self.name = ''\r\n\r\n self.isGameOver = False\r\n\r\n self.isPaused = True\r\n self.waitingForFirstKeyPress = True\r\n # later, currMap will be initialized to original map instead of None\r\n self.currMap = None\r\n # initialize main character to be in center\r\n self.mainCharacter.reset()\r\n\r\n self.scrollingLeft = False\r\n self.scrollingRight = False\r\n self.scrollingUp = False\r\n self.scrollingDown = False\r\n\r\n self.distance = 0\r\n self.score = 0\r\n self.gameScroll = 0\r\n self.mapCreationScroll = 0\r\n self.mapListScroll = 0\r\n self.playerScroll = 0\r\n\r\n self.slopeAngle = 0\r\n\r\n self.theta = 0\r\n self.g = 1\r\n\r\n self.parabolaSign = 1\r\n self.cosDir = 1\r\n self.endlessMap = Map()\r\n self.loadEndlessMap()\r\n\r\n def loadEndlessMap(self, xParameter=1000):\r\n startY = random.randint(200, 350)\r\n for x in range(100, 106, 5):\r\n self.endlessMap.line += [(x, startY)]\r\n self.mainCharacter.cx, self.mainCharacter.cy = self.endlessMap.line[0]\r\n self.mainCharacter.cy -= self.mainCharacter.height\r\n self.extendEndlessMapCos(xParameter)\r\n self.const = 0.5 * self.mainCharacter.velX**2 + self.g*self.endlessMap.line[0][1]\r\n self.trees = pygame.sprite.Group()\r\n i = 0\r\n while i < len(self.endlessMap.line):\r\n x, y = self.endlessMap.line[i]\r\n self.trees.add(Tree(x, y))\r\n i += random.randint(75, 150)\r\n\r\n def extendEndlessMap(self, xParameter):\r\n mapX = self.endlessMap.line[-1][0]\r\n previousLen = len(self.endlessMap.line)\r\n # load endless map\r\n while mapX < xParameter:\r\n # generate a parabola\r\n previousY = self.endlessMap.line[-1][1]\r\n width = random.randint(300, 500)\r\n if self.parabolaSign == -1:\r\n height = random.randint(25, 75)\r\n else:\r\n height = random.randint(200, 350)\r\n # extent = random.randint(100, int(2*width/3))\r\n a = height/(width/2)**2\r\n if self.parabolaSign == -1:\r\n for x in range(0, int(width/2) + 5, 5):\r\n yValue = -1*(a*(x-width/2)**2) + height\r\n self.endlessMap.line += [(mapX + x, previousY + yValue)]\r\n lastX, lastY = self.endlessMap.line[-1]\r\n for x in range(0, 100, 5):\r\n yValue = -1*(a*(x-100/2)**2) + 100\r\n self.endlessMap.line += [(lastX + x, lastY + yValue - 100)]\r\n mapX += width/2 + 100\r\n else:\r\n for x in range(0, width + 5, 5):\r\n yValue = -1*(a*(x-width/2)**2) - height\r\n self.endlessMap.line += [(mapX + x, previousY - yValue - height*2)]\r\n mapX += width\r\n self.parabolaSign *= -1\r\n for i in range(previousLen, len(self.endlessMap.line)):\r\n if random.randint(0, 100) % 100 == 0:\r\n x, y = self.endlessMap.line[i]\r\n self.trees.add(Tree(x, y))\r\n while self.endlessMap.line[0][0] < self.endlessMap.line[-1][0] - 5000:\r\n self.endlessMap.line.pop(0)\r\n \r\n def extendEndlessMapCos(self, xParameter):\r\n mapX = self.endlessMap.line[-1][0]\r\n previousLen = len(self.endlessMap.line)\r\n # load endless map\r\n while mapX < xParameter:\r\n previousY = self.endlessMap.line[-1][1]\r\n width = random.randint(300, 600)\r\n if self.cosDir == -1:\r\n height = random.randint(75, 150)\r\n for x in range(0, width + 5, 5):\r\n yValue = math.cos(x*math.pi/width)\r\n self.endlessMap.line += [(mapX + x, previousY - yValue*height + height)]\r\n else:\r\n height = random.randint(25, 50)\r\n for x in range(0, width + 5, 5):\r\n yValue = math.cos(x*math.pi/width + math.pi)\r\n self.endlessMap.line += [(mapX + x, previousY - yValue*height - height)]\r\n self.cosDir *= -1\r\n mapX += width\r\n i = previousLen + 75\r\n while i < len(self.endlessMap.line):\r\n x, y = self.endlessMap.line[i]\r\n self.trees.add(Tree(x, y))\r\n i += random.randint(75, 150)\r\n while self.endlessMap.line[0][0] < self.endlessMap.line[-1][0] - 5000:\r\n self.endlessMap.line.pop(0)\r\n\r\n # code based from \r\n # https://inventwithpython.com/blog/2012/05/03/implement-a-save-game-feature-in-python-with-the-shelve-module/\r\n def loadGame(self):\r\n # load the game\r\n shelfFile = shelve.open('save_adventure_file')\r\n Game.maps = shelfFile['maps']\r\n Game.bestScore = shelfFile['bestScore']\r\n Game.bestDistance = shelfFile['bestDistance']\r\n shelfFile.close()\r\n for myMap in Game.maps:\r\n self.mapListButtons.add(Button(self.mapListButtonX, self.mapListButtonY, myMap.name))\r\n self.mapListButtonX += self.width/3\r\n if self.mapListButtonX >= self.width:\r\n self.mapListButtonX = self.width/3\r\n self.mapListButtonY += self.height/4\r\n\r\n def keyPressed(self, keyCode, modifier, event):\r\n if self.mapCreationMode:\r\n if keyCode == pygame.K_LEFT:\r\n self.scrollingLeft = True\r\n elif keyCode == pygame.K_RIGHT:\r\n self.scrollingRight = True\r\n if self.recordName:\r\n if keyCode == pygame.K_RETURN:\r\n Game.maps[-1].name = self.name\r\n self.mapListButtons.add(Button(self.mapListButtonX, self.mapListButtonY, self.name))\r\n self.mapListButtonX += self.width/3\r\n if self.mapListButtonX >= self.width:\r\n self.mapListButtonX = self.width/3\r\n self.mapListButtonY += self.height/4\r\n self.name = ''\r\n self.mapCreationMode = False\r\n elif keyCode == pygame.K_BACKSPACE:\r\n self.name = self.name[:-1]\r\n else:\r\n self.name += event.unicode\r\n\r\n # if in map list mode, use left and right arrow keys to scroll\r\n # between different maps\r\n elif self.mapListMode:\r\n # scroll left\r\n if keyCode == pygame.K_UP:\r\n self.scrollingUp = True\r\n # scroll right\r\n elif keyCode == pygame.K_DOWN:\r\n self.scrollingDown = True\r\n\r\n # if in game mode, press space to jump\r\n # if in game mode, press p to pause and unpause\r\n # press r to restart game in game mode\r\n elif self.gameMode or self.endlessMapMode:\r\n if self.waitingForFirstKeyPress:\r\n if keyCode == pygame.K_SPACE:\r\n self.isPaused = False\r\n self.waitingForFirstKeyPress = False\r\n elif keyCode == pygame.K_p:\r\n self.isPaused = not self.isPaused\r\n elif keyCode == pygame.K_r:\r\n self.restartGame()\r\n elif keyCode == pygame.K_UP and self.mainCharacter.canRotate:\r\n self.mainCharacter.isRotating = True\r\n elif keyCode == pygame.K_q:\r\n self.isGameOver = True\r\n self.gameMode = False\r\n self.endlessMapMode = False\r\n self.loadEndlessMap()\r\n else:\r\n if keyCode == pygame.K_SPACE and not self.isPaused and self.mainCharacter.canJump:\r\n self.mainCharacter.jump()\r\n self.mainCharacter.canRotate = True\r\n else:\r\n if keyCode == pygame.K_r:\r\n self.restartGame()\r\n\r\n # in any mode, press h to enter and exit the help screen mode\r\n # this will pause the current game if in gameplay\r\n if keyCode == pygame.K_h:\r\n self.helpScreenMode = not self.helpScreenMode\r\n self.isPaused = self.helpScreenMode\r\n \r\n def keyReleased(self, keyCode, modifier):\r\n if self.mapCreationMode:\r\n if keyCode == pygame.K_LEFT:\r\n self.scrollingLeft = False\r\n elif keyCode == pygame.K_RIGHT:\r\n self.scrollingRight = False\r\n\r\n if self.mapListMode:\r\n if keyCode == pygame.K_UP or keyCode == pygame.K_DOWN:\r\n self.scrollingUp = False\r\n self.scrollingDown = False\r\n for button in self.mapListButtons:\r\n if button.text != 'Create' and button.text != 'Home':\r\n button.cy -= self.mapListScroll\r\n button.update()\r\n\r\n def mousePressed(self, x, y):\r\n if self.mapCreationMode:\r\n # if save map button is clicked, then return to start screen\r\n # else if discard map button is saved, pop off of list\r\n if self.saveMapButton.clicked(x, y):\r\n # create a pop-up asking for the name of the map\r\n # set the name of the map\r\n # go back to the maps mode\r\n self.recordName = True\r\n elif self.discardMapButton.clicked(x, y):\r\n if len(Game.maps) > 0:\r\n deleteMap = Game.maps.pop()\r\n newButtons = pygame.sprite.Group()\r\n for button in self.mapListButtons:\r\n if button.text != deleteMap.name:\r\n newButtons.add(button)\r\n self.mapListButtons = newButtons\r\n self.mapCreationMode = False\r\n self.startScreenMode = True\r\n elif self.newMapButton.clicked(x,y):\r\n # start creating a map\r\n # make a new Map object, and add to Game.maps\r\n Game.maps.append(Map())\r\n self.mapCreationScroll = 0\r\n for button in self.mapCreationButtons:\r\n if button.text == '':\r\n button.cx = self.width/10\r\n button.update()\r\n elif self.returnButton.clicked(x, y):\r\n self.mapCreationMode = False\r\n self.mapListMode = True\r\n elif self.mapListMode:\r\n if self.createButton.clicked(x, y):\r\n self.mapCreationMode = True\r\n elif self.homeButton.clicked(x, y):\r\n self.mapListMode = False\r\n self.startScreenMode = True\r\n else:\r\n for button in self.mapListButtons:\r\n if button.clicked(x, y):\r\n self.currMap = button.text\r\n self.distance = 0\r\n for myMap in self.maps:\r\n if myMap.name == self.currMap:\r\n self.mainCharacter.cx, self.mainCharacter.cy = myMap.line[0]\r\n self.mainCharacter.cy -= self.mainCharacter.height\r\n self.trees = pygame.sprite.Group()\r\n for i in range(len(myMap.line)):\r\n if random.randint(0, 50) % 50 == 0:\r\n x, y = myMap.line[i]\r\n self.trees.add(Tree(x, y))\r\n self.const = 0.5 * self.mainCharacter.velX**2 + self.g*myMap.line[0][1]\r\n if self.currMap != None:\r\n self.startScreenMode = False\r\n self.mapListMode = False\r\n self.gameMode = True\r\n\r\n self.mainCharacter.cy -= self.mainCharacter.height*3\r\n\r\n # if in game mode, hold the mouse to flip\r\n elif self.gameMode and not self.isPaused:\r\n pass\r\n\r\n # if save game button is clicked, call save game\r\n # if clicked on the map creation button, change modes\r\n elif self.startScreenMode:\r\n if self.saveGameButton.clicked(x, y):\r\n self.saveGame()\r\n elif self.mapModeButton.clicked(x, y):\r\n self.mapListMode = True\r\n self.startScreenMode = False\r\n elif self.endlessMapButton.clicked(x, y):\r\n self.endlessMapMode = True\r\n self.startScreenMode = False\r\n\r\n def mouseDrag(self, x, y):\r\n if self.mapCreationMode:\r\n # start creating a map\r\n if len(Game.maps) > 0:\r\n Game.maps[-1].line.append((x+self.mapCreationScroll, y))\r\n # can also switch to drag to draw a longer terrain\r\n\r\n # if in game mode, hold the mouse to flip\r\n elif self.gameMode and not self.isPaused:\r\n if self.mainCharacter.isRotating:\r\n self.mainCharacter.rotate(self.rotateAngle)\r\n self.rotateAngle += 45\r\n self.rotateAngle %= 360\r\n\r\n def mouseReleased(self, x, y):\r\n # self.scrolling = False\r\n self.mainCharacter.isRotating = False\r\n\r\n def timerFired(self, dt):\r\n if self.isGameOver:\r\n return\r\n # if in any of the other modes (i.e. help mode, paused, map, start),\r\n # then do nothing\r\n\r\n if self.mapCreationMode:\r\n if self.scrollingLeft:\r\n self.mapCreationScroll -= 5\r\n elif self.scrollingRight:\r\n self.mapCreationScroll += 5\r\n\r\n if self.mapListMode:\r\n if self.scrollingUp:\r\n self.mapListScroll = -5\r\n elif self.scrollingDown:\r\n self.mapListScroll = 5\r\n\r\n elif self.gameMode and not self.isPaused:\r\n # else, adjust position of player on line and move forward\r\n # later, currMap will be initialized to original map instead of None\r\n if self.currMap != None:\r\n for myMap in self.maps:\r\n if myMap.name == self.currMap:\r\n self.mainCharacter.velX = min(self.mainCharacter.velX, 30)\r\n # if reached the end of the map, game over\r\n if myMap.line[-1][0] <= self.mainCharacter.cx + 10:\r\n self.isGameOver = True\r\n self.gameMode = False\r\n if self.distance > Game.bestDistance:\r\n Game.bestDistance = self.distance\r\n return\r\n\r\n self.movePlayer(myMap)\r\n \r\n elif self.endlessMapMode and not self.isPaused:\r\n myMap = self.endlessMap\r\n self.mainCharacter.velX = min(self.mainCharacter.velX, 30)\r\n\r\n if myMap.line[-1][0] <= self.mainCharacter.cx + 10:\r\n self.isGameOver = True\r\n self.endlessMapMode = False\r\n self.loadEndlessMap()\r\n if self.distance > Game.bestDistance:\r\n Game.bestDistance = self.distance\r\n return\r\n\r\n self.movePlayer(myMap)\r\n\r\n if self.mainCharacter.cx > self.endlessMap.line[-1][0]-self.width:\r\n self.extendEndlessMapCos(self.endlessMap.line[-1][0]+self.width)\r\n # update self.score and self.distance as playing\r\n\r\n def movePlayer(self, myMap):\r\n # find your current map\r\n # move the player\r\n y = self.mainCharacter.cy\r\n self.mainCharacter.cx += self.mainCharacter.velX\r\n self.gameScroll += self.mainCharacter.velX\r\n self.mainCharacter.cy += self.mainCharacter.velY\r\n\r\n self.distance = round(max(self.distance, self.mainCharacter.cx))\r\n\r\n # store original x to recenter when rotated\r\n x = self.mainCharacter.cx\r\n if self.findLeftRightPoints(myMap) == None:\r\n print('failed to find left right points')\r\n self.isGameOver = True\r\n self.gameMode = False\r\n self.endlessMapMode = False\r\n self.loadEndlessMap()\r\n return\r\n leftX, leftY, rightX, rightY = self.findLeftRightPoints(myMap)\r\n\r\n if rightX-leftX == 0: rightX += 0.1\r\n if rightY-leftY == 0: rightY += 0.1\r\n\r\n cy = self.findYAtX(leftX, leftY, rightX, rightY)\r\n x1, y2, x2, y2 = self.findImmediatePoints(myMap)\r\n \r\n # calculate angle to rotate player\r\n self.calculateAngle(leftX, leftY, rightX, rightY)\r\n if not self.mainCharacter.isRotating:\r\n self.mainCharacter.rotate(self.theta)\r\n \r\n if self.mainCharacter.isRotating:\r\n self.mainCharacter.rotate(self.rotateAngle)\r\n self.rotateAngle += 10\r\n self.rotateAngle %= 360\r\n\r\n # if im on the curve, attach to the curve\r\n if ((cy - self.mainCharacter.height <= self.mainCharacter.cy) and abs(x2-x1) < 25):\r\n # calculate acceleration on a slope\r\n thetaRadians = abs(self.theta * math.pi / 180)\r\n if self.theta > 0:\r\n thetaRadians *= -1\r\n accelX = self.g * math.cos(thetaRadians) * math.cos(math.pi/2 - thetaRadians)\r\n accelY = self.g * (math.sin(math.pi/2 - thetaRadians) * math.cos(thetaRadians) - 1)\r\n self.mainCharacter.velX += accelX\r\n self.mainCharacter.velY += accelY\r\n # bound to curve\r\n self.mainCharacter.cx = x\r\n self.mainCharacter.cy = cy - self.mainCharacter.height\r\n # adjust velocity\r\n self.mainCharacter.velY = (abs(-1 * self.mainCharacter.velX**2 + 2 * self.const - 2 * self.g * cy))**0.5\r\n self.mainCharacter.canJump = True\r\n\r\n if self.rotateAngle > 45 and self.rotateAngle < 315:\r\n print('failed jump')\r\n self.isGameOver = True\r\n self.gameMode = False\r\n self.endlessMapMode = False\r\n self.loadEndlessMap()\r\n \r\n self.mainCharacter.canRotate = False\r\n self.mainCharacter.isRotating = False\r\n else:\r\n self.mainCharacter.fall()\r\n self.mainCharacter.canJump = False\r\n\r\n if self.mainCharacter.cy > cy + self.mainCharacter.height + 10:\r\n print('below end of canvas')\r\n print(self.mainCharacter.cy, cy)\r\n self.isGameOver = True\r\n self.gameMode = False\r\n self.endlessMapMode = False\r\n self.loadEndlessMap()\r\n if self.distance > Game.bestDistance:\r\n Game.bestDistance = self.distance \r\n self.mainCharacter.update()\r\n\r\n self.playerScroll -= y - self.mainCharacter.cy\r\n\r\n def calculateAngle(self, leftX, leftY, rightX, rightY):\r\n slope = (rightY-leftY)/(rightX-leftX)\r\n slopeSign = slope/(abs(slope))\r\n absReciprocal = abs((rightX-leftX)/(rightY-leftY))\r\n self.theta = 180 / math.pi * math.atan(absReciprocal) - 90\r\n self.theta = slopeSign * self.theta\r\n\r\n def findLeftRightPoints(self, myMap):\r\n for i in range(len(myMap.line)):\r\n currX, currY = myMap.line[i]\r\n if currX > self.mainCharacter.cx:\r\n for j in range(10, -1, -1):\r\n if 0 <= i+j < len(myMap.line):\r\n rightX, rightY = myMap.line[i+j]\r\n break\r\n for j in range(10, -1, -1):\r\n if 0 <= i-j < len(myMap.line):\r\n leftX, leftY = myMap.line[i-j]\r\n return leftX, leftY, rightX, rightY\r\n \r\n def findImmediatePoints(self, myMap):\r\n for i in range(len(myMap.line)):\r\n currX, currY = myMap.line[i]\r\n if currX > self.mainCharacter.cx:\r\n x2, y2 = currX, currY\r\n x1, y1 = myMap.line[i-1]\r\n return x1, y1, x2, y2\r\n \r\n def findYAtX(self, x1, y1, x2, y2):\r\n m = (y2-y1)/(x2-x1)\r\n b = y1 - m * x1\r\n return m * (self.mainCharacter.cx+self.mainCharacter.width/2) + b\r\n\r\n def findTwoPoints(self, myMap):\r\n characterPoint = self.mainCharacter.cx, self.mainCharacter.cy\r\n closestPoint = myMap.line[0]\r\n closestIndex = 0\r\n for i in range(len(myMap.line)):\r\n point = myMap.line[i]\r\n if self.calDistance(point, characterPoint) < self.calDistance(closestPoint, characterPoint):\r\n closestPoint = point\r\n closestIndex = i\r\n x1, y1 = closestPoint\r\n if i + 5 < len(myMap.line):\r\n x2, y2 = myMap.line[i+5]\r\n else:\r\n x2, y2 = myMap.line[i-5]\r\n return x1, y1, x2, y2\r\n \r\n def findClosestPointOnLine(self, x0, y0, x1, y1, x2, y2):\r\n a = y2 - y1\r\n b = x1 - x2\r\n c1 = a * x1 + b * y1\r\n c2 = -b * x0 + a * y0\r\n d = a**2 + b**2\r\n if d == 0:\r\n return x0, y0\r\n cx = (a * c1 - b * c2)/d\r\n cy = (a * c2 + b * c1)/d\r\n return cx, cy\r\n\r\n def calDistance(self, point1, point2):\r\n x1, y1 = point1\r\n x2, y2 = point2\r\n return ((x2-x1)**2 + (y2-y1)**2)**0.5\r\n\r\n def redrawAll(self, screen):\r\n # first, check mode\r\n # if in any of the other modes, draw said mode\r\n if self.helpScreenMode:\r\n self.drawHelpScreen(screen)\r\n elif self.mapCreationMode:\r\n self.drawMapCreation(screen)\r\n elif self.mapListMode:\r\n self.drawMapList(screen)\r\n elif self.endlessMapMode:\r\n self.drawEndlessMap(screen)\r\n elif self.startScreenMode:\r\n self.drawStartScreen(screen)\r\n elif self.isGameOver:\r\n self.drawGameOver(screen)\r\n\r\n # otherwise, in game mode\r\n # draw game (foreground, background, terrain, weather, day)\r\n elif self.gameMode:\r\n self.drawGameMode(screen)\r\n\r\n def drawHelpScreen(self, screen):\r\n screen.fill((255,255,255))\r\n myfont = pygame.font.Font('Seaside.ttf', 20)\r\n line1 = myfont.render('HELP SCREEN', False, (0, 0, 0))\r\n line2 = myfont.render('In map list mode: use up down to scroll', False, (0, 0, 0))\r\n line3 = myfont.render('In map creation mode: use left down to scroll', False, (0, 0, 0))\r\n line4 = myfont.render('In game: space to jump, up to turn, q to give up', False, (0, 0, 0))\r\n line5 = myfont.render('PRESS H TO RETURN', False, (0, 0, 0))\r\n screen.blit(line1,(100, 150))\r\n screen.blit(line2,(100, 200))\r\n screen.blit(line3,(100, 250))\r\n screen.blit(line4,(100, 300))\r\n screen.blit(line5,(100, 350))\r\n\r\n def drawMapList(self, screen):\r\n # scroll using arrow keys (keyPressed)\r\n self.mapListButtons.draw(screen)\r\n self.drawButtonText(self.mapListButtons, screen)\r\n\r\n def drawMapCreation(self, screen):\r\n self.mapCreationButtons.draw(screen)\r\n self.drawButtonText(self.mapCreationButtons, screen)\r\n if len(Game.maps) > 0:\r\n Game.maps[-1].draw(screen, self.mapCreationScroll, self.playerScroll, self, False)\r\n if self.recordName:\r\n myfont = pygame.font.Font('Seaside.ttf', 30)\r\n line1 = myfont.render('Please enter a name for the map:', False, (48, 73, 12))\r\n screen.blit(line1,(100, 150))\r\n if self.name != '':\r\n myfont = pygame.font.Font('Seaside.ttf', 30)\r\n line1 = myfont.render(self.name, False, (48, 73, 12))\r\n screen.blit(line1,(100, 200))\r\n\r\n def drawStartScreen(self, screen):\r\n screen.fill((255,255,255))\r\n myfont = pygame.font.Font('Seaside.ttf', 30)\r\n line1 = myfont.render('WELCOME TO SNOWY ADVENTURE', False, (48, 73, 12))\r\n screen.blit(line1,(200, 50))\r\n\r\n self.startScreenButtons.draw(screen)\r\n self.drawButtonText(self.startScreenButtons, screen)\r\n \r\n def drawGameOver(self, screen):\r\n screen.fill((255,255,255))\r\n myfont = pygame.font.Font('Seaside.ttf', 30)\r\n line1 = myfont.render('GAME OVER', False, (48, 73, 12))\r\n line2 = myfont.render('PRESS R TO RESTART', False, (48, 73, 12))\r\n distance = 'DISTANCE: ' + str(self.distance)\r\n line3 = myfont.render(distance, False, (48, 73, 12))\r\n bestDistance= 'BEST DISTANCE: ' + str(Game.bestDistance)\r\n line4 = myfont.render(bestDistance, False, (48, 73, 12))\r\n screen.blit(line1,(100, 150))\r\n screen.blit(line2,(100, 250))\r\n screen.blit(line3,(100, 350))\r\n screen.blit(line4,(100, 450))\r\n \r\n def drawEndlessMap(self, screen):\r\n screen.fill((194,245,255))\r\n self.trees.draw(screen)\r\n self.endlessMap.draw(screen, self.gameScroll, self.playerScroll, self, True)\r\n for tree in self.trees:\r\n tree.fixX(self.gameScroll)\r\n tree.fixY(self.playerScroll)\r\n tree.update()\r\n screen.blit(self.mainCharacter.image, (self.mainCharacter.cx-self.gameScroll, self.mainCharacter.cy-self.playerScroll))\r\n\r\n \r\n def drawGameMode(self, screen):\r\n screen.fill((194,245,255))\r\n self.trees.draw(screen)\r\n if self.currMap == None:\r\n screen.fill((255,255,255))\r\n myfont = pygame.font.Font('Seaside.ttf', 25)\r\n line1 = myfont.render('NO MAP SELECTED; PRESS R', False, (0, 0, 0))\r\n line2 = myfont.render('GO TO THE MAPS PAGE TO CHOOSE/CREATE A MAP', False, (0, 0, 0))\r\n screen.blit(line1,(100, 150))\r\n screen.blit(line2,(100, 350))\r\n else:\r\n for myMap in self.maps:\r\n if myMap.name == self.currMap:\r\n myMap.draw(screen, self.gameScroll, self.playerScroll, self, True)\r\n # if self.mainCharacter.cx > myMap.line[-1][0] - self.width:\r\n # myMap.extend()\r\n for tree in self.trees:\r\n tree.fixX(self.gameScroll)\r\n tree.fixY(self.playerScroll)\r\n tree.update()\r\n screen.blit(self.mainCharacter.image, (self.mainCharacter.cx-self.gameScroll, self.mainCharacter.cy-self.playerScroll))\r\n\r\n def drawButtonText(self, buttonList, screen):\r\n for button in buttonList:\r\n myfont = pygame.font.Font('Antonio-Regular.ttf', 18)\r\n text = myfont.render(button.text, False, (0, 0, 0))\r\n text_rect = text.get_rect(center=(button.cx, button.cy))\r\n screen.blit(text, text_rect)\r\n \r\n # code based from \r\n # https://inventwithpython.com/blog/2012/05/03/implement-a-save-game-feature-in-python-with-the-shelve-module/\r\n def saveGame(self):\r\n # save the game\r\n shelfFile = shelve.open('save_adventure_file')\r\n shelfFile['maps'] = Game.maps\r\n shelfFile['bestScore'] = Game.bestScore\r\n shelfFile['bestDistance'] = Game.bestDistance\r\n shelfFile.close()\r\n\r\nGame(1000, 600).run()","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":29687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"265726634","text":"#!/usr/bin/env python\n\nimport sys\nimport signal\n\nfrom decouple import config\n\nfrom server import Server, CustomHTTPServer\nfrom visualization import Visualization\n\n\nPORT = config('HTTP_PORT', default=8080, cast=int)\n\n# LED strip configuration:\nLED_COUNT = config('LED_COUNT', default=300, cast=int) # Number of LED pixels.\nLED_PIN = config('LED_PIN', default=18, cast=int) # GPIO pin connected to the pixels (must support PWM!).\nLED_FREQ_HZ = config('LED_FREQ_HZ', default=800000, cast=int) # LED signal frequency in hertz (usually 800khz)\nLED_DMA = config('LED_DMA', default=10, cast=int) # DMA channel to use for generating signal (try 10)\nLED_BRIGHTNESS = config('LED_BRIGHTNESS', default=255, cast=int) # Set to 0 for darkest and 255 for brightest\n# True to invert the signal (when using NPN transistor level shift)\nLED_INVERT = config('LED_INVERT', default=False, cast=bool)\n\nMIN_FREQ = config('MIN_FREQ', default=16, cast=int)\nMAX_FREQ = config('MAX_FREQ', default=5000, cast=int)\n\nMIN_MULTIPLIER = config('MIN_MULTIPLIER', default=.5, cast=float)\n\nMIN_AMPLITUDE = config('MIN_AMPLITUDE', default=0, cast=int)\n\n\ndef shutdown():\n print('shutdown starting')\n visualization.close()\n sys.exit()\n\n\ndef signal_handler(signal, frame):\n print('You pressed Ctrl+C')\n shutdown()\n\n\nsignal.signal(signal.SIGINT, signal_handler)\nvisualization = Visualization(\n LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_BRIGHTNESS, LED_INVERT, MIN_MULTIPLIER, MIN_FREQ, MAX_FREQ,\n MIN_AMPLITUDE)\nhttpd = CustomHTTPServer((\"\", PORT), Server)\nvisualization.loop(shutdown, httpd)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"406395721","text":"# a real pipeline\nimport sys as sys\nimport validator as val\nimport injector as inj\nfrom onto_graph import OntoGraph\n\npath_data = \"../data/\"\nsource_path = path_data + \"000/onto.owl\" # fixed source path 000/onto.owl\n\n\"\"\"\nRun experiments through all steps\n (1) inject a fraction of wrong sameAs links in\n (2) validate the erroneous files --> result: #wrong sameAs found/#sameAs added\n (3) compute the avg over all 80 input folders\n \nRequired parameters:\n - threshold: to compute the degree functionality of a property\n - ratio: fraction of manually added erroneous sameAs\n - do_injection: to include wrong sameAs injection to the experiments\n (False if we've already done it, to prevent redundant work & loss of time)\n\"\"\"\n\n# prompt for custom parameters, if not provided, take default values\nif len(sys.argv) < 5:\n print(\"Syntax: python experiments.py num_input(from 1 to 80) threshold(float) ratio(float) do_injection(boolean)\")\n sys.exit(0)\nelse:\n # otherwise, parse from the command line\n num_input = int(sys.argv[1])\n threshold = float(sys.argv[2])\n ratio = float(sys.argv[3])\n do_inj = bool(sys.argv[4])\n\n# inject erroneous sameAs in all input folder\nif do_inj:\n print(\"Injecting erroneous sameAs links...\")\n for i in range(1, num_input+1):\n folder = \"00\" + str(i) + \"/\" if i < 10 else \"0\" + str(i) + \"/\"\n target_path = path_data + folder + \"onto.owl\"\n refalign_path = path_data + folder + \"refalign.rdf\"\n output_path = path_data + folder + \"err_refalign.rdf\"\n\n # create the graphs, no need to extract functional properties\n g_source = OntoGraph(source_path)\n g_target = OntoGraph(target_path)\n\n inj.create_wrong_sameas(target_graph=g_target, source_graph=g_source,\n output_path=output_path, target_refalign_path=refalign_path,\n ratio=ratio)\n print(\"\\tDone injecting in \" + folder)\n\n# create the source ontology 000/onto.owl\ng_source = OntoGraph(path_data + source_path)\ng_source.extract_func_properties(threshold=threshold)\n\n# run validation for each input folder\nfor i in range(1, num_input+1):\n # get the folder name\n folder = \"00\" + str(i) + \"/\" if i < 10 else \"0\" + str(i) + \"/\"\n\n # the target graph (anything of 00i/onto.owl where i != 0)\n target_path = path_data + folder + \"onto.owl\"\n g_target = OntoGraph(path_data + target_path)\n g_target.extract_func_properties(threshold=threshold)\n\n # the set of sameAs links to validate\n val_path = path_data + folder + \"err_refalign.rdf\"\n to_validate = inj.extract_sameas(path_data + val_path)\n\n # we also want to keep track of the number of wrong sameAs being added in\n gold_path = path_data + folder + \"refalign.rdf\"\n gold_standard = inj.extract_sameas(path_data + gold_path)\n G = len(gold_standard)\n assert G / len(to_validate) == 1 / (1 + ratio)\n\n # validate sameAs statements\n num_true, num_false = val.detect_false_sameas(to_validate, g_source, g_target)\n print(\"%d wrong sameAs links detected over %d erroneous links\" % (num_false, num_false / W))\n","sub_path":"code/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"461781729","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Longgeek \n\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render_to_response\nfrom django.views.generic.base import View\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.template import loader\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.contrib.auth.models import User\nimport models, re, threading\nimport random\n\nclass Index(View):\n def get(self, request):\n context = {}\n return render_to_response('index.html', context)\n\n\nclass Download(View):\n RANDSTRING = '1234567890qwertyuiopasdfghjklzxcvbnm,./;[]`QWERTYUIOPASDFGHJKLZXCVBNM'\n def generateRandStr(self, email, total):\n '''\n @param email: Email\n @type email: string\n @param total: the length of string\n @type total: string\n '''\n\n index = 0\n randL = []\n\n while index < total:\n randL.append(random.choice(self.RANDSTRING))\n index += 1\n\n return email + ''.join(randL)\n\n def post(self, request):\n context = {}\n email = request.POST.get('email')\n who = email\n username = email.split('@')[0]\n password = self.generateRandStr(username, 6)\n recontact = re.compile(r'^[a-zA-Z0-9_.]{3,18}\\@[a-zA-z0-9]{2,10}\\.[a-zA-Z0-9]{3,10}(\\.[a-zA-Z0-9]{2,10})?$')\n\n if recontact.match(email):\n sendmail('[LiveStack] Download LiveStack iso', [email,])\n sendmail('[LiveStack] Request download livestack iso', ['livestackgroup@thstack.com',], who)\n if not User.objects.filter(username=username):\n user = User.objects.create_user(username, email, password)\n user.save()\n return HttpResponse(\"Checkout your email right now!\", context)\n else:\n return HttpResponse(\"ERROR: Email address is valid!\", context)\n\n\nclass EmailThread(threading.Thread):\n def __init__(self, subject, html_content, email):\n self.subject = subject\n self.html_content = html_content\n self.email = email\n threading.Thread.__init__(self)\n\n def run(self):\n msg = EmailMultiAlternatives(self.subject,\n self.html_content,\n 'LiveStack',\n self.email)\n msg.attach_alternative(self.html_content, \"text/html\")\n msg.send()\n\n\ndef sendmail(subject, email, who=None):\n template_path = \"email.html\"\n for name in email:\n context = {\n 'email': name.split('@')[0]\n }\n\n if name.split('@')[0] == 'livestackgroup':\n context = {\n 'email': name.split('@')[0],\n 'emailuser': who\n }\n\n html_content = loader.render_to_string(template_path, context)\n emails = EmailThread(subject, html_content, email)\n emails.start()\n","sub_path":"livestack/livestack/apphome/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"293222484","text":"#------------------------------------------------------------------------------- \n# Name: Ermal Dedej.\n# Project 1\n# Section 210\n# Due Date: 12/31/1999 \n#------------------------------------------------------------------------------- \n# Honor Code Statement: I received no assistance on this assignment that\n# violates the ethical guidelines set forth by professor and class syllabus.\n#------------------------------------------------------------------------------- \n# References: (list any lecture slides, text book pages, any other resources)\n# Note: you may not use code from websites, so don't bother looking any up.\n#------------------------------------------------------------------------------- \n# Comments and assumptions: A note to the grader as to any problems or\n# uncompleted aspects of the assignment, as well as any assumptions about the\n# meaning of the specification. \n#------------------------------------------------------------------------------- \n# NOTE: width of source code should be <= 80 characters to facilitate printing. \n#2345678901234567890123456789012345678901234567890123456789012345678901234567890 \n# \t\t10 \t\t 20 \t\t30 \t\t 40 \t\t50 \t\t 60 \t\t70 \t\t 80\n#-------------------------------------------------------------------------------\n\n# Welcoming the user on our program\nprint(\"Welcome to Weasleyws' Wizard Wheezes!\")\n\n# setting up the variable and their conversions from galleon on knuts knowing \n# that one galleon is equal to 17 sickles and one sickles is equal to 29 knuts\none_sickle = 29\none_galleon = 17 \none_galleon = (29 * 17) \n\n#Asking the user for his name\nuser_name = str(input('What is your name?\\n'))\n\n# Asking the user to input how many headless wants to buy\nHH_bought = int(input ('How many Headless' +\n'Hats do you want to buy, at 2 galleons each?\\n'))\n\n# Asking the user to input how many boxing telescopes wants to buy\nBT_bought = int(input ('How many Boxing Telescopes do you want to buy,' \n+ ' at 12 sickles 26 knuts each?\\n'))\n\n#Asking the user to input how many canary cream wants to buy\nCC_bought = int(input('How many Canary Creams do you want to buy,'\n+ ' at 7 sickles each?\\n'))\n\n#Calculating the total that will cost the user for what he/she choose\n# to buy at given fixed price of items\n\nHH_price = (2*one_galleon)\nHH_cost = (HH_bought * HH_price)\nBT_price = (12*one_sickle)+26\nBT_cost = (BT_bought * BT_price)\nCC_price = 7 * one_sickle\nCC_cost = (CC_bought * CC_price )\n\n# calculating the total cost for all 3 items\ntotal_bought = ( HH_cost + BT_cost + CC_cost )\n\n# telling the user what the total is and asking the user with how much\n# knuts is paying with. I'm using end ='' call function show in the same line.\nprint('Your total is:',total_bought , 'knuts.', end ='')\ntotal_paying = int(input('How many knuts are you paying with ?\\n'))\n\n# calculating the change in knuts and giving the user the change\nchange_knuts = (total_paying - total_bought)\nprint( 'Your change is :', change_knuts, 'knuts, given as:\\n')\n\n# calculating the change using //- floor division operator to give the lower\n# integer divider for the change in galleons\nchange_galleon = int(change_knuts // one_galleon)\n\n#calculating the reminder change in sickles using % reminder and // operators\nchange_sickles = int((change_knuts % one_galleon)//one_sickle)\n\n# calculating the change that is left in knuts by subtracting \n# from total change the change in galleon and in sickles that has given.\nchange_knut = int (change_knuts - ((change_galleon * one_galleon) + \n(change_sickles * one_sickle)))\n\n# printing the change galleons, sickles and knuts in new line\nprint(change_galleon, 'galleons')\nprint( change_sickles, 'sickles')\nprint( change_knut, 'knuts\\n')\n\n# Thanking a user with the name from the input on first question asked.\nprint('Thank you,' , user_name +'!')","sub_path":"CS112/other proj/210_Ermal_Dedej_P1.py","file_name":"210_Ermal_Dedej_P1.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"530493191","text":"from __future__ import annotations\n\nimport importlib\nimport os\nimport pathlib\nimport re\nimport shutil\nimport sys\nfrom io import StringIO\nfrom typing import List, Optional, Pattern\nfrom urllib.request import urlopen\n\nfrom duty import duty\n\nPACKAGE_NAME = \"panaetius\"\nREPO_URL = \"https://github.com/dtomlinson91/panaetius\"\n\n\n@duty(post=[\"export\"])\ndef update_deps(ctx, dry: bool = False):\n \"\"\"\n Update the dependencies using Poetry.\n\n Args:\n ctx: The context instance (passed automatically).\n dry (bool, optional) = If True will update the `poetry.lock` without updating the\n dependencies themselves. Defaults to False.\n\n Example:\n `duty update_deps dry=False`\n \"\"\"\n dry_run = \"--dry-run\" if dry else \"\"\n ctx.run(\n [\"poetry\", \"update\", dry_run],\n title=f\"Updating poetry deps {dry_run}\",\n )\n\n\n@duty\ndef test(ctx):\n \"\"\"\n Run tests using pytest.\n\n Args:\n ctx: The context instance (passed automatically).\n \"\"\"\n pytest_results = ctx.run([\"pytest\", \"-v\"], pty=True)\n print(pytest_results)\n\n\n@duty\ndef coverage(ctx):\n \"\"\"\n Generate a coverage report and save to XML and HTML.\n\n Args:\n ctx: The context instance (passed automatically).\n\n Example:\n `duty coverage`\n \"\"\"\n ctx.run([\"coverage\", \"run\", \"--source\", PACKAGE_NAME, \"-m\", \"pytest\"])\n res = ctx.run([\"coverage\", \"report\"], pty=True)\n print(res)\n ctx.run([\"coverage\", \"html\"])\n ctx.run([\"coverage\", \"xml\"])\n\n\n@duty\ndef bump(ctx, version: str = \"patch\"):\n \"\"\"\n Bump the version using Poetry and update _version.py.\n\n This duty is ran as part of `duty release`.\n\n Args:\n ctx: The context instance (passed automatically).\n version (str, optional) = poetry version flag. Available options are:\n patch, minor, major. Defaults to patch.\n\n Example:\n `duty bump version=major`\n \"\"\"\n\n # bump with poetry\n result = ctx.run([\"poetry\", \"version\", version])\n new_version = re.search(r\"(?:.*)(?:\\s)(\\d+\\.\\d+\\.\\d+)$\", result)\n print(new_version.group(0))\n\n # update _version.py\n version_file = pathlib.Path(PACKAGE_NAME) / \"_version.py\"\n with version_file.open(\"w\", encoding=\"utf-8\") as version_file:\n version_file.write(\n f'\"\"\"Module containing the version of {PACKAGE_NAME}.\"\"\"\\n\\n' + f'__version__ = \"{new_version.group(1)}\"\\n'\n )\n print(f\"Bumped _version.py to {new_version.group(1)}\")\n\n\n@duty\ndef build(ctx):\n \"\"\"\n Build with poetry and extract the setup.py and copy to project root.\n\n Args:\n ctx: The context instance (passed automatically).\n\n Example:\n `duty build`\n \"\"\"\n\n repo_root = pathlib.Path(\".\")\n\n # build with poetry\n result = ctx.run([\"poetry\", \"build\"])\n print(result)\n\n # extract the setup.py from the tar\n extracted_tar = re.search(r\"(?:.*)(?:Built\\s)(.*)\", result)\n tar_file = pathlib.Path(f\"./dist/{extracted_tar.group(1)}\")\n shutil.unpack_archive(tar_file, tar_file.parents[0])\n\n # copy setup.py to repo root\n extracted_path = tar_file.parents[0] / os.path.splitext(tar_file.stem)[0]\n setup_py = extracted_path / \"setup.py\"\n shutil.copyfile(setup_py, (repo_root / \"setup.py\"))\n\n # cleanup\n shutil.rmtree(extracted_path)\n\n\n@duty\ndef release(ctx, version: str = \"patch\") -> None:\n \"\"\"\n Prepare package for a new release.\n\n Will run bump, build, export. Manual running of publish is required afterwards.\n\n Args:\n ctx: The context instance (passed automatically).\n version (str): poetry version flag. Available options are: patch, minor, major.\n \"\"\"\n print(ctx.run([\"duty\", \"bump\", f\"version={version}\"]))\n ctx.run([\"duty\", \"build\"])\n ctx.run([\"duty\", \"export\"])\n print(\n \"✔ Check generated files. Run `duty changelog planned_release= previous_release=` and `duty publish password=`\"\n \" when ready to publish.\"\n )\n\n\n@duty\ndef export(ctx):\n \"\"\"\n Export the dependencies to a requirements.txt file.\n\n Args:\n ctx: The context instance (passed automatically).\n\n Example:\n `duty export`\n \"\"\"\n requirements_content = ctx.run(\n [\n \"poetry\",\n \"export\",\n \"-f\",\n \"requirements.txt\",\n \"--without-hashes\",\n ]\n )\n requirements_dev_content = ctx.run(\n [\n \"poetry\",\n \"export\",\n \"-f\",\n \"requirements.txt\",\n \"--without-hashes\",\n \"--dev\",\n ]\n )\n\n requirements = pathlib.Path(\".\") / \"requirements.txt\"\n requirements_dev = pathlib.Path(\".\") / \"requirements_dev.txt\"\n\n with requirements.open(\"w\", encoding=\"utf-8\") as req:\n req.write(requirements_content)\n\n with requirements_dev.open(\"w\", encoding=\"utf-8\") as req:\n req.write(requirements_dev_content)\n\n\n@duty\ndef publish(ctx, password: str):\n \"\"\"\n Publish the package to pypi.org.\n\n Args:\n ctx: The context instance (passed automatically).\n password (str): pypi.org password.\n\n Example:\n `duty publish password=$my_password`\n \"\"\"\n dist_dir = pathlib.Path(\".\") / \"dist\"\n rm_result = rm_tree(dist_dir)\n print(rm_result)\n\n publish_result = ctx.run([\"poetry\", \"publish\", \"-u\", \"dtomlinson\", \"-p\", password, \"--build\"])\n print(publish_result)\n\n\n@duty(silent=True)\ndef clean(ctx):\n \"\"\"\n Delete temporary files.\n\n Args:\n ctx: The context instance (passed automatically).\n \"\"\"\n ctx.run(\"rm -rf .mypy_cache\")\n ctx.run(\"rm -rf .pytest_cache\")\n ctx.run(\"rm -rf tests/.pytest_cache\")\n ctx.run(\"rm -rf build\")\n ctx.run(\"rm -rf dist\")\n ctx.run(\"rm -rf pip-wheel-metadata\")\n ctx.run(\"rm -rf site\")\n ctx.run(\"rm -rf coverage.xml\")\n ctx.run(\"rm -rf pytest.xml\")\n ctx.run(\"rm -rf htmlcov\")\n ctx.run(\"find . -iname '.coverage*' -not -name .coveragerc | xargs rm -rf\")\n ctx.run(\"find . -type d -name __pycache__ | xargs rm -rf\")\n ctx.run(\"find . -name '*.rej' -delete\")\n\n\n@duty\ndef format(ctx):\n \"\"\"\n Format code using Black and isort.\n\n Args:\n ctx: The context instance (passed automatically).\n \"\"\"\n res = ctx.run([\"black\", \"--line-length=99\", PACKAGE_NAME], pty=True, title=\"Running Black\")\n print(res)\n\n res = ctx.run([\"isort\", PACKAGE_NAME])\n print(res)\n\n\n@duty(pre=[\"check_code_quality\", \"check_types\", \"check_docs\", \"check_dependencies\"])\ndef check(ctx):\n \"\"\"\n Check the code quality, check types, check documentation builds and check dependencies for vulnerabilities.\n\n Args:\n ctx: The context instance (passed automatically).\n \"\"\"\n\n\n@duty\ndef check_code_quality(ctx):\n \"\"\"\n Check the code quality using prospector.\n\n Args:\n ctx: The context instance (passed automatically).\n \"\"\"\n ctx.run([\"prospector\", PACKAGE_NAME], pty=True, title=\"Checking code quality with prospector\")\n\n\n@duty\ndef check_types(ctx):\n \"\"\"\n Check the types using mypy.\n\n Args:\n ctx: The context instance (passed automatically).\n \"\"\"\n ctx.run([\"mypy\", PACKAGE_NAME], pty=True, title=\"Checking types with MyPy\")\n\n\n@duty\ndef check_docs(ctx):\n \"\"\"\n Check the documentation builds successfully.\n\n Args:\n ctx: The context instance (passed automatically).\n \"\"\"\n ctx.run([\"mkdocs\", \"build\"], title=\"Building documentation\")\n\n\n@duty\ndef check_dependencies(ctx):\n \"\"\"\n Check dependencies with safety for vulnerabilities.\n\n Args:\n ctx: The context instance (passed automatically).\n \"\"\"\n for module in sys.modules:\n if module.startswith(\"safety.\") or module == \"safety\":\n del sys.modules[module]\n\n importlib.invalidate_caches()\n\n from safety import safety\n from safety.formatter import report\n from safety.util import read_requirements\n\n requirements = ctx.run(\n \"poetry export --dev --without-hashes\",\n title=\"Exporting dependencies as requirements\",\n allow_overrides=False,\n )\n\n def check_vulns():\n packages = list(read_requirements(StringIO(requirements)))\n vulns = safety.check(packages=packages, ignore_ids=\"41002\", key=\"\", db_mirror=\"\", cached=False, proxy={})\n output_report = report(vulns=vulns, full=True, checked_packages=len(packages))\n print(vulns)\n if vulns:\n print(output_report)\n\n ctx.run(\n check_vulns,\n stdin=requirements,\n title=\"Checking dependencies\",\n pty=True,\n )\n\n\n@duty\ndef changelog(ctx, planned_release: Optional[str] = None, previous_release: Optional[str] = None):\n \"\"\"\n Generate a changelog with git-cliff.\n\n Args:\n ctx: The context instance (passed automatically).\n planned_release (str, optional): The planned release version. Example: v1.0.2\n previous_release (str, optional): The previous release version. Example: v1.0.1\n \"\"\"\n generated_changelog: str = ctx.run([\"git\", \"cliff\", \"-u\", \"-t\", planned_release, \"-s\", \"header\"])[:-1]\n if previous_release is not None:\n generated_changelog: list = generated_changelog.splitlines()\n generated_changelog.insert(\n 1,\n f\"[Compare with {previous_release}]({REPO_URL}/compare/{previous_release}...{planned_release})\",\n )\n generated_changelog: str = \"\\n\".join([line for line in generated_changelog]) + \"\\n\"\n new_changelog = []\n\n changelog_file = pathlib.Path(\".\") / \"CHANGELOG.md\"\n with changelog_file.open(\"r\", encoding=\"utf-8\") as changelog_contents:\n all_lines = changelog_contents.readlines()\n for line_string in all_lines:\n regex_string = re.search(r\"()\", line_string)\n new_changelog.append(line_string)\n if isinstance(regex_string, re.Match):\n new_changelog.append(generated_changelog)\n with changelog_file.open(\"w\", encoding=\"utf-8\") as changelog_contents:\n changelog_contents.writelines(new_changelog)\n\n\ndef rm_tree(directory: pathlib.Path):\n \"\"\"\n Recursively delete a directory and all its contents.\n\n Args:\n directory (pathlib.Path): The directory to delete.\n \"\"\"\n for child in directory.glob(\"*\"):\n if child.is_file():\n child.unlink()\n else:\n rm_tree(child)\n directory.rmdir()\n","sub_path":"duties.py","file_name":"duties.py","file_ext":"py","file_size_in_byte":10321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"75408339","text":"import sys, os\n\nsys.path.append(os.path.abspath('..'))\nimport chinese_nlp\nimport openpyxl as px\nimport pandas as pd\nimport glob\nfrom collections import Counter\nimport re\nfrom googletrans import Translator\n\ndef get_company_name(row):\n if row[5]:\n name = row[5]\n elif row[4]:\n name = row[4]\n elif row[6]:\n name = row[6]\n else:\n name = row[2]\n return name\n\ndef load_company_names(file, sheet, exclude_alias):\n workbook = px.load_workbook(file)\n sheet = workbook.get_sheet_by_name(name=sheet)\n with open(exclude_alias, encoding=\"utf-8\") as f:\n exclude = set([chinese_nlp.convert2simplified(l.split()[0]) for l in iter(f)])\n companies = []\n for row in sheet.iter_rows():\n row1 = []\n for cell in row:\n row1.append(cell.internal_value)\n # row2 = [x for x in row1 if not pd.isnull(x)]\n row2 = row1\n companies.append(row2)\n companies = companies[1:]\n companies1 = {}\n for company in companies:\n key = str(company[0])\n companies1[key] = {}\n companies1[key]['PermID'] = company[0]\n companies1[key]['RIC'] = company[1]\n companies1[key]['Name'] = get_company_name(company)\n if company[3]:\n companies1[key]['Name_EN'] = company[3]\n else:\n companies1[key]['Name_EN'] = company[2]\n\n companies1[key]['lexicon'] = set(company[2:])\n companies1[key]['lexicon_simp'] = set(\n [chinese_nlp.convert2simplified(x) for x in companies1[key]['lexicon']]) - exclude\n return companies1\n\n\ndef matching(text, companies):\n input_text = dict()\n input_text['text'] = text\n input_text['text_simp'] = chinese_nlp.convert2simplified(input_text['text'])\n matched = []\n w = chinese_nlp.pseg_2gram(input_text['text_simp'])\n words = set(w['words'])\n # words1 = Counter(w['words'])\n for k in companies:\n matched1 = words & companies[k]['lexicon_simp']\n if len(matched1) > 0:\n # companies[k][\"Matched\"] = \",\".join(matched1)\n companies[k][\"Matched\"] = matched1\n matched.append(companies[k])\n # matched_occur = {}\n # for id in matched:\n # matched_occur[id] = []\n # for word in matched[id]:\n # matched_occur[id] += [(x.start(), x.end()) for x in re.finditer(word, input_text['text_simp'])]\n # input_text['matched'] = matched\n # input_text['matched_occur'] = matched_occur\n return matched\n\n\ndef format_tagged_text(tagged):\n permid = []\n start = []\n end = []\n english_word_list = []\n translator = Translator()\n for id in tagged['matched_occur']:\n for x in tagged['matched_occur'][id]:\n permid.append(id)\n start.append(x[0])\n end.append(x[1])\n pos = pd.DataFrame({'permid': permid, 'start': start, 'end': end}).sort_values(['start', 'end'])\n pos['remove'] = 0\n for i in range(1, len(pos)):\n previous = pos.iloc[:i]\n previous = previous[previous['remove'] == 0]\n if pos['start'].iloc[i] < previous['end'].iloc[-1]:\n pos['remove'].iloc[i] = 1\n pos1 = pos[pos['remove'] == 0]\n text_format = ''\n current_pos = 0\n for i in range(len(pos1)):\n start_pos = pos1['start'].iloc[i]\n end_pos = pos1['end'].iloc[i]\n current_permid = 'https://permid.org/1-' + pos1['permid'].iloc[i]\n text_format += tagged['text'][current_pos:start_pos] + '' + \\\n tagged['text'][start_pos:end_pos] + ''\n current_pos = end_pos\n\n text_format += tagged['text'][current_pos:]\n tagged['text_format'] = text_format\n english_text = translator.translate(tagged['text_simp'].replace(\"
\", \"\\n\")).text\n tagged['english_format'] = \"\"\n\n current_pos = 0\n for i in range(len(pos1)):\n start_pos = pos1['start'].iloc[i]\n end_pos = pos1['end'].iloc[i]\n current_permid = 'https://permid.org/1-' + pos1['permid'].iloc[i]\n english_word = translator.translate(tagged['text'][start_pos:end_pos]).text\n print(tagged['text'][start_pos:end_pos])\n print(english_word)\n pos2 = [(x.start(), x.end()) for x in re.finditer(english_word, english_text)]\n if pos2 and len(pos2) > english_word_list.count(english_word):\n\n pos2 = pos2[english_word_list.count(english_word)]\n if pos2[0] > current_pos:\n tagged['english_format'] += english_text[current_pos\n :pos2[\n 0]] + '' + \\\n english_text[pos2[0]:pos2[1]] + ''\n print(current_pos)\n current_pos = pos2[1]\n english_word_list.append(english_word)\n\n tagged['english_format'] += english_text[current_pos:]\n tagged['english_format'] = tagged['english_format'].replace(\"\\n\", \"
\")\n return tagged\n","sub_path":"marco-polo/chinese_tagging_api.py","file_name":"chinese_tagging_api.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"179001091","text":"import pyttsx3\nimport webbrowser\nimport smtplib\nimport random\nimport speech_recognition as sr\nimport wikipedia\nimport datetime\nimport wolframalpha\nimport os\nimport sys\nimport subprocess\nimport requests\nfrom bs4 import BeautifulSoup\n\nengine = pyttsx3.init('sapi5')\nvoices = engine.getProperty('voices')\nengine.setProperty('voice', voices[0].id)\n\ndef speak(audio):\n print('Computer: ' + audio)\n engine.say(audio)\n engine.runAndWait()\n\ndef greetMe():\n currentH = int(datetime.datetime.now().hour)\n if currentH >= 0 and currentH < 12:\n speak('Good Morning!')\n\n if currentH >= 12 and currentH < 18:\n speak('Good Afternoon!')\n\n if currentH >= 18 and currentH !=0:\n speak('Good Evening!')\n\n \n\ngreetMe()\n\n\nspeak('Hi abc, my name is apollo!')\nspeak('How may I help you?')\n\n\ndef myCommand():\n \n r = sr.Recognizer() \n with sr.Microphone() as source: \n print(\"Listening...\")\n r.pause_threshold = 1\n audio = r.listen(source)\n try:\n query = r.recognize_google(audio, language='en-in')\n print('User: ' + query + '\\n')\n \n except sr.UnknownValueError:\n speak('Sorry abc! I didn\\'t get that! Try typing the command!')\n query = str(input('Command: '))\n\n return query\n\ndef sendemail(to,content):\n server = smtplib.SMTP('smtp.gmail.com',587)\n server.ehlo()\n server.starttls()\n server.login('your_mail','your_password') #enter yor email id and password \n server.sendmail('your_email',to,content)\n server.close()\n\n\n \n\nif __name__ == '__main__':\n\n while True:\n \n query = myCommand();\n query = query.lower()\n \n if 'open youtube' in query:\n speak('okay')\n webbrowser.open('www.youtube.com')\n\n elif 'open google' in query:\n speak('okay')\n webbrowser.open('www.google.co.in')\n\n elif 'time' in query:\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\")\n speak(f\"hey, the time is {strTime}\")\n \n \n elif 'open code' in query:\n speak('okay')\n pathw=\"C:\\\\Users\\\\hp\\\\AppData\\\\Local\\\\Programs\\\\Microsoft VS Code\\\\Code.exe\" #enter the target location to your vs code\n os.startfile(pathw)\n\n elif 'open gmail' in query:\n speak('okay')\n webbrowser.open('www.gmail.com')\n\n elif \"all good\" in query or 'how are you' in query:\n stMsgs = ['Just doing my thing!', 'I am fine!, thanks for asking', 'great , its a good day afterall', 'I am nice and full of energy']\n speak(random.choice(stMsgs))\n speak('hope you are doing good as well')\n \n elif 'email' in query:\n try:\n speak(\"what should i say?\")\n content = myCommand()\n to = input(\"enter the email of receiver:\")\n sendemail(to,content)\n speak(\"email has been sent!\")\n \n except Exception as e :\n print(e)\n speak(\"sorry abc. i am not able to send your email right now\")\n\n\n \n elif 'hello' in query:\n speak('Hello abc , hope you are having a good day !')\n\n \n elif 'play music' in query:\n music_folder = r\"C:\\\\Users\\\\hp\\\\Desktop\\\\audios\" #path to your audios folder\n songs = os.listdir(music_folder)\n print(songs)\n os.startfile(os.path.join(music_folder,songs[0]))\n \n speak('Okay, here is your music! Enjoy!')\n\n elif 'wikipedia' in query:\n speak(\"searching your query..\")\n query = query.replace(\"wikipedia\",\"\")\n results = wikipedia.summary(query,sentences=2)\n speak(\"according to wikipedia\")\n print(results)\n speak(results)\n\n elif 'open notepad' in query:\n subprocess.call('notepad.exe')\n\n elif 'open whatsapp' in query:\n subprocess.call('C:\\\\ProgramData\\\\HP\\\\WhatsApp\\\\whatsapp.exe') # path to your whatsapp\n\n elif 'open calculator' in query:\n subprocess.call('calc.exe')\n\n \n\n elif 'temperature' in query :\n search = \"temperature in jammu and kashmir\"\n url = f\" https://www.google.com/search?q={search}\"\n x=requests.get(url)\n data = BeautifulSoup(x.text,\"html.parser\")\n temp=data.find(\"div\",class_=\"BNeawe\").text\n speak(f\"current {search} is {temp}\")\n\n\n elif 'bye' or 'exit' in query:\n speak(\"okay\")\n speak(\"bye abc have a nice day!!\") # say bye/exit to leave the program \n sys.exit() \n\n\n \n \n speak('Next Command! abc!')\n","sub_path":"python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"163069587","text":"import torch\nfrom numpy.random.mtrand import rand, randn, randint\nfrom scipy.ndimage import rotate\n\n\ndef random_augmentation(imageBatch):\n if(rand()>=0.0):\n imageBatch = random_rotate(imageBatch)\n if(rand()>=0.0):\n imageBatch = random_shift(imageBatch)\n if(rand()>=0.0):\n imageBatch = gaussian_noise(imageBatch)\n # if(rand()>=0.5):\n # imageBatch = invert_colors(imageBatch)\n return imageBatch\n\n\ndef gaussian_noise(imageBatch):\n b,c,x,y = imageBatch.shape\n gaussian = randn(b,c,x,y)*0.05\n return imageBatch+torch.Tensor(gaussian)\n\n\ndef blur(imageBatch):\n return imageBatch\n\n\ndef random_shift(imageBatch):\n shiftRange = 7\n _, _, x, y = imageBatch.shape\n xShift = randint(-shiftRange,shiftRange)\n yShift = randint(-shiftRange,shiftRange)\n startX = abs(xShift)\n startY = abs(yShift)\n zeros = torch.zeros([sum(x) for x in zip(imageBatch.shape,(0,0,startX*2,startY*2))])\n # print(xShift)\n # print(yShift)\n zeros[:,:,startX:startX+x, startY:startY+y] = imageBatch[:,:,:,:]\n imageBatch_cropped = crop(zeros, startX-xShift, startY-yShift, imageBatch.shape)\n return torch.Tensor(imageBatch_cropped)\n\n\ndef random_rotate(imageBatch):\n angleRange = 20\n angle = randint(-angleRange,angleRange)\n # print(angle)\n if torch.cuda.is_available():\n imageBatch_rotated = crop_center(rotate(imageBatch, angle, axes=(2,3)), imageBatch.shape)\n else:\n imageBatch_rotated = crop_center(rotate(imageBatch.detach().numpy(), angle, axes=(2,3)), imageBatch.shape)\n return torch.Tensor(imageBatch_rotated)\n\n\ndef crop(imageBatch, startX, startY, newShape):\n _, _, x, y = imageBatch.shape\n _, _, newX, newY = newShape\n endX = min(startX+newX, x)\n endY = min(startY+newY, y)\n return imageBatch[:, :, startX:endX, startY:endY]\n\n\ndef crop_center(imageBatch,newShape):\n _,_,x,y = imageBatch.shape\n newB, newC, newX, newY = newShape\n startX = x//2 - newX//2\n startY = y//2 - newY//2\n return crop(imageBatch, startX, startY, newShape)\n\n\ndef invert_colors(imageBatch):\n return 1-imageBatch","sub_path":"LearnDistance/fix_one/augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"582703973","text":"# hptiny prediction script\r\n#\r\n# Author: Claudemir Casa\r\n# Copyright: Copyright 2019. GIS Technologies\r\n# License: GIS\r\n# Version: 1.0.4\r\n# Mmaintainer: claudemircasa\r\n# Email: claudemir.casa@ufpr.br\r\n# Status: under development\r\n\r\nfrom threading import Thread\r\nfrom queue import Queue\r\nimport argparse\r\nimport numpy as np\r\nimport onnxruntime as rt\r\nfrom PIL import Image, ImageDraw\r\nfrom os import path\r\nimport time\r\nimport cv2\r\nfrom cv2 import dnn\r\nimport onnx\r\nfrom onnx import optimizer\r\nimport uuid\r\nimport glob\r\n\r\nclass HPTiny:\r\n def __init__(self, options):\r\n self.options = options\r\n self.image_ext = ['jpeg', 'jpg', 'jpe', 'jp2', 'png', 'bmp', 'dib', 'pbm', 'pgm', 'ppm', 'sr', 'ras', 'tiff', 'tif']\r\n self.video_ext = ['mp4', 'avi', 'webm']\r\n self.boxes = []\r\n self.confidences = []\r\n self.classes = []\r\n \r\n with open('classes') as f:\r\n self.labels = f.read().strip().split(\"\\n\")\r\n self.colors = np.random.randint(0, 255, size=(len(self.labels), 3), dtype=\"uint8\")\r\n\r\n self.model = onnx.load(self.options.model)\r\n self.session = rt.InferenceSession(self.options.model)\r\n self.inputs = self.session.get_inputs()[0].name\r\n self.outputs = [o for o in self.session.get_outputs()]\r\n\r\n def check(self):\r\n return onnx.checker.check_model(self.model)\r\n \r\n def readable(self):\r\n return onnx.helper.printable_graph(self.model.graph)\r\n \r\n def optimize(self):\r\n # A full list of supported optimization passes can be found using get_available_passes()\r\n all_passes = optimizer.get_available_passes()\r\n print(\"Available optimization passes:\")\r\n for p in all_passes:\r\n print(p)\r\n print()\r\n\r\n # Apply the optimization on the original model\r\n optimized_model = optimizer.optimize(self.model, all_passes)\r\n\r\n # save new model\r\n onnx.save(optimized_model, 'optimized_model.onnx')\r\n\r\n def predict(self, frm):\r\n frame = frm.copy()\r\n\r\n (height, width) = frame.shape[:2]\r\n resized = cv2.resize(frame, (self.options.size, self.options.size))\r\n \r\n blob = cv2.dnn.blobFromImage(resized, scalefactor=self.options.scale, size=(self.options.size, self.options.size), mean=(0,0,0), swapRB=True, crop=False)\r\n inferences = self.session.run(None, {self.inputs: blob.astype(np.float32)})\r\n\r\n self.boxes = []\r\n self.confidences = []\r\n self.classes = []\r\n\r\n # loop over each detection\r\n for scores, box in zip(inferences[0], inferences[1]):\r\n\r\n # extract class id and confidence\r\n class_id = np.argmax(scores)\r\n confidence = scores[class_id]\r\n \r\n # filter out weak predictions by ensuring the detected\r\n # probability is greater than the minimum probability\r\n if confidence > self.options.confidence:\r\n # scale the bounding box coordinates back relative to the\r\n # size of the image, keeping in mind that YOLO actually\r\n # returns the center (x, y)-coordinates of the bounding\r\n # box followed by the boxes' width and height\r\n _box = box[0:4] * np.array([width, height, width, height])\r\n (x, y, w, h) = _box.astype('int')\r\n\r\n # use the center (x, y)-coordinates to derive the top and\r\n # and left corner of the bounding box\r\n x = int(x - (w / 2))\r\n y = int(y - (h / 2))\r\n \r\n # update our list of bounding box coordinates, confidences,\r\n # and class ids\r\n self.boxes.append([x, y, int(w), int(h)])\r\n self.confidences.append(float(confidence))\r\n self.classes.append(class_id)\r\n \r\n idxs = dnn.NMSBoxes(self.boxes, self.confidences, self.options.confidence, self.options.threshold)\r\n\r\n # ensure at least one detection exists\r\n if len(idxs) > 0:\r\n # loop over the indexes we are keeping\r\n for i in idxs.flatten():\r\n # extract the bounding box coordinates\r\n (x, y) = (self.boxes[i][0], self.boxes[i][1])\r\n (w, h) = (self.boxes[i][2], self.boxes[i][3])\r\n\r\n # get image part\r\n roi = frm[y:y+h, x:x+w]\r\n mask = np.zeros((roi.shape[:2][0], roi.shape[:2][1], 3), np.uint8)\r\n\r\n # draw a bounding box rectangle and label on the image\r\n color = [int(c) for c in self.colors[self.classes[i]]]\r\n\r\n mask[:] = color\r\n #mask[:, :, :3] = color\r\n #mask[:, :, 3:] = 100\r\n\r\n #frame[y:y+h, x:x+w] = mask\r\n\r\n cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)\r\n if self.options.show_percentage > 0:\r\n text = \"{}: {:.4f}\".format(self.labels[self.classes[i]], self.confidences[i])\r\n else:\r\n text = \"{}\".format(self.labels[self.classes[i]])\r\n cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,\r\n 0.5, color, 2)\r\n\r\n return frame\r\n\r\n def run(self):\r\n _type = 0\r\n # detect from camera\r\n for i, j in zip(self.image_ext, self.video_ext):\r\n if (self.options.device.endswith(i)):\r\n _type = 1\r\n break\r\n elif (self.options.device.endswith(j)):\r\n _type = 2\r\n break\r\n \r\n if (_type == 0 or _type == 2):\r\n if (_type == 2):\r\n stream = cv2.VideoCapture(self.options.device)\r\n else:\r\n stream = cv2.VideoCapture(int(self.options.device))\r\n writer = None\r\n\r\n total = int(stream.get(cv2.CAP_PROP_FRAME_COUNT))\r\n while stream.isOpened():\r\n _, frame = stream.read()\r\n\r\n # Run detection\r\n start = time.time()\r\n pimage = self.predict(frame)\r\n end = time.time()\r\n\r\n # some information on processing single frame\r\n elapsed = (end - start)\r\n fps = 1 / elapsed\r\n if (fps < 1):\r\n fps = 1\r\n\r\n print(\"[INFO] FPS: {:.2f} seconds\".format(fps))\r\n print(\"[INFO] single frame took {:.4f} seconds\".format(elapsed))\r\n if (_type == 2):\r\n print(\"[INFO] estimated total time to finish: {:.4f}\".format(elapsed * total))\r\n\r\n # write the output frame to disk\r\n if self.options.save_output > 0:\r\n # check if the video writer is None\r\n if writer is None:\r\n # initialize our video writer\r\n fourcc = cv2.VideoWriter_fourcc(*'MJPG')\r\n writer = cv2.VideoWriter('{}.avi'.format(self.options.output_name), fourcc, 15, (pimage.shape[1], pimage.shape[0]), True)\r\n writer.write(pimage)\r\n\r\n cv2.imshow('', pimage)\r\n total += 1\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n # When everything done, release the capture\r\n if (writer):\r\n writer.release()\r\n stream.release()\r\n cv2.destroyAllWindows()\r\n elif (_type == 1):\r\n image = cv2.imread(self.options.device)\r\n\r\n # Run detection\r\n start = time.time()\r\n image = self.predict(image)\r\n end = time.time()\r\n\r\n elapsed = (end - start)\r\n print(\"[INFO] single frame took {:.4f} seconds\".format(elapsed))\r\n\r\n if self.options.save_output > 0:\r\n cv2.imwrite('{}.jpg'.format(self.options.output_name), image)\r\n\r\n cv2.imshow('', image)\r\n while True:\r\n if (cv2.waitKey(1) & 0xFF == ord('q')):\r\n break\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(prog='test.py')\r\n parser.add_argument('device', type=str, help='device, video or image file')\r\n parser.add_argument('--show_percentage', type=int, default=1, help='show box prediction percentage')\r\n parser.add_argument('--save_output', type=int, default=0, help='save the output')\r\n parser.add_argument('--size', type=int, default=608, help='size of net input')\r\n parser.add_argument('--scale', type=float, default=(1/255))\r\n parser.add_argument('--confidence', type=float, default=0.01)\r\n parser.add_argument('--threshold', type=float, default=0.4)\r\n parser.add_argument('--model', type=str, default='model.onnx')\r\n parser.add_argument('--output_name', type=str, default=str(uuid.uuid4()))\r\n options = parser.parse_args()\r\n \r\n m = HPTiny(options=options)\r\n m.run()\r\n","sub_path":"model/hptiny.py","file_name":"hptiny.py","file_ext":"py","file_size_in_byte":8956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"235133290","text":"import copy\nimport decimal\nfrom unittest import mock\n\nfrom applications.api.v1.serializers import HandlerApplicationSerializer\nfrom applications.enums import ApplicationStatus, BenefitType, OrganizationType\nfrom applications.tests.conftest import * # noqa\nfrom applications.tests.test_applications_api import (\n add_attachments_to_application,\n get_detail_url,\n get_handler_detail_url,\n)\nfrom calculator.api.v1.serializers import CalculationSerializer\nfrom calculator.tests.factories import CalculationFactory, PaySubsidyFactory\n\n\ndef test_application_retrieve_calculation_as_handler(handler_api_client, application):\n response = handler_api_client.get(get_handler_detail_url(application))\n assert \"calculation\" in response.data\n assert \"pay_subsidies\" in response.data\n assert response.status_code == 200\n\n\ndef test_application_try_retrieve_calculation_as_applicant(api_client, application):\n response = api_client.get(get_detail_url(application))\n assert \"calculation\" not in response.data\n assert \"pay_subsidies\" not in response.data\n assert response.status_code == 200\n\n\ndef test_application_create_calculation_on_submit(\n request, handler_api_client, application\n):\n application.status = ApplicationStatus.DRAFT\n application.pay_subsidy_percent = 50\n application.pay_subsidy_granted = True\n application.benefit_type = BenefitType.SALARY_BENEFIT\n application.save()\n assert not hasattr(application, \"calculation\")\n data = HandlerApplicationSerializer(application).data\n\n data[\"status\"] = ApplicationStatus.RECEIVED\n data[\"bases\"] = [] # as of 2021-10, bases are not used when submitting application\n add_attachments_to_application(request, application)\n if data[\"company\"][\"organization_type\"] == OrganizationType.ASSOCIATION:\n data[\"association_has_business_activities\"] = False\n data[\"association_immediate_manager_check\"] = True\n\n with mock.patch(\n \"terms.models.ApplicantTermsApproval.terms_approval_needed\", return_value=False\n ):\n response = handler_api_client.put(\n get_handler_detail_url(application),\n data,\n )\n\n assert response.status_code == 200\n application.refresh_from_db()\n assert hasattr(application, \"calculation\")\n\n assert response.data[\"calculation\"] is not None\n assert response.data[\"calculation\"][\"monthly_pay\"] == str(\n application.employee.monthly_pay\n )\n assert response.data[\"calculation\"][\"start_date\"] == str(application.start_date)\n assert len(response.data[\"calculation\"][\"rows\"]) > 1\n assert response.status_code == 200\n\n\ndef test_application_can_not_create_calculation_through_api(\n handler_api_client, application\n):\n \"\"\" \"\"\"\n assert not hasattr(application, \"calculation\")\n data = HandlerApplicationSerializer(application).data\n calc_data = CalculationSerializer(CalculationFactory()).data\n data[\"calculation\"] = calc_data\n response = handler_api_client.put(\n get_handler_detail_url(application),\n data,\n )\n assert response.status_code == 200\n assert response.data[\"calculation\"] is None\n application.refresh_from_db()\n assert not hasattr(application, \"calculation\")\n\n\ndef test_modify_calculation(handler_api_client, received_application):\n \"\"\"\n modify existing calculation\n \"\"\"\n data = HandlerApplicationSerializer(received_application).data\n assert received_application.calculation\n assert received_application.pay_subsidies.count() == 0\n data[\"calculation\"][\"monthly_pay\"] = \"1234.56\"\n # also modify pay_subsidies. Although multiple objects are modified, calculate() should only\n # be called once.\n data[\"pay_subsidies\"] = [\n {\n \"start_date\": str(received_application.start_date),\n \"end_date\": str(received_application.end_date),\n \"pay_subsidy_percent\": 50,\n \"work_time_percent\": 100,\n }\n ]\n with mock.patch(\"calculator.models.Calculation.calculate\") as calculate_wrap:\n response = handler_api_client.put(\n get_handler_detail_url(received_application),\n data,\n )\n calculate_wrap.assert_called_once()\n\n assert response.status_code == 200\n assert response.data[\"calculation\"][\"monthly_pay\"] == \"1234.56\"\n received_application.refresh_from_db()\n assert received_application.calculation.monthly_pay == decimal.Decimal(\"1234.56\")\n assert received_application.pay_subsidies.count() == 1\n assert received_application.pay_subsidies.first().pay_subsidy_percent == 50\n assert (\n received_application.pay_subsidies.first().start_date\n == received_application.start_date\n )\n assert (\n received_application.pay_subsidies.first().end_date\n == received_application.end_date\n )\n\n\ndef test_can_not_delete_calculation(handler_api_client, received_application):\n \"\"\"\n application.calculation can not be deleted through the API - setting application to None is ignored\n \"\"\"\n data = HandlerApplicationSerializer(received_application).data\n data[\"calculation\"] = None\n handler_api_client.put(\n get_handler_detail_url(received_application),\n data,\n )\n received_application.refresh_from_db()\n assert received_application.calculation\n\n\ndef test_application_replace_pay_subsidy(handler_api_client, received_application):\n data = HandlerApplicationSerializer(received_application).data\n\n data[\"pay_subsidies\"] = [\n {\n \"start_date\": str(received_application.start_date),\n \"end_date\": str(received_application.end_date),\n \"pay_subsidy_percent\": 50,\n \"work_time_percent\": 100,\n \"disability_or_illness\": True,\n }\n ]\n response = handler_api_client.put(\n get_handler_detail_url(received_application),\n data,\n )\n assert response.status_code == 200\n received_application.refresh_from_db()\n new_data = HandlerApplicationSerializer(received_application).data\n del new_data[\"pay_subsidies\"][0][\"id\"]\n assert new_data[\"pay_subsidies\"] == data[\"pay_subsidies\"]\n\n\ndef test_application_edit_pay_subsidy(handler_api_client, received_application):\n PaySubsidyFactory(application=received_application)\n PaySubsidyFactory(application=received_application)\n data = HandlerApplicationSerializer(received_application).data\n\n # edit fields\n data[\"pay_subsidies\"][0][\"start_date\"] = \"2021-06-01\"\n data[\"pay_subsidies\"][0][\"pay_subsidy_percent\"] = 40\n # swap order\n data[\"pay_subsidies\"][0], data[\"pay_subsidies\"][1] = (\n data[\"pay_subsidies\"][1],\n data[\"pay_subsidies\"][0],\n )\n response = handler_api_client.put(\n get_handler_detail_url(received_application),\n data,\n )\n assert response.status_code == 200\n assert len(response.data[\"pay_subsidies\"]) == 2\n assert response.data[\"pay_subsidies\"][1][\"start_date\"] == \"2021-06-01\"\n assert response.data[\"pay_subsidies\"][1][\"pay_subsidy_percent\"] == 40\n\n\ndef test_application_delete_pay_subsidy(handler_api_client, received_application):\n data = HandlerApplicationSerializer(received_application).data\n\n data[\"pay_subsidies\"] = []\n\n response = handler_api_client.put(\n get_handler_detail_url(received_application),\n data,\n )\n assert response.status_code == 200\n assert response.data[\"pay_subsidies\"] == []\n\n\ndef test_application_edit_pay_subsidy_invalid_values(\n handler_api_client, received_application\n):\n data = HandlerApplicationSerializer(received_application).data\n\n previous_data = copy.deepcopy(data[\"pay_subsidies\"])\n\n data[\"pay_subsidies\"] = [\n {\n \"start_date\": str(received_application.start_date),\n \"end_date\": str(received_application.end_date),\n \"pay_subsidy_percent\": 150,\n \"work_time_percent\": -10,\n }\n ]\n\n response = handler_api_client.put(\n get_handler_detail_url(received_application),\n data,\n )\n assert response.status_code == 400\n\n received_application.refresh_from_db()\n data_after = HandlerApplicationSerializer(received_application).data\n assert previous_data == data_after[\"pay_subsidies\"]\n","sub_path":"backend/benefit/calculator/tests/test_calculator_api.py","file_name":"test_calculator_api.py","file_ext":"py","file_size_in_byte":8227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"36947007","text":"# -*- coding: utf-8 -*-\nimport csv\nimport os\nimport time\nfrom threading import Thread\n# Описание предметной области:\n#\n# При торгах на бирже совершаются сделки - один купил, второй продал.\n# Покупают и продают ценные бумаги (акции, облигации, фьючерсы, етс). Ценные бумаги - это по сути долговые расписки.\n# Ценные бумаги выпускаются партиями, от десятка до несколько миллионов штук.\n# Каждая такая партия (выпуск) имеет свой торговый код на бирже - тикер - https://goo.gl/MJQ5Lq\n# Все бумаги из этой партии (выпуска) одинаковы в цене, поэтому говорят о цене одной бумаги.\n# У разных выпусков бумаг - разные цены, которые могут отличаться в сотни и тысячи раз.\n# Каждая биржевая сделка характеризуется:\n# тикер ценнной бумаги\n# время сделки\n# цена сделки\n# обьем сделки (сколько ценных бумаг было куплено)\n#\n# В ходе торгов цены сделок могут со временем расти и понижаться. Величина изменения цен называтея волатильностью.\n# Например, если бумага №1 торговалась с ценами 11, 11, 12, 11, 12, 11, 11, 11 - то она мало волатильна.\n# А если у бумаги №2 цены сделок были: 20, 15, 23, 56, 100, 50, 3, 10 - то такая бумага имеет большую волатильность.\n# Волатильность можно считать разными способами, мы будем считать сильно упрощенным способом -\n# отклонение в процентах от средней цены за торговую сессию:\n# средняя цена = (максимальная цена + минимальная цена) / 2\n# волатильность = ((максимальная цена - минимальная цена) / средняя цена) * 100%\n# Например для бумаги №1:\n# average_price = (12 + 11) / 2 = 11.5\n# volatility = ((12 - 11) / average_price) * 100 = 8.7%\n# Для бумаги №2:\n# average_price = (100 + 3) / 2 = 51.5\n# volatility = ((100 - 3) / average_price) * 100 = 188.34%\n#\n# В реальности волатильность рассчитывается так: https://goo.gl/VJNmmY\n#\n# Задача: вычислить 3 тикера с максимальной и 3 тикера с минимальной волатильностью.\n# Бумаги с нулевой волатильностью вывести отдельно.\n# Результаты вывести на консоль в виде:\n# Максимальная волатильность:\n# ТИКЕР1 - ХХХ.ХХ %\n# ТИКЕР2 - ХХХ.ХХ %\n# ТИКЕР3 - ХХХ.ХХ %\n# Минимальная волатильность:\n# ТИКЕР4 - ХХХ.ХХ %\n# ТИКЕР5 - ХХХ.ХХ %\n# ТИКЕР6 - ХХХ.ХХ %\n# Нулевая волатильность:\n# ТИКЕР7, ТИКЕР8, ТИКЕР9, ТИКЕР10, ТИКЕР11, ТИКЕР12\n# Волатильности указывать в порядке убывания. Тикеры с нулевой волатильностью упорядочить по имени.\n#\n# Подготовка исходных данных\n# 1. Скачать файл https://drive.google.com/file/d/1l5sia-9c-t91iIPiGyBc1s9mQ8RgTNqb/view?usp=sharing\n# (обратите внимание на значок скачивания в правом верхнем углу,\n# см https://drive.google.com/file/d/1M6mW1jI2RdZhdSCEmlbFi5eoAXOR3u6G/view?usp=sharing)\n# 2. Раззиповать средствами операционной системы содержимое архива\n# в папку python_base_source/lesson_012/trades\n# 3. В каждом файле в папке trades содержится данные по сделакам по одному тикеру, разделенные запятыми.\n# Первая строка - название колонок:\n# SECID - тикер\n# TRADETIME - время сделки\n# PRICE - цена сделки\n# QUANTITY - количество бумаг в этой сделке\n# Все последующие строки в файле - данные о сделках\n#\n# Подсказка: нужно последовательно открывать каждый файл, вычитывать данные, высчитывать волатильность и запоминать.\n# Вывод на консоль можно сделать только после обработки всех файлов.\n#\n# Для плавного перехода к мультипоточности, код оформить в обьектном стиле, используя следующий каркас\n#\n# class <Название класса>:\n#\n# def __init__(self, <параметры>):\n# <сохранение параметров>\n#\n# def run(self):\n# <обработка данных>\nFILES = []\n\nSECID_VOLATILITY = {}\n\nTICKER = []\nMAX_VALUES = []\nMIN_VALUES = []\nZERO_VALUES = []\n\npath = '/Users/sasha/Documents/New_Projects/practise_12_multiprocesing/trades/'\nfile_list = os.listdir(path)\n\nfor file_name in file_list:\n FILES.append(file_name)\n\n\ndef time_track(func):\n def surrogate(*args, **kwargs):\n start_time = time.time()\n\n result = func(*args, **kwargs)\n\n end_time = time.time()\n elapsed = round(end_time - start_time, 4)\n print(f'Function was working {elapsed} seconds.')\n return result\n return surrogate\n\n# def last_4chars(x):\n# return(x[-8:])\n\n\nclass Main(Thread):\n\n def __init__(self, file):\n super(Main, self).__init__()\n self.file = file\n\n def run(self):\n if self.file:\n with open(os.path.join('/Users/sasha/Documents/New_Projects/practise_12_multiprocesing/trades/'\n + self.file), 'r', encoding='utf8') as trade:\n reader = csv.reader(trade, delimiter=',')\n secid = []\n tradetime = []\n prices = []\n quantity = []\n for row in reader:\n if row[0] == 'SECID':\n continue\n secid.append(row[0])\n tradetime.append(row[1])\n prices.append(row[2])\n quantity.append(row[3])\n price = map(float, prices)\n prices = list(price)\n max_price = max(prices)\n min_price = min(prices)\n average_price = round((max_price + min_price) / 2, 2)\n volatility = round((max_price - min_price) / average_price * 100, 2)\n SECID_VOLATILITY[secid[0]] = volatility\n\n\n# def main(path):\n# file_list = os.listdir(path)\n# file_listed = sorted(file_list, key=last_4chars)\n# for file in file_listed:\n# with open(os.path.join('/Users/sasha/Documents/New_Projects/practise_12_multiprocesing/trades/' + file), 'r',\n# encoding='utf8') as trade:\n# reader = csv.reader(trade, delimiter=',')\n# secid = []\n# tradetime = []\n# prices = []\n# quantity = []\n# for row in reader:\n# if row[0] == 'SECID':\n# continue\n# secid.append(row[0])\n# tradetime.append(row[1])\n# prices.append(row[2])\n# quantity.append(row[3])\n# price = map(float, prices)\n# prices = list(price)\n# max_price = max(prices)\n# min_price = min(prices)\n# average_price = round((max_price + min_price)/2, 2)\n# volatility = round((max_price - min_price)/average_price * 100, 2)\n# yield secid[0], volatility\n\nfor file_name in file_list:\n FILES.append(file_name)\n\n@time_track\ndef func():\n\n sizers = [Main(file=file) for file in FILES]\n for sizer in sizers:\n sizer.start()\n for sizer in sizers:\n sizer.join()\n\n dict_volatility = {}\n dict_zero_volatility = {}\n for secid, volatility in SECID_VOLATILITY.items():\n if volatility >= 0.1:\n dict_volatility[secid] = volatility\n else:\n dict_zero_volatility[secid] = volatility\n\n sorted_dict = {k: v for k, v in sorted(dict_volatility.items(), key=lambda item: item[1], reverse=True)}\n sorted_zero_dict = {k: v for k, v in sorted(dict_zero_volatility.items(), key=lambda item: item[0], reverse=False)}\n zero_list = list(sorted_zero_dict.items())\n my_list = list(sorted_dict.items())\n MAX_VALUES.extend([my_list[0], my_list[1], my_list[2]])\n MIN_VALUES.extend([my_list[-1], my_list[-2], my_list[-3]])\n ZERO_VALUES.extend(zero_list)\n\n\n\n\n\n\n\nif __name__ == '__main__':\n func()\n print(f' Максимальная волатильность:\\n\\t{MAX_VALUES[0][0]} - {MAX_VALUES[0][1]}%\\n\\t'\n f'{MAX_VALUES[1][0]} - {MAX_VALUES[1][1]}%\\n\\t{MAX_VALUES[2][0]} - {MAX_VALUES[2][1]}%')\n print(f' Минимальная волатильность:\\n\\t{MIN_VALUES[0][0]} - {MIN_VALUES[0][1]}%\\n\\t'\n f'{MIN_VALUES[1][0]} - {MIN_VALUES[1][1]}%\\n\\t{MIN_VALUES[2][0]} - {MIN_VALUES[2][1]}%')\n print(f' Нулевая волатильность:\\n\\t{list(item for sublist in ZERO_VALUES for item in sublist)}%')\n","sub_path":"practise_12_multiprocesing/01_volatility.py","file_name":"01_volatility.py","file_ext":"py","file_size_in_byte":10061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"371936627","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom .serialization import Model\n\n\nclass ServiceSasParameters(Model):\n \"\"\"The parameters to list service SAS credentials of a specific resource.\n\n :param canonicalized_resource: The canonical path to the signed resource.\n :type canonicalized_resource: str\n :param resource: The signed services accessible with the service SAS.\n Possible values include: Blob (b), Container (c), File (f), Share (s).\n Possible values include: 'b', 'c', 'f', 's'\n :type resource: str or :class:`enum\n `\n :param permissions: The signed permissions for the service SAS. Possible\n values include: Read (r), Write (w), Delete (d), List (l), Add (a), Create\n (c), Update (u) and Process (p). Possible values include: 'r', 'd', 'w',\n 'l', 'a', 'c', 'u', 'p'\n :type permissions: str or :class:`enum\n `\n :param ip_address_or_range: An IP address or a range of IP addresses from\n which to accept requests.\n :type ip_address_or_range: str\n :param protocols: The protocol permitted for a request made with the\n account SAS. Possible values include: 'https,http', 'https'\n :type protocols: str or :class:`HttpProtocol\n `\n :param shared_access_start_time: The time at which the SAS becomes valid.\n :type shared_access_start_time: datetime\n :param shared_access_expiry_time: The time at which the shared access\n signature becomes invalid.\n :type shared_access_expiry_time: datetime\n :param identifier: A unique value up to 64 characters in length that\n correlates to an access policy specified for the container, queue, or\n table.\n :type identifier: str\n :param partition_key_start: The start of partition key.\n :type partition_key_start: str\n :param partition_key_end: The end of partition key.\n :type partition_key_end: str\n :param row_key_start: The start of row key.\n :type row_key_start: str\n :param row_key_end: The end of row key.\n :type row_key_end: str\n :param key_to_sign: The key to sign the account SAS token with.\n :type key_to_sign: str\n :param cache_control: The response header override for cache control.\n :type cache_control: str\n :param content_disposition: The response header override for content\n disposition.\n :type content_disposition: str\n :param content_encoding: The response header override for content\n encoding.\n :type content_encoding: str\n :param content_language: The response header override for content\n language.\n :type content_language: str\n :param content_type: The response header override for content type.\n :type content_type: str\n \"\"\"\n\n _validation = {\n 'canonicalized_resource': {'required': True},\n 'resource': {'required': True},\n 'identifier': {'max_length': 64},\n }\n\n _attribute_map = {\n 'canonicalized_resource': {'key': 'canonicalizedResource', 'type': 'str'},\n 'resource': {'key': 'signedResource', 'type': 'str'},\n 'permissions': {'key': 'signedPermission', 'type': 'str'},\n 'ip_address_or_range': {'key': 'signedIp', 'type': 'str'},\n 'protocols': {'key': 'signedProtocol', 'type': 'HttpProtocol'},\n 'shared_access_start_time': {'key': 'signedStart', 'type': 'iso-8601'},\n 'shared_access_expiry_time': {'key': 'signedExpiry', 'type': 'iso-8601'},\n 'identifier': {'key': 'signedIdentifier', 'type': 'str'},\n 'partition_key_start': {'key': 'startPk', 'type': 'str'},\n 'partition_key_end': {'key': 'endPk', 'type': 'str'},\n 'row_key_start': {'key': 'startRk', 'type': 'str'},\n 'row_key_end': {'key': 'endRk', 'type': 'str'},\n 'key_to_sign': {'key': 'keyToSign', 'type': 'str'},\n 'cache_control': {'key': 'rscc', 'type': 'str'},\n 'content_disposition': {'key': 'rscd', 'type': 'str'},\n 'content_encoding': {'key': 'rsce', 'type': 'str'},\n 'content_language': {'key': 'rscl', 'type': 'str'},\n 'content_type': {'key': 'rsct', 'type': 'str'},\n }\n\n def __init__(self, canonicalized_resource, resource, permissions=None, ip_address_or_range=None, protocols=None, shared_access_start_time=None, shared_access_expiry_time=None, identifier=None, partition_key_start=None, partition_key_end=None, row_key_start=None, row_key_end=None, key_to_sign=None, cache_control=None, content_disposition=None, content_encoding=None, content_language=None, content_type=None):\n self.canonicalized_resource = canonicalized_resource\n self.resource = resource\n self.permissions = permissions\n self.ip_address_or_range = ip_address_or_range\n self.protocols = protocols\n self.shared_access_start_time = shared_access_start_time\n self.shared_access_expiry_time = shared_access_expiry_time\n self.identifier = identifier\n self.partition_key_start = partition_key_start\n self.partition_key_end = partition_key_end\n self.row_key_start = row_key_start\n self.row_key_end = row_key_end\n self.key_to_sign = key_to_sign\n self.cache_control = cache_control\n self.content_disposition = content_disposition\n self.content_encoding = content_encoding\n self.content_language = content_language\n self.content_type = content_type\n","sub_path":"packages/autorest.python/test/unittests/storage_models/service_sas_parameters.py","file_name":"service_sas_parameters.py","file_ext":"py","file_size_in_byte":5880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"185590463","text":"import math\n\ndef quadratic(a,b,c):\n d = b*b-4*a*c\n if d >= 0:\n x = (-b+math.sqrt(d))/(2*a)\n y = (-b-math.sqrt(d))/(2*a)\n return x, y\n else:\n return 'no answer!'\n\nif __name__ == '__main__':\n a=quadratic(2, 3, 1)\n b=quadratic(1, 3, -4)\n print('quadratic(2,3,1) =', a)\n print('quadratic(1,3,4) =', b)\n\n if a != (-0.5, -1.0):\n print('测试失败')\n elif b != (1.0, -4.0):\n print('测试失败')\n else:\n print('测试成功')","sub_path":"函数/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"334204297","text":"from sklearn import linear_model\nfrom sklearn.linear_model import Ridge\nfrom sklearn.feature_extraction.text import TfidfTransformer\nimport pandas as pd\nimport math\nimport numpy as np\nimport pickle\nimport json\n\nimport read_data as rd\n\nX0 = rd.items.values\nX_train_counts = X0[:, -19:]\n\ncategory = np.array(['unknown ', 'Action ', 'Adventure ',\n 'Animation ', 'Children\\'s ', 'Comedy ', 'Crime ', 'Documentary ', 'Drama ', 'Fantasy ',\n 'Film-Noir ', 'Horror ', 'Musical ', 'Mystery ', 'Romance ', 'Sci-Fi ', 'Thriller ', 'War ', 'Western'])\n\n# lấy thể loại phim\n\n\ndef get_category(array):\n arr_category = []\n for id in array:\n category_item = category.dot(X_train_counts[id]).strip()\n arr_category.append(category_item)\n return np.array(arr_category)\n\n\n# tfidf\ntransformer = TfidfTransformer(smooth_idf=True, norm='l2')\ntfidf = transformer.fit_transform(X_train_counts.tolist()).toarray()\n\n# print(tfidf[[0, 1, 2, 3, 4], :])\n\n\ndef get_items_rated_by_user(rate_matrix, user_id):\n \"\"\"\n in each line of rate_matrix, we have infor: user_id, item_id, rating (scores), time_stamp\n we care about the first three values\n return (item_ids, scores) rated by user user_id\n \"\"\"\n y = rate_matrix[:, 0] # all users\n # item indices rated by user_id\n # we need to +1 to user_id since in the rate_matrix, id starts from 1\n # while index in python starts from 0\n ids = np.where(y == user_id + 1)[0]\n item_ids = rate_matrix[ids, 1] - 1 # index starts from 0\n scores = rate_matrix[ids, 2]\n return (item_ids, scores)\n\n\n# Tìm mô hình cho mỗi user\nd = tfidf.shape[1] # data dimension\nW = np.zeros((d, rd.n_users))\nb = np.zeros((1, rd.n_users))\n\n\nfilename = 'models/user_model_'\n\n\nfor n in range(rd.n_users):\n ids, scores = get_items_rated_by_user(rd.rate_train, n)\n clf = Ridge(alpha=0.01, fit_intercept=True)\n Xhat = tfidf[ids, :]\n\n clf.fit(Xhat, scores)\n\n # lưu model\n tuple_objects = (clf, Xhat, scores)\n pickle.dump(tuple_objects, open(filename + str(n+1) + '.pkl', 'wb'))\n\n W[:, n] = clf.coef_\n b[0, n] = clf.intercept_\n\n# predicted scores\n# Yhat = tfidf.dot(W) + b\n# # Ví dụ với với user có id=10\n# n = 0\n# np.set_printoptions(precision=2) # 2 digits after .\n# ids, scores = get_items_rated_by_user(rd.rate_test, n)\n\n# Yhat[n, ids]\n\n# Đánh giá mô hình\n\n\n# def evaluate(Yhat, rates, W, b):\n# se = 0\n# cnt = 0\n# for n in range(rd.n_users):\n# ids, scores_truth = get_items_rated_by_user(rates, n)\n# scores_pred = Yhat[ids, n]\n# e = scores_truth - scores_pred\n# se += (e*e).sum(axis=0)\n# cnt += e.size\n# return np.sqrt(se/cnt)\n\n\n# print('RMSE for training:', evaluate(Yhat, rd.rate_train, W, b))\n# print('RMSE for test :', evaluate(Yhat, rd.rate_test, W, b))\n\n\nn = 10\n\nids, ratings = get_items_rated_by_user(rd.rate_test, n-1)\n\nmovie_name = rd.items.values[ids, 1]\ncategory_list = get_category(ids)\n\n\npickled_model, pickled_Xhat, pickled_scores = pickle.load(\n open(filename + str(n) + '.pkl', 'rb'))\n\n\npredict = pickled_model.predict(tfidf[ids, :])\n\n# hiển thị theo dataframe pandas\ntable_user_item = pd.DataFrame(\n {'Rated movies ids': ids+[1], \"Name movie\": movie_name, 'category': category_list, 'Predicted ratings': predict})\n\n# Sort theo predict rating\ntable_sorted = table_user_item.sort_values(\n by='Predicted ratings', ascending=False)\n\nprint(table_sorted)\n\nresult = table_sorted.to_json(orient='records')\nparsed = json.loads(result)\nprint(json.dumps(parsed, indent=2))\n","sub_path":"content_base_filter.py","file_name":"content_base_filter.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"424867158","text":"import flask_wtf\nimport itertools\nimport os\nimport wtforms.fields as fields\nfrom wtforms.validators import DataRequired\n\nimport util\n\ntry:\n import ConfigParser as configparser\n from ConfigParser import SafeConfigParser\nexcept ImportError:\n import configparser\n from configparser import SafeConfigParser\n\n_none = object()\n_pass_thru = lambda x: x\nclass ConfigFile:\n _section = 'config'\n def __init__(self, path):\n self.path = path\n self.parser = SafeConfigParser()\n self.parser.read(path)\n\n def has(self, key):\n return self.parser.has_option(self._section, key)\n\n def get(self, key, default=_none, type=_pass_thru):\n try:\n return type(self.parser.get(self._section, key))\n except configparser.Error:\n if default is _none:\n raise\n else:\n return type(default)\n\n def set(self, key, value):\n if self._section not in self.parser.sections():\n self.parser.add_section(self._section)\n self.parser.set(self._section, key, str(value))\n\n def save(self):\n with open(self.path, 'w') as f:\n self.parser.write(f)\n\nconfig = ConfigFile('config.txt')\n\nclass ConfigForm(flask_wtf.Form):\n def __init__(self, *args, **kwargs):\n super(ConfigForm, self).__init__(*args, **kwargs)\n event_names = [('', '')]\n for f in os.listdir(util.abspath('match_schedules')):\n name, ext = os.path.splitext(f)\n if ext == '.json':\n event_names.append((name, name))\n self.event_name.choices = event_names\n\n computer_name = fields.StringField('Computer name',\n default=lambda: config.get('computer_name', None) or os.environ.get('COMPUTERNAME', None),\n validators=[DataRequired()])\n export_id = fields.IntegerField('Export ID',\n default=lambda: config.get('export_id', '1'),\n validators=[DataRequired()])\n station = fields.SelectField('Station',\n choices=[(name, name) for name in\n ['None'] + list(map(lambda item: ' '.join(map(str, item)),\n itertools.product(['Red', 'Blue'], [1, 2, 3])))],\n default=lambda: config.get('station', None))\n event_name = fields.SelectField('Event schedule',\n choices=[], default=lambda: config.get('event_name', ''))\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"244305483","text":"from flask import Flask, render_template, flash, redirect, url_for, session, logging, request\nfrom data import Products, Biokons\n# from produk import Products\n# from flask_mysqldb import MySQL\nfrom flaskext.mysql import MySQL\nfrom pymysql.cursors import DictCursor\nfrom flask_googlemaps import GoogleMaps\nfrom flask_googlemaps import Map, icons\n\nfrom wtforms import Form, StringField, TextAreaField, PasswordField, SelectField, validators\n# from passlib.hash import sha256_crypt\nfrom functools import wraps\n\nimport sys\n\napp = Flask(__name__)\n\nmysql = MySQL(cursorclass=DictCursor)\n\n#config MySQL\napp.config['MYSQL_DATABASE_HOST'] = 'localhost'\napp.config['MYSQL_DATABASE_USER'] = 'root'\napp.config['MYSQL_DATABASE_PASSWORD'] = '123'\napp.config['MYSQL_DATABASE_DB'] = 'biokonversi'\n# app.config['MYSQL_DATABASE_CURSORCLASS'] = 'DictCursor'\n\n# googlemaps config\napp.config['GOOGLEMAPS_KEY'] = \"AIzaSyCsC7xyIEr_nOZzitGARoVgpAyMeN9WoqQ\"\n\n# Init google maps\nGoogleMaps(app, key=\"AIzaSyCsC7xyIEr_nOZzitGARoVgpAyMeN9WoqQ\")\n\n#init MySQL\nmysql.init_app(app)\n\n# Articles = Articles()\n\nProducts = Products()\n\nBiokons = Biokons()\n\n# index\n@app.route('/')\ndef index():\n # create cursor\n cur = mysql.get_db().cursor()\n\n # get articles\n result = cur.execute(\"SELECT * FROM articles WHERE stat='post' ORDER BY id DESC LIMIT 2\")\n\n articles = cur.fetchall()\n\n # get testimoni\n result = cur.execute(\"SELECT * FROM testimonis WHERE stat='post' ORDER BY id DESC LIMIT 2\")\n\n testimonis = cur.fetchall()\n\n # get kegiatans\n result = cur.execute(\"SELECT * FROM kegiatans WHERE stat='post' ORDER BY id DESC LIMIT 2\")\n\n kegiatans = cur.fetchall()\n\n if result > 0:\n return render_template('index.html', articles=articles, testimonis=testimonis, kegiatans=kegiatans)\n else:\n msg='NO ARTICLES FOUND'\n return render_template('index.html', msg=msg)\n\n #close connection\n cur.close()\n # return render_template('index.html', articles = Articles)\n\n# produk\n@app.route('/produk')\ndef produk():\n return render_template('produk.html')\n\n@app.route('/produk_biokonversi')\ndef produk_biokonversi():\n return render_template('produk_biokonversi.html', products = Products)\n\n@app.route('/produk_biokonversi_detail_1')\ndef produk_biokonversi_detail_1():\n return render_template('produk_biokonversi_detail_1.html')\n\n@app.route('/produk_biokonversi_detail_2')\ndef produk_biokonversi_detail_2():\n return render_template('produk_biokonversi_detail_2.html')\n\n@app.route('/produk_biokonversi_detail_3')\ndef produk_biokonversi_detail_3():\n return render_template('produk_biokonversi_detail_3.html')\n\n@app.route('/produk_biokon')\ndef produk_biokon():\n return render_template('produk_biokon.html', biokons = Biokons)\n\n@app.route('/produk_biokon_detail_1')\ndef produk_biokon_detail_1():\n return render_template('produk_biokon_detail_1.html')\n\n@app.route('/produk_biokon_detail_2')\ndef produk_biokon_detail_2():\n return render_template('produk_biokon_detail_2.html')\n\n@app.route('/produk_biokon_detail_3')\ndef produk_biokon_detail_3():\n return render_template('produk_biokon_detail_3.html')\n\n@app.route('/produk_biokon_detail_4')\ndef produk_biokon_detail_4():\n return render_template('produk_biokon_detail_4.html')\n\n@app.route('/produk_biokon_detail_5')\ndef produk_biokon_detail_5():\n return render_template('produk_biokon_detail_5.html')\n\n\n@app.route('/tentang')\ndef tentang():\n return render_template('tentang.html')\n\n\n@app.route('/distribusi')\ndef distribusi():\n distributionmap = Map(\n identifier=\"distributionmap\",\n varname=\"distributionmap\",\n lat=-6.25,\n lng=106.83,\n maptype_control=False,\n # zoom=6,\n style=(\n \"height:500px;\"\n \"width:100%;\"\n \"box-shadow: 0px 5px 15px;\"\n ),\n scroll_wheel=False,\n # zoom_control=False,\n streetview_control=False,\n markers=[\n {\n # 'icon': icons.alpha.B,\n 'lat': -6.253787, \n 'lng': 106.833527,\n 'infobox': (\n \"
Toko Hobinosco
\"\n \"

Jl. Raya Cilangkap No.15, RT.1/RW.5,
Cipayung, Kota Jakarta Timur,
Daerah Khusus Ibukota Jakarta 13870

\"\n \"Tokopedia\"\n \"Bukalapak\"\n \"Shopee\"\n )\n },\n {\n # 'icon': icons.dots.blue,\n 'lat': -6.257317, \n 'lng': 106.819891,\n 'infobox': (\n \"
Toko Hobinosco
\"\n \"

Jl. Raya Cilangkap No.15, RT.1/RW.5,
Cipayung, Kota Jakarta Timur,
Daerah Khusus Ibukota Jakarta 13870

\"\n \"Tokopedia\"\n \"Bukalapak\"\n \"Shopee\"\n )\n },\n {\n # 'icon': '//maps.google.com/mapfiles/ms/icons/yellow-dot.png',\n 'lat': -6.238729, \n 'lng': 106.812288,\n 'infobox': (\n \"
Toko Hobinosco
\"\n \"

Jl. Raya Cilangkap No.15, RT.1/RW.5,
Cipayung, Kota Jakarta Timur,
Daerah Khusus Ibukota Jakarta 13870

\"\n \"Tokopedia\"\n \"Bukalapak\"\n \"Shopee\"\n )\n }\n ]\n )\n return render_template('distribusi.html', distributionmap = distributionmap)\n\n\n@app.route('/dokumen')\ndef dokumen():\n return render_template('dokumen.html')\n\n@app.route('/dokumen_isi//')\ndef dokumen_isi(id):\n # create cursor\n cur = mysql.get_db().cursor()\n\n # get article\n result = cur.execute(\"SELECT * FROM articles WHERE id = %s AND stat!='del'\", [id])\n\n article = cur.fetchone()\n\n return render_template('dokumen_isi.html', article = article)\n\n@app.route('/testimoni_isi//')\ndef testimoni_isi(id):\n # create cursor\n cur = mysql.get_db().cursor()\n\n # get testimoni\n result = cur.execute(\"SELECT * FROM testimonis WHERE id = %s AND stat!='del'\", [id])\n\n testimoni = cur.fetchone()\n\n return render_template('testimoni_isi.html', testimoni = testimoni)\n\n@app.route('/kegiatan_isi//')\ndef kegiatan_isi(id):\n # create cursor\n cur = mysql.get_db().cursor()\n\n # get kegiatan\n result = cur.execute(\"SELECT * FROM kegiatans WHERE id = %s AND stat!='del'\", [id])\n\n kegiatan = cur.fetchone()\n\n return render_template('kegiatan_isi.html', kegiatan = kegiatan)\n\n@app.route('/media')\ndef media():\n return render_template('media.html')\n\n@app.route('/kontak')\ndef kontak():\n return render_template('kontak.html')\n\n# Admin Login Panel\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n # Get Form Fields\n username = request.form['username']\n password_candidate = request.form['password']\n\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Get User by Username\n result = cur.execute(\"SELECT * FROM user WHERE username = %s\", [username])\n\n if result > 0:\n # get stored hash\n data = cur.fetchone()\n password = data['password']\n\n # compare the password\n if password == password_candidate:\n # Password Matched\n session['logged_in'] = True\n session['username'] = username\n return redirect(url_for('admin'))\n\n else:\n error = 'Invalid Passowrd'\n return render_template('login.html', error=error)\n\n #close connection\n cur.close()\n\n else:\n error = 'Username not found'\n return render_template('login.html', error=error)\n\n return render_template('login.html')\n\n# check if user logged in\ndef is_logged_in(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if 'logged_in' in session:\n return f(*args, **kwargs)\n else:\n return redirect(url_for('login'))\n return wrap\n\n@app.route('/logout')\ndef logout():\n session.clear()\n return redirect(url_for('login'))\n\n@app.route('/admin')\n@is_logged_in\ndef admin():\n # create cursor\n cur = mysql.get_db().cursor()\n\n # get articles\n result = cur.execute(\"SELECT * FROM articles WHERE stat!='del'\")\n\n articles = cur.fetchall()\n\n if result >0:\n return render_template('admin.html', articles=articles)\n else:\n msg='NO ARTICLES FOUND'\n return render_template('admin.html', msg=msg)\n\n #close connection\n cur.close()\n\n# Article Form Class\nclass ArticleForm(Form):\n title = StringField('Title', [validators.length(min=1, max=500)])\n body = TextAreaField('Body', [validators.length(min=10)])\n img = StringField('Img', [validators.length(min=1, max=100)])\n stat = SelectField('Stat', choices=[('arch', 'archive'), ('post', 'post')])\n \n@app.route('/buat_berita', methods=['GET', 'POST'])\n@is_logged_in\ndef buat_berita():\n form = ArticleForm(request.form)\n if request.method == 'POST' and form.validate():\n title = form.title.data\n body = form.body.data\n img = form.img.data\n stat = form.stat.data\n\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Execute\n cur.execute('INSERT INTO articles(title, body, img, stat) VALUES(%s, %s, %s, %s)', (title, body, img, stat))\n\n # Commit to DB\n mysql.get_db().commit()\n\n # Close Connection\n cur.close()\n\n return redirect(url_for('admin'))\n\n return render_template('buat_berita.html', form=form)\n\n@app.route('/edit_berita/', methods=['GET', 'POST'])\n@is_logged_in\ndef edit_berita(id):\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Execute\n result = cur.execute(\"SELECT * FROM articles WHERE id = %s\", [id])\n\n article = cur.fetchone()\n\n # get form\n form = ArticleForm(request.form)\n\n # populate article form fields\n form.title.data = article['title']\n form.body.data = article['body']\n form.img.data = article['img']\n form.stat.data = article['stat']\n\n if request.method == 'POST' and form.validate():\n title = request.form['title']\n body = request.form['body']\n img = request.form['img']\n stat = request.form['stat']\n\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Execute\n cur.execute('UPDATE articles SET title=%s, body=%s, img=%s, stat=%s WHERE id=%s', (title, body, img, stat, id))\n\n # Commit to DB\n mysql.get_db().commit()\n\n # Close Connection\n cur.close()\n\n return redirect(url_for('admin'))\n\n return render_template('edit_berita.html', form=form)\n\n# TESTIMONI\n@app.route('/view_testimoni')\n@is_logged_in\ndef view_testimoni():\n # create cursor\n cur = mysql.get_db().cursor()\n\n # get articles\n result = cur.execute(\"SELECT * FROM testimonis WHERE stat!='del'\")\n\n testimonis = cur.fetchall()\n\n if result >0:\n return render_template('view_testimoni.html', testimonis=testimonis)\n else:\n msg='NO ARTICLES FOUND'\n return render_template('view_testimoni.html', msg=msg)\n\n #close connection\n cur.close()\n\n# Testimoni Form Class\nclass TestimoniForm(Form):\n title = StringField('Title', [validators.length(min=1, max=500)])\n body = TextAreaField('Body', [validators.length(min=10)])\n img = StringField('Img', [validators.length(min=1, max=100)])\n stat = SelectField('Stat', choices=[('arch', 'archive'), ('post', 'post')])\n \n@app.route('/buat_testimoni', methods=['GET', 'POST'])\n@is_logged_in\ndef buat_testimoni():\n form = TestimoniForm(request.form)\n if request.method == 'POST' and form.validate():\n title = form.title.data\n body = form.body.data\n img = form.img.data\n stat = form.stat.data\n\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Execute\n cur.execute('INSERT INTO testimonis(title, body, img, stat) VALUES(%s, %s, %s, %s)', (title, body, img, stat))\n\n # Commit to DB\n mysql.get_db().commit()\n\n # Close Connection\n cur.close()\n\n return redirect(url_for('view_testimoni'))\n\n return render_template('buat_testimoni.html', form=form)\n\n@app.route('/edit_testimoni/', methods=['GET', 'POST'])\n@is_logged_in\ndef edit_testimoni(id):\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Execute\n result = cur.execute(\"SELECT * FROM testimonis WHERE id = %s\", [id])\n\n testimoni = cur.fetchone()\n\n # get form\n form = TestimoniForm(request.form)\n\n # populate article form fields\n form.title.data = testimoni['title']\n form.body.data = testimoni['body']\n form.img.data = testimoni['img']\n form.stat.data = testimoni['stat']\n\n if request.method == 'POST' and form.validate():\n title = request.form['title']\n body = request.form['body']\n img = request.form['img']\n stat = request.form['stat']\n\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Execute\n cur.execute('UPDATE testimonis SET title=%s, body=%s, img=%s, stat=%s WHERE id=%s', (title, body, img, stat, id))\n\n # Commit to DB\n mysql.get_db().commit()\n\n # Close Connection\n cur.close()\n\n return redirect(url_for('view_testimoni'))\n\n return render_template('edit_testimoni.html', form=form)\n\n\n# kegiatan\n@app.route('/view_kegiatan')\n@is_logged_in\ndef view_kegiatan():\n # create cursor\n cur = mysql.get_db().cursor()\n\n # get articles\n result = cur.execute(\"SELECT * FROM kegiatans WHERE stat!='del'\")\n\n kegiatans = cur.fetchall()\n\n if result >0:\n return render_template('view_kegiatan.html', kegiatans=kegiatans)\n else:\n msg='NO ARTICLES FOUND'\n return render_template('view_kegiatan.html', msg=msg)\n\n #close connection\n cur.close()\n\n# kegiatan Form Class\nclass kegiatanForm(Form):\n title = StringField('Title', [validators.length(min=1, max=500)])\n body = TextAreaField('Body', [validators.length(min=10)])\n img = StringField('Img', [validators.length(min=1, max=100)])\n stat = SelectField('Stat', choices=[('arch', 'archive'), ('post', 'post')])\n \n@app.route('/buat_kegiatan', methods=['GET', 'POST'])\n@is_logged_in\ndef buat_kegiatan():\n form = kegiatanForm(request.form)\n if request.method == 'POST' and form.validate():\n title = form.title.data\n body = form.body.data\n img = form.img.data\n stat = form.stat.data\n\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Execute\n cur.execute('INSERT INTO kegiatans(title, body, img, stat) VALUES(%s, %s, %s, %s)', (title, body, img, stat))\n\n # Commit to DB\n mysql.get_db().commit()\n\n # Close Connection\n cur.close()\n\n return redirect(url_for('view_kegiatan'))\n\n return render_template('buat_kegiatan.html', form=form)\n\n@app.route('/edit_kegiatan/', methods=['GET', 'POST'])\n@is_logged_in\ndef edit_kegiatan(id):\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Execute\n result = cur.execute(\"SELECT * FROM kegiatans WHERE id = %s\", [id])\n\n kegiatan = cur.fetchone()\n\n # get form\n form = kegiatanForm(request.form)\n\n # populate article form fields\n form.title.data = kegiatan['title']\n form.body.data = kegiatan['body']\n form.img.data = kegiatan['img']\n form.stat.data = kegiatan['stat']\n\n if request.method == 'POST' and form.validate():\n title = request.form['title']\n body = request.form['body']\n img = request.form['img']\n stat = request.form['stat']\n\n # Create Cursor\n cur = mysql.get_db().cursor()\n\n # Execute\n cur.execute('UPDATE kegiatans SET title=%s, body=%s, img=%s, stat=%s WHERE id=%s', (title, body, img, stat, id))\n\n # Commit to DB\n mysql.get_db().commit()\n\n # Close Connection\n cur.close()\n\n return redirect(url_for('view_kegiatan'))\n\n return render_template('edit_kegiatan.html', form=form)\n\n\nif __name__ == '__main__':\n app.secret_key = 'BIOKON2018'\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":16257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"344834518","text":"import os\nimport glob\n# Our numerical workhorses\nimport numpy as np\nimport pandas as pd\nimport scipy\n# Import matplotlib stuff for plotting\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\n# Seaborn, useful for graphics\nimport seaborn as sns\n\n# favorite Seaborn settings for notebooks\nrc={'lines.linewidth': 2,\n 'axes.labelsize' : 16,\n 'axes.titlesize' : 18,\n 'axes.facecolor' : 'F4F3F6',\n 'axes.edgecolor' : '000000',\n 'axes.linewidth' : 1.2,\n 'xtick.labelsize' : 13,\n 'ytick.labelsize' : 13,\n 'grid.linestyle' : ':',\n 'grid.color' : 'a6a6a6'}\nsns.set_context('notebook', rc=rc)\nsns.set_style('darkgrid', rc=rc)\nsns.set_palette(\"deep\", color_codes=True)\n\n#===============================================================================\n# define variables to use over the script\ndate = 20170422\nusername = 'nbellive'\n# run = 'r1'\n#operator = np.array(['01new007', '01new010', '01new011', '01new013','01new014'])\n\n# read the CSV file with the mean fold change\ndf = pd.read_csv('output/' + str(date) + '_' + 'O1new' + \\\n '_lacI_titration_MACSQuant.csv')\nrbs = df.rbs.unique()\noperator = df.operator.unique()\n\ndef set_color_cycle(self, clist=None):\n if clist is None:\n clist = rcParams['axes.color_cycle']\n self.color_cycle = itertools.cycle(clist)\n\n#===============================================================================\n\n# plot the curve for the 0 IPTG cultures\nplt.figure(figsize=(7, 7))\nbinding_energy = df.binding_energy.unique()\nfor i, op in enumerate(operator):\n repressor_array = np.logspace(0, 3, 200)\n fc_theory = 1 / (1 + 2 * repressor_array / 5E6 * np.exp(- binding_energy[i]))\n\n plt.plot(repressor_array, fc_theory)\n\n#reset color cycle to match colors\nplt.gca().set_color_cycle(None)\n\n#no_iptg = df.groupby('operator').get_group(0)\nfor op in operator:\n plt.plot(df[df.operator == op].repressors, df[df.operator == op].fold_change_A, \\\n marker='o', linewidth=0, label = op)\nplt.xscale('log')\nplt.yscale('log')\nplt.xlabel('repressor copy number')\nplt.ylabel('fold-change')\nplt.legend(loc='upper right')\nplt.tight_layout()\nplt.savefig('output/' + 'lacI_titration_ctrl.png')\n\n# Produce a second plot showing the cultures on a semi-log scale.\n\nplt.figure(figsize=(7, 7))\nbinding_energy = df.binding_energy.unique()\nfor i, op in enumerate(operator):\n repressor_array = np.logspace(0, 3, 200)\n fc_theory = 1 / (1 + 2 * repressor_array / 5E6 * np.exp(- binding_energy[i]))\n\n plt.plot(repressor_array, fc_theory)\n\n#reset color cycle to match colors\nplt.gca().set_color_cycle(None)\n\n#no_iptg = df.groupby('operator').get_group(0)\nfor op in operator:\n plt.plot(df[df.operator == op].repressors, df[df.operator == op].fold_change_A, \\\n marker='o', linewidth=0, label = op)\nplt.xscale('log')\nplt.xlabel('repressor copy number')\nplt.ylabel('fold-change')\nplt.legend(loc='upper right')\nplt.tight_layout()\nplt.savefig('output/' + 'lacI_titration_semilog.png')\n","sub_path":"code/processing/20170422_O1new/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"566688267","text":"# _*_ coding: utf-8 _*_\n\n\"\"\"\n保存经营异常,抽查检查\n\"\"\"\nfrom src.head import *\nfrom src.plugins.Enterprise.CommonEnterprisePlugin import *\n\nclass EnterprisePlugin00(CommonEnterprisePlugin):\n\n def __init__(self):\n pass\n\n def process(self, data_instance):\n __P4 = re.compile(\"\\\\d{4}\")\n db_query = CommonEnterprisePlugin._build_query(self, data_instance)\n\n if \"name\" in data_instance.dict.keys():\n data_instance.dict[\"name\"]=data_instance.dict[\"name\"].replace(\"。\",\"\")\n\n reg_no_temp=data_instance.dict[\"reg_no\"]\n reg_arr=reg_no_temp.split('/')\n if len(db_query) == 0 \\\n or (len(reg_arr)==2 and (reg_arr[0]==\"无\" or len(reg_arr[0])==15 or len(reg_arr[0])==18))\\\n or (not data_instance.dict[\"name\"] and\n not data_instance.dict[\"oper_name\"] and\n not data_instance.dict[\"start_date\"]):\n # RedisClient.lpush(CONFIG_R2M_ERROR_KEY_PREFIX + \"query\" + \"_enterpise_error\", json.dumps(data_instance.dict))\n RedisHub.lpush(\"R2M\", CONFIG_R2M_ERROR_KEY_PREFIX + \"query\" + \"_enterpise_error\", json.dumps(data_instance.dict))\n logging.warning(\"Invalid company..\")\n data_instance.dict[\"invalid\"] = True\n return\n\n org_ent_data,db_query = CommonEnterprisePlugin._find_org_ent(self, db_query, data_instance,data_instance.dict[\"history_names\"],data_instance.dict[\"province\"])\n\n temp_reg_no = \"\"\n if len(org_ent_data) > 0:\n temp_reg_no = org_ent_data[\"reg_no\"]\n else:\n temp_reg_no = data_instance.dict[\"reg_no\"]\n if self._is_special_words(temp_reg_no):\n return\n if \"abnormal_dtl_items\" in data_instance.dict.keys() and len(data_instance.dict[\"abnormal_dtl_items\"]) > 0:\n ####异常去重\n postjson = json.dumps(json.dumps(data_instance.dict[\"abnormal_dtl_items\"]))\n headers = {'Content-Type':'application/json'}\n try:\n response = requests.post(\"http://114.55.176.196/api/removal_duplicate_risk_info\", data=postjson, headers=headers, timeout=15)\n if response.ok or 200==response.status_code:\n data_instance.dict[\"abnormal_dtl_items\"] = json.loads(response.text) # [{\"department\": \"\", \"in_date\": \"\", \"_id\": \"djhtrhngkjkjfh\"}]\n except Exception as e:\n logging.exception(\"abnormal duplicate api not access.\")\n\n ####\n\n for ab_dtl in data_instance.dict[\"abnormal_dtl_items\"]:\n ab_dtl[\"reg_no\"] = temp_reg_no\n if temp_reg_no==\"110114010610343\":\n continue\n #if \"in_date\" in ab_dtl.keys():\n #ab_dtl[\"in_date\"]=CommonUtils.format_date(ab_dtl[\"in_date\"],\"%Y-%m-%d\")\n #if \"in_date\" in ab_dtl.keys():\n #ab_dtl[\"out_date\"]=CommonUtils.format_date(ab_dtl[\"out_date\"],\"%Y-%m-%d\")\n temp=CommonUtils.format_date(ab_dtl[\"in_date\"], \"%Y-%m-%d\")\n abnormal_valid=False\n if len(temp)>0:\n matcher =__P4.search(temp)\n if matcher is not None and len(matcher.group())>0 :\n abnormal_valid=True\n if len(temp)==0:\n abnormal_valid=True\n table_name=\"abnormals\"\n if not abnormal_valid:\n table_name=\"abnormal_errors\"\n db_query = self.__build_query(ab_dtl)\n db_update = self.__build_update(ab_dtl)\n data_instance.dict[\"abnormal_valid\"]=abnormal_valid\n #db_result = MongoDBDAO.find_and_modify(\"GS\",\"abnormals\",db_query,db_update)\n #if db_result is None:\n # db_result = MongoDBDAO.find_one(\"GS\",\"abnormals\",db_query)\n\n db_result = MongoDBDAO.update_one(\"GS\",table_name,db_query,db_update, True)\n ab_id = None\n if (not db_result[\"updatedExisting\"]) and db_result[\"n\"] == 1 and \"upserted\" in db_result.keys():\n # new record\n ab_id = str(db_result[\"upserted\"])\n elif db_result[\"updatedExisting\"] and db_result[\"n\"] == 1:\n # existing record\n db_result = MongoDBDAO.find_one(\"GS\", table_name, db_query)\n if db_result is not None:\n ab_id = str(db_result[\"_id\"])\n else:\n # logging.info(\"query result=%s\"%str(db_result))\n # logging.info(\"query string=%s\"%str(db_query))\n # logging.info(\"companyname=%s\"%str(data_instance.dict[\"name\"]))\n continue\n ab_dtl[\"_id\"] = ab_id\n #temp=\"abnormal\"+ab_id\n data_instance.dict[ab_id]=abnormal_valid\n if not self.__is_dulplicated(data_instance.dict[\"abnormal_items\"], ab_id):\n data_instance.dict[\"abnormal_items\"].append({\n \"item\":ObjectId(ab_id)\n })\n\n if \"checkup_dtl_items\" in data_instance.dict.keys() and len(data_instance.dict[\"checkup_dtl_items\"]) > 0:\n for cu_dtl in data_instance.dict[\"checkup_dtl_items\"]:\n cu_dtl[\"reg_no\"] = temp_reg_no\n #if \"date\" in cu_dtl.keys():\n #cu_dtl[\"date\"]=CommonUtils.format_date(cu_dtl[\"date\"],\"%Y-%m-%d\")\n temp=CommonUtils.format_date(cu_dtl[\"date\"],\"%Y-%m-%d\")\n checkup_valid=False\n if len(temp)>0:\n matcher =__P4.search(temp)\n if matcher:\n checkup_valid=True\n if len(temp)==0:\n checkup_valid=True\n table_name=\"checkups\"\n if not checkup_valid:\n table_name=\"checkups_errors\"\n\n db_query = self.__build_query_cu(cu_dtl)\n db_update = self.__build_update_cu(cu_dtl)\n data_instance.dict[\"checkup_valid\"]=checkup_valid\n #db_result = MongoDBDAO.find_and_modify(\"GS\",\"checkups\",db_query,db_update)\n #if db_result is None:\n # db_result = MongoDBDAO.find_one(\"GS\",\"checkups\",db_query)\n db_result = MongoDBDAO.update_one(\"GS\",table_name,db_query,db_update, True)\n cu_id = None\n if (not db_result[\"updatedExisting\"]) and db_result[\"n\"] == 1 and \"upserted\" in db_result.keys():\n # new record\n cu_id = str(db_result[\"upserted\"])\n elif db_result[\"updatedExisting\"] and db_result[\"n\"] == 1:\n # existing record\n db_result = MongoDBDAO.find_one(\"GS\", table_name, db_query)\n cu_id = str(db_result[\"_id\"])\n cu_dtl[\"_id\"] = cu_id\n #temp=\"checkup\"+cu_id\n data_instance.dict[cu_id]=checkup_valid\n if not self.__is_dulplicated(data_instance.dict[\"checkup_items\"], cu_id):\n data_instance.dict[\"checkup_items\"].append({\n \"item\":ObjectId(cu_id)\n })\n\n def __is_dulplicated(self, object_id_list, new_object_id):\n result = False\n for item in object_id_list:\n if str(item[\"item\"]) == str(new_object_id):\n result = True\n break\n return result\n\n def __build_query(self, ab_dtl):\n db_query = {}\n db_or_list = []\n db_query[\"reg_no\"] = ab_dtl[\"reg_no\"]\n date1=\"\"\n date2=CommonUtils.format_date(ab_dtl[\"in_date\"],\"%Y-%m-%d\")\n if ab_dtl[\"in_date\"] is None:\n date1 = \"null\"\n else:\n date1 = ab_dtl[\"in_date\"]\n db_or_list.append({\"in_date\":date1})\n if date1!=date2:\n db_or_list.append({\"in_date\":date2})\n if len(db_or_list) > 1:\n db_query[\"$or\"] = db_or_list\n else:\n db_query[db_or_list[0].keys()[0]] = db_or_list[0].values()[0]\n db_query[\"in_reason\"] = ab_dtl[\"in_reason\"]\n return db_query\n\n def __build_update(self, ab_dtl):\n db_update = {}\n db_update[\"name\"] = ab_dtl[\"name\"]\n db_update[\"reg_no\"] = ab_dtl[\"reg_no\"]\n db_update[\"province\"] = ab_dtl[\"province\"]\n db_update[\"in_reason\"] = ab_dtl[\"in_reason\"]\n if ab_dtl[\"in_date\"] is None:\n db_update[\"in_date\"] = \"null\"\n else:\n db_update[\"in_date\"] = CommonUtils.format_date(ab_dtl[\"in_date\"],\"%Y-%m-%d\")\n db_update[\"out_reason\"] = ab_dtl[\"out_reason\"]\n db_update[\"out_date\"] =CommonUtils.format_date(ab_dtl[\"out_date\"],\"%Y-%m-%d\")\n db_update[\"department\"] = ab_dtl[\"department\"]\n db_update[\"last_update_time\"] = datetime.datetime.utcnow()\n return {\"$set\": db_update}\n\n def __build_query_cu(self, cu_dtl):\n db_query = {}\n db_or_list = []\n db_query[\"reg_no\"] = cu_dtl[\"reg_no\"]\n date1=\"\"\n date2=CommonUtils.format_date(cu_dtl[\"date\"],\"%Y-%m-%d\")\n if cu_dtl[\"date\"] is None:\n date1 = \"null\"\n else:\n date1 = cu_dtl[\"date\"]\n db_or_list.append({\"date\":date1})\n if date1!=date2:\n db_or_list.append({\"date\":date2})\n if len(db_or_list) > 1:\n db_query[\"$or\"] = db_or_list\n else:\n db_query[db_or_list[0].keys()[0]] = db_or_list[0].values()[0]\n db_query[\"department\"] = cu_dtl[\"department\"]\n return db_query\n\n def __build_update_cu(self, cu_dtl):\n db_update = {}\n db_update[\"name\"] = cu_dtl[\"name\"]\n db_update[\"reg_no\"] = cu_dtl[\"reg_no\"]\n db_update[\"province\"] = cu_dtl[\"province\"]\n db_update[\"type\"] = cu_dtl[\"type\"]\n if cu_dtl[\"date\"] is None:\n db_update[\"date\"] = \"null\"\n else:\n db_update[\"date\"] = CommonUtils.format_date(cu_dtl[\"date\"],\"%Y-%m-%d\")\n db_update[\"result\"] = cu_dtl[\"result\"]\n db_update[\"department\"] = cu_dtl[\"department\"]\n db_update[\"last_update_time\"] = datetime.datetime.utcnow()\n return {\"$set\": db_update}\n\n def __call__(self):\n pass\n\n\n","sub_path":"source/src/plugins/Enterprise/EnterprisePlugin00.py","file_name":"EnterprisePlugin00.py","file_ext":"py","file_size_in_byte":10318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"559150295","text":"from restful.decorators import restful_view_templates\nfrom django.views.generic.base import View\n\nfrom restful.exception.verbose import VerboseRedirectException\nfrom ecomap.services import *\n\n@restful_view_templates\nclass HomeView(View):\n def get(self, request):\n criteria = {\n \"types\": request.params.getlist('types[]')\n }\n bounds = BoundsForm(data=request.params, prefix='bounds')\n if bounds.is_valid():\n criteria[\"bounds\"] = bounds.cleaned_data\n return {\n 'recyclables': RecycleMaterialService.get_all(),\n 'spot_types': RecycleSpotType.objects.all(),\n }\n\n def put(self, request):\n # ...nothing happens here yet, test redirection with errors...\n failure = VerboseRedirectException('Unable to change home page').set_redirect('home')\n # ...processing changes on home page...\n # Ooops, an error occurred\n raise failure.add_error('sidebar', 'Your chosen sidebar widgets are unavailable')\n","sub_path":"ecomap/views/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"345469264","text":"from nose.tools import set_trace, eq_, assert_raises\n\nfrom . import (\n DatabaseTest,\n)\n\nfrom core.lane import (\n Lane,\n LaneList,\n)\nfrom core.metadata_layer import Metadata\n\nfrom api.config import (\n Configuration,\n temp_config,\n)\nfrom api.lanes import (\n make_lanes,\n make_lanes_default,\n lanes_for_large_collection,\n lane_for_small_collection,\n lane_for_other_languages,\n RecommendationLane,\n RelatedBooksLane,\n SeriesLane,\n)\nfrom api.novelist import MockNoveListAPI\n\n\nclass TestLaneCreation(DatabaseTest):\n\n def test_lanes_for_large_collection(self):\n languages = ['eng', 'spa']\n lanes = lanes_for_large_collection(self._db, languages)\n [lane] = lanes\n\n # We have one top-level lane for English & Spanish\n eq_('English & Spanish', lane.name)\n assert lane.invisible\n\n # The top-level lane has five sublanes.\n eq_(\n ['English & Spanish - Best Sellers', 'Adult Fiction', 'Adult Nonfiction', 'Young Adult Fiction', \n 'Young Adult Nonfiction', 'Children and Middle Grade'],\n [x.name for x in lane.sublanes]\n )\n\n # They all are restricted to English and Spanish.\n assert all(x.languages==languages for x in lane.sublanes)\n\n # The Adult Fiction and Adult Nonfiction lanes reproduce the\n # genre structure found in the genre definitions.\n fiction, nonfiction = lane.sublanes.lanes[1:3]\n [sf] = [x for x in fiction.sublanes.lanes if x.name=='Science Fiction']\n [periodicals] = [x for x in nonfiction.sublanes.lanes if x.name=='Periodicals']\n [humor] = [x for x in nonfiction.sublanes.lanes if x.name=='Humorous Nonfiction']\n eq_(True, sf.fiction)\n eq_(\"Science Fiction\", sf.name)\n eq_(\"Humor\", humor.display_name)\n assert 'Science Fiction' in sf.genre_names\n assert 'Cyberpunk' in sf.genre_names\n assert periodicals.invisible\n\n [space_opera] = [x for x in sf.sublanes.lanes if x.name=='Space Opera']\n eq_(True, sf.fiction)\n eq_(\"Space Opera\", space_opera.name)\n eq_([\"Space Opera\"], space_opera.genre_names)\n\n [history] = [x for x in nonfiction.sublanes.lanes if x.name=='History']\n eq_(False, history.fiction)\n eq_(\"History\", history.name)\n assert 'History' in history.genre_names\n assert 'European History' in history.genre_names\n\n def test_lane_for_small_collection(self):\n lane = lane_for_small_collection(self._db, ['eng', 'spa', 'chi'])\n eq_(\"English, Spanish, & Chinese\", lane.display_name)\n sublanes = lane.sublanes.lanes\n eq_(\n ['Adult Fiction', 'Adult Nonfiction', 'Children & Young Adult'],\n [x.name for x in sublanes]\n )\n eq_(\n [set(['Adults Only', 'Adult']), \n set(['Adults Only', 'Adult']), \n set(['Young Adult', 'Children'])],\n [x.audiences for x in sublanes]\n )\n eq_([True, False, Lane.BOTH_FICTION_AND_NONFICTION],\n [x.fiction for x in sublanes]\n )\n\n def test_lane_for_other_languages(self):\n\n with temp_config() as config:\n config[Configuration.POLICIES] = {\n Configuration.LANGUAGE_POLICY: {\n Configuration.TINY_COLLECTION_LANGUAGES : 'ger,fre,ita'\n }\n }\n\n exclude = ['eng', 'spa']\n lane = lane_for_other_languages(self._db, exclude)\n eq_(None, lane.languages)\n eq_(exclude, lane.exclude_languages)\n eq_(\"Other Languages\", lane.name)\n eq_(\n ['German', 'French', 'Italian'],\n [x.name for x in lane.sublanes.lanes]\n )\n eq_([['ger'], ['fre'], ['ita']],\n [x.languages for x in lane.sublanes.lanes]\n )\n\n # If no tiny languages are configured, the other languages lane\n # doesn't show up.\n with temp_config() as config:\n config[Configuration.POLICIES] = {\n Configuration.LANGUAGE_POLICY: {\n Configuration.LARGE_COLLECTION_LANGUAGES : 'eng'\n }\n }\n\n exclude = ['eng', 'spa']\n lane = lane_for_other_languages(self._db, exclude)\n eq_(None, lane)\n\n def test_make_lanes_default(self):\n with temp_config() as config:\n config[Configuration.POLICIES] = {\n Configuration.AUTHENTICATION_POLICY : \"Millenium\",\n Configuration.LANGUAGE_POLICY : {\n Configuration.LARGE_COLLECTION_LANGUAGES : 'eng',\n Configuration.SMALL_COLLECTION_LANGUAGES : 'spa,chi',\n Configuration.TINY_COLLECTION_LANGUAGES : 'ger,fre,ita'\n }\n }\n lane_list = make_lanes_default(self._db)\n\n assert isinstance(lane_list, LaneList)\n lanes = lane_list.lanes\n\n # We have a top-level lane for the large collections,\n # a top-level lane for each small collection, and a lane\n # for everything left over.\n eq_(['English', 'Spanish', 'Chinese', 'Other Languages'],\n [x.name for x in lane_list.lanes]\n )\n\n english_lane = lanes[0]\n eq_(['English - Best Sellers', 'Adult Fiction', 'Adult Nonfiction', 'Young Adult Fiction', 'Young Adult Nonfiction', 'Children and Middle Grade'],\n [x.name for x in english_lane.sublanes.lanes]\n )\n eq_(['Best Sellers', 'Fiction', 'Nonfiction', 'Young Adult Fiction', 'Young Adult Nonfiction', 'Children and Middle Grade'],\n [x.display_name for x in english_lane.sublanes.lanes]\n )\n\n\nclass TestRelatedBooksLane(DatabaseTest):\n\n def test_initialization(self):\n \"\"\"Asserts that a RelatedBooksLane won't be initialized for a work\n without related books\n \"\"\"\n work = self._work(with_license_pool=True)\n [lp] = work.license_pools\n with temp_config() as config:\n # A book without a series on a circ manager without\n # NoveList recommendations raises an error.\n config['integrations'][Configuration.NOVELIST_INTEGRATION] = {}\n assert_raises(\n ValueError, RelatedBooksLane, self._db, lp, \"\"\n )\n\n # But a book from a series initializes a RelatedBooksLane just fine.\n lp.presentation_edition.series = \"All By Myself\"\n result = RelatedBooksLane(self._db, lp, \"\")\n eq_(lp, result.license_pool)\n [sublane] = result.sublanes\n eq_(True, isinstance(sublane, SeriesLane))\n\n with temp_config() as config:\n config['integrations'][Configuration.NOVELIST_INTEGRATION] = {\n Configuration.NOVELIST_PROFILE : 'library',\n Configuration.NOVELIST_PASSWORD : 'sure'\n }\n # When NoveList is configured and recommendations are available,\n # a RecommendationLane will be included.\n mock_api = MockNoveListAPI()\n response = Metadata(\n lp.data_source, recommendations=[self._identifier()]\n )\n mock_api.setup(response)\n result = RelatedBooksLane(self._db, lp, \"\", novelist_api=mock_api)\n eq_(2, len(result.sublanes))\n recommendations, series = result.sublanes\n eq_(True, isinstance(recommendations, RecommendationLane))\n eq_(True, isinstance(series, SeriesLane))\n","sub_path":"tests/test_lanes.py","file_name":"test_lanes.py","file_ext":"py","file_size_in_byte":7604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"307622342","text":" \n#\n# This is the main file for our Tkinter Student program \n# \n\nstudents = []\n\n\ndef get_students_titlecase():\n students_titlecase = []\n for student in students:\n students_titlecase.append(str(student[0]).title())\n students_titlecase.append(str(student[1]).title())\n return students_titlecase\n\n\ndef print_students_titlecase():\n students_titlecase = get_students_titlecase()\n print(students_titlecase)\n\n\ndef add_student(first_name, last_name, student_id):\n student = {\"first_name\": first_name, \n \"last_name\": last_name, \n \"student_id\": student_id}\n students.append(student)\n \n\ndef save_file(student):\n with open(\"students.txt\", \"a\") as f:\n f.write(\"{0}, {1} - {2}\".format(new_student[1], \n new_student[0],\n new_student[2])+ \"\\n\")\n \ndef read_file():\n with open(\"students.txt\", \"r\")as f:\n for student in f.readlines():\n add_student(student[0], \n student[1], \n student[2])\n\nread_file()\n\nprint_students_titlecase()\n\nmore_students = True\n\nwhile more_students is True:\n student_first_name = input(\"Enter student first name: \")\n student_last_name = input(\"Please eenter student last name: \")\n student_id = input(\"Enter student ID: \")\n new_student = [student_first_name, student_last_name, student_id]\n yn = input(\"Would you like to enter another student? [y/n]:\")\n if yn == 'n' or 'N':\n print_students_titlecase()\n break\n continue\n\nadd_student(student_first_name, student_last_name, student_id)\nsave_file(new_student)\n\n","sub_path":"TkPy_student/student_functions.py","file_name":"student_functions.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"528828668","text":"import os\nimport sys\n\nclass Environment:\n\n PATH = \".env\"\n\n class Vars:\n CONFIG_PATH = \"CONFIG_PATH\"\n PATH_TO_PORTS_FILE = \"PATH_TO_PORTS_FILE\"\n PATH_TO_VESSEL_MOVEMENTS_DATA = \"PATH_TO_VESSEL_MOVEMENTS_DATA\"\n PATH_TO_OD_FILE = \"PATH_TO_OD_FILE\"\n PATH_TO_OUTPUT_DIRECTORY = \"PATH_TO_OUTPUT_DIRECTORY\"\n PATH_TO_LOG_FILE_DIRECTORY = \"PATH_TO_LOG_FILE_DIRECTORY\"\n\n @classmethod\n def set(cls):\n env_path: str = sys.argv[1].strip() if len(sys.argv) > 1 else cls.PATH\n with open(env_path, 'r') as env_file:\n for line in env_file.readlines():\n var, value = line.strip().split(\"=\")\n os.environ[var] = value\n","sub_path":"ocean_pta_training/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"131694679","text":"import cv2 as cv\nimport numpy as np\n\nwidth = 640\nheight = 480\n\ncap = cv.VideoCapture(0)\nwhile(1):\n # Take each frame\n _, frame = cap.read()\n # Convert BGR to HSV\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\n # define range of color in HSV\n color = np.uint8([[frame[int(height/2)][int(width/2)]]])\n hsv_color = cv.cvtColor(color,cv.COLOR_BGR2HSV)\n print(hsv_color[0][0][0])\n lower_color = np.array([hsv_color[0][0][0]-5,50,50])\n upper_color = np.array([hsv_color[0][0][0]+5,255,255])\n # Threshold the HSV image to get only color colors\n mask = cv.inRange(hsv, lower_color, upper_color)\n # Close and open image\n kernel = np.ones((6,6),np.uint8)\n binclose = cv.erode(mask, kernel)\n binopen = cv.dilate(binclose, kernel)\n # Bitwise-AND mask and original image\n res = cv.bitwise_and(frame,frame, mask= binopen)\n\n cv.line(frame, (int(width/2), int(height/2) - 10), (int(width/2), int(height/2) + 10), (255,255,255), 2)\n cv.line(frame, (int(width/2) - 10, int(height/2)), (int(width/2) + 10, int(height/2)), (255,255,255), 2)\n\n cv.imshow('frame',frame)\n cv.imshow('mask',mask)\n cv.imshow('res',res)\n cv.imshow('binclose',binclose)\n cv.imshow('binopen',binopen)\n k = cv.waitKey(5) & 0xFF\n if k == 27:\n break\ncv.destroyAllWindows()\n\n\n","sub_path":"Projet Perso/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"167021266","text":"import pandas as pd\n\nfilename2='world_bank.csv'\nGDP=pd.read_csv(filename2, skiprows=4)\nGDP.rename(columns={'Country Name':'Country'}, inplace=True)\nGDP.drop(['Indicator Code', 'Indicator Name'],axis=1, inplace=True)\ntrailers = [', The', ', Fed', ', Arab', ', Islam', ' SAR, China', ', FYR']\nfor trailer in trailers:\n GDP['Country'] = GDP['Country'].apply(lambda x: x.split(trailer)[0])\n\nGDP.replace({'Virgin Islands (U.S.)':'United States Virgin Islands',\n 'Congo, Dem. Rep.': 'Democratic Republic of the Congo',\n 'Congo, Rep.':'Congo',\n 'Korea, Dem. People’s Rep.':'North Korea',\n 'Sint Maarten (Dutch part)':'Sint Maarten',\n 'Yemen, Rep.':'Yemen',\n 'Venezuela, RB':'Venezuela',\n 'St. Martin (French part)':'St. Martin'}, inplace=True)\n\n#GDP.set_index('Country', inplace=True)\nGDP.to_csv('data/world_bank_clean.csv')\nprint(GDP.head())","sub_path":"world_bank_cleaning.py","file_name":"world_bank_cleaning.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"641039244","text":"import pandas as pd\nimport tempfile\n\ndef fileToString(inputFileName, limit=100):\n # temp = tempfile.NamedTemporaryFile(mode='w+t')\n input = open(inputFileName, \"r\")\n temp = open('temp.csv',\"w\")\n\n temp.write('rsid,chromosome,position,genotype\\n')\n\n for line in input:\n if not line.lstrip().startswith(\"#\"):\n temp.write(line.replace('\\t',','))\n \n input.close()\n temp.close()\n\n df = pd.read_csv('temp.csv')\n saved_column = df.genotype\n \n dnaString = \"\"\n\n for stuff in saved_column:\n if len(dnaString) <= limit:\n dnaString = dnaString + stuff\n\n return dnaString\n\ndef split(word): \n return [char for char in word] \n\ndef stringToFile(originalFile, modifiedList):\n testBool = True\n output = open('modifiedDNA.txt', \"w\")\n original = open(originalFile, \"r\")\n count = 10\n lineCount = 0\n\n for line in original:\n \n if not line.lstrip().startswith(\"#\"):\n lineCount+=1\n temp = line.split(\"\\t\")\n # print(lineCount)\n i = float(count)/float(2)\n # print(str(i) + \" - \" + str(float(lineCount)))\n if i == float(lineCount):\n if len(modifiedList) >= count:\n tempLine = line.split('\\t')\n dnaPair = tempLine[3].split()\n stringTemp = \"\"\n stringTemp = dnaPair[0]\n dnaPair = split(stringTemp)\n dnaPair[1] = modifiedList[count-1]\n stringTemp = \"\".join(dnaPair)\n tempLine[3] = stringTemp\n output.write('\\t'.join(tempLine)+'\\n')\n else: \n output.write('\\t'.join(temp))\n if (lineCount % 5) == 0:\n count+=10\n else:\n output.write(line)\n\n# Testing this out \n# stringToFile('orta_dna.txt', 'EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE')\n\n# This is a testing zone \n# print(convertToCSV('orta_dna.txt',200))\n","sub_path":"dnaToString.py","file_name":"dnaToString.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569128191","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: longshuicui\n@date : 2021/2/1\n@function:\n413. Arithmetic Slices (Medium)\nhttps://leetcode.com/problems/arithmetic-slices/\n题目描述\n 给定一个数组,求这个数组中连续且等差的子数组一共有多少个。返回等差数列的个数\n输入输出样例\n 输入是一个一维数组,输出是满足等差条件的连续字数组个数。\n Input: nums = [1,2,3,4]\n Output: 3\n 在这个样例中,等差数列有 [1,2,3]、 [2,3,4] 和 [1,2,3,4]。\n题解\n 要求是等差数列,所以满足 nums[i]-nums[i-1]=nums[i-1]-nums[i-2]\n 返回等差数列的个数,数列中元素的个数不能小于三个\n 该题最后需要对dp数组求和\n\"\"\"\n\n\ndef numberOfArithmeticSlices(nums):\n if len(nums)<3:\n return 0\n dp=[0,0]\n for i in range(2,len(nums)):\n if nums[i]-nums[i-1]==nums[i-1]-nums[i-2]:\n dp.append(dp[i-1]+1)\n else:\n dp.append(0)\n return sum(dp)\n\n\nnums=[1,2,3,5,6,7,8]\ncnt=numberOfArithmeticSlices(nums)\nprint(cnt)","sub_path":"06.动态规划/一维动态规划/413.Arithmetic Slices (Medium).py","file_name":"413.Arithmetic Slices (Medium).py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"638790207","text":"from threading import Thread\nimport socket\nimport sys\n\nserver_addr = ('127.0.0.1', 9999)\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)\nmy_name = input('Enter your name: ')\nsock.sendto(my_name.encode(), server_addr)\nprint(\"enter the name of the person you want to send a message + space and the message\")\n\n\ndef output_recvfrom(sock):\n while True:\n data, _ = sock.recvfrom(1024)\n if not data: break\n print(data.decode())\n\n\nx = Thread(target=output_recvfrom, args=(sock,))\nx.start()\nfor line in sys.stdin:\n line = f\"{my_name} \" + line\n sock.sendto(line.strip().encode(), server_addr)\nsock.close()\nx.join()\n","sub_path":"client2.py","file_name":"client2.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"358008544","text":"#\n# Copyright 2017 Red Hat, Inc.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n#\n# Refer to the README and COPYING files for full details of the license\n#\nimport nose.tools as nt\nfrom ovirtlago import testlib\nimport ovirtsdk4\n\nimport test_utils\n\nDC_NAME = 'test-dc'\nCLUSTER_NAME = 'test-cluster'\n\nSD_SECOND_NFS_NAME = 'second-nfs'\nVM2_NAME = 'vm2'\n\n\ndef _mac_value(mac):\n return int(mac.replace(':', ''), base=16)\n\n\ndef _get_storage_domain(root, name, service=False):\n storage_domains = root.storage_domains_service()\n # AttachedStorageDomainsService.list doesn't have the 'search' parameter\n # (StorageDomainsService.list does but this helper is overloaded)\n sd = next(sd for sd in storage_domains.list() if sd.name == name)\n return storage_domains.storage_domain_service(sd.id) if service else sd\n\n\ndef _get_vm_service(root, name, unregistered=None):\n virtual_machines = root.vms_service()\n # StorageDomainVmsService.list has no 'search' parameter and ignores\n # query={'name': 'spam'} so we have to do the filtering ourselves\n vm = next(vm for vm in virtual_machines.list(query={\n 'unregistered': unregistered}) if vm.name == name)\n return virtual_machines.vm_service(vm.id)\n\n\n@testlib.with_ovirt_api4\ndef deactivate_storage_domain(connection):\n dc = test_utils.data_center_service(connection.system_service(), DC_NAME)\n\n _get_storage_domain(dc, SD_SECOND_NFS_NAME, service=True).deactivate()\n\n testlib.assert_equals_within_short(\n lambda: _get_storage_domain(dc, SD_SECOND_NFS_NAME).status,\n ovirtsdk4.types.StorageDomainStatus.MAINTENANCE)\n\n\n@testlib.with_ovirt_api4\ndef detach_storage_domain(connection):\n engine = connection.system_service()\n dc = test_utils.data_center_service(engine, DC_NAME)\n\n _get_storage_domain(dc, SD_SECOND_NFS_NAME, service=True).remove()\n\n testlib.assert_equals_within_short(\n lambda: _get_storage_domain(engine, SD_SECOND_NFS_NAME).status,\n ovirtsdk4.types.StorageDomainStatus.UNATTACHED)\n\n\n@testlib.with_ovirt_api4\ndef reattach_storage_domain(connection):\n engine = connection.system_service()\n dc = test_utils.data_center_service(engine, DC_NAME)\n sd = _get_storage_domain(engine, SD_SECOND_NFS_NAME)\n\n dc.storage_domains_service().add(sd)\n\n testlib.assert_equals_within_short(\n lambda: _get_storage_domain(dc, SD_SECOND_NFS_NAME).status,\n ovirtsdk4.types.StorageDomainStatus.ACTIVE)\n\n\n@testlib.with_ovirt_api4\ndef import_lost_vm(connection):\n engine = connection.system_service()\n sd = _get_storage_domain(engine, SD_SECOND_NFS_NAME, service=True)\n lost_vm = _get_vm_service(sd, VM2_NAME, unregistered=True)\n\n lost_vm.register(\n cluster=ovirtsdk4.types.Cluster(name=CLUSTER_NAME),\n vm=ovirtsdk4.types.Vm(name=VM2_NAME),\n reassign_bad_macs=True)\n\n vm = _get_vm_service(engine, VM2_NAME)\n vm_nic = vm.nics_service().list()[0]\n mac_address = _mac_value(vm_nic.mac.address)\n\n default_mac_pool = engine.mac_pools_service().list()[0]\n mac_range = default_mac_pool.ranges[0]\n\n nt.assert_greater_equal(mac_address, _mac_value(mac_range.from_))\n nt.assert_less_equal(mac_address, _mac_value(mac_range.to))\n\n\n_TEST_LIST = [\n deactivate_storage_domain,\n detach_storage_domain,\n reattach_storage_domain,\n import_lost_vm,\n]\n\n\ndef test_gen():\n for t in testlib.test_sequence_gen(_TEST_LIST):\n test_gen.__name__ = t.description\n yield t\n","sub_path":"basic-suite-master/test-scenarios/007_sd_reattach.py","file_name":"007_sd_reattach.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"252870651","text":"#\n# Copyright (c) 2013-2014, Prometheus Research, LLC\n#\n\n\nfrom rex.core import Error, guard, MaybeVal, StrVal, BoolVal, MapVal\nfrom rex.web import authorize, trusted, confine, render_to_response\nfrom .load import _merge\nfrom .map import Map\nfrom webob.exc import HTTPUnauthorized, HTTPForbidden\nimport os.path\n\n\nclass TemplateRenderer:\n # Renders a Jinja template.\n\n def __init__(self, path, template, access, unsafe,\n parameters, context):\n # Path mask for extracting labeled segments.\n self.path = path\n # Package path to the template.\n self.template = template\n # Permission to request the URL.\n self.access = access\n # If set, enables CSRF protection.\n self.unsafe = unsafe\n # Maps parameter names to default values.\n self.parameters = parameters\n # Maps parameter names and segment labels to their validators (TODO).\n self.validates = {}\n # Arguments to pass to the template.\n self.context = context\n\n def __call__(self, req):\n # Check permissions.\n self.authorize(req)\n with confine(req, self):\n # Parse the URL and prepare template arguments.\n try:\n context = self.parse(req)\n except Error as error:\n return req.get_response(error)\n # Render the template.\n return render_to_response(self.template, req, **context)\n\n def authorize(self, req):\n # Check access permissions.\n if not authorize(req, self.access):\n raise HTTPUnauthorized()\n # Protect against CSRF attacts.\n if self.unsafe and not trusted(req):\n raise HTTPForbidden()\n\n def parse(self, req):\n # Start with regular context parameters.\n context = self.context.copy()\n # Reject unknown parameters.\n for name in sorted(req.params):\n if not (name in self.parameters or name.startswith('_')):\n raise Error(\"Received unexpected parameter:\", name)\n # Process expected parameters.\n for name in sorted(self.parameters):\n all_values = req.params.getall(name)\n if not all_values:\n value = self.parameters[name]\n elif len(all_values) > 1:\n raise Error(\"Got multiple values for parameter:\", name)\n else:\n [value] = all_values\n # TODO:\n #if name in self.validates:\n # with guard(\"While parsing parameter:\", name):\n # value = self.validates[name](value)\n context[name] = value\n # Process segment labels.\n for label, segment in sorted(self.path(req.path_info).items()):\n # TODO:\n #if label in self.validates:\n # with guard(\"While parsing segment:\", \"$\"+label):\n # segment = self.validates[label](segment)\n context[label] = segment\n return context\n\n\nclass MapTemplate(Map):\n # Parses a `template` entry.\n\n fields = [\n ('template', StrVal(r'[/0-9A-Za-z:._-]+')),\n ('access', StrVal, None),\n ('unsafe', BoolVal, False),\n ('parameters', MapVal(StrVal(r'[A-Za-z_][0-9A-Za-z_]*'),\n MaybeVal(StrVal)), {}),\n ('context', MapVal(StrVal(r'[A-Za-z_][0-9A-Za-z_]*')), {}),\n ]\n\n def __call__(self, spec, path, context):\n context = _merge(context, spec.context)\n access = spec.access or self.package.name\n return TemplateRenderer(\n path=path,\n template=spec.template,\n access=access,\n unsafe=spec.unsafe,\n parameters=spec.parameters,\n context=context)\n\n def override(self, spec, override_spec):\n if override_spec.template is not None:\n spec = spec.__clone__(template=override_spec.template)\n if override_spec.access is not None:\n spec = spec.__clone__(access=override_spec.access)\n if override_spec.unsafe is not None:\n spec = spec.__clone__(unsafe=override_spec.unsafe)\n if override_spec.parameters is not None:\n parameters = _merge(spec.parameters, override_spec.parameters)\n spec = spec.__clone__(parameters=parameters)\n if override_spec.context is not None:\n context = _merge(spec.context, override_spec.context)\n spec = spec.__clone__(context=context)\n return spec\n\n def abspath(self, spec, current_package, current_directory):\n if ':' not in spec.template:\n template = \"%s:%s\" % \\\n (current_package,\n os.path.join(current_directory, spec.template))\n spec = spec.__clone__(template=template)\n return spec\n\n\n","sub_path":"src/rex.urlmap/src/rex/urlmap/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":4868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"284245652","text":"from pmb import *\n\nconfig = get_config()\n\nTIME_LIMIT = config['postsmailer']['timelimit']\n\nreddit = praw.Reddit(config['bot_name'], user_agent=config['user_agent'])\n\nsubreddits = config['postsmailer']['subreddits']\n\ndef generate_message(subreddit, posts):\n\tsubject = subreddit\n\n\tposts = posts[::-1]\n\tposts = '\\n'.join([str(x+1) + '. [' + pendulum.from_timestamp(posts[x].created_utc, tz='local').to_datetime_string() + ' UTC] [' + posts[x].title + '](https://redd.it/' + posts[x].id + ') by /u/' + posts[x].author.name for x in range(len(posts))])\n\n\tbody = \"# Last Week in /r/{}\\n\\n## The following new submissions were posted within the last week on /r/{}:\\n\\n{}\\n\\nPlease be sure to weigh in on any brainstorms or props, review new results, and cast your vote in any open votes.\".format(subreddit, subreddit, posts)\n\n\treddit.redditor('mod_mailer').message(subject, body)\n\ndef get_newest_posts(subreddit):\n\tposts = []\n\tnow = pendulum.now('UTC').timestamp()\n\tfor submission in reddit.subreddit(subreddit).new():\n\t\tage = now - submission.created_utc\n\t\tif age > TIME_LIMIT:\n\t\t\tbreak\n\n\t\tposts.append(submission)\n\n\tif len(posts) > 0:\n\t\tgenerate_message(subreddit, posts)\n\ndef job():\n\tfor subreddit in subreddits:\n\t\tget_newest_posts(subreddit)\n\ndef start():\n\tschedule.every().monday.at(\"03:00\").do(job)\n\twhile True:\n\t\ttry:\n\t\t\tschedule.run_pending()\n\t\t\ttime.sleep(600)\n\t\texcept Exception as e:\n\t\t\tlog('exception', e)\n\nt = Thread(target=start)\nt.daemon = True\nt.start()","sub_path":"modules/postsmailer.py","file_name":"postsmailer.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"233541137","text":"\"\"\"Test the rayvison_sync.rayvision_transfer functions.\"\"\"\n\n# pylint: disable=import-error\nimport pytest\n\n\ndef test_transport_info(rayvision_transfer):\n \"\"\"Test we can get transport info.\"\"\"\n assert sorted(list(rayvision_transfer.transport_info.keys())) == [\n 'engine_type',\n 'server_ip',\n 'server_name',\n 'server_port']\n\n\ndef test_create_cmd(rayvision_transfer):\n \"\"\"Test we can get a str.\"\"\"\n cmd_params = [\n \"upload_files\",\n \"D:/gitlab_demo/temp/demo_bak/rayvision/help/scenes/demo_scenc.mb\",\n \"/D/gitlab_demo/temp/demo_bak/rayvision/help/scenes/demo_scenc.mb\",\n \"1048576\",\n \"false\", \"config_bid\"\n ]\n data = rayvision_transfer.create_cmd(cmd_params)\n # noqa: E501 # pylint: disable=line-too-long\n result = '\"aspera\" \"CTCC\" \"45.251.92.29\" \"10221\" \"54252\" \"100093088\" \"upload_files\" ' \\\n '\"D:/gitlab_demo/temp/demo_bak/rayvision/help/scenes/demo_scenc.mb\" ' \\\n '\"/D/gitlab_demo/temp/demo_bak/rayvision/help/scenes/demo_scenc.mb\" \"1\" \"false\" \"1048576\" \"None\" '\n assert result in data\n\n\n@pytest.mark.parametrize(\"transports_json, domain_name, platform\", [\n (None, None, '2'),\n (None, \"jop.foxrenderfarm.com\", '3'),\n (None, \"task.renderbus.com\", '3'),\n (None, \"jop.test.com\", '2'),\n])\ndef test_parse_transports_json(rayvision_transfer, transports_json,\n domain_name, platform):\n \"\"\"Test we can get correct data.\"\"\"\n result = rayvision_transfer.parse_transports_json(transports_json,\n domain_name, platform)\n assert sorted(list(result.keys())) == ['engine_type', 'server_ip',\n 'server_name', 'server_port']\n","sub_path":"rayvision_sync/tests/test_transfer.py","file_name":"test_transfer.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"6156650","text":"#-*-coding: utf-8 -*-\n#@author:tyhj\nimport numpy as np\nfrom scipy.stats import rankdata\n\nimport numpy as np\nimport pandas as pd\nfrom zht.util.listu import chunkify,chunkifyByBreakPoints\n\ndef _arrPortId(arr,param):\n '''\n sort the arr and divide them into n portfolio,then return the portfolio id.\n the id begin with 1,and the large the element the large the id\n :param arr:an array or list\n :param param:int or list\n :return:\n For example:\n arr=np.array(range(50))\n np.random.shuffle(arr)\n id=getPortId(arr,5)\n\n '''\n # arr=np.array(arr) #this line is neccessary,especially when 'arr' is a dataframe\n\n df = pd.DataFrame(arr)\n df.columns = ['arr']\n df = df.sort_values('arr')\n df['id'] = 0\n\n if isinstance(param,int):\n chunks=chunkify(range(len(arr)),param)\n idlist=[]\n for n,chunk in enumerate(chunks):\n idlist+=[n+1]*len(chunk)\n df['id']=idlist\n\n # for i in range(n):\n # df['id'][int(i * len(arr)*1.0 / n):int((i + 1) * len(arr)*1.0 / n)] = i + 1 # include left but not the right\n\n else:#break points\n chunks=chunkifyByBreakPoints(range(len(arr)),param)\n idlist=[]\n for n,chunk in enumerate(chunks):\n idlist+=[n+1]*len(chunk)\n df['id']=idlist\n\n # bps = param\n # bps = np.sort(bps)\n # ns=[int(param)*len(df['id'])]\n # bvs = [0] + [int(len(arr) * bp) for bp in bps] + [len(arr)]\n # for i in range(1, len(bvs)):\n # df['id'][bvs[i - 1]:bvs[i]] = i\n df = df.sort_index()\n return df['id'].values\n\ndef getSortedPortId(mydata,param,axis=0):\n '''\n\n Args:\n mydata: array,series or dataframe\n param: int or a list of break points such as [0.3,0.7]\n axis: 0 or 1,0 denotes row by row,1 means column by column,\n so,usually the index in mydata is time and the column in mydata\n is stock codes.\n\n Returns:\n\n '''\n if len(np.shape(mydata))==1:\n if isinstance(mydata,pd.DataFrame):\n ids=pd.DataFrame(index=mydata.index,columns=mydata.columns)\n tmpdf=mydata.dropna().to_frame()\n tmpdf['id']=_arrPortId(tmpdf.values,param)\n ids.loc[tmpdf.index,ids.columns[0]]=tmpdf['id'].values\n return ids\n\n elif isinstance(mydata,pd.Series):\n ids=pd.Series(index=mydata.index)\n tmpdf=mydata.dropna().to_frame()\n tmpdf['id']=_arrPortId(tmpdf.values,param)\n ids.loc[tmpdf.index]=tmpdf['id'].values\n return ids\n\n elif isinstance(mydata,np.ndarray):\n return _arrPortId(mydata,param)\n\n elif len(np.shape(mydata))==2:\n if isinstance(mydata,pd.DataFrame):\n ids = pd.DataFrame(columns=mydata.columns)\n for ind in mydata.index.tolist():\n sub = mydata.loc[ind].to_frame()\n sub = sub.dropna() # this will negnect the NaN\n sub['id'] = _arrPortId(sub, param)\n ids.loc[ind] = sub['id']\n return ids\n","sub_path":"py27/zht/util/mathu.py","file_name":"mathu.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"32636182","text":"import json\nimport requests\nfrom info import UID, SECRET\n\n# https://api.intra.42.fr/oauth/authorize?client_id=fd16a486a7cf324ef92830dcced304aaca15f64a3370321aa7f58293cddb137a&redirect_uri=http%3A%2F%2Flocalhost%3A1919%2Fusers%2Fauth%2Fft%2Fcallback&response_type=code\n# https://api.intra.42.fr/oauth/authorize?client_id=fd16a486a7cf324ef92830dcced304aaca15f64a3370321aa7f58293cddb137a&redirect_uri=https://profile.intra.42.fr&response_type=code\nredirect_uri = \"https://httpbin.org/anything\" \n# redirect_uri = \"http://127.0.0.1\" \n\nparams = {'grant_type': 'client_credentials',\n 'client_id': UID,\n 'client_secret': SECRET}\n\nresponse = requests.post(\"https://api.intra.42.fr/oauth/token\", params=params)\n\n\nif response.ok == False:\n print(\"an error ocurred\")\n exit()\n\nresp_json = response.json()\n\nprint(resp_json)\n\nf = open(\"ex00.out\", \"w\")\nf.write(resp_json['access_token'])\nf.close()\n","sub_path":"experiments/intra_try_2.py","file_name":"intra_try_2.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"486244657","text":"# To run server cd into `./nlp_backend` and run this command in terminal:\n# `gunicorn --reload --timeout 600 -b 0.0.0.0:8000 qa_api:api`\n# you may then make calls to: `localhost:8000/qa`\n# POST request expects to recieve json = {'question': 'your question'}\n# and returns an array of matches\n\nimport falcon\nimport json\nimport spacy\nimport requests\nimport time\nfrom collections import Counter\nfrom dotenv import load_dotenv\nimport os\nimport pandas as pd\nimport subprocess\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport string\nimport random\n\n# NLTK related imports\nimport nltk\nfrom nltk.tokenize import word_tokenize # Word Tokenizer\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer # Word Lemmatizer\n\nnltk.download('punkt')\nnltk.download('stopwords')\nnltk.download('wordnet')\n\ntable = str.maketrans('', '', string.punctuation)\nstop_words = stopwords.words('english')\nstop_words = set(stop_words)\n\nlemmatizer = WordNetLemmatizer()\n\nload_dotenv()\nAIRTABLE_KEY = os.getenv('AIRTABLE_KEY')\nDEBUG_MODE = os.getenv('DEBUG_MODE')\n\nif DEBUG_MODE == 'ON':\n finalT0 = time.time()\n\nnlp = spacy.load(\"en_core_web_sm\")\n\n\ndef get_jaccard_sim(str1, str2):\n \"\"\"\n Jaccard similarity:\n Also called intersection over union is defined as size of intersection\n divided by size of union of two sets.\n \"\"\"\n a = set(str1.split())\n b = set(str2.split())\n c = a.intersection(b)\n return float(len(c)) / (len(a) + len(b) - len(c))\n\n\ndef get_cosine_sim(*strs):\n \"\"\"\n Cosine similarity:\n Calculates similarity by measuring the cosine of angle between two vectors.\n \"\"\"\n vectors = [t for t in get_vectors(*strs)]\n return cosine_similarity(vectors)[0][1]\n\n\ndef get_vectors(*strs):\n text = [t for t in strs]\n vectorizer = CountVectorizer(text)\n vectorizer.fit(text)\n return vectorizer.transform(text).toarray()\n\n\ndef clean_text(text):\n \"\"\"\n Cleaning the document before vectorization.\n \"\"\"\n # Tokenize by word\n tokens = word_tokenize(text)\n # Make all words lowercase\n lowercase_tokens = [w.lower() for w in tokens]\n # Strip punctuation from within words\n no_punctuation = [x.translate(table) for x in lowercase_tokens]\n # Remove words that aren't alphabetic\n alphabetic = [word for word in no_punctuation if word.isalpha()]\n # Remove stopwords\n no_stop_words = [w for w in alphabetic if not w in stop_words] # noqa E713\n # Lemmatize words\n lemmas = [lemmatizer.lemmatize(word) for word in no_stop_words]\n return ' '.join(lemmas)\n\n\ndef getAirData():\n \"\"\"Generates ./tables json data from Airtable:\"\"\"\n if DEBUG_MODE == 'ON':\n print(\"Start of getAirData--->\\n\")\n t0 = time.time()\n\n # Obtain all Modules:\n url = \"https://api.airtable.com/v0/app84GmnQ9SxIBjrJ/Modules\"\n auth_value = 'Bearer '+AIRTABLE_KEY\n headers = {\"Authorization\": auth_value}\n response = requests.get(url, headers=headers,)\n\n if response:\n m = response.json()\n modules = m[\"records\"]\n\n while \"offset\" in m:\n offset = m[\"offset\"]\n\n url = \"https://api.airtable.com/v0/app84GmnQ9SxIBjrJ/\"\\\n \"Modules?offset=\"+offset # noqa E999\n auth_value = \"Bearer \"+AIRTABLE_KEY\n headers = {\"Authorization\": auth_value}\n response = requests.get(url, headers=headers,)\n\n if response:\n m = response.json()\n for module in m[\"records\"]:\n modules.append(module)\n else:\n print(\"Error getting offset\")\n else:\n print(\"Error getting modules\")\n\n # Make modules.json\n with open(\"./tables/modules.json\", \"w\") as f:\n json.dump(modules, f, indent=4)\n\n # Obtain all Objectives:\n url = \"https://api.airtable.com/v0/app84GmnQ9SxIBjrJ/Objectives\"\n auth_value = \"Bearer \"+AIRTABLE_KEY\n headers = {\"Authorization\": auth_value}\n response = requests.get(url, headers=headers,)\n\n if response:\n o = response.json()\n objectives = o[\"records\"]\n\n while \"offset\" in o:\n offset = o[\"offset\"]\n\n url = \"https://api.airtable.com/v0/app84GmnQ9SxIBjrJ/\"\\\n \"Objectives?offset=\"+offset\n auth_value = \"Bearer \"+AIRTABLE_KEY\n headers = {\"Authorization\": auth_value}\n response = requests.get(url, headers=headers,)\n\n if response:\n o = response.json()\n\n for obj in o[\"records\"]:\n objectives.append(obj)\n else:\n print(\"Error getting offset\")\n else:\n print(\"Error getting objectives\")\n\n # Make objectives.json\n with open(\"./tables/objectives.json\", \"w\") as f:\n json.dump(objectives, f, indent=4)\n\n # Obtain all Currriculum Sets:\n url = \"https://api.airtable.com/v0/app84GmnQ9SxIBjrJ/Curriculum%20Sets\"\n auth_value = \"Bearer \"+AIRTABLE_KEY\n headers = {\"Authorization\": auth_value}\n response = requests.get(url, headers=headers,)\n\n if response:\n c = response.json()\n curriculumSets = c[\"records\"]\n\n while \"offset\" in c:\n offset = c[\"offset\"]\n\n url = \"https://api.airtable.com/v0/app84GmnQ9SxIBjrJ/\"\\\n \"Curriculum%20Sets?offset=\"+offset\n auth_value = \"Bearer \"+AIRTABLE_KEY\n headers = {\"Authorization\": auth_value}\n response = requests.get(url, headers=headers,)\n\n if response:\n c = response.json()\n\n for curriculumSet in c[\"records\"]:\n curriculumSets.append(curriculumSet)\n else:\n print(\"Error getting offset\", response.text)\n else:\n print(\"Error getting Curriculum Sets\", response.text)\n\n # Make curriculumSets.json\n with open(\"./tables/curriculumSets.json\", \"w\") as f:\n json.dump(curriculumSets, f, indent=4)\n\n getRecord = {}\n for module in modules:\n getRecord[module[\"id\"]] = module\n\n for objective in objectives:\n getRecord[objective[\"id\"]] = objective\n\n for curriculumSet in curriculumSets:\n getRecord[curriculumSet[\"id\"]] = curriculumSet\n\n with open(\"./tables/getRecord.json\", \"w\") as f:\n json.dump(getRecord, f, indent=4)\n\n if DEBUG_MODE == 'ON':\n speed = time.time() - t0\n print(\"Speed: \"+str(speed))\n print(\"\\n<---End of getAirData\")\n\n\ndef genModSearchData():\n \"\"\"Generates modSearchData.json\"\"\"\n\n if DEBUG_MODE == 'ON':\n print(\"Start of genModSearchData--->\\n\")\n t0 = time.time()\n\n modSearchData = []\n\n # Loads jsons from ./tables\n with open('./tables/modules.json', 'r') as modules:\n modules = json.load(modules)\n\n with open('./tables/objectives.json', 'r') as objectives:\n objectives = json.load(objectives)\n\n with open('./tables/curriculumSets.json', 'r') as curriculumSets:\n curriculumSets = json.load(curriculumSets)\n\n with open('./tables/getRecord.json', 'r') as getRecord:\n getRecord = json.load(getRecord)\n\n # Creates newEntry for modSearchData:\n for module in modules:\n newEntry = {}\n modSearchProfile = {}\n newEntry[\"id\"] = module[\"id\"]\n moduleFields = module[\"fields\"]\n\n # text is a compilation of relavent search text found\n # in modules fields and objectives fields\n text = \"\"\n\n if \"Name\" in moduleFields:\n newEntry[\"name\"] = moduleFields[\"Name\"]\n else:\n newEntry[\"name\"] = \"GHOST\"\n\n if \"Description\" in moduleFields:\n newEntry[\"description\"] = moduleFields[\"Description\"]\n text = text + moduleFields[\"Description\"]\n else:\n newEntry[\"description\"] = \"NO_DESCRIPTION\"\n\n # Generates newEntry[\"URL\"]\n # Uses Curriculum Sets Short ID field to complete module URL's:\n newCurriculumSets = []\n noCurriculum = []\n noShortID = []\n\n if \"Curriculum Sets\" in moduleFields:\n for curriculumSet in moduleFields[\"Curriculum Sets\"]:\n newCurriculumSets.append(getRecord[curriculumSet])\n\n for curriculumSet in newCurriculumSets:\n if \"Short ID\" in curriculumSet[\"fields\"]:\n shortID = curriculumSet[\"fields\"][\"Short ID\"].lower()\n newURL = \"https://learn.lambdaschool.com/\"+shortID\n newURL += \"/module/\" + moduleFields[\"RecordID\"]\n response = requests.get(newURL)\n\n if response:\n newEntry[\"URL\"] = newURL\n else:\n break\n else:\n noShortID.append(module)\n else:\n noCurriculum.append(module)\n\n if \"URL\" in newEntry:\n # Creates newEntry[\"modSearchProfile\"]\n def getFreq(text):\n counts = Counter()\n t = nlp(text)\n for word in t:\n if word.pos_ == \"PUNCT\" and len(word) > 1:\n counts[word.orth_] += 2\n else:\n counts[word.orth_] += 1\n\n return counts\n\n # Gathers objectives linked to module:\n linkedObjectives = []\n if \"Objectives\" in moduleFields:\n for objective in moduleFields[\"Objectives\"]:\n linkedObjectives.append(getRecord[objective])\n\n # Generates text from objectives\n if \"Instructors Notes\" in moduleFields:\n text += moduleFields[\"Instructors Notes\"]\n\n for objective in linkedObjectives:\n objectiveFields = objective[\"fields\"]\n\n if \"Student can\" in objectiveFields:\n text += \" \" + objectiveFields[\"Student can\"]\n if \"Description/Rationale\" in objectiveFields:\n text += \" \" + objectiveFields[\"Description/Rationale\"]\n if \"Introduction\" in objectiveFields:\n text += \" \" + objectiveFields[\"Introduction\"]\n if \"Tutorial\" in objectiveFields:\n text += \" \" + objectiveFields[\"Tutorial\"]\n if \"Instructor Notes\" in objectiveFields:\n text += \" \" + objectiveFields[\"Instructor Notes\"]\n if \"Challenge\" in objectiveFields:\n text += \" \" + objectiveFields[\"Challenge\"]\n\n text = text.lower()\n modSearchProfile[\"text\"] = text\n modSearchProfile[\"textFreq\"] = getFreq(text)\n newEntry[\"modSearchProfile\"] = modSearchProfile\n modSearchData.append(newEntry)\n\n with open(\"./modSearchData.json\", \"w\") as f:\n json.dump(modSearchData, f, indent=4)\n\n if DEBUG_MODE == 'ON':\n speed = time.time() - t0\n print(\"modSearchData length: \"+str(len(modSearchData)))\n print(\"Speed: \"+str(speed))\n print(\"\\n<---End of genModSearchData\")\n\n # Reload data after updating modSearchData.json file\n load_data()\n\n\ndef load_data():\n \"\"\"Loading function before 1st query\"\"\"\n print(\"Data loading started..............................................\")\n global available_category\n global df\n\n # Loading data onto dataframe\n df = pd.read_json('modSearchData.json')\n\n # Dropping NaN values\n if df.isnull().sum().sum():\n df.dropna(inplace=True)\n\n # Categorizing the training kit information\n category = []\n\n cmd = \"\"\"cat \"modSearchData.json\" | grep '\"URL\"' | cut -d/ -f4\"\"\"\n section_names = subprocess.check_output(cmd, shell=True)\\\n .decode(\"utf-8\").split()\n\n for section in section_names:\n if section in ['and-pre', 'android']:\n category.append('android')\n elif section in ['cd', 'cr', 'ls-edu', 'nxt', 'p4s']:\n category.append('career')\n elif section in ['cs']:\n category.append('cs')\n elif section in ['ds', 'ds-pre']:\n category.append('ds')\n elif section in ['fsw', 'fsw-pre', 'web1', 'web2',\n 'web3', 'web4java', 'web4node']:\n category.append('web')\n elif section in ['ios', 'ios-pre']:\n category.append('ios')\n elif section in ['ux', 'ux-pre']:\n category.append('ux')\n else:\n category.append('other')\n\n df['category'] = category\n\n # Extract text information from modSearchProfile\n def extract_text(row):\n return dict(row)['text']\n\n df['modSearchText'] = df['modSearchProfile'].apply(extract_text)\n\n # Combining text based information\n df['text'] = df.apply(lambda row: row['name'] + \" \" + row['description']\n + \" \" + row['modSearchText'], axis=1)\n\n # Dropping detailed text information.\n # This can be used later if needed.\n df.drop(columns=['modSearchProfile'], inplace=True)\n\n # Clean up the text\n df['cleaned_text'] = df.text.apply(clean_text)\n\n # Used for category based search\n available_category = df.category.unique()\n print(\"Data loading complete.............................................\")\n\n\ndef build_response(df, match_type, similarity_metrics, match_count=3):\n \"\"\"Populates the records to be returned in response.\"\"\"\n # Dictionary to build response packet\n resp_dict = {}\n\n # Building the response\n resp_dict['match_type'] = match_type\n resp_dict['similarity_metrics'] = similarity_metrics\n\n match = []\n for i in range(min(df.shape[0], match_count)):\n row = df.iloc[i, :]\n\n record = {}\n record['id'] = row['id']\n record['name'] = row['name']\n record['description'] = row['description']\n record['URL'] = row['URL']\n match.append(record)\n\n resp_dict['match'] = match\n # return json.dumps(resp_dict)\n return resp_dict\n\n\n# Initializing empty globals\ndf = pd.DataFrame()\navailable_category = []\n\n# Need to ensure data is loaded at init for content based search\nload_data()\n\n\nclass QA:\n\n def on_get(self, req, resp):\n \"\"\"Handles GET requests\"\"\"\n with open(\"./modSearchData.json\", \"r\") as modSearchData:\n modSearchData = json.load(modSearchData)\n\n if modSearchData:\n resp.media = modSearchData\n else:\n resp.media = {\"Error\": \"No modSearchData\"}\n\n def on_post(self, req, resp):\n \"\"\"Handles POST requests\"\"\"\n global available_category\n global df\n\n # User Input\n student_query = req.media[\"question\"]\n\n # Using choice to decide Jaccard or Cosine similarity metrics.\n # Based on choice we design of A/B testing.\n choice = random.choice([0, 1, 1, 1])\n\n # Check if the category is available\n query_category = student_query.split(\":\")[0]\n\n if query_category in available_category:\n df_match_by_category = df[df['category'] == query_category].copy()\n\n query_without_category = \\\n clean_text(student_query.replace(query_category+\":\", \"\"))\n\n df_match_by_category['jaccard_sim_value'] = \\\n df_match_by_category.cleaned_text.\\\n apply(get_jaccard_sim, args=(query_without_category,))\n sort_by_jaccard_sim = \\\n df_match_by_category.sort_values('jaccard_sim_value',\n ascending=False).head(10)\n jaccard_match = sort_by_jaccard_sim[\n sort_by_jaccard_sim['jaccard_sim_value'] > 0]\n\n df_match_by_category['cosine_sim_value'] = \\\n df_match_by_category.cleaned_text.\\\n apply(get_cosine_sim, args=(query_without_category,))\n sort_by_cosine_sim = \\\n df_match_by_category.sort_values('cosine_sim_value',\n ascending=False).head(10)\n\n cosine_match = sort_by_cosine_sim[\n sort_by_cosine_sim['cosine_sim_value'] > 0]\n\n # Building the response\n if choice == 0:\n # Using Jaccard similarity metrics\n resp.media = build_response(jaccard_match,\n 'category search', 'jaccard')\n return\n else:\n # Using Cosine similarity metrics\n resp.media = build_response(cosine_match,\n 'category search', 'cosine')\n return\n\n else:\n df_full_match = df.copy()\n\n df_full_match['jaccard_sim_value'] = \\\n df_full_match.cleaned_text.\\\n apply(get_jaccard_sim, args=(clean_text(student_query),))\n sort_by_jaccard_sim = \\\n df_full_match.sort_values('jaccard_sim_value',\n ascending=False).head(10)\n jaccard_match = sort_by_jaccard_sim[\n sort_by_jaccard_sim['jaccard_sim_value'] > 0]\n\n df_full_match['cosine_sim_value'] = \\\n df_full_match.cleaned_text.\\\n apply(get_cosine_sim, args=(clean_text(student_query),))\n\n sort_by_cosine_sim = \\\n df_full_match.sort_values('cosine_sim_value',\n ascending=False).head(10)\n cosine_match = sort_by_cosine_sim[\n sort_by_cosine_sim['cosine_sim_value'] > 0]\n\n # Building the response\n if choice == 0:\n # Using Jaccard similarity metrics\n resp.media = build_response(jaccard_match,\n 'full search', 'jaccard')\n return\n else:\n # Using Cosine similarity metrics\n resp.media = build_response(cosine_match,\n 'full search', 'cosine')\n return\n\n\nclass UpdateQA:\n\n def on_post(self, req, resp):\n updates = req.media\n\n if DEBUG_MODE == \"ON\":\n print(\"Updates : \", updates)\n\n # Example:\n # This updates object triggers the creation/update of modSearchData\n # updates = {\n # \"airData\": 0,\n # \"modSearchData\": 1\n # }\n # updates is an object with keys of the update to make and\n # a value of 1 in order to update and a value of of 0 to not\n\n if updates[\"airData\"]:\n getAirData()\n resp.media = {\"message\": \"Success updating airData\"}\n if updates[\"modSearchData\"]:\n genModSearchData()\n resp.media = {\"message\": \"Success updating modSearchData\"}\n\n\napi = falcon.API()\napi.add_route('/qa', QA())\napi.add_route('/update', UpdateQA())\n\nif DEBUG_MODE == \"ON\":\n loadTime = time.time() - finalT0\n print(\"<---QA Ready---> \\nLoad Time: \"+str(loadTime))\n","sub_path":"qa_api.py","file_name":"qa_api.py","file_ext":"py","file_size_in_byte":19009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"264087861","text":"from django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.models import User\nfrom .models import Message, Account\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.db.models import Q\nimport json\n\n# Create your views here.\n\n@login_required\ndef homePageView(request):\n users = User.objects.exclude(pk=request.user.id)\n messages = Message.objects.filter(Q(source=request.user) | Q(target=request.user))\n return render(request, 'pages/index.html', {'msgs': messages, 'users': users})\n\n@login_required \ndef writePageView(request):\n users = User.objects.exclude(pk=request.user.id)\n messages = Message.objects.filter(Q(source=request.user) | Q(target=request.user))\n return render(request, 'pages/write.html', {'msgs': messages, 'users': users})\n\n@login_required\ndef userView(request):\n target = User.objects.get(id=request.GET.get('user'))\n account = Account.objects.get(owner=target)\n return render(request, 'pages/user.html', {'user': target, \"account\" : account})\n \n@login_required\ndef userView2(request):\n return redirect('/user/?user=' + str(request.user.id)) \n\ndef addView(request):\n\ttarget = User.objects.get(username=request.POST.get('to'))\n\tMessage.objects.create(source=request.user, target=target, content=request.POST.get('content'))\n\treturn redirect('/')\n\n@login_required\ndef readPageView(request):\n\tmessages = Message.objects.filter(Q(source=request.user) | Q(target=request.user))\n\tusers = User.objects.exclude(pk=request.user.id)\n\treturn render(request, 'pages/read.html', {'msgs': messages, 'users': users})\n\n@login_required \ndef badReadView(request, user):\n messages = Message.objects.filter(Q(source=user) | Q(target=user))\n users = User.objects.exclude(pk=request.user.id)\n return render(request, 'pages/read.html', {'msgs': messages, 'users': users})\n \n@login_required \ndef searchView(request):\n search = request.GET.get('search')\n if len(search) == 0:\n search = \"\\'i\\'\"\n userid = str(request.user.id)\n messages = Message.objects.raw('SELECT * FROM pages_message WHERE target_id = '+str(userid)+' AND content LIKE \\'' + search + '\\'')\n users = User.objects.exclude(pk=request.user.id)\n return render(request, 'pages/read.html', {'msgs': messages, 'users': users})\n \n","sub_path":"src/pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"94726490","text":"def get_earliest(date1, date2, *date3):\n \"\"\"\n This function takes three dates in a string format\n MM/DD/YYYY. It supports invalid dates to deter\n the use of the time module\n Returns\n A string with the earliest date of the three\n \"\"\"\n if not date3: # run this where only 2 arguments are provided\n d1 = (int(date1[6:]), int(date1[:2]), int(date1[3:5]))\n d2 = (int(date2[6:]), int(date2[:2]), int(date2[3:5]))\n\n if d1 < d2:\n return(date1)\n else:\n return(date2)\n else: # run this where 3 arguments are provided\n d1 = (int(date1[6:]), int(date1[:2]), int(date1[3:5]))\n d2 = (int(date2[6:]), int(date2[:2]), int(date2[3:5]))\n td3 = date3[0] # get first entry of tuple\n d3 = (int(td3[6:]), int(td3[:2]), int(td3[3:5]))\n\n if d1 < d2 and d1 < d3:\n return(date1)\n elif d2 < d1 and d2 < d3:\n return(date2)\n else:\n return(td3)\n\n\nget_earliest()\n","sub_path":"earliest/earliest.py","file_name":"earliest.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"27049620","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\n\nclass WindowGenerator:\n def __init__(self, input_width, label_width, shift,\n train_df, val_df, test_df, label_columns=None):\n self.train_df = train_df\n self.val_df = val_df\n self.test_df = test_df\n self.label_columns = label_columns\n if label_columns is not None:\n self.label_columns_indices = {name: i for i, name in enumerate(label_columns)}\n self.column_indices = {name: i for i, name in enumerate(train_df.columns)}\n self.input_width = input_width\n self.label_width = label_width\n self.shift = shift\n self.total_window_size = input_width + shift\n self.input_slice = slice(0, input_width)\n self.input_indices = np.arange(self.total_window_size)[self.input_slice]\n self.label_start = self.total_window_size - self.label_width\n self.labels_slice = slice(self.label_start, None)\n self.label_indices = np.arange(self.total_window_size)[self.labels_slice]\n\n def split_window(self, features):\n inputs = features[:, self.input_slice, :]\n labels = features[:, self.labels_slice, :]\n if self.label_columns is not None:\n labels = tf.stack([labels[:, :, self.column_indices[name]] for name in self.label_columns], axis=-1)\n inputs.set_shape([None, self.input_width, None])\n labels.set_shape([None, self.label_width, None])\n return inputs, labels\n\n def plot(self, model=None, plot_col='Confirmed_daily', max_subplots=7):\n inputs, labels = self.example\n plt.figure(figsize=(12, 18))\n plot_col_index = self.column_indices[plot_col]\n max_n = min(max_subplots, len(inputs))\n for n in range(max_n):\n plt.subplot(max_n, 1, n + 1)\n plt.ylabel(f'{plot_col} [normed]')\n plt.plot(self.input_indices, inputs[n, :, plot_col_index], label='Inputs', marker='.', zorder=-10)\n if self.label_columns:\n label_col_index = self.label_columns_indices.get(plot_col, None)\n else:\n label_col_index = plot_col_index\n if label_col_index is None:\n continue\n plt.scatter(self.label_indices, labels[n, :, label_col_index],\n edgecolors='k', label='Labels', c='#2ca02c', s=64)\n if model is not None:\n predictions = model(inputs)\n plt.scatter(self.label_indices, predictions[n, :, label_col_index],\n marker='X', edgecolors='k', label='Predictions', c='#ff7f0e', s=64)\n if n == 0:\n plt.legend()\n plt.xlabel('Time [d]')\n\n def make_dataset(self, data):\n data = np.array(data, dtype=np.float32)\n ds = tf.keras.preprocessing.timeseries_dataset_from_array(\n data=data, targets=None, sequence_length=self.total_window_size,\n sequence_stride=1, shuffle=True, batch_size=64, )\n ds = ds.map(self.split_window)\n return ds\n\n @property\n def train(self):\n return self.make_dataset(self.train_df)\n\n @property\n def val(self):\n return self.make_dataset(self.val_df)\n\n @property\n def test(self):\n return self.make_dataset(self.test_df)\n\n @property\n def example(self):\n \"\"\"Get and cache an example batch of `inputs, labels` for plotting.\"\"\"\n result = getattr(self, '_example', None)\n if result is None:\n result = next(iter(self.train))\n self._example = result\n return result\n\n\ndef compile_and_fit(model, window, patience=2):\n early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss',\n patience=patience,\n mode='min')\n\n model.compile(loss=tf.losses.MeanSquaredError(),\n optimizer=tf.optimizers.Adam(),\n metrics=[tf.metrics.MeanAbsoluteError()])\n\n history = model.fit(window.train, epochs=100,\n validation_data=window.val,\n callbacks=[early_stopping])\n\n return history\n\n\ndef create_model(num_features, OUT_STEPS):\n multi_dense_model = tf.keras.Sequential([\n # Take the last time step.\n # Shape [batch, time, features] => [batch, 1, features]\n tf.keras.layers.Lambda(lambda x: x[:, -1:, :]),\n # Shape => [batch, 1, dense_units]\n tf.keras.layers.Dense(512, activation='relu'),\n # Shape => [batch, out_steps*features]\n tf.keras.layers.Dense(OUT_STEPS*num_features,\n kernel_initializer=tf.initializers.zeros()),\n # Shape => [batch, out_steps, features]\n tf.keras.layers.Reshape([OUT_STEPS, num_features])\n ])\n return multi_dense_model\n\n\ndef fit_model(train_df, val_df, test_df, IN_STEPS, OUT_STEPS):\n num_features = train_df.shape[1]\n window = WindowGenerator(IN_STEPS, OUT_STEPS, OUT_STEPS,\n train_df, val_df, test_df)\n model = create_model(num_features, OUT_STEPS)\n history = compile_and_fit(model, window)\n return model, window\n","sub_path":"ldm_forecast_methods.py","file_name":"ldm_forecast_methods.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"650046088","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom ykdl.extractor import VideoExtractor\nfrom ykdl.videoinfo import VideoInfo\nfrom ykdl.util.html import get_content, get_location\nfrom ykdl.util.match import match1, matchall\n\nimport json\n\nclass BiliLive(VideoExtractor):\n name = u\"Bilibili live (哔哩哔哩 直播)\"\n\n supported_stream_profile = [u'原画', u'超清', u'高清', u'流畅']\n profile_2_type = {u'原画': 'BD', u'超清': 'TD', u'高清': 'HD', u'流畅' :'SD'}\n\n def prepare(self):\n info = VideoInfo(self.name, True)\n ID = match1(self.url, \"/(\\d+)\")\n api1_data = json.loads(get_content(\"https://api.live.bilibili.com/room/v1/Room/room_init?id={}\".format(ID)))\n self.vid = api1_data[\"data\"][\"room_id\"]\n api2_data = json.loads(get_content(\"https://api.live.bilibili.com/room/v1/Room/get_info?room_id={}&from=room\".format(self.vid)))\n info.title = api2_data[\"data\"][\"title\"]\n assert api2_data[\"data\"][\"live_status\"] == 1, u\"主播正在觅食......\"\n for profile in self.supported_stream_profile:\n data = json.loads(get_content(\"https://api.live.bilibili.com/api/playurl?player=1&cid={}&quality={}&platform=flash&otype=json\".format(self.vid, 4-self.supported_stream_profile.index(profile))))\n urls = [data[\"durl\"][0][\"url\"]]\n size = float('inf')\n ext = 'flv'\n info.stream_types.append(self.profile_2_type[profile])\n info.streams[self.profile_2_type[profile]] = {'container': ext, 'video_profile': profile, 'src' : urls, 'size': size}\n return info\n\nsite = BiliLive()\n","sub_path":"ykdl/extractors/bilibili/live.py","file_name":"live.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"84938387","text":"from rest_framework.views import APIView\r\nfrom rest_framework import generics\r\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\r\nfrom rest_xops.basic import XopsResponse\r\nfrom rest_framework.viewsets import ModelViewSet\r\nfrom ops.models import AnsibleRole,AnsibleFileList\r\nfrom django.conf import settings\r\nfrom ops.serializers.role_serializer import RoleSerializer,RoleFilesSerializer,RoleFileContentSerializer\r\nfrom common.custom import CommonPagination, RbacPermission,TreeAPIView,TreeSerializer,FileTreeSerializer\r\nfrom rest_framework.filters import SearchFilter, OrderingFilter\r\nimport django_filters,os,shutil,zipfile\r\nfrom ops.filters import RoleFilesFilter\r\nfrom rest_framework.serializers import ValidationError\r\nfrom rest_xops.basic import XopsResponse\r\nfrom rest_framework.decorators import action\r\nfrom rest_framework.permissions import IsAuthenticated\r\n\r\nclass RoleViewSet(ModelViewSet):\r\n perms_map =(\r\n {'*','admin'},{'*','playrole_all'}\r\n )\r\n queryset = AnsibleRole.objects.all()\r\n serializer_class = RoleSerializer\r\n pagination_class = CommonPagination\r\n filter_backends = (SearchFilter,OrderingFilter)\r\n search_fields = ('role_name',)\r\n ordering_fields = ('role_time',)\r\n authentication_classes = (JSONWebTokenAuthentication,)\r\n permission_classes = (RbacPermission,)\r\n\r\n @action(methods=['post'], detail=False, permission_classes=[IsAuthenticated],\r\n url_path='upload', url_name='upload')\r\n def upload(self, request):\r\n role_file= request.FILES.get('file')\r\n if role_file:\r\n obj_ansible_role=AnsibleRole.objects.create(\r\n role_name=role_file.name.split('.zip')[0],\r\n role_file=role_file,\r\n role_user=request.user,\r\n role_desc=request.data['role_desc']\r\n )\r\n z = zipfile.ZipFile(obj_ansible_role.role_file.path, 'r')\r\n # print(z.infolist())\r\n try:\r\n # if 1==1:\r\n for zip_file in z.namelist():\r\n print(zip_file)\r\n try:\r\n filename = zip_file.encode('cp437').decode('gbk') # 先使用cp437编码,然后再使用gbk解码\r\n except:\r\n filename = zip_file.encode('utf-8').decode('utf-8')\r\n finally:\r\n z.extract(zip_file, settings.ANSIBLE_ROLE_PATH) # 解压缩ZIP文件\r\n os.chdir(settings.ANSIBLE_ROLE_PATH) # 切换到目标目录\r\n os.rename(zip_file, filename) # 重命名文件\r\n # z.extractall(path=settings.ANSIBLE_ROLE_PATH)\r\n role_dir=os.path.join(settings.ANSIBLE_ROLE_PATH,obj_ansible_role.role_name)\r\n if os.path.isdir(role_dir):\r\n obj_role_file=AnsibleFileList.objects.create(\r\n file_name=obj_ansible_role.role_name,\r\n is_dir=True,\r\n pid=0,\r\n role_id=obj_ansible_role.id\r\n )\r\n for root,dir,file in os.walk(role_dir):\r\n print(root,dir,file)\r\n root_path = root.replace(settings.ANSIBLE_ROLE_PATH, '')\r\n lst_dir = root_path.split('/')\r\n pid = AnsibleFileList.objects.order_by('-id').filter(file_name=str(lst_dir[-1]),is_dir=True,role_id=obj_ansible_role.id).first().id if lst_dir[-2] else obj_role_file.id\r\n if dir:\r\n for d in dir:\r\n AnsibleFileList.objects.create(\r\n file_name=d,\r\n is_dir=True,\r\n pid=pid,\r\n role_id=obj_ansible_role.id\r\n )\r\n if file:\r\n for f in file:\r\n AnsibleFileList.objects.create(\r\n file_name=f,\r\n is_dir=False,\r\n pid=pid,\r\n role_id=obj_ansible_role.id\r\n )\r\n role_serializer = RoleSerializer(data=obj_ansible_role)\r\n result = role_serializer.validated_data if role_serializer.is_valid() else None\r\n return XopsResponse(data=result)\r\n except Exception as e:\r\n # print(e)\r\n raise ValidationError('服务器创建文件失败')\r\n finally:\r\n z.close()\r\n os.remove(obj_ansible_role.role_file.path)\r\n\r\n\r\n\r\nclass RoleUploadView(APIView):\r\n def post(self,request, format=None):\r\n if request.FILES:\r\n print(request.FILES)\r\n\r\nclass RoleFilesViewSet(ModelViewSet):\r\n '''\r\n playrole文件管理:增删改查\r\n '''\r\n parent_path=''\r\n perms_map = ({'*': 'admin'}, {'*': 'playrole_all'})\r\n queryset = AnsibleFileList.objects.all()\r\n serializer_class = RoleFilesSerializer\r\n pagination_class = CommonPagination\r\n filter_backends = (SearchFilter,)\r\n search_fields = ('file_name',)\r\n authentication_classes = (JSONWebTokenAuthentication,)\r\n permission_classes = (RbacPermission,)\r\n\r\n def get_parant_path(self,pid):\r\n for i in AnsibleFileList.objects.filter(id=pid):\r\n if i.pid:\r\n self.parent_path=os.path.join(i.file_name,self.parent_path)\r\n self.get_parant_path(i.pid)\r\n else:\r\n self.parent_path=os.path.join(settings.ANSIBLE_ROLE_PATH,i.file_name, self.parent_path)\r\n\r\n def destroy(self, request, *args, **kwargs):\r\n try:\r\n obj_role_files=AnsibleFileList.objects.get(id= kwargs['pk'])\r\n file_name = obj_role_files.file_name\r\n is_dir=obj_role_files.is_dir\r\n pid=obj_role_files.pid\r\n self.get_parant_path(pid)\r\n if is_dir:\r\n shutil.rmtree(os.path.join(self.parent_path, file_name),ignore_errors=True)\r\n else:\r\n os.remove(os.path.join(self.parent_path, file_name))\r\n return super(RoleFilesViewSet,self).destroy(request,*args,**kwargs)\r\n except Exception as e:\r\n # print(e)\r\n raise ValidationError('服务器创建文件失败')\r\n\r\n def create(self, request, *args, **kwargs):\r\n try:\r\n file_name=request.data.get('file_name')\r\n is_dir=request.data.get('is_dir')==str(True)\r\n pid = request.data.get('pid')\r\n self.get_parant_path(pid)\r\n if is_dir:\r\n os.mkdir(os.path.join(self.parent_path,file_name))\r\n else:\r\n open(os.path.join(self.parent_path,file_name), 'w')\r\n return super(RoleFilesViewSet, self).create(request, *args, **kwargs)\r\n except Exception as e:\r\n raise ValidationError('服务器创建文件失败')\r\n else:\r\n return super(RoleFilesViewSet, self).create(request, *args, **kwargs)\r\n\r\n\r\n\r\n\r\n def update(self, instance, validated_data):\r\n try:\r\n old_file_name=instance.file_name\r\n new_file_name=validated_data.get('file_name')\r\n pid = validated_data.get('pid')\r\n self.get_parant_path(pid)\r\n os.rename(os.path.join(self.parent_path, old_file_name),os.path.join(self.parent_path, new_file_name))\r\n return super(RoleFilesSerializer, self).update(instance,validated_data)\r\n except Exception as e:\r\n raise ValidationError('服务器创建文件失败')\r\n\r\nclass RoleFileContentView(generics.UpdateAPIView,generics.RetrieveAPIView):\r\n parent_path = ''\r\n perms_map = ({'*': 'admin'}, {'*': 'playrole_all'})\r\n serializer_class =RoleFileContentSerializer\r\n\r\n def get_parent_path(self, pid):\r\n for i in AnsibleFileList.objects.filter(id=pid):\r\n if i.pid:\r\n self.parent_path = os.path.join(i.file_name, self.parent_path)\r\n self.get_parent_path(i.pid)\r\n else:\r\n self.parent_path = os.path.join(settings.ANSIBLE_ROLE_PATH, i.file_name, self.parent_path)\r\n\r\n def retrieve(self, request, *args, **kwargs):\r\n print(args)\r\n print(kwargs)\r\n id=kwargs['pk']\r\n obj_role_file=AnsibleFileList.objects.get(id=id)\r\n self.get_parent_path(obj_role_file.pid)\r\n file=os.path.join(self.parent_path,obj_role_file.file_name)\r\n content = ''\r\n if os.path.exists(file):\r\n with open(file, 'r') as f:\r\n for line in f.readlines():\r\n content = content + line\r\n result={'file_name':file,'file_content':content}\r\n return XopsResponse(data=result)\r\n\r\n def update(self, request, *args, **kwargs):\r\n print(request.data)\r\n id = kwargs['pk']\r\n obj_role_file = AnsibleFileList.objects.get(id=id)\r\n self.get_parent_path(obj_role_file.pid)\r\n file = os.path.join(self.parent_path, obj_role_file.file_name)\r\n result = {'file_name': file, 'file_content': request.data['file_content']}\r\n with open(file,'w') as f:\r\n f.write(request.data['file_content'])\r\n return XopsResponse(data=result)\r\n\r\n # def update(self, request, *args, **kwargs):\r\n\r\n\r\n\r\n\r\n\r\nclass RoleFilesTreeView(TreeAPIView):\r\n serializer_class = FileTreeSerializer\r\n queryset=AnsibleFileList.objects.all()\r\n filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)\r\n filter_class = RoleFilesFilter","sub_path":"apps/ops/views/role.py","file_name":"role.py","file_ext":"py","file_size_in_byte":9732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"35452250","text":"#!/usr/bin/env python3\nimport yaml\nimport sys\nimport os\n\nfrom kijiji_scraper.kijiji_scraper import KijijiScraper\nfrom kijiji_scraper.email_client import EmailClient\n\nif __name__ == \"__main__\":\n args = sys.argv\n skip_flag = \"-s\" in args\n \n # Change working directory to current directory\n abspath = os.path.abspath(__file__)\n dname = os.path.dirname(abspath)\n os.chdir(dname)\n\n # Get config values\n with open(\"config.yaml\", \"r\") as config_file:\n email_config, urls_to_scrape = yaml.safe_load_all(config_file)\n\n # Initialize the KijijiScraper and email client\n kijiji_scraper = KijijiScraper()\n email_client = EmailClient(email_config)\n\n # Scrape each url given in config file\n for url_dict in urls_to_scrape:\n url = url_dict.get(\"url\")\n exclude_words = url_dict.get(\"exclude\", [])\n\n print(\"Scraping: %s\"%url)\n if len(exclude_words):\n print(\"Excluding: \" + \", \".join(exclude_words))\n\n kijiji_scraper.set_exclude_list(exclude_words)\n ads, email_title = kijiji_scraper.scrape_kijiji_for_ads(url)\n\n info_string = \"Found %s new ads\\n\"%len(ads) \\\n if len(ads) != 1 else \"Found 1 new ad\\n\"\n print(info_string)\n\n if not skip_flag and len(ads):\n email_client.mail_ads(ads, email_title)\n\n kijiji_scraper.save_ads()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"31469744","text":"from datasets import Simple, Split, Xor\nN = 100\n\n\ndef classify(pt):\n \"Classify based on x position\"\n if pt[0] < 0.5:\n return 1.0\n else:\n return 0.0\n\nSimple(N, vis=True).graph(\"initial\", model=classify)","sub_path":"Module-0/project/task051.py","file_name":"task051.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"53826741","text":"import random\n\nfrom copy import deepcopy\n\nclass Matrix():\n def __init__(self, nrows, ncols):\n \"\"\"Construct a (nrows X ncols) matrix\"\"\"\n self.wrong_count = 0 #問題: 為何不能在其他方法直接寫 self.wromg_count += 1,而一定要先寫宣告\n self.rows = nrows\n self.cols = ncols\n self.matrix = list()\n for i in range(0, self.rows):\n swap = list()\n for j in range(0, self.cols):\n swap.append(random.randint(0,9))\n j += 1\n self.matrix.append(swap)\n i += 1\n self.orig_matrix = deepcopy(self.matrix)\n \n def add(self, m):\n \"\"\"return a new Matrix object after summation\"\"\"\n added_matrix = list()\n added_matrix = m.extent()\n for i in range(0, self.cols):\n for j in range(0, self.rows): \n self.matrix[i][j] = self.orig_matrix[i][j] + added_matrix[i][j]\n return Matrix2(self.matrix)\n def sub(self, m):\n \"\"\"return a new Matrix object after substraction\"\"\"\n added_matrix = list()\n added_matrix = m.extent()\n for i in range(0, self.rows):\n for j in range(0, self.cols):\n try:\n self.matrix[i][j] = self.orig_matrix[i][j] - added_matrix[i][j]\n except IndexError:\n print(\"wrong type\")\n return \n return Matrix2(self.matrix)\n def mul(self, m):\n \"\"\"return a new Matrix object after multiplication\"\"\"\n added_matrix = list()\n added_matrix = m.extent()\n res = [[0] * len(added_matrix[0]) for i in range(self.rows)]\n for i in range(self.rows):#self.rows 直的\n for j in range(len(added_matrix[0])):#len(m[0]) 橫的\n for k in range(len(added_matrix)):\n res[i][j] += self.orig_matrix[i][k] * added_matrix[k][j]\n self.matrix = list()\n self.matrix = res\n self.cols = len(added_matrix[0])\n return Matrix2(self.matrix)\n def transpose(self):\n \"\"\"return a new Matrix object after transpose\"\"\"\n res = [[0] * self.rows for i in range(self.cols)]\n for i in range(0, self.rows):\n for j in range(0, self.cols):\n res[j][i] = self.matrix[i][j]\n self.matrix = list()\n self.matrix = res\n return Matrix2(self.matrix)\n \n def display(self):\n \"\"\"Display the content in the matrix\"\"\"\n for i in range(0, self.rows):\n for j in range(0, self.cols):\n print(self.matrix[i][j],end = ' ')\n j += 1\n i += 1\n print(' ')\n def extent(self):#接入轉成list\n return self.matrix\nclass Matrix2(Matrix):\n def __init__(self,m):\n self.rows = len(m)\n self.cols = len(m[0])\n self.matrix = m\nA_row = int(input(\"Enter A matrix's rows: \"))\nA_cols = int(input(\"Enter A matrix's cols: \"))\nA_matrix = Matrix(A_row,A_cols)\nprint('A matrix: ')\nA_matrix.display()\n\nB_row = int(input(\"Enter B matrix's rows: \"))\nB_cols = int(input(\"Enter B matrix's cols: \"))\nB_matrix = Matrix(B_row,B_cols)\nprint('B matrix: ')\nB_matrix.display()\nprint('======== A + B ========')\nc = A_matrix.add(B_matrix)\nc.display()\nprint('======== A - B ========')\ne = A_matrix.sub(B_matrix)\ne.display()\nprint('======== A * B ========')\nd = A_matrix.mul(B_matrix)\nd.display()\nprint('=======================')\nf = A_matrix.transpose()\nf.display()","sub_path":"matrix_HW3.py","file_name":"matrix_HW3.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"637304551","text":"# The MIT License (MIT)\n#\n# Copyright (c) 2016 Sean Quinn\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all 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\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\nfrom dice.tokens import Integer\nfrom pyparsing import (CaselessLiteral, Literal, Optional, StringStart, StringEnd, Word, nums)\n#: Empty\n\n\ndef dice():\n token = Optional(integer()) + CaselessLiteral(\"d\") + dice_sides()\n token.setName(\"dice\")\n token.setResultsName(\"dice\")\n return token\n\n\ndef dice_sides():\n token = integer()\\\n | CaselessLiteral(\"fate\") \\\n | CaselessLiteral(\"f\")\n #| StringStart() + CaselessLiteral(\"f\") + StringEnd() \\\n #| StringStart() + CaselessLiteral(\"fate\") + StringEnd()\n token.setResultsName(\"dice_sides\")\n return token\n\n\ndef expression():\n token = Optional(Literal(\"(\")) + term() + Optional(Literal(\")\"))\n token.setName(\"expression\")\n return token\n\n\ndef flags():\n\n token = (\n CaselessLiteral(\"!advantage\")\n | CaselessLiteral(\"!adv\")\n | CaselessLiteral(\"!disadvantage\")\n | CaselessLiteral(\"!dis\")\n | CaselessLiteral(\"!drop\")\n | CaselessLiteral(\"!grow\")\n | CaselessLiteral(\"!keep\")\n | CaselessLiteral(\"!shrink\")\n | CaselessLiteral(\"!take\")\n )\n\n token.setName(\"flags\")\n token.setResultsName(\"flags\")\n return token\n\n\ndef integer():\n token = Word(nums)\n token.setParseAction(Integer.parse)\n token.setName(\"integer\")\n return token\n\n\ndef operator():\n token = Literal(\"+\") | Literal(\"-\") | Literal(\"/\") | Literal(\"*\")\n token.setName(\"operator\")\n token.setResultsName(\"operator\")\n return token\n\n\ndef term():\n \"\"\"\n \"\"\"\n token = StringStart() + dice() + StringEnd() \\\n | StringStart() + dice() + operator() + integer() + StringEnd() \\\n | StringStart() + dice() + flags() + StringEnd() \\\n | StringStart() + dice() + flags() + operator() + integer() + StringEnd()\n token.setName(\"term\")\n token.setResultsName(\"term\")\n return token\n\n\n","sub_path":"dice/grammar.py","file_name":"grammar.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"37553720","text":"import numpy as np\r\nimport cv2\r\nimport tkinter.filedialog as tkfd\r\nfrom lesson_functions import *\r\nfrom scipy.ndimage.measurements import label\r\nfrom sklearn.externals import joblib\r\n\r\n\r\ndef find_cars(img, ystart, ystop, scale, svc, X_scaler, orient, pix_per_cell, cell_per_block, spatial_size, hist_bins,\r\n window, cells_per_step):\r\n test_features = []\r\n box = []\r\n\r\n draw_img = np.copy(img)\r\n img = img.astype(np.float32) / 255\r\n\r\n img_tosearch = img[ystart:ystop, :, :]\r\n ctrans_tosearch = convert_color(img_tosearch, conv='RGB2YCrCb')\r\n\r\n if scale != 1:\r\n imshape = ctrans_tosearch.shape\r\n ctrans_tosearch = cv2.resize(ctrans_tosearch, (np.int(imshape[1] / scale), np.int(imshape[0] / scale)))\r\n\r\n ch1 = ctrans_tosearch[:, :, 0]\r\n ch2 = ctrans_tosearch[:, :, 1]\r\n ch3 = ctrans_tosearch[:, :, 2]\r\n\r\n # Define blocks and steps as above\r\n nxblocks = (ch1.shape[1] // pix_per_cell) - cell_per_block + 1\r\n nyblocks = (ch1.shape[0] // pix_per_cell) - cell_per_block + 1\r\n nfeat_per_block = orient * cell_per_block ** 2\r\n\r\n nblocks_per_window = (window // pix_per_cell) - cell_per_block + 1\r\n nxsteps = (nxblocks - nblocks_per_window) // cells_per_step\r\n nysteps = (nyblocks - nblocks_per_window) // cells_per_step\r\n\r\n # Compute individual channel HOG features for the entire image\r\n hog1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=False)\r\n hog2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=False)\r\n hog3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=False)\r\n\r\n for xb in range(nxsteps):\r\n for yb in range(nysteps):\r\n ypos = yb * cells_per_step\r\n xpos = xb * cells_per_step\r\n # Extract HOG for this patch\r\n hog_feat1 = hog1[ypos:ypos + nblocks_per_window, xpos:xpos + nblocks_per_window].ravel()\r\n hog_feat2 = hog2[ypos:ypos + nblocks_per_window, xpos:xpos + nblocks_per_window].ravel()\r\n hog_feat3 = hog3[ypos:ypos + nblocks_per_window, xpos:xpos + nblocks_per_window].ravel()\r\n hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))\r\n\r\n xleft = xpos * pix_per_cell\r\n ytop = ypos * pix_per_cell\r\n\r\n # Extract the image patch\r\n subimg = cv2.resize(ctrans_tosearch[ytop:ytop + window, xleft:xleft + window], (64, 64))\r\n\r\n # Get color features\r\n spatial_features = bin_spatial(subimg, size=spatial_size)\r\n hist_features = color_hist(subimg, nbins=hist_bins)\r\n\r\n # Scale features and make a prediction\r\n test_features = X_scaler.transform(\r\n np.hstack((spatial_features, hist_features, hog_features)).reshape(1, -1), y=None, copy=None)\r\n # test_features = X_scaler.transform(np.hstack((shape_feat, hist_feat)).reshape(1, -1))\r\n test_prediction = svc.predict(test_features)\r\n\r\n if test_prediction == 1:\r\n xbox_left = np.int(xleft * scale)\r\n ytop_draw = np.int(ytop * scale)\r\n win_draw = np.int(window * scale)\r\n cv2.rectangle(draw_img, (xbox_left, ytop_draw + ystart),\r\n (xbox_left + win_draw, ytop_draw + win_draw + ystart), (0, 0, 255), 6)\r\n box.append([(xbox_left, ytop_draw + ystart), (xbox_left + win_draw, ytop_draw + win_draw + ystart)])\r\n\r\n return draw_img, box\r\n\r\n\r\nclass ObjectDetector(object):\r\n def __init__(self):\r\n svc, X_scaler, orient, pix_per_cell, cell_per_block, spatial_size, hist_bins = joblib.load(\"vehicle_detector_tmp.pkl\")\r\n self.box_tmp_1 = []\r\n self.box_tmp_2 = []\r\n self.box_tmp_3 = []\r\n self.box_tmp_4 = []\r\n self.box_tmp_5 = []\r\n self.box_tmp = []\r\n self.boxes = []\r\n self.heat = []\r\n self.svc = svc\r\n self.X_scaler = X_scaler\r\n self.orient = orient\r\n self.pix_per_cell = pix_per_cell\r\n self.cell_per_block = cell_per_block\r\n self.spatial_size = spatial_size\r\n self.hist_bins = hist_bins\r\n\r\n def process_image(self, image):\r\n\r\n # while (cap.isOpened()):\r\n # ret, frame = cap.read()\r\n # if ret == True:\r\n\r\n #######################################################################################################\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\n\r\n ystart = 400\r\n ystop = 656\r\n\r\n scale = 1.5\r\n window = 64\r\n cells_per_step = 1\r\n out_img, boxes_1 = find_cars(image, ystart, ystop, scale, self.svc, self.X_scaler, self.orient, self.pix_per_cell, self.cell_per_block,\r\n self.spatial_size, self.hist_bins, window, cells_per_step)\r\n\r\n scale = 1\r\n window = 64\r\n cells_per_step = 1\r\n out_img, boxes_2 = find_cars(image, ystart, ystop, scale, self.svc, self.X_scaler, self.orient, self.pix_per_cell, self.cell_per_block,\r\n self.spatial_size, self.hist_bins, window, cells_per_step)\r\n\r\n scale = 2\r\n window = 128\r\n cells_per_step = 1\r\n out_img, boxes_3 = find_cars(image, ystart, ystop, scale, self.svc, self.X_scaler, self.orient, self.pix_per_cell, self.cell_per_block,\r\n self.spatial_size, self.hist_bins, window, cells_per_step)\r\n\r\n self.boxes = boxes_1 + boxes_2 + boxes_3\r\n\r\n #######################################################################################################\r\n\r\n # Read in a pickle file with bboxes saved\r\n # Each item in the \"all_bboxes\" list will contain a\r\n # list of boxes for one of the images shown above\r\n box_list = self.boxes\r\n self.box_tmp_5 = self.box_tmp_4\r\n self.box_tmp_4 = self.box_tmp_3\r\n self.box_tmp_3 = self.box_tmp_2\r\n self.box_tmp_2 = self.box_tmp_1\r\n self.box_tmp_1 = box_list\r\n box_tmp = self.box_tmp_5 + self.box_tmp_4 + self.box_tmp_3 + self.box_tmp_2 + self.box_tmp_1\r\n\r\n # Read in image similar to one shown above\r\n heat = np.zeros_like(image[:, :, 0]).astype(np.float)\r\n\r\n # Add heat to each box in box list\r\n heat = add_heat(heat, box_tmp)\r\n\r\n # Apply threshold to help remove false positives\r\n heat = apply_threshold(heat, 10)\r\n\r\n # Visualize the heatmap when displaying\r\n heatmap = np.clip(heat, 0, 255)\r\n\r\n # Find final boxes from heatmap using label function\r\n labels = label(heatmap)\r\n draw_img = draw_labeled_bboxes(np.copy(image), labels)\r\n\r\n #######################################################################################################\r\n showed_image = draw_img\r\n cv2.imwrite(\"./video_images.jpg\", showed_image)\r\n # showed_image = image\r\n #\r\n # # Show movie\r\n # # out.write(showed_image)\r\n # # cv2.imshow('frame', showed_image)\r\n\r\n return cv2.cvtColor(showed_image, cv2.COLOR_BGR2RGB)\r\n\r\n # if cv2.waitKey(1) & 0xFF == ord('q'):\r\n # break\r\n # else:\r\n # break\r\n\r\n # cap.release()\r\n # out.release()\r\n # cv2.destroyAllWindows()","sub_path":"object_detection.py","file_name":"object_detection.py","file_ext":"py","file_size_in_byte":7342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"110542973","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom oslo_serialization import jsonutils\nfrom tempest.lib.common import rest_client\nfrom tempest.lib.common.utils import data_utils\nfrom tempest.lib import exceptions\n\n\nclass ClusteringClient(rest_client.RestClient):\n version = 'v1'\n\n def get_obj(self, obj_type, obj_id):\n uri = '{0}/{1}/{2}'.format(self.version, obj_type, obj_id)\n resp, body = self.get(uri)\n self.expected_success(200, resp.status)\n return self._parse_resp(body)\n\n def create_profile(self, spec, name=None, metadata=None):\n if name is None:\n name = data_utils.rand_name(\"tempest-created-profile\")\n uri = '{0}/profiles'.format(self.version)\n params = {\n 'profile': {\n 'name': name,\n 'spec': spec,\n 'metadata': metadata,\n }\n }\n resp, body = self.post(uri, body=jsonutils.dumps(params))\n self.expected_success(201, resp.status)\n return self._parse_resp(body)\n\n def list_profile(self):\n uri = '{0}/profiles'.format(self.version)\n resp, body = self.get(uri)\n self.expected_success(200, resp.status)\n return self._parse_resp(body)\n\n def delete_profile(self, profile_id, ignore_missing=False):\n uri = '{0}/profiles/{1}'.format(self.version, profile_id)\n try:\n resp, body = self.delete(uri)\n except exceptions.NotFound as ex:\n if ignore_missing:\n return\n raise ex\n self.expected_success(204, resp.status)\n\n def show_profile(self, profile_id):\n uri = '{0}/profiles/{1}'.format(self.version, profile_id)\n resp, body = self.get(uri)\n self.expected_success(200, resp.status)\n return self._parse_resp(body)\n\n def update_profile(self, profile_id, name=None, metadata=None):\n uri = '{0}/profiles/{1}'.format(self.version, profile_id)\n params = {}\n if name:\n params['name'] = name\n if metadata:\n params['metadata'] = metadata\n data = {'profile': params}\n resp, body = self.patch(uri, body=jsonutils.dumps(data))\n self.expected_success(200, resp.status)\n return self._parse_resp(body)\n\n def create_cluster(self, profile_id, desired_capacity,\n min_size=None, max_size=None, timeout=None,\n metadata=None, name=None):\n if name is None:\n name = data_utils.rand_name(\"tempest-created-cluster\")\n params = {\n 'cluster': {\n 'name': name,\n 'profile_id': profile_id,\n 'desired_capacity': desired_capacity,\n 'min_size': min_size,\n 'max_size': max_size,\n 'timeout': timeout,\n 'metadata': metadata,\n }\n }\n uri = '{0}/clusters'.format(self.version)\n resp, body = self.post(uri, body=jsonutils.dumps(params))\n self.expected_success(202, resp.status)\n action_id = resp['location'].split('/actions/')[1]\n return self._parse_resp(body), action_id\n\n def list_cluster(self):\n uri = '{0}/clusters'.format(self.version)\n resp, body = self.get(uri)\n self.expected_success(200, resp.status)\n return self._parse_resp(body)\n\n def delete_cluster(self, cluster_id, ignore_missing=False):\n uri = '{0}/clusters/{1}'.format(self.version, cluster_id)\n try:\n resp, body = self.delete(uri)\n except exceptions.NotFound as ex:\n if ignore_missing:\n return\n raise ex\n self.expected_success(202, resp.status)\n action_id = resp['location'].split('/actions/')[1]\n return action_id\n\n def show_cluster(self, cluster_id):\n uri = '{0}/clusters/{1}'.format(self.version, cluster_id)\n resp, body = self.get(uri)\n self.expected_success(200, resp.status)\n return self._parse_resp(body)\n\n def update_cluster(self, cluster_id, name=None, metadata=None,\n timeout=None, profile_id=None):\n uri = '{0}/clusters/{1}'.format(self.version, cluster_id)\n params = {}\n if name:\n params['name'] = name\n if metadata:\n params['metadata'] = metadata\n if timeout:\n params['timeout'] = timeout\n if profile_id:\n params['profile_id'] = profile_id\n data = {'cluster': params}\n resp, body = self.patch(uri, body=jsonutils.dumps(data))\n self.expected_success(202, resp.status)\n action_id = resp['location'].split('/actions/')[1]\n return action_id\n\n def create_node(self, profile_id, cluster_id=None, metadata=None,\n name=None):\n if name is None:\n name = data_utils.rand_name(\"tempest-created-node\")\n params = {\n 'node': {\n 'name': name,\n 'profile_id': profile_id,\n 'cluster_id': cluster_id,\n 'metadata': metadata,\n }\n }\n uri = '{0}/nodes'.format(self.version)\n resp, body = self.post(uri, body=jsonutils.dumps(params))\n self.expected_success(202, resp.status)\n action_id = resp['location'].split('/actions/')[1]\n return self._parse_resp(body), action_id\n\n def list_node(self):\n uri = '{0}/nodes'.format(self.version)\n resp, body = self.get(uri)\n self.expected_success(200, resp.status)\n return self._parse_resp(body)\n\n def delete_node(self, node_id, ignore_missing=False):\n uri = '{0}/nodes/{1}'.format(self.version, node_id)\n try:\n resp, body = self.delete(uri)\n except exceptions.NotFound as ex:\n if ignore_missing:\n return\n raise ex\n self.expected_success(202, resp.status)\n action_id = resp['location'].split('/actions/')[1]\n return action_id\n\n def show_node(self, node_id, show_details=False):\n uri = '{0}/nodes/{1}'.format(self.version, node_id)\n if show_details:\n uri += '?show_details=True'\n resp, body = self.get(uri)\n self.expected_success(200, resp.status)\n return self._parse_resp(body)\n\n def update_node(self, node_id, name=None, metadata=None,\n profile_id=None):\n uri = '{0}/nodes/{1}'.format(self.version, node_id)\n params = {}\n if name:\n params['name'] = name\n if metadata:\n params['metadata'] = metadata\n if profile_id:\n params['profile_id'] = profile_id\n data = {'node': params}\n resp, body = self.patch(uri, body=jsonutils.dumps(data))\n self.expected_success(202, resp.status)\n action_id = resp['location'].split('/actions/')[1]\n return action_id\n","sub_path":"senlin/tests/tempest/services/clustering/clustering_client.py","file_name":"clustering_client.py","file_ext":"py","file_size_in_byte":7391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"41915119","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/1/23 8:57\n# @Author : xxx\n# @Email : xxx@admin.com\n# @File : server.py\n# @Software: PyCharm\nimport json\nimport socket\nimport hashlib\n\nsk = socket.socket()\nsk.bind(('127.0.0.1',9000))\nsk.listen()\ndef get_md5_code(usr,pwd):\n md5 = hashlib.md5(usr.encode())\n md5.update(pwd.encode())\n return md5.hexdigest()\n\nconn,addr = sk.accept()\nmsg = conn.recv(1024).decode()\ndic = json.loads(msg)\n\nwith open('userinfo') as f:\n for line in f:\n usr,pwd = line.strip().split('|')\n if usr == dic['username'] and pwd == get_md5_code(dic['username'],dic['password']):\n ret = {'code':1}\n res_msg = json.dumps(ret).encode()\n conn.send(res_msg)\n break\n else:\n ret = {'code': 0}\n res_msg = json.dumps(ret).encode()\n conn.send(res_msg)\nconn.close()\nsk.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"day25/作业讲解1/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"63892966","text":"\r\nimport pymysql\r\nimport pandas as pd\r\n\r\nimport pandas as pd\r\nimport math\r\n\r\ndef cnt(x):\r\n x = str(x)\r\n x = x[0:4]\r\n return float(x)\r\n\r\n\r\ndef convert_state(x,df):\r\n \r\n lat = x[2]\r\n lng = x[3]\r\n \r\n #df = pd.read_excel(\"C:\\\\Users\\\\shubham\\\\Documents\\\\dash_board\\\\in.xlsx\")\r\n \r\n lat = cnt(lat)\r\n lng = cnt(lng)\r\n\r\n for i in range(df.shape[0]):\r\n if abs(cnt(df['lat'][i]- lat))<=0.1 and abs(cnt(df['lng'][i] -lng))<=0.1 :\r\n return df['state'][i]\r\n\r\ndef convert_city(x,df):\r\n \r\n lat = x[2]\r\n lng = x[3]\r\n \r\n \r\n \r\n lat = cnt(lat)\r\n lng = cnt(lng)\r\n\r\n for i in range(df.shape[0]):\r\n if abs(cnt(df['lat'][i]- lat))<=0.1 and abs(cnt(df['lng'][i] -lng))<=0.1 :\r\n return df['city'][i]\r\ndef split_pages(x):\r\n return x.split(',')\r\n\r\ndef get_data():\r\n\r\n df1 = pd.read_excel(\"C:\\\\Users\\\\shubham\\\\Documents\\\\dash_board\\\\in.xlsx\")\r\n\r\n conn = pymysql.connect(\"localhost\",\"root\",\"1234\",\"visiters\")\r\n SQL_Query = pd.read_sql_query('''select * from info''', conn)\r\n df = pd.DataFrame(SQL_Query, columns=['sno','uid','lat','lng','pages','date','count'])\r\n\r\n a = df.apply(lambda x: convert_state(x,df1), axis=1)\r\n b = df.apply(lambda x: convert_city(x,df1), axis=1)\r\n\r\n df.rename(columns = {'lat':'state', 'lng':'city'}, inplace = True)\r\n\r\n df['state'] = a\r\n df['city'] = b\r\n\r\n df['pages'] = df['pages'].apply(lambda x: split_pages(x))\r\n\r\n\r\n \r\n conn.close()\r\n return df\r\n","sub_path":"get_data_from_db/fetch_db.py","file_name":"fetch_db.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"166409143","text":"import logging\nimport operator\nimport os\nfrom abc import ABC, abstractmethod\nfrom functools import reduce\n\nfrom servicelib.logging_utils import log_catch\nfrom watchdog.events import FileSystemEvent, FileSystemEventHandler\nfrom watchdog.observers.api import DEFAULT_OBSERVER_TIMEOUT, BaseObserver\nfrom watchdog.observers.inotify import InotifyBuffer, InotifyEmitter\nfrom watchdog.observers.inotify_c import Inotify, InotifyConstants\nfrom watchdog.utils import BaseThread\nfrom watchdog.utils.delayed_queue import DelayedQueue\n\n_EVENTS_TO_WATCH = reduce(\n operator.or_,\n [\n InotifyConstants.IN_MODIFY,\n InotifyConstants.IN_MOVED_FROM,\n InotifyConstants.IN_MOVED_TO,\n InotifyConstants.IN_CREATE,\n InotifyConstants.IN_DELETE,\n InotifyConstants.IN_DELETE_SELF,\n InotifyConstants.IN_DONT_FOLLOW,\n InotifyConstants.IN_CLOSE_WRITE,\n ],\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass _ExtendedInotifyBuffer(InotifyBuffer):\n def __init__(self, path, recursive=False): # pylint:disable=super-init-not-called\n # below call to `BaseThread.__init__` is correct since we want to\n # overwrite the `InotifyBuffer.__init__` method\n BaseThread.__init__(self) # pylint:disable=non-parent-init-called\n self._queue = DelayedQueue(self.delay)\n self._inotify = Inotify(path, recursive, _EVENTS_TO_WATCH)\n self.start()\n\n\nclass _ExtendedInotifyEmitter(InotifyEmitter):\n def on_thread_start(self):\n path = os.fsencode(self.watch.path)\n # pylint:disable=attribute-defined-outside-init\n self._inotify = _ExtendedInotifyBuffer(path, self.watch.is_recursive)\n\n\nclass ExtendedInotifyObserver(BaseObserver):\n \"\"\"\n Observer thread that schedules watching directories and dispatches\n calls to event handlers.\n\n Extended to ignore some events which were undesired\n such as attribute changes (permissions, ownership, etc..).\n \"\"\"\n\n def __init__(self):\n BaseObserver.__init__(\n self,\n emitter_class=_ExtendedInotifyEmitter,\n timeout=DEFAULT_OBSERVER_TIMEOUT,\n )\n\n\nclass SafeFileSystemEventHandler(ABC, FileSystemEventHandler):\n \"\"\"\n If an error is raised by `on_any_event` watchdog will stop\n working, no further events will be emitted.\n \"\"\"\n\n @abstractmethod\n def event_handler(self, event: FileSystemEvent) -> None:\n \"\"\"\n User code for handling the event.\n If this raises an error it will not stop future events.\n \"\"\"\n\n def on_any_event(self, event: FileSystemEvent) -> None:\n \"\"\"overwrite and use `event_handler`\"\"\"\n super().on_any_event(event)\n\n # NOTE: if an exception is raised by this handler\n # which is running in the context of the\n # ExtendedInotifyObserver will cause the\n # observer to stop working.\n with log_catch(logger, reraise=False):\n self.event_handler(event)\n","sub_path":"services/dynamic-sidecar/src/simcore_service_dynamic_sidecar/modules/outputs/_watchdog_extensions.py","file_name":"_watchdog_extensions.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"81969399","text":"\"\"\"Определение координат повторителя\"\"\"\r\n# -*- coding: utf-8 -*-\r\nimport random\r\nimport math\r\nfrom math import sqrt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nclass Point():\r\n \"\"\" Класс, объекты которого являются точками в 3-мерном пространстве \"\"\"\r\n in_range = False\r\n def __init__(self, x, y, z):\r\n self.x = x\r\n self.y = y\r\n self.z = z\r\n def In_range(self):\r\n self.in_range = True\r\n\r\n def Out_of_range(self):\r\n self.in_range = False\r\n\r\ndef clustering(dev_mas, clust_num, iter_num):\r\n \"\"\" Алгоритм нахождения координат повторителя \"\"\"\r\n iterations = 0 # Число итераций\r\n k = 0\r\n flag = False # Условие окончания цикла\r\n Sum = {} # Сумма квадратов расстояний от устройства до повторителя\r\n Sumx = {} # Сумма квадратов значений координат x устройств\r\n Sumy = {} # Сумма квадратов значений координат y устройств\r\n Sumz = {} # Сумма квадратов значений координат z устройств\r\n dev_count = {} # Массив, содержащий количество устройств, подключенных к повторителям\r\n dist = {} # Массив расстояний между устройством и повторителем\r\n rep_mas = {} # Массив координат повторителей\r\n\r\n for i in range(clust_num):\r\n rep_mas[i] = Point(random.randint(0, 50), random.randint(0, 50), random.randint(0, 50))\r\n\r\n while flag is False:\r\n iterations = iterations + 1\r\n full_sum = 0\r\n\r\n for i in range(len(dev_mas)):\r\n dist[i] = 10000\r\n dev_mas[i].Out_of_range()\r\n\r\n for i in range(clust_num):\r\n Sum[i] = 0\r\n Sumx[i] = 0\r\n Sumy[i] = 0\r\n Sumz[i] = 0\r\n dev_count[i] = 0\r\n\r\n for j in range(len(dev_mas)):\r\n for i in range(len(rep_mas)):\r\n if sqrt((rep_mas[i].x - dev_mas[j].x) ** 2 + (rep_mas[i].x - dev_mas[j].x) ** 2 +\r\n (rep_mas[i].x - dev_mas[j].x) ** 2) < dist[j]:\r\n dist[j] = sqrt((rep_mas[i].x - dev_mas[j].x) ** 2 +\r\n (rep_mas[i].x - dev_mas[j].x) ** 2 +\r\n (rep_mas[i].x - dev_mas[j].x) ** 2)\r\n k = i\r\n Sum[k] = Sum[k] + (rep_mas[k].x - dev_mas[j].x) ** 2 + \\\r\n (rep_mas[k].x - dev_mas[j].x) ** 2 + (rep_mas[k].x - dev_mas[j].x) ** 2\r\n Sumx[k] = Sumx[k] + dev_mas[j].x ** 2\r\n Sumy[k] = Sumy[k] + dev_mas[j].y ** 2\r\n Sumz[k] = Sumz[k] + dev_mas[j].z ** 2\r\n\r\n if sqrt((rep_mas[i].x - dev_mas[j].x) ** 2 + (rep_mas[i].x - dev_mas[j].x) ** 2 +\r\n (rep_mas[i].x - dev_mas[j].x) ** 2) < 50:\r\n dev_mas[j].In_range()\r\n\r\n for i in range(clust_num):\r\n full_sum = full_sum + Sum[i]\r\n\r\n for i in range(len(dist)):\r\n print(\"dist[\", i, \"] = \", dist[i], sep=\"\")\r\n\r\n print(\"full_sum = \", full_sum, sep=\"\")\r\n all_in_range = True\r\n\r\n for i in range(len(dev_mas)):\r\n if dev_mas[i].in_range == False:\r\n all_in_range = False\r\n break\r\n\r\n if all_in_range is True:\r\n print(\"Связь со всеми устройствами установлена после \", iterations, \" итераций(-и)\", sep=\"\")\r\n flag = True\r\n elif iterations == iter_num:\r\n print(\"Превышено число итераций. Для установления связи необходимо больше повторителей\")\r\n flag = True\r\n else:\r\n print(\"Не со всеми устройствами установлена связь\")\r\n for i in range(clust_num):\r\n rep_mas[i].x = sqrt(Sumx[i]) * random.randint(0, 1)\r\n rep_mas[i].y = sqrt(Sumy[i]) * random.randint(0, 1)\r\n rep_mas[i].z = sqrt(Sumz[i]) * random.randint(0, 1)\r\n\r\n u = np.linspace(0, 2 * np.pi, 50)\r\n v = np.linspace(0, np.pi, 50)\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n for i in range(len(dev_mas)):\r\n if dev_mas[i].technology == \"WiFi\":\r\n clr = \"orange\"\r\n else:\r\n clr = \"blue\"\r\n x1 = 5 * np.outer(np.cos(u), np.sin(v)) + dev_mas[i].x\r\n y1 = 5 * np.outer(np.sin(u), np.sin(v)) + dev_mas[i].y\r\n z1 = 5 * np.outer(np.ones(np.size(u)), np.cos(v)) + dev_mas[i].z\r\n ax.plot_surface(x1, y1, z1, color=clr)\r\n\r\n for j in range(len(rep_mas)):\r\n x2 = 5 * np.outer(np.cos(u), np.sin(v)) + rep_mas[j].x\r\n y2 = 5 * np.outer(np.sin(u), np.sin(v)) + rep_mas[j].y\r\n z2 = 5 * np.outer(np.ones(np.size(u)), np.cos(v)) + rep_mas[j].z\r\n ax.plot_surface(x2, y2, z2, color='g')\r\n\r\n ax.set_xlabel('X Label')\r\n ax.set_ylabel('Y Label')\r\n ax.set_zlabel('Z Label')\r\n plt.show()\r\n\r\n\r\n","sub_path":"repeater.py","file_name":"repeater.py","file_ext":"py","file_size_in_byte":5339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"246324279","text":"import pymongo\n\n#Inicializamos la BD\nfrom pymongo import MongoClient\nclient = MongoClient()\ndb = client.primer\n# Creamos la conex\ndb = client.database\ncamps = db.camps\nfor camp in camps.find():\n\tprint(camp)","sub_path":"docs/trash/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"347678819","text":"import random\nimport json\nfrom django.test import TestCase\n\nimport os\nimport dr.models\n\ndef a():\n with open('static/json/goodlist.json','r') as f :\n jsondict = json.load(f)\n for i in jsondict :\n for j in i :\n goods = dr.models.Goodslist()\n goods.name = j['title']\n goods.price = j['price']\n goods.price1 = int(j['price1'])\n goods.price2 = int(j['price2'])\n goods.material2 = j['material2']\n\n goods.com = int(j['com'])\n goods.src = j['src']\n goods.index = j['index']\n goods.discript = j['discript']\n goods.material1 = j['material1']\n goods.sale = int(j['sale'])\n goods.save()\n if j.get('img') :\n for k in j['img']:\n img = dr.models.Goodsimg()\n img.src = k['src']\n img.goods = goods\n img.save()\n\n\n\n\n\"\"\"\n{'material2': '白18K金', \n 'img': [{'src': 'images/2016060812454522d7889f26.jpg'},\n {'src': 'images/201509301425347b86245a0e.jpg'}, \n {'src': 'images/201603301519256b9cccee8f.jpg'},\n {'src': 'images/20160620101350d2f9fcb5a8.jpg'}],\n 'id': '1', \n 'price': '9999',\n 'com': '756',\n 'price2': '10008',\n 'src': 'images/2016060812454522d7889f26.jpg',\n 'price1': '9898',\n 'index': '1',\n 'discript': 'TRUE LOVE系列 典雅 40分 F色',\n 'title': '黑骑士',\n 'material1': 'PT950',\n 'sale': '1341'}\n\"\"\"\n\n\n","sub_path":"DR/dr/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"155380719","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom urllib.request import urlopen\n#Plot figures in external window:\nfrom IPython import get_ipython\nget_ipython().run_line_magic('matplotlib', 'qt') \n\nshot = input(\"Cislo vyboje:\")\n\n# =============================================================================\n# Diagnostiky z tokamaku\n## ============================================================================\n\nData_current = None\nData_HXR = None\nData_SXR = None\nData_neutron = None\nData_gas = None\n\ntry:\n url_current = 'https://webcdb.tok.ipp.cas.cz/data_signals/728/%s/data?variant=&revision=1&downsample=100' % (shot)\n ourl_current = urlopen(url_current)\n Data_current = np.loadtxt(ourl_current)\nexcept Exception:\n pass\n\ntry:\n url_HXR = 'https://webcdb.tok.ipp.cas.cz/data_signals/1266/%s/data?variant=&revision=1&downsample=100' % (shot)\n ourl_HXR = urlopen(url_HXR)\n Data_HXR = np.loadtxt(ourl_HXR)\nexcept Exception:\n pass\n\ntry:\n url_SXR = 'https://webcdb.tok.ipp.cas.cz/data_signals/1195/%s/data?variant=&revision=1&downsample=100' % (shot)\n ourl_SXR = urlopen(url_SXR)\n Data_SXR = np.loadtxt(ourl_SXR)\nexcept Exception:\n pass\n\ntry:\n url_neutron = 'https://webcdb.tok.ipp.cas.cz/data_signals/2122/%s/data?variant=&revision=1&downsample=100' % (shot)\n ourl_neutron = urlopen(url_neutron)\n Data_neutron = np.loadtxt(ourl_neutron)\nexcept Exception:\n pass\n\ntry:\n url_gas = 'https://webcdb.tok.ipp.cas.cz/data_signals/4789/%s/data?variant=&revision=1' % (shot)\n ourl_gas = urlopen(url_gas)\n Data_gas = np.loadtxt(ourl_gas)\nexcept Exception:\n pass\n\n\n\n\n# =============================================================================\n# \n# =============================================================================\n\n# HXR\nif Data_HXR is not None:\n time_HXR = np.array([row[0] for row in Data_HXR])\n data_HXR = np.array([row[1] for row in Data_HXR])\nelse: print(\"Data_HXR is failed\")\n# Neutrony - HXR\nif Data_neutron is not None:\n time_neutron = np.array([row[0] for row in Data_neutron])\n data_neutron = np.array([row[1] for row in Data_neutron])\nelse: print(\"Data_neutron is failed\")\n# SXR\nif Data_SXR is not None:\n time_SXR = np.array([row[0] for row in Data_SXR])\n data_SXR = np.array([row[1] for row in Data_SXR])\nelse: print(\"Data_SXR is failed\")\n# gas puff\nif Data_gas is not None:\n time_gas = np.array([row[0] for row in Data_gas])\n data_gas = np.array([row[1] for row in Data_gas])\nelse: print(\"Data_gas is failed\")\n# Current\nif Data_current is not None:\n time_current = np.array([row[0] for row in Data_current])\n data_current = np.array([row[1] for row in Data_current])\nelse: print(\"Data_current is failed\")\n\n# =============================================================================\n# Graf\n# =============================================================================\n\n#fig = plt.figure()\n\nleft = 920\nright = 1500\n\nplt.subplots(4, 1, sharex='all')\n\nif Data_current is not None:\n ax1 = plt.subplot(221)\n ax1.set_xlim(left,right)\n ax1.plot(time_current, data_current/1e3, color='red', label=\"current\")\n ax2 = ax1.twinx()\n ax2.axes.get_yaxis().set_ticks([])\nelse: \n ax1 = plt.subplot(221)\n ax1.set_xlim(left,right)\n ax1.plot(color='red', label=\"current\")\n \nif Data_SXR is not None:\n ax3 = plt.subplot(222)\n ax3.set_xlim(left,right)\n ax3.plot(time_SXR, data_SXR*-1, color='blue', label=\"SXR\")\n ax3.axes.get_yaxis().set_ticks([])\n ax4 = ax3.twinx()\n ax4.axes.get_yaxis().set_ticks([])\nelse:\n ax3 = plt.subplot(222)\n ax3.set_xlim(left,right)\n ax3.plot(color='blue', label=\"SXR\")\n\nif Data_HXR is not None:\n ax5 = plt.subplot(223)\n ax5.set_xlim(left,right)\n ax5.plot(time_HXR, data_HXR*-1, color='green', label=\"HXR\")\n ax6 = ax5.twinx()\n ax6.axes.get_yaxis().set_ticks([])\n ax6.plot(time_gas, data_gas, color='orange', label=\"gaspuff\")\nelse: \n ax5 = plt.subplot(223)\n ax5.set_xlim(left,right)\n ax5.plot(color='green', label=\"HXR\")\n \nif Data_neutron is not None:\n ax7 = plt.subplot(224)\n ax7.set_xlim(left,right)\n ax7.plot(time_neutron, data_neutron*-1, color='cyan', label=\"neutrons\")\n ax8 = ax7.twinx()\n ax8.axes.get_yaxis().set_ticks([])\n ax8.plot(time_gas, data_gas, color='orange', label=\"gaspuff\")\nelse:\n ax7 = plt.subplot(224)\n ax7.set_xlim(left,right)\n ax7.plot(color='cyan', label=\"neutrons\")\n \nax1.set_xlabel(\"Time, [ms]\",)\nax1.set_ylabel(\"Ip, [kA]\")\nax3.set_ylabel(\"[a.u.]\")\nax5.set_ylabel(\"[a.u.]\")\nax7.set_ylabel(\"[a.u.]\")\n\nax1.xaxis.label.set_size(14)\nax1.yaxis.label.set_size(14)\nax3.yaxis.label.set_size(14)\nax5.yaxis.label.set_size(14)\nax7.yaxis.label.set_size(14)\n\n\nax1.tick_params(axis='x', labelsize = 14)\nax1.tick_params(axis='y', labelsize = 14)\n#ax1.ticklabel_format(axis='y', style='sci', scilimits=(0,0))\nax3.tick_params(axis='y', labelsize = 14)\nax5.tick_params(axis='y', labelsize=14)\nax7.tick_params(axis='y', labelsize=14)\n#ax3.tick_params(axis='y', colors=\"orange\", labelsize=14)\n#ax3.tick_params(axis='y', colors=\"orange\", labelsize=14)\n\nax1.legend(loc=\"upper right\")\nax3.legend(loc=\"upper right\")\nax5.legend(loc=\"upper right\")\nax7.legend(loc=\"upper right\")\nplt.show()\n\n#fig.savefig('19950:HXR_SXR_X-chip.pdf')\nplt.show()","sub_path":"wtf/Scrappy/teset.py","file_name":"teset.py","file_ext":"py","file_size_in_byte":5277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"239784037","text":"# _make\r\nfrom collections import namedtuple\r\n\r\n\r\ndef student_info():\r\n Student = namedtuple('Student', ['usn', 'name', 'college'])\r\n #s = Student('1ms09cs416', 'Arun', 'msrit')\r\n # print(s)\r\n #_make()\r\n\r\n lst = ['1ms09cs417', 'Gautham', 'msrit']\r\n s1 = Student._make(lst)\r\n print(s1)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n student_info()\r\n '''\r\nOutput:\r\nStudent(usn='1ms09cs417', name='Gautham', college='msrit') '''\r\n","sub_path":"python programs/data wise notes/25 april/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"346432165","text":"from __future__ import print_function, absolute_import\n\nfrom functools import partial\nimport operator\nimport os\nimport traceback\n\nfrom ...vendor import Qt\n\n\nfrom pymel.core import Callback, confirmDialog, getAttr, hide, objExists, scriptJob, select, selected, setParent, setAttr, \\\n shelfButton, shelfLayout, showHidden, tabLayout, warning, xform\n\nfrom ... import core\n\nfrom . import card as fossil_card # Hack to not deal with the fact that \"card\" is a var used all over, thusly shadowing this import\nfrom . import cardlister\nfrom . import cardparams\nfrom . import cardRigging\nfrom . import controllerShape\nfrom . import moveCard\nfrom . import proxy\nfrom . import util\n\nfrom .ui import artistToolsTab\nfrom .ui import controllerEdit\nfrom .ui import _visGroup\n\nfrom .ui import spacesTab\nfrom .ui import startingTab\n\n\nRigToolUI = core.ui.getQtUIClass( os.path.dirname(__file__) + '/ui/rigToolUI.ui', 'pdil.tool.fossil.ui.rigToolUI')\n\n\ndef matchOrient():\n if len(selected()) < 2:\n return\n \n src = selected()[0]\n rot = xform(src, q=True, ws=True, ro=True)\n \n for dest in selected()[1:]:\n xform( dest, ws=True, ro=rot )\n\n\ndef customUp(self):\n if not selected():\n return\n \n arrow = selected()[0]\n\n if not arrow.name().count('arrow'):\n arrow = None\n \n if not util.selectedJoints():\n warning('No BPJoints were selected')\n return\n\n for jnt in util.selectedJoints():\n fossil_card.customUp(jnt, arrow)\n\n\nclass RigTool(Qt.QtWidgets.QMainWindow):\n \n _inst = None\n \n FOSSIL_START_TAB = 'Fossil_RigTool_StartTab'\n FOSSIL_ARTIST_TOOLS = 'Fossil_RigTool_ToolsTab'\n FOSSIL_SPACE_TAB = 'Fossil_RigTool_SpacedTab'\n \n settings = core.ui.Settings( \"Skeleton Tool Settings\",\n {\n \"spineCount\": 5,\n \"fingerCount\": 4,\n \"thumb\": True,\n \"spineOrient\": \"Vertical\",\n \"legType\": \"Human\",\n \"tabIndex\": 1, # 1-base\n 'panels': [75, 75, 25, 100, 75, 25],\n 'rebuildMode': 'Use Current Shapes',\n\n 'closedControlFrame': False,\n 'closeDebugFrame': True,\n })\n \n @staticmethod\n @core.alt.name( 'Rig Tool' )\n def run():\n return RigTool()\n \n \n def connectorDisplayToggle(self):\n \n if self.ui.actionConnectors.isChecked():\n showHidden( fossil_card.getConnectors() )\n else:\n hide( fossil_card.getConnectors() )\n \n \n def handleDisplayToggle(self):\n \n val = self.ui.actionHandles.isChecked()\n \n #cards = ls( '*.skeletonInfo', o=1 )\n for card in core.findNode.allCards():\n for joint in card.joints:\n joint.displayHandle.set(val)\n \n \n def orientsToggle(self):\n if self.ui.actionCard_Orients_2.isChecked():\n showHidden( fossil_card.getArrows() )\n else:\n hide( fossil_card.getArrows() )\n \n \n def __init__(self, *args, **kwargs):\n global settings\n \n objectName = 'Rig_Tool'\n # Remove any existing windows first\n core.ui.deleteByName(objectName)\n \n super(RigTool, self).__init__(core.ui.mayaMainWindow())\n \n self.ui = RigToolUI()\n self.ui.setupUi(self)\n\n self.setObjectName(objectName)\n self.setWindowTitle('Fossil')\n \n # Menu callbacks\n self.ui.actionReconnect_Real_Joints.triggered.connect( Callback(fossil_card.reconnectRealBones) )\n self.ui.actionMatch_Selected_Orients.triggered.connect( Callback(matchOrient) )\n \n self.ui.actionCard_Orients_2.triggered.connect( Callback(self.orientsToggle) )\n \n # &&& I think this isn't useful but I'm going to wait a while to be sure.\n #self.ui.actionConnectors.triggered.connect( Callback(self.connectorDisplayToggle) )\n self.ui.menuVisibility.removeAction(self.ui.actionConnectors)\n \n self.ui.actionHandles.triggered.connect( Callback(self.handleDisplayToggle) )\n \n \n '''\n button(l=\"Custom Up\", c=Callback(customUp), w=200)\n \n '''\n \n \n # Callback setup\n \n self.ui.makeCardBtn.clicked.connect(self.makeCard)\n self.ui.selectAllBtn.clicked.connect(self.selectAll)\n self.ui.buildBonesBtn.clicked.connect(self.buildBones)\n self.ui.deleteBonesBtn.clicked.connect( partial(util.runOnEach, operator.methodcaller('removeBones'), 'Bones deleted') )\n self.ui.buildRigBtn.clicked.connect( self.buildRig )\n self.ui.deleteRigBtn.clicked.connect( partial(util.runOnEach, operator.methodcaller('removeRig'), 'Rig deleted') )\n self.ui.saveModsBtn.clicked.connect( partial(util.runOnEach, operator.methodcaller('saveState'), 'State saved') )\n self.ui.restoreModsBtn.clicked.connect( partial(util.runOnEach, operator.methodcaller('restoreState'), 'State restored') )\n \n \n self.ui.duplicateCardBtn.clicked.connect(self.duplicateCard)\n self.ui.mergeCardBtn.clicked.connect(self.mergeCard)\n self.ui.splitCardBtn.clicked.connect(self.splitCard)\n \n self.ui.insertJointBtn.clicked.connect(self.insertJoint)\n self.ui.addTipBtn.clicked.connect(partial(self.insertJoint, True))\n self.ui.deleteJointBtn.clicked.connect(self.deleteJoint)\n \n self.ui.rebuildProxyBtn.clicked.connect( proxy.rebuildConnectorProxy )\n \n self.ui.customUpBtn.clicked.connect(Callback(customUp))\n \n # Start Group Tab\n self.startTabLayout = Qt.QtWidgets.QVBoxLayout(self.ui.tab)\n self.startTabLayout.setObjectName( self.FOSSIL_START_TAB )\n setParent( self.FOSSIL_START_TAB )\n self.startTab = startingTab.StartLayout( self )\n \n \n # Vis Group Tab\n self.visGroupProxy = _visGroup.VisGroupLayout(self.ui)\n \n # Space Tab\n self.spaceTabLayout = Qt.QtWidgets.QVBoxLayout(self.ui.space_tab)\n \n self.spaceTabLayout.setObjectName( self.FOSSIL_SPACE_TAB )\n setParent( self.FOSSIL_SPACE_TAB)\n self.spaceTab = spacesTab.SpaceLayout()\n \n \n # Shelf tab\n \n \n self.artistShelfLayout = Qt.QtWidgets.QVBoxLayout(self.ui.artist_tools)\n self.artistShelfLayout.setObjectName( self.FOSSIL_ARTIST_TOOLS )\n setParent( self.FOSSIL_ARTIST_TOOLS )\n \n artistToolsTab.toolShelf()\n\n \n # Card Lister setup\n self.updateId = scriptJob( e=('SelectionChanged', core.alt.Callback(self.selectionChanged)) )\n self.ui.cardLister.setup()\n \n self.ui.cardLister.itemSelectionChanged.connect(self.cardListerSelection)\n \n self.ui.cardLister.cardListerRefresh(force=True)\n self.ui.cardLister.updateHighlight()\n \n self.ui.jointLister.setup()\n \n self.ui.cardLister.namesChanged.connect( self.ui.jointLister.jointListerRefresh )\n \n # Controller Edit\n self.shapeEditor = controllerEdit.ShapeEditor(self)\n self.show()\n \n core.pubsub.subscribe(core.pubsub.Event.MAYA_DAG_OBJECT_CREATED, self.ui.cardLister.newObjMade)\n \n self.uiActive = True\n self._uiActiveStack = []\n \n def noUiUpdate(self):\n self._uiActiveStack.append( self.uiActive )\n self.uiActive = False\n yield\n self.uiActive = self._uiActiveStack.pop()\n \n self.updateId = scriptJob( e=('SelectionChanged', core.alt.Callback(self.selectionChanged)) )\n\n def selectAll(self):\n select( core.findNode.allCards() )\n \n @staticmethod\n def buildBones():\n sel = set(util.selectedCards())\n if not sel:\n confirmDialog( m='No cards selected' )\n return\n \n # Only build the selected cards, but always do it in the right order.\n for card in cardlister.cardJointBuildOrder():\n if card in sel:\n card.buildJoints()\n \n @staticmethod\n def buildRig():\n '''\n Makes the rig, saving shapes and removing the old rig if needed.\n '''\n cards = util.selectedCards()\n \n mode = 'Use Rig Info Shapes'\n \n if not cards:\n confirmDialog( m='No cards to selected to operate on.' )\n return\n \n \n for card in cards:\n if mode == 'Use Current Shapes':\n card.saveShapes()\n \n # If this being rebuilt, also restore the if it's in ik or fk\n switchers = [controllerShape.getSwitcherPlug(x[0]) for x in card._outputs()]\n prevValues = [ (s, getAttr(s)) for s in switchers if s]\n\n card.removeRig()\n cardRigging.buildRig([card])\n\n if mode != 'Use Rig Info Shapes':\n card.restoreShapes()\n \n # Restore ik/fk-ness\n for switch, value in prevValues:\n if objExists(switch):\n setAttr(switch, value)\n\n def closeEvent(self, event):\n #print('------ - - - i am closing')\n core.pubsub.unsubscribe(core.pubsub.Event.MAYA_DAG_OBJECT_CREATED, self.ui.cardLister.newObjMade)\n try:\n if self.updateId is not None:\n id = self.updateId\n self.updateId = None\n scriptJob(kill=id)\n except Exception:\n pass\n \n # Might be overkill but I'm trying to prevent new gui parenting to the old widgets\n self.artistShelfLayout.setObjectName( 'delete_me' )\n self.spaceTabLayout.setObjectName( 'delete_me2' )\n self.shapeEditor.curveColorLayout.setObjectName( 'delete_me3' )\n self.shapeEditor.surfaceColorLayout.setObjectName( 'delete_me4' )\n self.startTabLayout.setObjectName('delete_me5')\n \n event.accept()\n \n def selectionChanged(self):\n self.ui.cardLister.updateHighlight()\n \n selectedCard = util.selectedCardsSoft(single=True)\n \n cardparams.update(self, selectedCard)\n self.ui.jointLister.jointListerRefresh(selectedCard)\n self.ui.jointLister.refreshHighlight()\n self.shapeEditor.refresh()\n \n def cardListerSelection(self):\n if self.ui.cardLister.uiActive:\n cards = [item.card for item in self.ui.cardLister.selectedItems()]\n select(cards)\n\n def makeCard(self):\n '''\n Make a new card and child it if a BPJoint is selected.\n \n .. todo::\n I think, when adding a chain, if the parent doesn't have an orient target\n already, give it its existing child. Of course this won't quite work\n for the pelvis but whatever.\n '''\n try:\n radius = 1\n targetParent = util.selectedJoints()[0] if util.selectedJoints() else None\n if not targetParent and selected():\n # Quick hack for if the annotation is selected instead of the\n # handle. This is really just a pain and I should link the\n # Annotation to the real joint.\n try:\n intendedTarget = selected()[0].t.listConnections()[0].output3D.listConnections()[0]\n if intendedTarget.__class__.__name__ == 'BPJoint':\n targetParent = intendedTarget\n except Exception:\n pass\n \n count = self.ui.jointCount.value()\n name = str(self.ui.cardJointNames.text())\n \n # Auto repeat the name if only one was given\n if len(name.split()) == 1 and count > 1 and name[-1] != '*':\n name += '*'\n \n try:\n head, repeat, tail = util.parse(name)\n except Exception:\n raise Exception('Invalid characters given')\n \n if count <= 0:\n raise Exception( 'You must specify at least one joint!' )\n\n namedCount = len(head) + len(tail) + (1 if repeat else 0)\n print( namedCount )\n if count < namedCount:\n raise Exception( 'Not enough joints exist to take all of the given names' )\n if count > namedCount and not repeat:\n raise Exception( 'No name was specified as repeating and too many joints were given.' )\n \n #card = skeletonTool.core.Card( jointCount=count, name=name, rigInfo=None, size=(4, 6) )\n newCard = fossil_card.makeCard(jointCount=count, jointNames=name, rigInfo=None, size=(4, 6) )\n \n if targetParent:\n moveCard.to( newCard, targetParent )\n \n #skeletonTool.proxy.pointer( targetParent, newCard.start() )\n newCard.start().setBPParent(targetParent)\n radius = targetParent.radius.get()\n else:\n proxy.makeProxy(newCard.start())\n newCard.start().proxy.setParent( proxy.getProxyGroup() )\n \n for j in newCard.joints:\n j.radius.set(radius)\n j.proxy.radius.set(radius)\n \n select( newCard )\n except Exception as ex:\n print( traceback.format_exc() )\n m = str(ex) + '''\\n\n All names must be valid as Maya names.\n Optionally one may end with a '*' signifying it repeats.\n \n Ex: Chest Neck* Head HeadTip\n \n Would only be valid if the card had at least 4 joints, any above\n that would increase the Neck: Chest Neck01 Neck02 .. Neck Head HeadTip\n \n Repeating can be at the start or end or no repeats at all, as long as the numbers make sense.\n '''\n \n confirmDialog(t='Error', m=m)\n raise\n\n #-- Joints and Cards ------------------------------------------------------\n def insertJoint(self, tip=False):\n sel = util.selectedJoints()\n if not sel:\n warning('You must select the blueprint joint you want to insert after.')\n return\n \n children = sel[0].proxyChildren[:]\n \n card = sel[0].card\n newJoint = card.insertJoint(sel[0])\n \n if tip:\n \n rigData = card.rigData\n \n names = rigData.get('nameInfo', {})\n \n if names.get('tail'):\n names['tail'].append( names['tail'][-1] + 'Tip' )\n else:\n names['tail'] = ['Tip']\n \n card.rigData = rigData\n \n newJoint.isHelper = True\n \n # Repoint the children back to the selected joint since the tip is for orienting\n for child in children:\n proxy.pointer(sel[0], child)\n \n self.ui.cardLister.updateNames(card)\n \n select( newJoint )\n \n def deleteJoint(self):\n sel = util.selectedJoints()\n if not sel:\n return\n \n sel[0].card.deleteJoint(sel[0])\n \n def duplicateCard(self):\n\n '''\n Prompts, if possible, for a new name.\n \n .. todo:: See if it's possible to use difflib for more elaborate name\n matching.\n \n '''\n unableToRename = []\n dups = []\n sources = {}\n for card in util.selectedCards():\n d = fossil_card.duplicateCard(card)\n sources[card] = d\n dups.append(d)\n \n names = d.rigData.get('nameInfo', {})\n \n if not names:\n names['repeat'] = 'DUP'\n else:\n if 'head' in names['head']:\n for i, name in enumerate(names['head']):\n names['head'][i] = name + '_DUP'\n \n if 'repeat' in names['repeat']:\n names['repeat'] = name + '_DUP'\n \n if 'tail' in names['tail']:\n for i, name in enumerate(names['tail']):\n names['tail'][i] = name + '_DUP'\n \n rigData = d.rigData\n rigData['nameInfo'] = names\n d.rigData = rigData\n \n for src, newCard in zip(sources, dups):\n if src.parentCard:\n if src.parentCard in sources:\n index = src.parentCard.joints.index( src.parentCardJoint )\n\n newParent = sources[src.parentCard].joints[index]\n\n proxy.pointer( newParent, newCard.start())\n\n if unableToRename:\n confirmDialog( t='Unable to rename',\n m=\"{0} were unable to find a common element to rename, you must do this manually\".format( '\\n'.join(unableToRename)) )\n select(unableToRename)\n else:\n select(dups)\n \n def mergeCard(self):\n sel = util.selectedCards()\n if len(sel) != 2:\n confirmDialog(m='You can only merge two cards at a time, please select 2 cards')\n return\n \n if sel[0].parentCard == sel[1]:\n sel[1].merge(sel[0])\n elif sel[1].parentCard == sel[0]:\n sel[0].merge(sel[1])\n else:\n confirmDialog(m='You can only merge cards that are related to eachother')\n return\n \n def splitCard(self):\n j = util.selectedJoints()\n if j:\n fossil_card.splitCard(j[0])\n \n","sub_path":"pdil/tool/fossil/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"329221764","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import signal\n\nfrom listings import signals\n\n\ndef average_mean(noised_sig: np.ndarray, window_size: int) -> np.ndarray:\n assert window_size % 2 == 1, \"Parameter window_size should be odd\"\n wing = window_size // 2\n parts = np.concatenate(([noised_sig[0]] * wing, noised_sig, [noised_sig[-1]] * wing))\n parts = [parts[si: si + window_size] for si in range(len(noised_sig))]\n return np.mean(parts, 1)\n\n\ndef main():\n Fs = 200\n t = np.arange(0, 1, 1 / Fs)\n A = 2\n f_sig = 10\n f_noise = 80\n sig = A * np.cos(2 * np.pi * f_sig * t + np.pi / 4) # type: np.ndarray\n noise = A / 4 * np.cos(2 * np.pi * f_noise * t + np.pi / 4) # type: np.ndarray\n noised_sig = noise + sig # type: np.ndarray\n\n average_mean_sig = average_mean(noised_sig, 5)\n median_sig = signal.medfilt(noised_sig, (5,))\n # noinspection PyTypeChecker\n coefs = signal.butter(4, 0.2 / f_sig)\n batter_sig = signal.lfilter(*coefs, x=noised_sig)\n a = signal.firwin(300, cutoff=f_sig, window=\"hamming\", nyq=Fs / 2)\n firwin_sig = signal.lfilter(a, 1, noised_sig)\n\n signals.plot(t, sig, Fs)\n signals.plot(t, noised_sig, Fs)\n signals.plot(t, average_mean_sig, Fs)\n signals.plot(t, median_sig, Fs)\n signals.plot(t, batter_sig, Fs)\n signals.plot(t, firwin_sig, Fs)\n\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"dsp/lab3/listings/linear_filtration.py","file_name":"linear_filtration.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"243268252","text":"arr = [[0, 0, 1, 0, 0, 9, 0, 0, 8], \n [0, 6, 0, 0, 5, 0, 0, 3, 0], \n [4, 0, 0, 3, 0, 0, 5, 0, 0], \n [2, 0, 0, 8, 0, 0, 3, 0, 0], \n [0, 7, 0, 0, 9, 0, 0, 2, 0], \n [0, 0, 6, 0, 0, 3, 0, 0, 7], \n [0, 0, 8, 0, 0, 2, 0, 0, 1], \n [0, 4, 0, 0, 6, 0, 0, 7, 0], \n [7, 0, 0, 5, 0, 0, 9, 0, 0]]\n\ndef print_grid():\n\tfor i in range(9):\n\t\tfor j in range(9):\n\t\t\tprint(str(arr[i][j])+' '),\n\n\t\tprint('\\n')\n\ndef used_in_row(row, num):\n\tfor i in range(9):\n\t\tif arr[row][i] == num:\n\t\t\treturn True\n\treturn False\n\ndef used_in_col(col, num):\n\tfor i in range(9):\n\t\tif arr[i][col] == num:\n\t\t\treturn True\n\treturn False\n\ndef used_in_box(row, col, num):\n\tfor i in range(3):\n\t\tfor j in range(3):\n\t\t\tif arr[row+i][col+j] == num:\n\t\t\t\treturn True\n\treturn False\n\ndef can_place(row, col, num):\n\treturn not used_in_row(row, num) and not used_in_col(col, num) and not used_in_box(row - row%3, col - col%3, num)\n\ndef find_empty():\n\tfor i in range(9):\n\t\tfor j in range(9):\n\t\t\tif arr[i][j] == 0:\n\t\t\t\treturn (i,j)\n\treturn (10,10)\n\n\ndef solve():\n\trow, col = find_empty()\n\tif row == 10 and col == 10:\n\t\treturn True\n\tfor num in range(1,10):\n\t\tif can_place(row, col, num):\n\t\t\tarr[row][col] = num\n\t\t\tif solve():\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tarr[row][col] = 0\n\treturn False\n\n\nprint_grid()\nif solve():\n\tprint('---------------------------')\n\tprint_grid()\nelse:\n\tprint('Not solvable')\n\n\n\n\n\n\n\n\n\n\n","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"12840944","text":"#!/usr/bin/python\n\nimport math\nfrom ball_simulation.utils import *\nclass Ball:\n def __repr__(self):\n return \"<%s: Pos: %s, Vel: %s, Bounced: %s>\" % (self.name, self.position, self.velocity, self.bounced)\n\n def __init__(self, pos, spd,acce, name):\n \"\"\"\n Initialise a ball object with the required parameters.\n\n @param pos: An array of position components of the ball, given as [x, y]\n @param spd: An array of velocity components of the ball, given as [x, y]\n @param name: Plain text name for the ball. Helpful for debugging.\n \"\"\"\n self.position = {'x': pos[0], 'y': pos[1]}\n self.velocity = {'x': spd[0], 'y': spd[1]}\n self.acceleration={'x': acce[0], 'y': acce[1]}\n self.name = name\n self.bounced = False\n\n def get_polar_velocity(self):\n \"\"\"\n Calculate the polar velocity of the the ball.\n\n @return: Dict with magnitude and direction of ball's velocity\n \"\"\"\n return rect_to_polar(self.velocity['x'], self.velocity['y'])\n\n def set_polar_velocity(self, magnitude, direction):\n \"\"\"\n Set the velocity of the ball, stored internally as components, to a polar velocity.\n @param magnitude: Ball speed in m/s\n @param direction: Direction of travel in degrees.\n \"\"\"\n direction_rad = math.radians(direction)\n self.velocity['x'] = magnitude * math.cos(direction_rad)\n self.velocity['y'] = magnitude * math.sin(direction_rad)\n\n def try_edge_bounce(self, bottom, top, left, right):\n # Check all walls for collisions\n \"\"\"\n Given the size of the game board, calculate the velocity of the ball post-bounce\n if an edge hit has occurred in this ball state.\n\n @param bottom: Coordinate for the bottom of the board (usually 0)\n @param top: Coordinate for the top of the board.\n @param left: Coordinate for the left of the board (usually 0)\n @param right: Coordinate for the right of the board\n @return: True if ball has bounced. False if not.\n \"\"\"\n if self.position['y'] + ball_radius > top:\n # Bounce on top bumper\n self.position['y'] =top-ball_radius \n\n if self.position['x'] - ball_radius < left:\n #bounce on top and left \n self.position['x'] = left+ ball_radius \n\n if self.velocity['x'] < 0:\n self.velocity['x'] = -self.velocity['x']\n if self.velocity['y'] > 0:\n self.velocity['y'] = -self.velocity['y']\n\n elif self.position['x'] + ball_radius > right:\n #bounce on top and right\n self.position['x'] =right- ball_radius \n\n if self.velocity['x'] > 0:\n self.velocity['x'] = -self.velocity['x']\n if self.velocity['y'] > 0:\n self.velocity['y'] = -self.velocity['y']\n\n elif self.velocity['y'] > 0: # bounce only the top\n self.velocity['y'] = -self.velocity['y']\n\n elif self.position['y'] - ball_radius < bottom:\n # Bounce on bottom bumper\n self.position['y'] =bottom + ball_radius \n if self.position['x'] - ball_radius < left:\n #bounce on bottom and left\n self.position['x'] = left+ ball_radius\n if self.velocity['x'] < 0:\n self.velocity['x'] = -self.velocity['x']\n if self.velocity['y'] < 0:\n self.velocity['y'] = -self.velocity['y']\n\n elif self.position['x'] + ball_radius > right:\n #bounce on bottom and right\n self.position['x'] = right-ball_radius\n if self.velocity['x'] > 0:\n self.velocity['x'] = -self.velocity['x']\n if self.velocity['y'] < 0:\n self.velocity['y'] = -self.velocity['y']\n\n elif self.velocity['y'] < 0:\n self.velocity['y'] = -self.velocity['y']\n\n elif self.position['x'] + ball_radius > right:\n # Bounce on right bumper\n self.position['x']= right- ball_radius \n if self.velocity['x'] > 0:\n self.velocity['x'] = -self.velocity['x']\n\n elif self.position['x'] - ball_radius < left:\n # Bounce on left bumper\n self.position['x']= left+ ball_radius \n if self.velocity['x'] < 0:\n self.velocity['x'] = -self.velocity['x']\n\n else:\n # No wall bounce.\n return False\n\n self.bounced = True\n return True\n\n def get_next_state_undisturbed(self, new_force,update_this=True):\n \"\"\"\n Calculate the new position of the ball assuming that it travels in a straight line\n and does not bounce. Can either return a new ball in the new position, or update this ball\n object.\n\n @param update_this: Update the values on this ball object. Otherwise returns a new object to the caller.\n @return: Reference to ball in it's updated position. Can either be this ball object or a new instantiation.\n \"\"\"\n #Calculate the new acceleration\n new_x_acce=new_force[0]/mass- friction_factor \n new_y_acce=new_force[1]/mass- friction_factor \n\n # Calculate new position\n # print(\"ball_pos:\",self.velocity)\n new_x_pos = self.position['x'] + self.velocity['x'] * time_step+0.5*new_x_acce*time_step*time_step\n new_y_pos = self.position['y'] + self.velocity['y'] * time_step+0.5*new_y_acce*time_step*time_step\n \n # print(\"cal_force in ball.py\",2*(new_x_pos-self.position['x']-self.velocity['x']),2*(new_y_pos-self.position['y']-self.velocity['y']) )\n\n # Calculate the new velocity\n new_x_vel = self.velocity['x'] + (new_x_acce)*time_step\n new_y_vel = self.velocity['y'] + (new_y_acce)*time_step\n\n # constrain the ball from moving above a threshold.\n # print(\"in ball.py: before\",new_x_vel,new_y_vel)\n\n new_x_vel =min(new_x_vel,max_velocity)\n new_x_vel=max(new_x_vel,-1*max_velocity)\n\n new_y_vel= min(new_y_vel,max_velocity)\n new_y_vel= max(new_y_vel,-1*max_velocity)\n\n # print(\"in ball.py: after\",new_x_vel,new_y_vel)\n\n # Only update this ball, otherwise return a new one\n if update_this:\n self.position = {'x': new_x_pos, 'y': new_y_pos}\n self.velocity = {'x': new_x_vel, 'y': new_y_vel}\n self.acceleration = {'x': new_x_acce, 'y': new_y_acce}\n return self\n return Ball([new_x_pos, new_y_pos], [new_x_vel, new_y_vel] ,[new_x_acce, new_y_acce],self.name)\n\n","sub_path":"ball_simulation/ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":6720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"40149472","text":"\n\nfrom xai.brain.wordbase.nouns._amoeba import _AMOEBA\n\n#calss header\nclass _AMOEBAS(_AMOEBA, ):\n\tdef __init__(self,): \n\t\t_AMOEBA.__init__(self)\n\t\tself.name = \"AMOEBAS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"amoeba\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_amoebas.py","file_name":"_amoebas.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"62035538","text":"from functions.creating_schedule import full_schedule_in_str, get_one_day_schedule_in_str, get_next_day_schedule_in_str\nfrom functions.calculating_reminder_times import calculating_reminder_times\nfrom functions.near_lesson import get_near_lesson, get_now_lesson\nfrom functions.storage import MongodbService\nfrom vkbottle import Keyboard, KeyboardButtonColor, Text\nfrom functions.find_week import find_week\nfrom vk_api import vk_api, VkUpload\nimport requests\nimport json\nimport os\nimport pytz\nfrom datetime import datetime\nfrom vkbottle.bot import Bot, Message\n\n# from vkbottle.api.uploader.photo import PhotoUploader\n\nTOKEN = os.environ.get('VK')\n\nMAX_CALLBACK_RANGE = 41\nstorage = MongodbService().get_instance()\nbot = Bot(TOKEN) # TOKEN\n# photo_uploader = PhotoUploader(bot.api, generate_attachment_strings=True)\n\ncontent_types = {\n 'text': ['Расписание 🗓', 'Ближайшая пара ⏱', 'Расписание на сегодня 🍏', 'На текущую неделю',\n 'На следующую неделю',\n 'Расписание на завтра 🍎', 'Следующая', 'Текущая']}\n\nсontent_commands = {'text': ['Начать', 'начать', 'Начало', 'start']}\n\ncontent_map = {'text': ['map', 'Карта', 'карта', 'Map', 'Схема', 'схема']}\n\nTZ_IRKUTSK = pytz.timezone('Asia/Irkutsk')\n\nauthorize = vk_api.VkApi(token=TOKEN)\nupload = VkUpload(authorize)\nmap_image = \"map.jpg\"\n\n\ndef parametres_for_buttons_start_menu_vk(text, color):\n '''Возвращает параметры кнопок'''\n return {\n \"action\": {\n \"type\": \"text\",\n \"payload\": \"{\\\"button\\\": \\\"\" + \"1\" + \"\\\"}\",\n \"label\": f\"{text}\"\n },\n \"color\": f\"{color}\"\n }\n\n\ndef get_notifications_status(time):\n \"\"\"Статус напоминаний\"\"\"\n if not time or time == 0:\n notifications_status = 'Напоминания выключены ❌\\n' \\\n 'Воспользуйтесь настройками, чтобы включить'\n else:\n notifications_status = f'Напоминания включены ✅\\n' \\\n f'Сообщение придёт за {time} мин до начала пары 😇'\n return notifications_status\n\n\ndef make_inline_keyboard_notifications():\n \"\"\"Кнопка 'Настройка уведомлений'\"\"\"\n keyboard = Keyboard(one_time=False)\n keyboard.row()\n keyboard.add(Text(label='Настройки ⚙'), color=KeyboardButtonColor.PRIMARY)\n keyboard.row()\n keyboard.add(Text(label='<==Назад'), color=KeyboardButtonColor.SECONDARY)\n return keyboard\n\n\ndef make_keyboard_start_menu():\n \"\"\"Создаём основные кнопки\"\"\"\n keyboard = Keyboard(one_time=False)\n keyboard.row()\n keyboard.add(Text(label=\"Расписание 🗓\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.add(Text(label=\"Ближайшая пара ⏱\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.row()\n keyboard.add(Text(label=\"Расписание на сегодня 🍏\"), color=KeyboardButtonColor.SECONDARY)\n keyboard.row()\n keyboard.add(Text(label=\"Расписание на завтра 🍎\"), color=KeyboardButtonColor.SECONDARY)\n keyboard.row()\n keyboard.add(Text(label=\"Напоминание 📣\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.add(Text(label=\"Другое ⚡\"), color=KeyboardButtonColor.PRIMARY)\n return keyboard\n\n\ndef make_keyboard_commands():\n \"\"\"Создаём кнопки команд\"\"\"\n keyboard = Keyboard(one_time=False)\n keyboard.row()\n # keyboard.add(Text(label=\"about\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.add(Text(label=\"Авторы\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.row()\n keyboard.add(Text(label=\"Регистрация\"), color=KeyboardButtonColor.SECONDARY)\n keyboard.add(Text(label=\"Карта\"), color=KeyboardButtonColor.SECONDARY)\n keyboard.row()\n keyboard.add(Text(label=\"<==Назад\"), color=KeyboardButtonColor.SECONDARY)\n return keyboard\n\n\ndef make_keyboard_extra():\n keyboard = Keyboard(one_time=False)\n keyboard.row()\n keyboard.add(Text(label=\"Список команд\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.row()\n keyboard.add(Text(label=\"Поиск 🔎\"), color=KeyboardButtonColor.SECONDARY)\n keyboard.row()\n keyboard.add(Text(label=\"<==Назад\"), color=KeyboardButtonColor.SECONDARY)\n return keyboard\n\n\ndef make_keyboard_nearlesson():\n \"\"\"Создаём основные кнопки\"\"\"\n keyboard = Keyboard(one_time=False)\n keyboard.row()\n keyboard.add(Text(label=\"Текущая\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.add(Text(label=\"Следующая\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.row()\n keyboard.add(Text(label=\"<==Назад\"), color=KeyboardButtonColor.SECONDARY)\n return keyboard\n\n\ndef make_inline_keyboard_set_notifications(time=0):\n \"\"\"кнопки настройки уведомлений\"\"\"\n if time != 0:\n text_check = f'{time} мин'\n else:\n text_check = 'off'\n\n keyboard = Keyboard(one_time=False)\n\n keyboard.row()\n keyboard.add(Text(label=\"-\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.add(Text(label=text_check), color=KeyboardButtonColor.PRIMARY)\n keyboard.add(Text(label='+'), color=KeyboardButtonColor.PRIMARY)\n keyboard.row()\n keyboard.add(Text(label=\"Сохранить\"), color=KeyboardButtonColor.SECONDARY)\n\n return keyboard\n\n\ndef make_keyboard_institutes(institutes=[]):\n \"\"\"Кнопки выбора института\"\"\"\n keyboard = {\n \"one_time\": False\n }\n list_keyboard_main = []\n for institute in institutes:\n if len(institute['name']) >= MAX_CALLBACK_RANGE:\n name = sep_space(institute['name']) + ' ...'\n else:\n name = institute['name']\n list_keyboard = []\n list_keyboard.append(parametres_for_buttons_start_menu_vk(f'{name}', 'primary'))\n list_keyboard_main.append(list_keyboard)\n keyboard['buttons'] = list_keyboard_main\n keyboard = json.dumps(keyboard, ensure_ascii=False).encode('utf-8')\n keyboard = str(keyboard.decode('utf-8'))\n return keyboard\n\n\ndef make_keyboard_choose_course_vk(courses):\n '''Создаёт клавиатуру для выбора курса'''\n keyboard = {\n \"one_time\": False\n }\n list_keyboard_main = []\n for course in courses:\n name = course['name']\n list_keyboard = []\n list_keyboard.append(parametres_for_buttons_start_menu_vk(f'{name}', 'primary'))\n list_keyboard_main.append(list_keyboard)\n list_keyboard = []\n list_keyboard.append(parametres_for_buttons_start_menu_vk('Назад к институтам', 'primary'))\n list_keyboard_main.append(list_keyboard)\n keyboard['buttons'] = list_keyboard_main\n keyboard = json.dumps(keyboard, ensure_ascii=False).encode('utf-8')\n keyboard = str(keyboard.decode('utf-8'))\n return keyboard\n\n\ndef make_keyboard_choose_group_vk(groups=[]):\n \"\"\"Кнопки выбора группы\"\"\"\n keyboard = {\n \"one_time\": False\n }\n list_keyboard_main_2 = []\n list_keyboard_main = []\n list_keyboard = []\n overflow = 0\n for group in groups:\n overflow += 1\n if overflow == 27:\n list_keyboard_main.append(list_keyboard)\n list_keyboard = []\n list_keyboard.append(parametres_for_buttons_start_menu_vk('Далее', 'primary'))\n list_keyboard.append(parametres_for_buttons_start_menu_vk('Назад к курсам', 'primary'))\n list_keyboard_main.append(list_keyboard)\n else:\n if overflow < 28:\n if len(list_keyboard) == 3:\n list_keyboard_main.append(list_keyboard)\n list_keyboard = []\n list_keyboard.append(parametres_for_buttons_start_menu_vk(f'{group}', 'primary'))\n else:\n list_keyboard.append(parametres_for_buttons_start_menu_vk(f'{group}', 'primary'))\n\n else:\n list_keyboard = []\n list_keyboard.append(parametres_for_buttons_start_menu_vk(f'{group}', 'primary'))\n list_keyboard_main_2.append(parametres_for_buttons_start_menu_vk(f'{group}', 'primary'))\n\n if overflow < 28:\n list_keyboard_main.append(list_keyboard)\n list_keyboard = []\n list_keyboard.append(parametres_for_buttons_start_menu_vk('Назад к курсам', 'primary'))\n list_keyboard_main.append(list_keyboard)\n else:\n list_keyboard_main_2.append(list_keyboard)\n\n keyboard['buttons'] = list_keyboard_main\n keyboard = json.dumps(keyboard, ensure_ascii=False).encode('utf-8')\n keyboard = str(keyboard.decode('utf-8'))\n\n return keyboard\n\n\ndef make_keyboard_choose_schedule():\n '''Создаёт клавиатуру для выбора недели'''\n keyboard = Keyboard(one_time=False)\n keyboard.row()\n keyboard.add(Text(label=\"На текущую неделю\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.add(Text(label=\"На следующую неделю\"), color=KeyboardButtonColor.PRIMARY)\n keyboard.row()\n keyboard.add(Text(label=\"Основное меню\"), color=KeyboardButtonColor.SECONDARY)\n return keyboard\n\n\ndef make_keyboard_choose_group_vk_page_2(groups=[]):\n '''Создаёт клавиатуру для групп после переполнения первой'''\n keyboard = {\n \"one_time\": False\n }\n groups = groups[26:]\n list_keyboard_main = []\n list_keyboard = []\n for group in groups:\n if len(list_keyboard) == 3:\n list_keyboard_main.append(list_keyboard)\n list_keyboard = []\n list_keyboard.append(parametres_for_buttons_start_menu_vk(f'{group}', 'primary'))\n else:\n list_keyboard.append(parametres_for_buttons_start_menu_vk(f'{group}', 'primary'))\n list_keyboard_main.append(list_keyboard)\n list_keyboard_main.append([parametres_for_buttons_start_menu_vk('Назад', 'primary')])\n\n keyboard['buttons'] = list_keyboard_main\n keyboard = json.dumps(keyboard, ensure_ascii=False).encode('utf-8')\n keyboard = str(keyboard.decode('utf-8'))\n return keyboard\n\n\ndef sep_space(name):\n '''Обрезает длину института, если тот больше 40 символов'''\n dlina = abs(len(name) - MAX_CALLBACK_RANGE)\n name = name[:len(name) - dlina - 5]\n return name\n\n\ndef name_institutes(institutes=[]):\n '''Храним список всех институтов'''\n list_institutes = []\n for i in institutes:\n name = i['name']\n list_institutes.append(name)\n return list_institutes\n\n\ndef name_courses(courses=[]):\n '''Храним список всех институтов'''\n list_courses = []\n for i in courses:\n name = i['name']\n list_courses.append(name)\n return list_courses\n\n\ndef add_statistics(action: str):\n date_now = datetime.now(TZ_IRKUTSK).strftime('%d.%m.%Y')\n time_now = datetime.now(TZ_IRKUTSK).strftime('%H:%M')\n storage.save_statistics(action=action, date=date_now, time=time_now)\n\n\ndef name_groups(groups=[]):\n '''Храним список всех групп'''\n list_groups = []\n for i in groups:\n name = i['name']\n list_groups.append(name)\n return list_groups\n\n\n# ==================== Обработка команд ==================== #\n\n# Команда start\n@bot.on.message(text=сontent_commands['text'])\nasync def start_message(ans: Message):\n chat_id = ans.from_id\n\n # Проверяем есть пользователь в базе данных\n if storage.get_user(chat_id):\n storage.delete_user_or_userdata(chat_id) # Удаляем пользвателя из базы данных\n await ans.answer('Привет\\n')\n await ans.answer('Для начала пройдите небольшую регистрацию😉\\n')\n await ans.answer('Выберите институт.', keyboard=make_keyboard_institutes(storage.get_institutes()))\n\n add_statistics(action='start')\n\n\n# Команда Регистрация\n@bot.on.message(text='Регистрация')\nasync def registration(ans: Message):\n chat_id = ans.from_id\n # Проверяем есть пользователь в базе данных\n if storage.get_user(chat_id):\n storage.delete_user_or_userdata(chat_id) # Удаляем пользвателя из базы данных\n await ans.answer('Повторная регистрация😉\\n')\n await ans.answer('Выберите институт.', keyboard=make_keyboard_institutes(storage.get_institutes()))\n\n add_statistics(action='reg')\n\n\n# Команда Карта\n@bot.on.message(text=content_map['text'])\nasync def map(ans: Message):\n chat_id = ans.from_id\n await ans.answer('Подождите, карта загружается...', keyboard=make_keyboard_start_menu())\n server = authorize.method(\"photos.getMessagesUploadServer\")\n b = requests.post(server['upload_url'], files={'photo': open('map.jpg', 'rb')}).json()\n c = authorize.method('photos.saveMessagesPhoto', {'photo': b['photo'], 'server': b['server'], 'hash': b['hash']})[0]\n authorize.method(\"messages.send\",\n {\"peer_id\": chat_id, \"attachment\": f'photo{c[\"owner_id\"]}_{c[\"id\"]}', 'random_id': 0})\n\n add_statistics(action='map')\n\n\n# # Команда help\n# @bot.on.message(text='help')\n# async def help(ans: Message):\n# chat_id = ans.from_id\n# await ans.answer('Список команд:\\n'\n# 'Авторы - список авторов \\n'\n# 'Регистрация - повторная регистрация\\n'\n# 'Карта - карта университета')\n#\n# add_statistics(action='help')\n\n\n# # Команда /about\n# @bot.on.message(text='about')\n# async def about(ans: Message):\n# chat_id = ans.from_id\n# await ans.answer('О боте:\\n'\n# 'Smart schedule IRNITU bot - это чат бот для просмотра расписания занятий в '\n# 'Иркутском национальном исследовательском техническом университете\\n\\n'\n# 'Благодаря боту можно:\\n'\n# '- Узнать актуальное расписание\\n'\n# '- Нажатием одной кнопки увидеть информацию о ближайшей паре\\n'\n# '- Настроить гибкие уведомления с информацией из расписания, '\n# 'которые бу��ут приходить за определённое время до начала занятия', keyboard=make_keyboard_start_menu())\n#\n# add_statistics(action='about')\n\n\n# Команда Авторы\n@bot.on.message(text='Авторы')\nasync def authors(ans: Message):\n chat_id = ans.from_id\n await ans.answer('Авторы проекта:\\n'\n '-[id132677094|Алексей]\\n'\n '-[id128784852|Султан]\\n'\n '-[id169584462|Александр] \\n'\n '-[id135615548|Владислав]\\n'\n '-[id502898628|Кирилл]\\n\\n'\n 'По всем вопросом и предложениям пишите нам в личные сообщения. '\n 'Будем рады 😉\\n', keyboard=make_keyboard_start_menu()\n )\n\n add_statistics(action='authors')\n\n\n@bot.on.message(text=content_types['text'])\nasync def scheduler(ans: Message):\n chat_id = ans.from_id\n data = ans.text\n user = storage.get_user(chat_id=chat_id)\n\n if 'Расписание 🗓' == data and user:\n await ans.answer('Выберите период\\n', keyboard=make_keyboard_choose_schedule())\n add_statistics(action='Расписание')\n\n if ('На текущую неделю' == data or 'На следующую неделю' == data) and user:\n group = storage.get_user(chat_id=chat_id)['group']\n schedule = storage.get_schedule(group=group)\n if schedule['schedule'] == []:\n await ans.answer('Расписание временно недоступно\\nПопробуйте позже⏱')\n add_statistics(action=data)\n return\n\n schedule = schedule['schedule']\n week = find_week()\n\n # меняем неделю\n if data == 'На следующую неделю':\n week = 'odd' if week == 'even' else 'even'\n\n week_name = 'четная' if week == 'odd' else 'нечетная'\n\n schedule_str = full_schedule_in_str(schedule, week=week)\n await ans.answer(f'Расписание {group}\\n'\n f'Неделя: {week_name}', keyboard=make_keyboard_start_menu())\n\n for schedule in schedule_str:\n await ans.answer(f'{schedule}')\n\n add_statistics(action=data)\n\n\n\n elif 'Расписание на сегодня 🍏' == data and user:\n group = storage.get_user(chat_id=chat_id)['group']\n schedule = storage.get_schedule(group=group)\n if not schedule:\n await ans.answer('Расписание временно недоступно🚫😣\\n'\n 'Попробуйте позже⏱', keyboard=make_keyboard_start_menu())\n add_statistics(action='Расписание на сегодня')\n return\n schedule = schedule['schedule']\n week = find_week()\n schedule_one_day = get_one_day_schedule_in_str(schedule=schedule, week=week)\n if not schedule_one_day:\n await ans.answer('Сегодня пар нет 😎')\n return\n await ans.answer(f'{schedule_one_day}')\n add_statistics(action='Расписание на сегодня')\n\n elif 'Расписание на завтра 🍎' == data and user:\n group = storage.get_user(chat_id=chat_id)['group']\n schedule = storage.get_schedule(group=group)\n if not schedule:\n await ans.answer('Расписание временно недоступно🚫😣\\n'\n 'Попробуйте позже⏱', keyboard=make_keyboard_start_menu())\n add_statistics(action='Расписание на завтра')\n return\n schedule = schedule['schedule']\n week = find_week()\n if datetime.today().isoweekday() == 7:\n if week == 'odd':\n week = 'even'\n elif week == 'even':\n week = 'odd'\n else:\n week = 'all'\n\n schedule_next_day = get_next_day_schedule_in_str(schedule=schedule, week=week)\n if not schedule_next_day:\n await ans.answer('Завтра пар нет 😎')\n return\n await ans.answer(f'{schedule_next_day}')\n add_statistics(action='Расписание на завтра')\n\n elif 'Ближайшая пара ⏱' in data and user:\n await ans.answer('Ближайшая пара', keyboard=make_keyboard_nearlesson())\n add_statistics(action='Ближайшая пара')\n return\n\n\n elif 'Текущая' in data and user:\n group = storage.get_user(chat_id=chat_id)['group']\n schedule = storage.get_schedule(group=group)\n if not schedule:\n await ans.answer('Расписание временно недоступно🚫😣\\n'\n 'Попробуйте позже⏱', keyboard=make_keyboard_start_menu())\n add_statistics(action='Текущая')\n return\n schedule = schedule['schedule']\n week = find_week()\n\n now_lessons = get_now_lesson(schedule=schedule, week=week)\n print(now_lessons)\n\n # если пар нет\n if not now_lessons:\n await ans.answer('Сейчас пары нет, можете отдохнуть)', keyboard=make_keyboard_start_menu())\n add_statistics(action='Текущая')\n return\n\n now_lessons_str = ''\n for near_lesson in now_lessons:\n name = near_lesson['name']\n if name == 'свободно':\n await ans.answer('Сейчас пары нет, можете отдохнуть)', keyboard=make_keyboard_start_menu())\n return\n now_lessons_str += '-------------------------------------------\\n'\n aud = near_lesson['aud']\n if aud:\n aud = f'Аудитория: {aud}\\n'\n time = near_lesson['time']\n info = near_lesson['info'].replace(\",\", \"\")\n prep = near_lesson['prep']\n\n now_lessons_str += f'{time}\\n' \\\n f'{aud}' \\\n f'👉{name}\\n' \\\n f'{info} {prep}\\n'\n now_lessons_str += '-------------------------------------------\\n'\n await ans.answer(f'🧠Текущая пара🧠\\n'f'{now_lessons_str}', keyboard=make_keyboard_start_menu())\n\n add_statistics(action='Текущая')\n\n elif 'Следующая' in data and user:\n group = storage.get_user(chat_id=chat_id)['group']\n schedule = storage.get_schedule(group=group)\n if not schedule:\n await ans.answer('Расписание временно недоступно🚫😣\\n'\n 'Попробуйте позже⏱', keyboard=make_keyboard_start_menu())\n add_statistics(action='Следующая')\n return\n schedule = schedule['schedule']\n week = find_week()\n\n near_lessons = get_near_lesson(schedule=schedule, week=week)\n\n # если пар нет\n if not near_lessons:\n await ans.answer('Сегодня больше пар нет 😎', keyboard=make_keyboard_start_menu())\n add_statistics(action='Следующая')\n return\n\n near_lessons_str = ''\n for near_lesson in near_lessons:\n name = near_lesson['name']\n if name == 'свободно':\n await ans.answer('Сегодня больше пар нет 😎', keyboard=make_keyboard_start_menu())\n return\n near_lessons_str += '-------------------------------------------\\n'\n aud = near_lesson['aud']\n if aud:\n aud = f'Аудитория: {aud}\\n'\n time = near_lesson['time']\n info = near_lesson['info'].replace(\",\", \"\")\n prep = near_lesson['prep']\n\n near_lessons_str += f'{time}\\n' \\\n f'{aud}' \\\n f'👉{name}\\n' \\\n f'{info} {prep}\\n'\n near_lessons_str += '-------------------------------------------\\n'\n await ans.answer(f'🧠Ближайшая пара🧠\\n'f'{near_lessons_str}', keyboard=make_keyboard_start_menu())\n\n add_statistics(action='Следующая')\n\n\n@bot.on.message()\nasync def wrapper(ans: Message):\n '''Регистрация пользователя'''\n chat_id = ans.from_id\n message_inst = ans.text\n message = ans.text\n user = storage.get_user(chat_id)\n\n # Сохраняет в месседж полное название универ для корректного сравнения\n institutes = name_institutes(storage.get_institutes())\n for institute in institutes:\n if len(message_inst) > 5:\n if message_inst[:-5] in institute:\n message_inst = institute\n\n # Если пользователя нет в базе данных\n if not user:\n institutes = name_institutes(storage.get_institutes())\n # Смотрим выбрал ли пользователь институт\n if message_inst in institutes:\n # Если да, то записываем в бд\n storage.save_or_update_user(chat_id=chat_id, institute=message_inst)\n await ans.answer(f'Вы выбрали: {message_inst}\\n')\n await ans.answer('Выберите курс.',\n keyboard=make_keyboard_choose_course_vk(storage.get_courses(message_inst)))\n else:\n await ans.answer('Ради твоего удобства, я вывел клавиатуру со списком инстиутов ниже 😸👇🏻')\n return\n\n # Если нажал кнопку Назад к институтам\n if message == \"Назад к институтам\" and not 'course' in user.keys():\n await ans.answer('Выберите институт.', keyboard=make_keyboard_institutes(storage.get_institutes()))\n storage.delete_user_or_userdata(chat_id=chat_id)\n return\n\n # Если нажал кнопку Назад к институтам\n if message == \"Назад к курсам\" and not 'group' in user.keys():\n\n await ans.answer('Выберите курс.', keyboard=make_keyboard_choose_course_vk(\n storage.get_courses(storage.get_user(chat_id=chat_id)['institute'])))\n storage.delete_user_or_userdata(chat_id=chat_id, delete_only_course=True)\n return\n\n # Регистрация после выбора института\n elif not 'course' in user.keys():\n institute = user['institute']\n course = storage.get_courses(institute)\n\n # Если нажал кнопку курса\n if message in name_courses(course):\n # Записываем в базу данных выбранный курс\n storage.save_or_update_user(chat_id=chat_id, course=message)\n groups = storage.get_groups(institute=institute, course=message)\n groups = name_groups(groups)\n await ans.answer(f'Вы выбрали: {message}\\n')\n await ans.answer('Выберите группу.', keyboard=make_keyboard_choose_group_vk(groups))\n else:\n await ans.answer('Не огорчай меня, я же не просто так старался над клавиатурой 😼👇🏻')\n return\n # Регистрация после выбора курса\n elif not 'group' in user.keys():\n institute = user['institute']\n course = user['course']\n groups = storage.get_groups(institute=institute, course=course)\n groups = name_groups(groups)\n # Если нажал кнопку группы\n if message in groups:\n # Записываем в базу данных выбранную группу\n storage.save_or_update_user(chat_id=chat_id, group=message)\n await ans.answer('Вы успешно зарегистрировались!😊\\n\\n'\n 'Для того чтобы пройти регистрацию повторно, напишите сообщение \"Регистрация\"\\n'\n , keyboard=make_keyboard_start_menu())\n else:\n if message == \"Далее\":\n await ans.answer('Выберите группу.', keyboard=make_keyboard_choose_group_vk_page_2(groups))\n elif message == \"Назад\":\n await ans.answer('Выберите группу.', keyboard=make_keyboard_choose_group_vk(groups))\n else:\n await ans.answer('Я очень сомневаюсь, что твоей группы нет в списке ниже 😉')\n return\n\n elif 'Напоминание 📣' in message and user:\n time = user['notifications']\n # Проверяем стату напоминания\n if not time:\n time = 0\n await ans.answer(f'{get_notifications_status(time)}', keyboard=make_inline_keyboard_notifications())\n\n add_statistics(action='Напоминание')\n\n elif 'Настройки' in message and user:\n time = user['notifications']\n await ans.answer('Настройка напоминаний ⚙\\n\\n'\n 'Укажите за сколько минут до начала пары должно приходить сообщение',\n keyboard=make_inline_keyboard_set_notifications(time))\n add_statistics(action='Настройки')\n\n elif '-' in message:\n time = user['notifications']\n if time == 0:\n await ans.answer('Хочешь уйти в минус?', keyboard=make_inline_keyboard_set_notifications(time))\n return\n time -= 5\n # Отнимаем и проверяем на положительность\n if time <= 0:\n time = 0\n storage.save_or_update_user(chat_id=chat_id, notifications=time)\n await ans.answer('Минус 5 минут', keyboard=make_inline_keyboard_set_notifications(time))\n return\n\n elif '+' in message:\n time = user['notifications']\n time += 5\n storage.save_or_update_user(chat_id=chat_id, notifications=time)\n await ans.answer('Плюс 5 минут', keyboard=make_inline_keyboard_set_notifications(time))\n\n elif 'Сохранить' in message:\n\n # Сохраняем статус в базу\n time = user['notifications']\n\n group = storage.get_user(chat_id=chat_id)['group']\n\n schedule = storage.get_schedule(group=group)['schedule']\n if time > 0:\n reminders = calculating_reminder_times(schedule=schedule, time=int(time))\n else:\n reminders = []\n storage.save_or_update_user(chat_id=chat_id, notifications=time, reminders=reminders)\n\n await ans.answer(f'{get_notifications_status(time)}', keyboard=make_keyboard_start_menu())\n\n\n elif 'Основное меню' in message and user:\n await ans.answer('Основное меню', keyboard=make_keyboard_start_menu())\n add_statistics(action='Основное меню')\n\n elif '<==Назад' == message and user:\n await ans.answer('Основное меню', keyboard=make_keyboard_start_menu())\n\n elif 'Далее' in message:\n await ans.answer('Далее', keyboard=make_keyboard_choose_group_vk_page_2())\n\n\n elif 'Список команд' == message and user:\n await ans.answer('Список команд:\\n'\n 'Авторы - список авторов \\n'\n 'Регистрация- повторная регистрация\\n'\n 'Карта - карта университета', keyboard=make_keyboard_commands())\n\n add_statistics(action='help')\n return\n\n elif 'Другое ⚡' == message and user:\n await ans.answer('Другое', keyboard=make_keyboard_extra())\n\n add_statistics(action='help')\n return\n\n else:\n await ans.answer('Такому ещё не научили 😇, знаю только эти команды:\\n'\n 'Авторы - список авторов \\n'\n 'Регистрация - повторная регистрация\\n'\n 'Карта - карта университета', keyboard=make_keyboard_start_menu())\n add_statistics(action='bullshit')\n\n\ndef main():\n '''Запуск бота'''\n bot.run_forever()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Bot_vk/VK_BOT_main.py","file_name":"VK_BOT_main.py","file_ext":"py","file_size_in_byte":31911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"455270955","text":"\nfrom django.core.paginator import Paginator\n\nfrom django.shortcuts import render, get_object_or_404\n\n\n\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\n\nfrom django.views.decorators.http import require_GET\n\nfrom qa.forms import AskForm, AnswerForm\n\nfrom qa.models import Question\n\n\n\n\n\ndef test(request, *args, **kwargs):\n\n resp = 'OK'\n\n for par in args:\n\n resp = resp + ', ' + par\n\n return HttpResponse(resp)\n\n\n\n\n\ndef question(request, q_id):\n\n q = get_object_or_404(Question, id=q_id)\n\n if request.method == 'POST':\n\n form = AnswerForm(request.POST)\n\n form.question = q.id\n\n if form.is_valid():\n\n form.save()\n\n return HttpResponseRedirect(q.get_url())\n\n else:\n\n form = AnswerForm(initial={'question': q.id})\n\n return render(request, 'qa/question.html',\n\n {'question': q,\n\n 'answers': q.answer_set.all(),\n\n 'answer': form})\n\n\n\n\n\n@require_GET\n\ndef index(request, *args, **kwargs):\n\n questions = Question.objects.all()\n\n questions = questions.order_by('-added_at')\n\n return pagination(request, questions, '/?page=')\n\n\n\n\n\n@require_GET\n\ndef popular(request, *args, **kwargs):\n\n questions = Question.objects.all()\n\n questions = questions.order_by('-rating')\n\n return pagination(request, questions, '/popular/?page=')\n\n\n\n\n\ndef ask(request, *args, **kwargs):\n\n if request.method == 'POST':\n\n form = AskForm(request.POST)\n\n if form.is_valid():\n\n return HttpResponseRedirect(form.save().get_url())\n\n else:\n\n form = AskForm()\n\n return render(request, 'qa/ask.html',\n\n {\n\n 'form': form\n\n })\n\n\n\n\n\n# TODO: move this helper function somewhere\n\ndef pagination(request, questions, url):\n\n num = request.GET.get('page', 1)\n\n limit = request.GET.get('limit', 10)\n\n paginator = Paginator(questions, limit)\n\n if len(paginator.page_range) < int(num) or int(num) < 1:\n\n raise Http404()\n\n paginator.baseurl = url\n\n page = paginator.page(num)\n\n return render(request, 'qa/page.html',\n\n {'posts': page.object_list,\n\n 'paginator': paginator,\n\n 'page': page,\n\n 'question_url': '/question/'})\n","sub_path":"ask/qa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"44064323","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nclass imshow_show_z:\n def __init__(self, ax, z, x, y):\n self.ax = ax\n self.x = x\n self.y = y\n self.z = z\n self.dx = self.x[1] - self.x[0]\n self.dy = self.y[1] - self.y[0]\n self.x0 = x[0]\n self.y0 = y[0]\n self.numrows, self.numcols = self.z.shape\n self.ax.format_coord = self.format_coord\n \n def format_coord(self, x, y):\n row = int((-y-self.y0)/self.dy+0.5)\n col = int((x-self.x0)/self.dx+0.5)\n #print \"Nx, Nf = \", len(self.x), len(self.y), \" x, y =\", x, y, \" dx, dy =\", self.dx, self.dy, \" col, row =\", col, row\n xyz_str = ''\n if ((col>=0) and (col=0) and (row tolerancia and contador < iter:\r\n xn = gx.evaluate2(xi)\r\n fi = fun.evaluate2(xn)\r\n\r\n if type_error == 0:\r\n error = abs(xn-xi)\r\n else:\r\n error = abs((xn-xi)/xn)\r\n\r\n xi = xn\r\n\r\n contador = contador + 1\r\n self.values.append([contador, str(xn), str(\r\n \"{:.2e}\".format(fi)), str(\"{:.2e}\".format(error))])\r\n\r\n if fx == 0:\r\n return f\"{xi} es raiz\"\r\n elif error < tolerancia:\r\n return f\"{xi} es una aprox. con una tolerancia = {tolerancia}\"\r\n else:\r\n return f\"El método fracasó en {iter} iteraciones\"\r\n\r\n def tabla_values(self):\r\n return self.values\r\n","sub_path":"UI/functions/FixedPointSearch.py","file_name":"FixedPointSearch.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"397275999","text":"import os\nimport time\nimport praw\nimport cfl_bot_config\n\nVERSION = \"0.1\"\nUSER_AGENT = \"An automated helper for /r/CFL, \" + VERSION + \" by /u/pudds\"\nSLEEP_TIME_SECONDS = 30\n\n# apparently reddit wants a unique user agent?\nr = praw.Reddit(user_agent=USER_AGENT)\n\nr.set_oauth_app_info(client_id = cfl_bot_config.CLIENT_ID,\n\t\t\t\t\t client_secret = cfl_bot_config.CLIENT_SECRET,\n\t\t\t\t\t redirect_uri = \"http://127.0.0.1:65010/authorize_callback\")\n\n\n\t\n\ndef TestReadCfl():\n\tfor submission in r.get_subreddit(\"cfl\").get_hot(limit=5):\n\t\tprint(submission)\n\n\t\t\n\t\t\n\n# Program loop. \n# Sleeps for designated amount of time, then checks to see which tasks it should work on\t \nwhile True:\n\tTestReadCfl()\n\ttime.sleep(SLEEP_TIME_SECONDS)","sub_path":"cfl_bot.py","file_name":"cfl_bot.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"151183752","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport gzip\nimport json\nimport hashlib\nimport math\nimport random as rd\n\nimport numpy as np\n\nimport fmt\nimport config as conf\nfrom sliding_diff import sliding_diff\nfrom audio import AudioRecorder\nfrom util import numeric_gradient, scale_array\nfrom svm import Svm\n\ndef check_gradient(reg, dataset, weights):\n # Считаем функцию стоимости и её градиент при заданных весах\n cost, grad = reg.cost(dataset, weights)\n print('Cost function: {}'.format(cost))\n print('Cost gradient: {}'.format(grad))\n\n # Проверяем правильность градиента: считаем его численно\n num_grad = numeric_gradient(lambda x: reg.cost(dataset, x)[0], weights)\n print('Num. gradient: {}'.format(num_grad))\n\n # Считаем средний квадрат разности полученных з��ачений\n average_error_sq = np.average((np.array(num_grad) - np.array(grad)) ** 2)\n print('Avg. error sq: {}'.format(average_error_sq))\n\n # Если он маленький, то всё верно\n if average_error_sq < 1e-3:\n print(fmt.format('Gradient seems to be correct', 'green'))\n else:\n print(fmt.format('Gradient seems to be incorrect', 'red'))\n\ndef main():\n if (len(sys.argv) < 2):\n print('Usage: {} {{set-labels | collect | transform | learn | recognize}}'.format(sys.argv[0]))\n return\n command = sys.argv[1]\n if command == 'learn':\n learn()\n elif command == 'set-labels':\n set_labels()\n elif command == 'collect':\n collect()\n elif command == 'transform':\n transform()\n elif command == 'recognize':\n recognize()\n else:\n print('Usage: {} {{set-labels | collect | transform | learn | recognize}}'.format(sys.argv[0]))\n return\n\ndef set_labels():\n print('Enter the space-separated label list: ')\n labels = input()\n with open('labels.txt', 'w') as f:\n f.write(labels)\n print('Labels written to labels.txt')\n\ndef get_labels():\n with open('labels.txt') as f:\n return f.read().split()\n\ndef recognize():\n with AudioRecorder(rate=conf.sampling_rate) as recorder:\n svm = Svm()\n with open('trained_data.pickle.b64') as f:\n svm.import_model(f.read())\n while True:\n print()\n print('\\x1b[A\\x1b[2K' 'Press Enter to start recording or Ctrl+C to exit')\n input()\n recorder.start_recording()\n print('\\x1b[A\\x1b[2K' '\\x1b[31mREC\\x1b[0m Press Enter to stop recording')\n input()\n data = list(recorder.bytes_to_numseq(recorder.finish_recording()))\n transformed_data = list(sliding_diff(data, conf.sliding_diff_winsize))\n scaled_data = scale_array(transformed_data, conf.svm_inputs)\n pred = svm.get(scaled_data)\n print('\\x1b[A\\x1b[2K' 'Predicted output: {}'.format(pred))\n\ndef transform():\n for data, y in read_examples('raw_data'):\n transformed_data = list(sliding_diff(data, conf.sliding_diff_winsize))\n scaled_data = scale_array(transformed_data, conf.svm_inputs)\n write_example((scaled_data, y), 'data')\n\ndef write_example(data, dirname):\n data_to_write = gzip.compress(json.dumps(data).encode())\n data_hash = hashlib.sha256(data_to_write).hexdigest()\n if not os.path.isdir(dirname):\n os.mkdir(dirname)\n filename = os.path.join(dirname, '{}.json.gz'.format(data_hash[:20]))\n with open(filename, 'wb') as f:\n f.write(data_to_write)\n\ndef read_examples(dirname):\n for basename in os.listdir(dirname):\n fullname = os.path.join(dirname, basename)\n with open(fullname, 'rb') as f:\n encoded = f.read()\n x, y = json.loads(gzip.decompress(encoded).decode())\n yield x, y\n\ndef collect():\n import readline\n labels = get_labels()\n with AudioRecorder(rate=conf.sampling_rate) as recorder:\n while True:\n y = input('Enter a label or press Enter to quit: ')\n if y == '':\n break\n elif y not in labels:\n print('No such label: {}'.format(y))\n continue\n\n print('--- RECORDING --- (Press Enter to stop recording)')\n recorder.start_recording()\n input()\n data = list(recorder.bytes_to_numseq(recorder.finish_recording()))\n print('--- FINISHED RECORDING ---')\n # transformed_data = list(sliding_diff(data, conf.sliding_diff_winsize))\n # scaled_data = scale_array(transformed_data, conf.lr_inputs)\n write_example((data, y), 'raw_data')\n\ndef learn():\n labels = get_labels()\n # mlr = MultiLogisticRegression(labels, conf.lr_inputs)\n svm = Svm()\n dataset = list(read_examples('data'))\n\n rd.shuffle(dataset)\n m = len(dataset)\n train_m = int(0.7 * m)\n train_set = dataset[:train_m]\n test_set = dataset[train_m:]\n test_m = len(test_set)\n print('Learning...')\n svm.learn(train_set)\n print('Learnt')\n\n\n correct = 0\n for x, y in train_set:\n pred = svm.get(x)\n if pred == y:\n correct += 1\n print('Results on train set: {:2f}% accuracy'.format(100 * correct / train_m))\n\n correct = 0\n for x, y in test_set:\n pred = svm.get(x)\n if pred == y:\n correct += 1\n print('Results on test set: {:2f}% accuracy'.format(100 * correct / test_m))\n with open('trained_data.pickle.b64', 'w') as wf:\n wf.write(svm.export_model())\n print('Weights written to trained_data.pickle.b64')\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"632031419","text":"# %% Importando as bibliotecas\nfrom os import getenv\nimport pandas as pd\nimport pymssql\nimport _mssql\nimport json\nimport sys\n# %% Conectando ao banco de dados\ndef read_server_config(path: str):\n try:\n if path.split('.')[-1] == \"json\":\n # Abre o arquivo JSON\n file = open(path)\n # return JSON object as a dictionary\n configs = json.load(file)\n # fecha o arquivo\n file.close()\n return configs\n else:\n print(\"O arquivo '{}' não é um arquivo json\")\n raise TypeError\n sys.exit()\n except Exception as e:\n print(e)\n file.close()\n return None\n\n\ndef connect_server(path):\n try:\n server = read_server_config(path)\n conn = pymssql.connect(host=\"{}:{}\".format(server['host'],\n server['port']),\n user=server['user'],\n password=server['password'],\n database=server['database'])\n return conn\n except Exception as e:\n print(e)\n sys.exit()\n return None\n\n\ndef request_server(req, cursor):\n\n cursor.execute(req)\n\n resposta = []\n row = cursor.fetchone()\n while row:\n resposta.append(row)\n row = cursor.fetchone()\n return resposta\n\n\nconn = connect_server('./src/config/server.json')\ncursor = conn.cursor()\n# %% Carregando os valores dos veiculos\n# %% Criando o dataframe para o pandas\nrequisicao_veiculos = \"\"\"SELECT * FROM Veiculo\"\"\"\nveiculo = request_server(requisicao_veiculos, cursor)\nveiculos = pd.DataFrame(veiculo)\nveiculos.head()\n# %% Renomeando as colunas\nveiculos.columns = ['IDVeiculo',\n 'IDMolelo',\n 'Ano',\n 'Valor',\n 'Placa',\n 'Renavam',\n 'Observacoes',\n 'Chassi',\n 'IDVeiculoMarca',\n 'NumeroFrota',\n 'IDMarcaEquipamento',\n 'IDModeloEquipamento',\n 'NumeroImobilizado',\n 'NumeroSerie',\n 'Tipo',\n 'IDEmpresa']\nveiculos.head()\n# %% Descobrindo a marca dos veiculos\n","sub_path":"plate.py","file_name":"plate.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"291491887","text":"import pytest\n\nfrom app import app\nimport config\n\ndata_set = [\n ({'name': \"

HELLOHELLO= max_bytes:\n break\n \nser.close()\nprint(\"done.\")\n","sub_path":"uart/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"435941789","text":"'''\nRPG test\n'''\nfrom player import Player\nfrom zombie import Zombie\n\ndef prompt_next_action(player, monster_name):\n '''\n Player has encountered a monster, ask if they want to attack it\n '''\n print(\"What would you like to attack the %s with\" % monster_name)\n attacks = player.list_attacks()\n for i, attack in enumerate(attacks, start=1):\n print('%d:%s ' % (i, attack['name']), end='')\n print()\n text = input(\"Enter the number of the attack or 0 to run away \")\n choice = int(text)\n if choice == 0:\n return None\n\n return attacks[choice - 1]\n\n\ndef attack_monster(player, monster, attack):\n '''\n Attack the monster\n '''\n # Player attacks which takes effort and magick\n print('%s attacks %s with a %s attack' % (player.name, monster.name, attack['name']))\n player.give_damage(attack)\n monster.take_damage(attack)\n\n # If monster is still alive it fights back\n if monster.is_alive():\n attack = monster.random_attack()\n if attack:\n print('%s attacks with %s' %(monster.name, attack['name']))\n player.take_damage(attack)\n else:\n print('%s has heroically slain the %s' % (player.name, monster.name))\n\n\ndef main():\n '''\n main entry point\n '''\n player = Player('Barry')\n monster = Zombie()\n print('%s approachs a %s' % (player.name, monster.name))\n\n while monster.is_alive() and player.is_alive():\n # See if player wants to attack the monster\n attack = prompt_next_action(player, monster.name)\n if attack:\n # Player chooses to attack the monster\n attack_monster(player, monster, attack)\n else:\n print('%s runs away like a little girl' % player.name)\n break\n\n #print('Player health %d' % player.health)\n #print('Player strength %d' % player.strength)\n #print('Player magick %d' % player.magick)\n #print('Monster health %d' % monster.health)\n print('Game over')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rpg/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"549856728","text":"import sys\n\nfrom jieba.analyse import TFIDF\nfrom optparse import OptionParser\n\nsys.path.append('../')\n\n\nUSAGE = \"usage: python extract_tags.py [file name] -k [top k]\"\n\nparser = OptionParser(USAGE)\nparser.add_option(\"-k\", dest=\"topK\")\nopt, args = parser.parse_args()\n\n\nif len(args) < 1:\n print(USAGE)\n sys.exit(1)\n\nfile_name = args[0]\n\nif opt.topK is None:\n topK = 10\nelse:\n topK = int(opt.topK)\n\ncontent = open(file_name, 'rb').read()\n\nprint('-'*40)\nprint(' TF-IDF')\nprint('-'*40)\ntfidf=TFIDF()\nfor x, w in tfidf.extract_tags(content, withWeight=True):\n print('%s %s' % (x, w))\n# for x, w in jieba.analyse.extract_tags(content, withWeight=True):\n# print('%s %s' % (x, w))\n\n","sub_path":"test/extract_tags_bytfidf.py","file_name":"extract_tags_bytfidf.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"225279069","text":"\nimport random\n\nimport node_\nfrom utilities_ import print_node as ptree\n\nimport unittest\n\n\nclass TestNode(unittest.TestCase):\n\n def setUp(self):\n self.root = node_.Node(1)\n self.seq = [37, 37, 96, -59, 96, -16, -100, 70, 68, 13]\n # (1)\n # (-59) (37)\n # (-100)(-16)(13) (96)\n # (70)\n # (68)\n\n def test_height(self):\n for num in self.seq:\n self.root.insert(num)\n self.assertGreater(self.root.height, 2)\n\n def test_balance_factor(self):\n lnode = node_.Node(10)\n self.root.left = lnode\n self.assertEqual(-1, self.root.balance)\n rnode = node_.Node(11)\n self.root.right = rnode\n self.assertEqual(0, self.root.balance)\n\n def test_delete(self):\n self.root = node_.Node(1)\n [self.root.insert(_) for _ in range(2, 100)]\n [self.root.delete(_) for _ in range(60, 100)]\n [self.root.delete(_) for _ in range(6, 75)]\n self.assertSequenceEqual(list(range(1, 6)),\n self.root.to_list())\n\n def test_color(self):\n for num in self.seq:\n self.root.insert(num)\n ptree(self.root)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"balancing_tree/rb/test_node.py","file_name":"test_node.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"76722780","text":"#! /usr/bin/env python3\nimport numpy as np\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import roc_auc_score, accuracy_score\nfrom libsvm.svmutil import *\nfrom libsvm.svm import *\nimport numpy as np\nfrom sklearn.svm import LinearSVC\n\n\ndef get_error_rate(pred, Y):\n return sum(pred != Y) / len(pred)\n\n\nclass AdaBoost:\n def __init__(self, T=20):\n self.T = T\n\n def adaboost(self, X_train, Y_train, X_test, Y_test):\n # init\n Linear_SVM = LinearSVC()\n n_train, n_test = len(X_train), len(X_test)\n distribute_weight = np.ones(n_train) / n_train\n pred_train, pred_test, pred_test_score = np.zeros(n_train), np.zeros(n_test), np.zeros(n_test)\n T = self.T\n\n for i in range(T):\n # fit a base classifier\n Linear_SVM.fit(X_train, Y_train, sample_weight=distribute_weight)\n temp_pred_train = Linear_SVM.predict(X_train)\n temp_pred_test = Linear_SVM.predict(X_test)\n # temp_pred_test_score = dec_tree.predict_proba(X_test)\n\n miss = [int(x) for x in temp_pred_train != Y_train]\n loss = np.dot(distribute_weight, miss)\n if loss > 0.5:\n break\n alpha = 0.5 * np.log(1 / loss - 1)\n # add to prediction\n pred_train += alpha * temp_pred_train\n pred_test += alpha * temp_pred_test\n # pred_test_score += alpha * temp_pred_test_score[:, 1].ravel()\n # update distribution_weight\n params = [1 if x == 1 else -1 for x in miss]\n distribute_weight = distribute_weight * [np.exp(alpha * x) for x in params]\n distribute_weight = distribute_weight * (1 / sum(distribute_weight))\n\n pred_train, pred_test = np.sign(pred_train), np.sign(pred_test)\n\n # print(get_error_rate(pred_test, Y_test))\n return pred_test\n\n\nif __name__ == '__main__':\n\n datapath = 'DogsVsCats/DogsVsCats/'\n train_y, train_x = svm_read_problem(f'{datapath}DogsVsCats.train')\n test_y, test_x = svm_read_problem(f'{datapath}DogsVsCats.test')\n\n X_train = []\n for x in train_x:\n x = list(x.values())\n X_train.append(x)\n X_train = np.array(X_train)\n\n X_test = []\n for x in test_x:\n x = list(x.values())\n X_test.append(x)\n X_test = np.array(X_test)\n\n Y_train = np.array(train_y).astype(float)\n Y_test = np.array(test_y).astype(float)\n\n\n Linear_SVM = LinearSVC()\n Linear_SVM.fit(X_train, Y_train)\n pred_test = Linear_SVM.predict(X_test)\n print('accuracy on test data (standard decision tree): %f, error rata: %f' % (\n accuracy_score(Y_test, pred_test), get_error_rate(pred_test, Y_test)))\n\n\n ada_boost = AdaBoost()\n pred_test = ada_boost.adaboost(X_train, Y_train, X_test, Y_test)\n print('T = %d, accuracy on test data: %f, error rate: %f' % (\n ada_boost.T, accuracy_score(Y_test, pred_test), get_error_rate(pred_test, Y_test)))\n","sub_path":"adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"508918794","text":"import requests\nfrom iterator_action import iterator_action\n\nclass geocode_lsd_iterator_action(iterator_action):\n\n\tAPI_KEY = '465351144075618807441x4574'\n\taddress_column_name = \"Address\"\n\n\tdef get_action_verb(self):\n\t\treturn \"Geocoding\"\n\n\tdef test_iterator_action(self):\n\t\treturn self.get_google_results({\"Address\":\"04-16-031-15W\"}, self.API_KEY)\n\n\tdef run_iterator_action(self, input):\n\t\treturn self.get_google_results(input)\n\n\n\tdef get_google_results(self, input, api_key=None, return_full_response=False):\n\t \"\"\"\n\t Get geocode results from Google Maps Geocoding API.\n\t \n\t Note, that in the case of multiple google geocode reuslts, this function returns details of the FIRST result.\n\t \n\t @param address: String address as accurate as possible. For Example \"18 Grafton Street, Dublin, Ireland\"\n\t @param api_key: String API key if present from google. \n\t If supplied, requests will use your allowance from the Google API. If not, you\n\t will be limited to the free usage of 2500 requests per day.\n\t @param return_full_response: Boolean to indicate if you'd like to return the full response from google. This\n\t is useful if you'd like additional location details for storage or parsing later.\n\t \"\"\"\n\t # Set up your Geocoding url\n\t #geocode_url = \"https://maps.googleapis.com/maps/api/geocode/json?address={}\".format(address)\n\t #if api_key is not None:\n\t # geocode_url = geocode_url + \"&key={}\".format(api_key)\n\n\t address = input[self.address_column_name]\n\n\t geocode_url = \"https://geocoder.ca/?locate={}\".format(address)\n\t geocode_url = geocode_url + \"&json=1\" \n\n\t \n\t # Ping google for the reuslts:\n\t results = requests.get(geocode_url)\n\t # Results will be in JSON format - convert to dict using requests functionality\n\t results = results.json()\n\t \n\t # if there's no results or an error, return empty results.\n\t #if len(results['results']) == 0:\n\t if len(results) == 0:\n\t output = {\n\t \"formatted_address\" : None,\n\t \"latitude\": None,\n\t \"longitude\": None,\n\t \"accuracy\": None,\n\t \"google_place_id\": None,\n\t \"type\": None,\n\t \"postcode\": None\n\t }\n\t else: \n\t #answer = results['results'][0]\n\t answer = results\n\t output = {\n\t \"formatted_address\" : answer.get('LSD'),\n\t \"latitude\": answer.get('latt'),\n\t \"longitude\": answer.get('longt'),\n\t \"accuracy\": answer.get('confidence'),\n\t \"city\": answer.get(\"city\"),\n\t \"prov\": answer.get('prov'),\n\t \"postcode\": answer.get('postal'),\n\t \"TimeZone\": answer.get('TimeZone'),\n\t \"stnumber\": answer.get('stnumber'),\n\t \"staddress\": answer.get('staddress'),\n\t \"AreaCode\": answer.get('AreaCode'),\n\t \"error\": answer.get('error')\n\t }\n\t \n\t # Append some other details: \n\t output['input_string'] = address\n\t #output['number_of_results'] = len(results)\n\t output['status'] = answer.get('confidence')\n\t if return_full_response is True:\n\t output['response'] = results\n\t \n\t return output\n\ndef main():\n\tprint(geocode_lsd_iterator_action().test_iterator_action())\n\nif __name__ == '__main__':\n\tmain()","sub_path":"geocode_lsd_iterator_action.py","file_name":"geocode_lsd_iterator_action.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"574959637","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 4 14:16:50 2020\n\n@author: zhangjuefei\n\"\"\"\n\nimport sys\nsys.path.append('../..')\n\nimport numpy as np\nfrom sklearn.datasets import make_classification\nimport matrixslow as ms\n\n# 特征维数\ndimension = 60\n\n# 构造二分类样本,有用特征占20维\nX, y = make_classification(600, dimension, n_informative=20)\ny = y * 2 - 1\n\n\n# 嵌入向量维度\nk = 20\n\n# 一次项\nx1 = ms.core.Variable(dim=(dimension, 1), init=False, trainable=False)\n\n# 标签\nlabel = ms.core.Variable(dim=(1, 1), init=False, trainable=False)\n\n# 一次项权值向量\nw = ms.core.Variable(dim=(1, dimension), init=True, trainable=True)\n\n# 嵌入矩阵\nE = ms.core.Variable(dim=(k, dimension), init=True, trainable=True)\n\n# 偏置\nb = ms.core.Variable(dim=(1, 1), init=True, trainable=True)\n\n# 用嵌入矩阵与特征向量相乘,得到嵌入向量\nembedding = ms.ops.MatMul(E, x1)\n\n\n# FM部分\nfm = ms.ops.Add(ms.ops.MatMul(w, x1), # 一次部分\n # 二次部分\n ms.ops.MatMul(ms.ops.Reshape(embedding, shape=(1, k)), embedding))\n\n\n# Deep部分,第一隐藏层\nhidden_1 = ms.layer.fc(embedding, k, 8, \"ReLU\")\n\n# 第二隐藏层\nhidden_2 = ms.layer.fc(hidden_1, 8, 4, \"ReLU\")\n\n# 输出层\ndeep = ms.layer.fc(hidden_2, 4, 1, None)\n\n# 输出\noutput = ms.ops.Add(deep, fm, b)\n\n# 预测概率\npredict = ms.ops.Logistic(output)\n\n# 损失函数\nloss = ms.ops.loss.LogLoss(ms.ops.Multiply(label, output))\n\nlearning_rate = 0.005\noptimizer = ms.optimizer.Adam(ms.default_graph, loss, learning_rate)\n\n\nbatch_size = 16\n\nfor epoch in range(20):\n \n batch_count = 0 \n for i in range(len(X)):\n \n x1.set_value(np.mat(X[i]).T)\n label.set_value(np.mat(y[i]))\n \n optimizer.one_step()\n \n batch_count += 1\n if batch_count >= batch_size:\n \n optimizer.update()\n batch_count = 0\n \n\n pred = []\n for i in range(len(X)):\n \n x1.set_value(np.mat(X[i]).T)\n \n predict.forward()\n pred.append(predict.value[0, 0])\n \n pred = (np.array(pred) > 0.5).astype(np.int) * 2 - 1\n accuracy = (y == pred).astype(np.int).sum() / len(X)\n \n print(\"epoch: {:d}, accuracy: {:.3f}\".format(epoch + 1, accuracy))","sub_path":"example/ch06/deepfm.py","file_name":"deepfm.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"194263411","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib import admin\nfrom .models import Pregunta, Respuesta\n\n\nclass RespuestaInLine(admin.StackedInline):\n model = Respuesta\n extra = 3\n\n\nclass PreguntaAdmin(admin.ModelAdmin):\n inlines = [RespuestaInLine]\n list_display = ('asunto', 'fecha_publicacion', 'publicado_hoy')\n\n\nadmin.site.register(Pregunta, PreguntaAdmin)\nadmin.site.register(Respuesta)\n\n# Register your models here.\n","sub_path":"preguntasyrespuestas/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"430902615","text":"import firedrake as fe \nimport sapphire.test\nimport sapphire_ice.simulation\n\n\ndatadir = sapphire.test.datadir\n\ndef heat_driven_cavity_variational_form_residual(sim, solution):\n \n mass = sapphire.simulations.convection_coupled_phasechange.\\\n mass(sim, solution)\n \n stabilization = sapphire.simulations.convection_coupled_phasechange.\\\n stabilization(sim, solution)\n \n p, u, T = fe.split(solution)\n \n b = sapphire_ice.simulation.water_buoyancy(sim = sim, temperature = T)\n \n Pr = sim.prandtl_number\n \n _, psi_u, psi_T = fe.TestFunctions(sim.function_space)\n \n inner, dot, grad, div, sym = \\\n fe.inner, fe.dot, fe.grad, fe.div, fe.sym\n \n momentum = dot(psi_u, grad(u)*u + b) \\\n - div(psi_u)*p + 2.*inner(sym(grad(psi_u)), sym(grad(u)))\n \n energy = psi_T*dot(u, grad(T)) + dot(grad(psi_T), 1./Pr*grad(T))\n \n return mass + momentum + energy + stabilization\n \n \ndef dirichlet_boundary_conditions(sim):\n\n W = sim.function_space\n \n return [fe.DirichletBC(\n W.sub(1), (0., 0.), \"on_boundary\"),\n fe.DirichletBC(W.sub(2), sim.hot_wall_temperature, 1),\n fe.DirichletBC(W.sub(2), sim.cold_wall_temperature, 2)]\n \n \ndef initial_values(sim):\n \n print(\"Solving steady heat driven cavity to obtain initial values\")\n \n Ra = 2.518084e6\n\n Pr = 6.99\n \n sim.reference_temperature_range__degC.assign(10.)\n \n sim.grashof_number = sim.grashof_number.assign(Ra/Pr)\n \n sim.prandtl_number = sim.prandtl_number.assign(Pr)\n \n w = fe.Function(sim.function_space)\n \n p, u, T = w.split()\n \n p.assign(0.)\n \n ihat, jhat = sim.unit_vectors()\n \n u.assign(0.*ihat + 0.*jhat)\n \n T.assign(sim.cold_wall_temperature)\n \n F = heat_driven_cavity_variational_form_residual(\n sim = sim,\n solution = w)*fe.dx(degree = sim.quadrature_degree)\n \n problem = fe.NonlinearVariationalProblem(\n F = F,\n u = w,\n bcs = dirichlet_boundary_conditions(sim),\n J = fe.derivative(F, w))\n \n solver = fe.NonlinearVariationalSolver(\n problem = problem,\n solver_parameters = {\n \"snes_type\": \"newtonls\",\n \"snes_monitor\": None,\n \"ksp_type\": \"preonly\", \n \"pc_type\": \"lu\", \n \"mat_type\": \"aij\",\n \"pc_factor_mat_solver_type\": \"mumps\"})\n \n def solve():\n \n solver.solve()\n \n return w\n \n w, _ = \\\n sapphire.continuation.solve_with_bounded_regularization_sequence(\n solve = solve,\n solution = w,\n backup_solution = fe.Function(w),\n regularization_parameter = sim.grashof_number,\n initial_regularization_sequence = (\n 0., sim.grashof_number.__float__()))\n \n return w\n \n\nclass WaterFreezingInCavitySimulation(\n sapphire_ice.simulation.Simulation):\n\n def __init__(self, *args, meshsize, **kwargs):\n \n self.reference_temperature_range__degC = fe.Constant(10.)\n \n self.hot_wall_temperature = fe.Constant(1.)\n \n self.cold_wall_temperature = fe.Constant(0.)\n \n super().__init__(\n *args,\n mesh = fe.UnitSquareMesh(meshsize, meshsize),\n initial_values = initial_values,\n dirichlet_boundary_conditions = dirichlet_boundary_conditions,\n **kwargs)\n \n self.stefan_number = self.stefan_number.assign(0.125)\n \n self.cold_wall_temperature = self.cold_wall_temperature.assign(-1.)\n \n \n \ndef freeze_water(endtime, s, tau, rx, nx, rt, nt, q, outdir = \"\"):\n \n mu_l__SI = 8.90e-4 # [Pa s]\n \n rho_l__SI = 999.84 # [kg / m^3]\n \n nu_l__SI = mu_l__SI/rho_l__SI # [m^2 / s]\n \n t_f__SI = endtime # [s]\n \n L__SI = 0.038 # [m]\n \n Tau = pow(L__SI, 2)/nu_l__SI\n \n t_f = t_f__SI/Tau\n \n \"\"\" For Kowalewski's water freezing experiment,\n at t_f__SI 2340 s, t_f = 1.44.\n \"\"\"\n \n sim = WaterFreezingInCavitySimulation(\n quadrature_degree = q,\n element_degree = rx - 1,\n time_stencil_size = rt + 1,\n meshsize = nx,\n output_directory_path = str(outdir.join(\"freeze_water/\")))\n \n sim.timestep_size = sim.timestep_size.assign(t_f/float(nt))\n \n sim.solid_velocity_relaxation_factor = \\\n sim.solid_velocity_relaxation_factor.assign(tau)\n \n sim.smoothing = sim.smoothing.assign(s)\n \n \n sim.solutions, _, = sim.run(endtime = t_f)\n \n \n print(\"Liquid area = {0}\".format(sim.liquid_area))\n \n return sim\n \n \ndef test__validate__freeze_water__regression(datadir):\n \n sim = freeze_water(\n outdir = datadir,\n endtime = 2340.,\n s = 1./200.,\n tau = 1.e-12,\n rx = 2,\n nx = 24,\n rt = 2,\n nt = 4,\n q = 4)\n \n assert(abs(sim.liquid_area - 0.69) < 0.01)\n \n","sub_path":"tests/test__regression__freezing_water_in_cavity.py","file_name":"test__regression__freezing_water_in_cavity.py","file_ext":"py","file_size_in_byte":5030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"55914614","text":"import os\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport matplotlib.ticker as ticker\nfrom matplotlib.ticker import FuncFormatter\nimport seaborn as sns\nimport pandas as pd\n\nimport mmap\nimport re\n\nLOG_BASE = '../log/constraints/'\n\nlocator = re.compile(\n rb'''\n (?Pwarning.*)\n ''',\n re.VERBOSE)\n\ndef parseLine(mm, match, _id):\n line = match.group('line').decode()\n # print(\"line: \", line)\n\n mTmp = re.search('Fitness', line)\n e = mTmp.end()\n line = line[e:]\n \n # pattern\n pFitness = re.compile('\\d(\\d)+')\n mFitness = re.search(pFitness, line)\n s = mFitness.start()\n e = mFitness.end()\n fitness = int(line[s:e])\n # print(\"Fitness: \", fitness)\n\n mTmp = re.search('Runtime', line)\n e = mTmp.end()\n line = line[e:]\n\n # pattern \n pRuntime = re.compile('(\\d)+\\.\\d')\n mRuntime = re.search(pRuntime, line)\n s = mRuntime.start()\n e = mRuntime.end()\n runtime = float(line[s:e])\n # print(\"Runtime: \", runtime)\n \n mTmp = re.search('Scosts ratio', line)\n e = mTmp.end()\n line = line[e:]\n\n pSr = re.compile('(\\d)+\\.(\\d)+')\n mSr = re.search(pSr, line)\n s = mSr.start()\n e = mSr.end()\n sr = float(line[s:e])\n # print(\"Scosts ratio: \", sr)\n \n mTmp = re.search('Ucost ratio', line)\n e = mTmp.end()\n line = line[e:]\n\n pUr = re.compile('(\\d)+\\.(\\d)+')\n mUr = re.search(pUr, line)\n e = mUr.end()\n ur = float(line[s:e])\n # print(\"Ucosts ratio: \", ur)\n\n return fitness, runtime, sr, ur\n\n \n\ndef parseFile(fname):\n fitnesses, runtimes, srs, urs = [], [], [], []\n with open(fname, 'r') as f:\n mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n for (_id, match) in enumerate(re.finditer(locator, mm)):\n #print(match)\n s = match.start()\n mm.seek(s)\n fitness, runtime, sr, ur = parseLine(mm, match, _id)\n fitnesses.append(fitness)\n runtimes.append(runtime)\n srs.append(sr)\n urs.append(ur)\n\n return fitnesses, runtimes, srs, urs \n\ndef parseEA():\n\n # dga\n fname = LOG_BASE + 'dga_g_1.log'\n fitnesses, runtimes, srs, urs = parseFile(fname)\n sLratio = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n uLratio = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ratio_list = []\n for sl in sLratio:\n for ul in uLratio:\n for i in range(10):\n ratio_list.append((sl, ul))\n dict_dga = {\n 'Evolutionary Algorithm': ['DGA']*len(srs)*2,\n 'Objective Value': fitnesses*2,\n 'Runtime(s)': runtimes*2,\n 'Constraints': srs+urs,\n 'Type': ['Size']*len(srs) + ['Update']*len(srs),\n 'Combinations': ratio_list * 2,\n }\n df_dga = pd.DataFrame(dict_dga)\n\n\n # dpso\n fname = LOG_BASE + 'dpso_g_1.log'\n fitnesses, runtimes, srs, urs = parseFile(fname)\n\n sLratio = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n uLratio = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ratio_list = []\n for sl in sLratio:\n for ul in uLratio:\n for i in range(10):\n ratio_list.append((sl, ul))\n\n dict_dpso = {\n 'Evolutionary Algorithm': ['DPSO']*len(srs)*2,\n 'Objective Value': fitnesses*2,\n 'Runtime(s)': runtimes*2,\n 'Constraints': srs+urs,\n 'Type': ['Size']*len(srs) + ['Update']*len(srs),\n 'Combinations': ratio_list * 2,\n }\n df_dpso = pd.DataFrame(dict_dpso)\n\n # isfla\n fname = LOG_BASE + 'isfla_g_1.log'\n fitnesses, runtimes, srs, urs = parseFile(fname)\n\n sLratio = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n uLratio = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ratio_list = []\n for sl in sLratio:\n for ul in uLratio:\n for i in range(10):\n ratio_list.append((sl, ul))\n \n dict_isfla = {\n 'Evolutionary Algorithm': ['ISFLA']*len(srs)*2,\n 'Objective Value': fitnesses*2,\n 'Runtime(s)': runtimes*2,\n 'Constraints': srs+urs,\n 'Type': ['Size']*len(srs) + ['Update']*len(srs),\n 'Combinations': ratio_list * 2,\n }\n df_isfla = pd.DataFrame(dict_isfla)\n\n df_ea = pd.concat([df_dga, df_dpso, df_isfla])\n return df_ea\n\n\ndef main():\n df_ea = parseEA()\n gridkw = dict(height_ratios=[1, 1, 1])\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, gridspec_kw=gridkw,\n figsize=(16.0, 8.0))\n sns.boxplot(ax=ax1,x='Combinations', y='Constraints', hue='Type', data=df_ea)\n sns.boxplot(ax=ax2,x='Combinations', y='Runtime(s)', hue='Evolutionary Algorithm', data=df_ea)\n sns.boxplot(ax=ax3,x='Combinations', y='Objective Value', hue='Evolutionary Algorithm', data=df_ea)\n plt.savefig(LOG_BASE+'ea.pdf', bbox_inches='tight')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/constraints.py","file_name":"constraints.py","file_ext":"py","file_size_in_byte":4824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"599258365","text":"# Introdução a Programação de Computadores - IPC\n# Universidade do Estado do Amazonas - UEA\n# Prof. Jucimar Jr\n#\n# Enrique Leão Barbosa Izel 1715310048\n# Hugo Thadeu Silva Cardoso 1715310013\n# Victor Summer Oliveira Pantaleao 1715310042\n# Wilbert Luís Evangelista Marins 1715310055\n# Yuri Leandro de Aquino Silva 1615100462\n#\n# Criar um algoritmo que leia os elementos de uma matriz inteira 10 x 10 e escreva\n# somente os elementos abaixo da diagonal secundária.\n#---------------------------------------------------------------------------------\n\na =[]\nb =[]\nc =[]\nd =[]\ne =[]\nf =[]\ng =[]\nh =[]\ni =[]\nj =[]\n\ncont = 1\ncont2 =1\ncont3 =1\ncont4 =1\ncont5 =1\ncont6 =1\ncont7 =1\ncont8 =1\ncont9 =1\ncont10 =1\n\nwhile cont <= 10:\n number1 = int(input(\"Digite o elemento1: \"))\n a.append(number1)\n cont += 1\n\nwhile cont2 <= 10:\n number2 = int(input(\"Digite o elemento2: \"))\n b.append(number2)\n cont2 += 1\n\nwhile cont3 <= 10:\n number3 = int(input(\"Digite o elemento3: \"))\n c.append(number3)\n cont3 += 1\n\nwhile cont4 <= 10:\n number4 = int(input(\"Digite o elemento4: \"))\n d.append(number4)\n cont4 += 1\n\nwhile cont5 <= 10:\n number5 = int(input(\"Digite o elemento5: \"))\n e.append(number5)\n cont5 += 1\n\nwhile cont6 <= 10:\n number6 = int(input(\"Digite o elemento6: \"))\n f.append(number6)\n cont6 += 1\n\nwhile cont7 <= 10:\n number7 = int(input(\"Digite o elemento7: \"))\n g.append(number7)\n cont7 += 1\n\nwhile cont8 <= 10:\n number8 = int(input(\"Digite o elemento8: \"))\n h.append(number8)\n cont8 += 1\n\nwhile cont9 <= 10:\n number9 = int(input(\"Digite o elemento9: \"))\n i.append(number9)\n cont9 += 1\n\nwhile cont10 <= 10:\n number10 = int(input(\"Digite o elemento10: \"))\n j.append(number10)\n cont10 += 1\n\n\nprint (b[9])\nprint (c[8:10])\nprint (d[7:10])\nprint (e[6:10])\nprint (f[5:10])\nprint (g[4:10])\nprint (h[3:10])\nprint (i[2:10])\nprint (j[1:10])","sub_path":"lista07/lista07_lista01_questao10.py","file_name":"lista07_lista01_questao10.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"603446131","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /users/payno/.local/share/virtualenvs/tomwer_venc/lib/python3.7/site-packages/tomwer/core/process/baseprocess.py\n# Compiled at: 2020-03-06 02:01:31\n# Size of source mod 2**32: 11133 bytes\n\"\"\"\nBasic class each orange widget processing an action should inheritate from\nher corresponding class in core.\nAnd all of those classes from core should implement this interface to deal\nwith the interpreter parser.\nAllowing to convert an orane workflow to a TOWER workflow ( same action but no\nGUI )\n\"\"\"\n__author__ = [\n 'H. Payno']\n__license__ = 'MIT'\n__date__ = '02/06/2017'\nimport threading, h5py, numpy\nfrom datetime import datetime\nfrom typing import Union\nfrom silx.io.dictdump import dicttoh5\nfrom collections import namedtuple\nfrom silx.io.dictdump import h5todict\nimport logging\n_logger = logging.getLogger(__name__)\n_input_desc = namedtuple('_input_desc', ['name', 'type', 'handler', 'doc'])\n_output_desc = namedtuple('_output_desc', ['name', 'type', 'doc'])\n_process_desc = namedtuple('_process_desc', ['process_order', 'configuration', 'results'])\n\nclass BaseProcess(object):\n __doc__ = 'Class from which all tomwer process should inherit\\n\\n :param logger: the logger used by the class\\n '\n endless_process = False\n inputs = []\n outputs = []\n _output_values = {}\n\n def __init__(self):\n self._scheme_title = None\n self._return_dict = False\n\n def setProperties(self, properties):\n raise NotImplementedError('BaseProcess is an abstract class')\n\n @staticmethod\n def properties_help():\n \"\"\"\n\n :return: display the list of all managed keys and possible values\n :rtype: str\n \"\"\"\n raise NotImplementedError('BaseProcess is an abstract class')\n\n def get_output_value(self, key):\n \"\"\"\n\n :param str key: \n :return: \n \"\"\"\n assert type(key) is str\n if key in self._output_values:\n return self._output_values[key]\n return\n\n def clear_output_values(self):\n self._output_values.clear()\n\n def register_output(self, key, value):\n \"\"\"\n\n :param str key: name of the output\n :param value: value of the output\n \"\"\"\n self._output_values[key] = value\n\n def key_exist(self, key):\n for _output in self.outputs:\n if _output.name == key:\n return True\n\n return False\n\n def input_handler(self, name):\n \"\"\"\n\n :param str name: name of input (can be see as link type)\n :return: handler name (str) or None if name not defined\n \"\"\"\n for _input in self.inputs:\n if _input.name == name:\n return _input.handler\n\n def _set_return_dict(self, return_dict):\n \"\"\"\n\n :param bool return_dict: if True, force the process to return a dict\n instead of a `.TomoBase` object\n \"\"\"\n self._return_dict = return_dict\n\n @staticmethod\n def program_name():\n \"\"\"Name of the program used for this processing\"\"\"\n raise NotImplementedError('Base class')\n\n @staticmethod\n def program_version():\n \"\"\"version of the program used for this processing\"\"\"\n raise NotImplementedError('Base class')\n\n @staticmethod\n def definition():\n \"\"\"definition of the process\"\"\"\n raise NotImplementedError('Base class')\n\n def get_configuration(self) -> Union[(None, dict)]:\n \"\"\"\n\n :return: configuration of the process\n :rtype: dict\n \"\"\"\n if len(self._settings) > 0:\n return self._settings\n return\n\n def set_configuration(self, configuration: dict) -> None:\n self._settings = configuration\n\n def register_process(self, process_file: str, configuration: Union[(dict, None)], results: Union[(dict, None)], process_index: int, overwrite: bool=True) -> None:\n \"\"\"\n Store the current process in the linked h5 file if any,\n output data stored will be the one defined by the data_keys\n\n :param process_file: where to store the processing information\n :type: str\n :param process: process to record\n :type: BaseProcess\n :param configuration: configuration of the process\n :type: Union[dict,None]\n :param results: result of the processing\n :type: Union[dict,None]\n :param process_index: index of the process\n :type: int\n :param overwrite: if True then overwrite the process if already exists\n \"\"\"\n assert process_file is not None\n try:\n self._register_process(process_file=process_file, process=self,\n configuration=configuration,\n results=results,\n process_index=process_index,\n overwrite=overwrite)\n except IOError as e:\n try:\n _logger.error(e)\n finally:\n e = None\n del e\n\n def _register_process(self, process_file: str, process, configuration: Union[(dict, None)], results: Union[(dict, None)], process_index: int, overwrite: bool=True) -> None:\n \"\"\"\n Store the current process in the linked h5 file if any,\n output data stored will be the one defined by the data_keys\n\n :param process_file: where to store the processing information\n :type: str\n :param process: process to record\n :type: BaseProcess\n :param configuration: configuration of the process\n :type: Union[dict,None]\n :param results: result of the processing\n :type: Union[dict,None]\n :param process_index: index of the process\n :type: int\n :param overwrite: if True then overwrite the process if already exists\n \"\"\"\n assert process_file is not None, 'The process file should be defined'\n assert isinstance(process, BaseProcess)\n process_name = 'tomwer_process_' + str(process_index)\n with h5py.File(process_file, mode='a') as (h5f):\n nx_process = h5f.require_group(process_name)\n nx_process.attrs['NX_class'] = 'NXprocess'\n if overwrite:\n for key in ('program', 'version', 'date', 'processing_order', 'class_instance'):\n if key in nx_process:\n del nx_process[key]\n\n nx_process['program'] = process.program_name()\n nx_process['version'] = process.program_version()\n nx_process['date'] = datetime.now().replace(microsecond=0).isoformat()\n nx_process['processing_order'] = numpy.int32(process_index)\n _class = process.__class__\n nx_process['class_instance'] = '.'.join((_class.__module__,\n _class.__name__))\n if results is not None:\n dicttoh5(results, h5file=process_file,\n h5path=('/'.join((process_name, 'results'))),\n overwrite_data=True,\n mode='a')\n if configuration is not None:\n dicttoh5(configuration, h5file=process_file,\n h5path=('/'.join((process_name, 'configuration'))),\n overwrite_data=True,\n mode='a')\n\n @staticmethod\n def get_processes_frm_type(process_file: str, process_type) -> list:\n \"\"\"\n\n :param str process_file: file to read\n :param process_type: process type we are looking for\n :return: list of _process_desc(processing_order, configuration, results)\n :rtype: list\n \"\"\"\n processes = []\n with h5py.File(process_file, mode='r') as (h5f):\n for process in h5f.keys():\n nx_process = h5f[process]\n if nx_process['program'][()] == process_type.program_name():\n p_order = nx_process['processing_order'][()]\n config = h5todict(process_file, '/'.join((nx_process.name, 'configuration')))\n results = h5todict(process_file, '/'.join((nx_process.name, 'results')))\n processes.append(_process_desc(process_order=p_order, configuration=config,\n results=results))\n\n return processes\n\n\nclass SingleProcess(BaseProcess):\n __doc__ = '\\n Interface for Single process (which can be applied on a single scan)\\n '\n\n def process(self, scan=None):\n \"\"\"\n Process should return an int. Default are zero for success and one for\n failure. It can also return an error value\n\n :param scan:\n :return:\n :rtype: int\n \"\"\"\n raise NotImplementedError('Base class')\n\n\nclass EndlessProcess(BaseProcess):\n __doc__ = '\\n Interface for Single process (which can be applied on a single scan)\\n '\n endless_process = True\n process_finished_event = threading.Event()\n\n def start(self):\n raise NotImplementedError('Base class')\n\n def stop(self):\n raise NotImplementedError('Base class')","sub_path":"pycfiles/tomwer-0.4.0.linux-x86_64.tar/baseprocess.cpython-37.py","file_name":"baseprocess.cpython-37.py","file_ext":"py","file_size_in_byte":9075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"38495528","text":"from __future__ import division\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nfrom six.moves import range\n\n\ndef random_walk(transition_matrix, alpha, err_tol, max_iter):\n \"\"\"\n Run random walk to compute stationary probabilities\n :param transition_matrix: scipy.sparse.csr_matrix defining the random walk\n :param alpha: damping parameter\n :param err_tol: convergence criterion for stationary probability\n :param max_iter: max number of steps to take for random walk\n :return:\n \"\"\"\n # shape of transition matrix will be length of vectors\n n = transition_matrix.shape[0]\n # damping vector\n damping_vec = ((1 - alpha) / n) * np.ones((n, 1))\n # stationary vector initialization\n pi = (1 / n) * np.ones((n, 1))\n\n for _ in range(max_iter):\n pi_next = damping_vec + alpha * transition_matrix.T.dot(pi)\n err = np.linalg.norm(pi - pi_next, ord=np.inf)\n if err <= err_tol:\n return pi_next\n pi = pi_next\n return pi\n\n\ndef row_normalize_csr_matrix(matrix):\n \"\"\"\n Row normalize a csr matrix without mutating the input\n :param matrix: scipy.sparse.csr_matrix instance\n \"\"\"\n if not isinstance(matrix, csr_matrix):\n input_type = matrix.__class__.__name__\n expected_type = csr_matrix.__class__.__name__\n raise TypeError('expected input of type {}, received input of type{}'.format(expected_type, input_type))\n if any(matrix.data == 0):\n raise ValueError('input must be scipy.sparse.csr_matrix and must not store zeros')\n # get row index for every nonzero element in matrix\n row_idx, col_idx = matrix.nonzero()\n # compute unraveled row sums\n row_sums = matrix.sum(axis=1).A1\n # divide data by (broadcasted) row sums\n normalized = matrix.data / row_sums[row_idx]\n return csr_matrix((normalized, (row_idx, col_idx)), shape=matrix.shape)\n","sub_path":"coupled_biased_random_walks/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"309599992","text":"#!/usr/bin/python\n#encoding=gbk\n\nimport time\nfrom cj.web import *\n\nsql = \"\"\"exec proc_statistics 0,'%s','%s'\"\"\" % (time.strftime('%Y-%m-01'),time.strftime('%Y-%m-%d'))\n \nfield = \"rq,skbs,skje,fkbs,fkje,kkbs,kkje,bs,je\"\nlabel = \"统计期,收款笔数,收款金额,付款笔数,付款金额,扣款笔数,扣款优惠,合计笔数,合计金额\"\n\ndm = modal.Modal(field, label, \"rq\")\n\ndm.skbs.align = \"right\"\ndm.fkbs.align = \"right\"\ndm.kkbs.align = \"right\"\ndm.bs.align = \"right\"\n\ndm.skbs.width = 80\ndm.fkbs.width = 80\ndm.kkbs.width = 80\ndm.bs.width = 80\n\ndm.skje.align = \"right\"\ndm.fkje.align = \"right\"\ndm.kkje.align = \"right\"\ndm.je.align = \"right\"\n\ndm.skje.renderer = js.format('$')\ndm.fkje.renderer = js.format('$')\ndm.kkje.renderer = js.format('$')\ndm.je.renderer = js.format('$')\n\ndm.skbs.summary_type = \"sum\" \ndm.fkbs.summary_type = \"sum\" \ndm.kkbs.summary_type = \"sum\" \ndm.bs.summary_type = \"sum\" \n\ndm.skje.summary_type = \"sum\" \ndm.skje.summary_renderer = js.format('$')\ndm.fkje.summary_type = \"sum\" \ndm.fkje.summary_renderer = js.format('$')\ndm.kkje.summary_type = \"sum\" \ndm.kkje.summary_renderer = js.format('$')\ndm.je.summary_type = \"sum\" \ndm.je.summary_renderer = js.format('$')\n\n\ncontrol={'addnew':False,'edit':False}\ncontrol['statistics1'] = {'location':'tbar1'}\ncontrol['statistics1']['quick_query'] = True\ncontrol['statistics1']['ctrl'] = ext.Combo(name='statistics1', value='0', store=ext.SimpleStore(data=[['0','按日统计'],['1','按月统计'],['2','按年统计']]), width=80, allowBlank=False)\n\ncontrol['month_begin'] = {'location':'tbar2'}\ncontrol['month_begin']['quick_query'] = True\ncontrol['month_begin']['ctrl'] = ext.DateField(name='month_begin', value=time.strftime('%Y-%m-01'), allowBlank=False)\n\ncontrol['month_end'] = {'location':'tbar3'}\ncontrol['month_end']['quick_query'] = True\ncontrol['month_end']['ctrl'] = ext.DateField(name='month_end', value=time.strftime('%Y-%m-%d'), allowBlank=False)\n\ngrid.DataGrid(dbconn(app_config.dbconn.cc_db), sql, dm, remote_sort=False, limit=1000, control=control, title='日数据统计')\n","sub_path":"ccrc/cc_statistics.py","file_name":"cc_statistics.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"22636938","text":"from starlette.applications import Starlette\nfrom starlette.responses import JSONResponse\nfrom starlette.routing import Router, Mount\nfrom starlette.staticfiles import StaticFiles\nfrom binascii import a2b_base64\nimport requests\nimport os\nimport uvicorn\n\napp = Router(routes=[\n Mount('/static', app=StaticFiles(directory='static')),\n])\n@app.route('/')\nasync def homepage(request):\n return JSONResponse({'hello': 'world'})\n\n\n@app.route('/face', methods=[\"GET\",\"POST\"])\nasync def face(request):\n body = await request.form()\n binary_data = a2b_base64(body['imgBase64'])\n fd = open('image.png', 'wb')\n fd.write(binary_data)\n fd.close()\n params = {\n 'returnFaceId': 'true',\n 'returnFaceLandmarks': 'false',\n 'returnFaceAttributes': 'emotion'\n }\n headers = {'Ocp-Apim-Subscription-Key': os.environ['MSKEY'], \"Content-Type\": \"application/octet-stream\" }\n response = requests.post(\"https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect\", params=params, headers=headers, data=binary_data)\n response.raise_for_status()\n analysis = response.json()\n \n return JSONResponse(analysis)\n\n\n\nif __name__ == '__main__':\n uvicorn.run(app, host='0.0.0.0', port=8000)","sub_path":"face/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"436135970","text":"from data_inputs import load_data\n\ndata = load_data(1)\n\nmasses = [int(i) for i in data]\n\n# Part 1\n\ndef calc_fuel(mass):\n return mass//3 - 2\n\nprint(sum(calc_fuel(m) for m in masses))\n\n\n# Part 2\n\ndef calc_fuel_recursive(mass):\n fuel = mass//3 - 2\n total = 0\n while fuel > 0:\n total += fuel\n fuel = fuel//3 - 2\n return total\n\nprint(sum(calc_fuel_recursive(m) for m in masses))\n\n\n####### END OF SOLUTION ###########\n\n# one-liner\ndef alternate_part1(masses):\n return sum(m//3-2 for m in masses)\nassert alternate_part1(masses)==3278434\n\n# could have just done one pass\ndef alternate_part2(masses):\n total = 0\n for i in masses:\n while i > 5:\n i = i//3 -2\n total += i\n return total\nassert alternate_part2(masses)==4914785\n\n\n","sub_path":"aoc01.py","file_name":"aoc01.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"624713926","text":"# -*- coding: utf-8 -*-\n# @Author: Puffrora\n# @Date: 2019-09-23 10:22:53\n# @Last Modified by: Puffrora\n# @Last Modified time: 2019-09-23 10:33:56\n\n\nclass Solution:\n\tdef search(self, nums, target):\n\t\tif nums == []:\n\t\t\treturn False\n\t\tstart, end = 0, len(nums)-1\n\t\twhile start <= end:\n\t\t\tmid = start + (end - start) // 2\n\t\t\tif nums[mid] == target:\n\t\t\t\treturn True\n\t\t\tif nums[mid] == nums[start]:\n\t\t\t\tstart += 1\n\t\t\t\tcontinue\n\t\t\t# 前半部分有序\n\t\t\tif nums[start] < nums[mid]:\n\t\t\t\t# 在前半部分\n\t\t\t\tif nums[mid] > target and target >= nums[start]:\n\t\t\t\t\tend = mid - 1\n\t\t\t\t# 在后半部分\n\t\t\t\telse:\n\t\t\t\t\tstart = mid + 1\n\t\t\t# 后半部分有序\n\t\t\telse:\n\t\t\t\t# 在后半部分\n\t\t\t\tif nums[mid] < target and target <= nums[end]:\n\t\t\t\t\tstart = mid + 1\n\t\t\t\t# 在前半部分\n\t\t\t\telse:\n\t\t\t\t\tend = mid - 1\n\t\treturn False\n\n\t\t","sub_path":"Leetcode/leetcode81 搜索旋转排序数组II.py","file_name":"leetcode81 搜索旋转排序数组II.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"102099261","text":"import pandas as pd, numpy as np\nimport statsmodels.api as sm\nimport cvxpy\nfrom sympy import *\nfrom statsmodels.tools.tools import add_constant\nfrom sympy.interactive.printing import init_printing\ninit_printing(use_unicode=False, wrap_line=False, no_global=True)\n\nglobal lambdStart\n\ndef calc(dCoeff, MC, totalR, per):\n \n q1, q2, q3, q4, q5, q6 = [[None]*per for i in range(6)]\n Q = MatrixSymbol('Q',6,per)\n t=[i + 1 for i in range(per)]\n ir = 0.1\n dCoeff = MatrixSymbol('c',2,2)\n dCoeff.values = Matrix([[99.88902098027,-0.00200352325186403],\n [109.081051916772,-0.00191130813045922]])\n totalR = [52800, 20240, 16280, 14520, 13200, 19360]\n P = [None]*per\n\n MC = [9,10,16,13,5,20]\n\n for t in range (per):\n q1[t] = Symbol('q_saud,{t}'.format(t=t))\n q2[t] = Symbol('q_iran,{t}'.format(t=t))\n q3[t] = Symbol('q_iraq,{t}'.format(t=t))\n q4[t] = Symbol('q_kuw,{t}'.format(t=t))\n q5[t] = Symbol('q_uae,{t}'.format(t=t))\n q6[t] = Symbol('q_ven,{t}'.format(t=t))\n\n\n P = MatrixSymbol(\"P\".format(t=t), per, 1)\n\n Q.values = Matrix([q1,q2,q3,q4,q5,q6])\n \n \n P.values = Matrix([dCoeff[int(t & 1 != 1),0] + dCoeff[int(t & 1 != 1),1]*sum(\n Q.values[:,t-1]) for t in range(1,per + 1)])\n\n def obj(qi, P, Q, MC, ir):\n add = []\n for i in range(P.shape[0] -1):\n temp = (P.values[i]*qi[i] - MC*qi[i])/(1+ir)**(i+1)\n add.append(temp)\n add.append(qi[-1]*(100-MC)/(1+ir)**(P.shape[0]))\n return [sum(add), qi]\n\n def lagrange(obj, constr,lambdStart):\n lambd = [None]*len(constr)\n constEq = [None]*len(constr)\n\n for i in range(len(constr)):\n lambd[i] = Symbol('lambda_{i}'.format(i=lambdStart))\n constEq[i] = lambd[i]*constr[i]\n lambdStart = lambdStart + 1\n endog = obj[1].tolist()[0]\n endog.extend(lambd)\n return [obj[0] + sum([x for x in constEq]), endog]\n\n eqList =[]\n lambdList = []\n for i in range(6):\n temp = lagrange(obj(Q.values[i,:], P, Q, MC[i], 0.1),\n [totalR[i] - sum(Q.values[i,:])], i)\n eqList.extend([diff(temp[0], var)\n .expand() for var in temp[1]])\n lambdList.append(temp[1][-1])\n\n varList =[]\n for i in range(6):\n varList.extend(Q.values.tolist()[i])\n\n for i in range(len(eqList)):\n for key1, coeff in enumerate(dCoeff):\n eqList[i] = eqList[i] .subs({coeff: dCoeff.values[key1]})\n\n varList.extend(lambdList)\n L = linear_eq_to_matrix(eqList, varList )\n\n n = len(L[0])\n sqn = int(np.sqrt(n))\n\n A = np.array([[None]*sqn]*sqn)\n\n\n\n for i in range(sqn):\n A[i, :]=[L[0][i*sqn + j] for j in range(sqn)]\n\n\n b = np.array(L[1]).astype('float')\n\n ans = np.linalg.solve(A.astype('float'),b)\n \n return ans[:6*per].reshape((6,per))\n\n","sub_path":"Economics/mysolver.py","file_name":"mysolver.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"129337035","text":"import requests\n\n# User definitions\nryant = \"ryan.taylor\"\nryanl = \"ryanl\"\nceci = \"cecilia.brookhier\"\nleigh = \"leighmathews\"\npeter = \"peter.king\"\njason = \"jason.mayes\"\noffice = \"channel\"\ntravie = \"travie\"\nghost = \"a secret admirer\"\nlab = \"Launchpad (the lab)\"\nAPI_KEY = \"YOUR_API_KEY\"\n\n\ndef alert_front_door():\n requests.post('https://maker.ifttt.com/trigger/front_door_buzzer/with/key/API_KEY') \n\ndef alert_room(name, summoner):\n payload = {}\n payload[\"value1\"] = \"@\" + name\n if summoner is None:\n payload[\"value2\"] = ghost\n else:\n payload[\"value2\"] = summoner\n \n requests.post('https://maker.ifttt.com/trigger/notify_user/with/key/API_KEY', data=payload)\n\n\n","sub_path":"Dash/notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"426394924","text":"from __future__ import division\nfrom __future__ import print_function\nimport numpy as np\nfrom quantize import vq, kmeans2\n\n\nclass PQ(object):\n def __init__(self, M, Ks=256, verbose=True, mahalanobis_matrix=None):\n assert 0 < Ks <= 2 ** 32\n self.M, self.Ks, self.verbose, self.mahalanobis_matrix = M, Ks, verbose, mahalanobis_matrix\n self.code_dtype = np.uint8 if Ks <= 2 ** 8 else (np.uint16 if Ks <= 2 ** 16 else np.uint32)\n self.codewords = None\n self.Ds = None\n\n def fit(self, vecs, iter=20, seed=123):\n assert vecs.dtype == np.float32\n assert vecs.ndim == 2\n N, D = vecs.shape\n assert self.Ks < N, \"the number of training vector should be more than Ks\"\n assert D % self.M == 0, \"input dimension must be dividable by M\"\n self.Ds = int(D / self.M)\n\n np.random.seed(seed)\n\n # [m][ks][ds]: m-th subspace, ks-the codeword, ds-th dim\n self.codewords = np.zeros((self.M, self.Ks, self.Ds), dtype=np.float32)\n for m in range(self.M):\n if self.verbose:\n print(\" Training the subspace: {} / {}\".format(m, self.M))\n vecs_sub = vecs[:, m * self.Ds : (m+1) * self.Ds]\n self.codewords[m], _ = kmeans2(vecs_sub, self.Ks, iter=iter, minit='points', matrix=self.mahalanobis_matrix)\n\n return self\n\n def encode(self, vecs):\n assert vecs.dtype == np.float32\n assert vecs.ndim == 2\n N, D = vecs.shape\n assert D == self.Ds * self.M, \"input dimension must be Ds * M\"\n\n # codes[n][m] : code of n-th vec, m-th subspace\n codes = np.empty((N, self.M), dtype=self.code_dtype)\n for m in range(self.M):\n vecs_sub = vecs[:, m * self.Ds : (m+1) * self.Ds]\n codes[:, m], _ = vq(vecs_sub, self.codewords[m], matrix=self.mahalanobis_matrix)\n\n return codes\n\n def decode(self, codes):\n assert codes.ndim == 2\n N, M = codes.shape\n assert M == self.M\n assert codes.dtype == self.code_dtype\n\n vecs = np.empty((N, self.Ds * self.M), dtype=np.float32)\n for m in range(self.M):\n vecs[:, m * self.Ds:(m+1) * self.Ds] = self.codewords[m][codes[:, m], :]\n\n return vecs\n\n def compress(self, vecs):\n return self.decode(self.encode(vecs))\n","sub_path":"pq.py","file_name":"pq.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"180801621","text":"import pandas as pd\nimport numpy as np\n\ndef prefilter_items(data, take_n_popular=5000, item_features=None):\n # Уберем самые популярные товары (их и так купят)\n popularity = data.groupby('item_id')['user_id'].nunique().reset_index() / data['user_id'].nunique()\n popularity.rename(columns={'user_id': 'share_unique_users'}, inplace=True)\n\n top_popular = popularity[popularity['share_unique_users'] > 0.2].item_id.tolist()\n data = data[~data['item_id'].isin(top_popular)]\n\n # Уберем самые НЕ популярные товары (их и так НЕ купят)\n top_notpopular = popularity[popularity['share_unique_users'] < 0.02].item_id.tolist()\n data = data[~data['item_id'].isin(top_notpopular)]\n\n # Уберем не интересные для рекоммендаций категории (department)\n if item_features is not None:\n department_size = pd.DataFrame(item_features.\\\n groupby('department')['item_id'].nunique().\\\n sort_values(ascending=False)).reset_index()\n\n department_size.columns = ['department', 'n_items']\n rare_departments = department_size[department_size['n_items'] < 150].department.tolist()\n items_in_rare_departments = item_features[item_features['department'].isin(rare_departments)].item_id.unique().tolist()\n\n data = data[~data['item_id'].isin(items_in_rare_departments)]\n\n\n # Уберем слишком дешевые товары (на них не заработаем). 1 покупка из рассылок стоит 60 руб.\n data['price'] = data['sales_value'] / (np.maximum(data['quantity'], 1))\n data = data[data['price'] > 1]\n\n # Уберем слишком дорогие товарыs\n data = data[data['price'] < 30]\n\n\t# Уберем товары, которые не продавались за последние 12 месяцев\n data = data[data['week_no'] >= data['week_no'].max() - 52]\n\t\n # Возбмем топ по популярности\n popularity = data.groupby('item_id')['quantity'].sum().reset_index()\n popularity.rename(columns={'quantity': 'n_sold'}, inplace=True)\n\n top = popularity.sort_values('n_sold', ascending=False).head(take_n_popular).item_id.tolist()\n \n # Заведем фиктивный item_id (если юзер покупал товары из топ-5000, то он \"купил\" такой товар)\n data.loc[~data['item_id'].isin(top), 'item_id'] = 999999\n \n # ...\n\n return data\n\ndef get_targets_sec_level(data, train, recommender, N):\n \"\"\"Подготовка обучающего датасета, разбиение на X и y\"\"\"\n\n users_lvl_2 = pd.DataFrame(data['user_id'].unique())\n\n users_lvl_2.columns = ['user_id']\n\n train_users = train['user_id'].unique()\n users_lvl_2 = users_lvl_2[users_lvl_2['user_id'].isin(train_users)]\n\n # Рекомендации на основе собственных покупок\n users_lvl_2_ = users_lvl_2.copy()\n users_lvl_2['candidates'] = users_lvl_2['user_id'].apply(\n lambda x: recommender.get_own_recommendations(x, N=N)\n )\n\n s = users_lvl_2.apply(\n lambda x: pd.Series(x['candidates']), axis=1\n ).stack().reset_index(level=1, drop=True)\n\n s.name = 'item_id'\n\n users_lvl_2 = users_lvl_2.drop('candidates', axis=1).join(s)\n\n users_lvl_2['flag'] = 1\n\n targets_lvl_2 = data[['user_id', 'item_id']].copy()\n targets_lvl_2.head(2)\n\n targets_lvl_2['target'] = 1 \n\n targets_lvl_2 = users_lvl_2.merge(targets_lvl_2, on=['user_id', 'item_id'], how='left')\n\n targets_lvl_2['target'].fillna(0, inplace=True)\n targets_lvl_2.drop('flag', axis=1, inplace=True)\n\n return targets_lvl_2\n\t\ndef extend_new_user_features(data, user_features, users_emb_df):\n \"\"\"Новые признаки для пользователей\"\"\"\n\t\n data['price']=data['sales_value']/data['quantity']\n new_user_features = user_features.merge(data, on='user_id', how='left')\n\n\n # Эмбеддинги\n user_features = user_features.merge(users_emb_df, how='left')\n\n\n # Standart sale time\n time = new_user_features.groupby('user_id')['trans_time'].mean().reset_index()\n time.rename(columns={'trans_time': 'mean_time'}, inplace=True)\n time = time.astype(np.float32)\n user_features = user_features.merge(time, how='left')\n\n\n # Age\n user_features['age'] = user_features['age_desc'].replace(\n {'65+': 70, '45-54': 50, '25-34': 30, '35-44': 40, '19-24':20, '55-64':60}\n )\n user_features = user_features.drop('age_desc', axis=1)\n\n\n # Income\n user_features['income'] = user_features['income_desc'].replace(\n {'35-49K': 45,\n '50-74K': 70,\n '25-34K': 30,\n '75-99K': 95,\n 'Under 15K': 15,\n '100-124K': 120,\n '15-24K': 20,\n '125-149K': 145,\n '150-174K': 170,\n '250K+': 250,\n '175-199K': 195,\n '200-249K': 245}\n )\n user_features = user_features.drop('income_desc', axis=1)\n\n\n # Children \n user_features['children'] = 0\n user_features.loc[(user_features['kid_category_desc'] == '1'), 'children'] = 1\n user_features.loc[(user_features['kid_category_desc'] == '2'), 'children'] = 2\n user_features.loc[(user_features['kid_category_desc'] == '3'), 'children'] = 3\n user_features = user_features.drop('kid_category_desc', axis=1)\n\n\n # Средний чек, средний чек в неделю\n basket = new_user_features.groupby(['user_id'])['price'].sum().reset_index()\n\n baskets = new_user_features.groupby('user_id')['basket_id'].count().reset_index()\n baskets.rename(columns={'basket_id': 'baskets'}, inplace=True)\n\n avr_bask = basket.merge(baskets)\n\n avr_bask['avr_bask'] = avr_bask.price / avr_bask.baskets\n avr_bask['sum_per_week'] = avr_bask.price / new_user_features.week_no.nunique()\n\n avr_bask = avr_bask.drop(['price', 'baskets'], axis=1)\n user_features = user_features.merge(avr_bask, how='left')\n\n return user_features\t\n\t\ndef extend_new_item_features(data, item_features, items_emb_df):\n \"\"\"Новые признаки для продуктов\"\"\"\n new_features = item_features.merge(data, on='item_id', how='left')\n\n # Эмбеддинги\n item_features = item_features.merge(items_emb_df, how='left')\n\n # manufacturer\n rare_manufacturer = item_features.manufacturer.value_counts()[item_features.manufacturer.value_counts() < 50].index\n item_features.loc[item_features.manufacturer.isin(rare_manufacturer), 'manufacturer'] = 999999999\n item_features.manufacturer = item_features.manufacturer.astype('object')\n\n # discount\n mean_disc = new_features.groupby('item_id')['coupon_disc'].mean().reset_index().sort_values('coupon_disc')\n item_features = item_features.merge(mean_disc, on='item_id', how='left') \n\n # Среднее количество продаж товара в категории в неделю\n items_in_department = new_features.groupby('department')['item_id'].count().reset_index().sort_values(\n 'item_id', ascending=False\n )\n items_in_department.rename(columns={'item_id': 'items_in_department'}, inplace=True)\n\n sales_count_per_dep = new_features.groupby(['department'])['quantity'].count().reset_index().sort_values(\n 'quantity', ascending=False\n )\n sales_count_per_dep.rename(columns={'quantity': 'sales_count_per_dep'}, inplace=True)\n\n items_in_department = items_in_department.merge(sales_count_per_dep, on='department')\n items_in_department['qnt_of_sales_per_item_per_dep_per_week'] = (\n items_in_department['sales_count_per_dep'] /\n items_in_department['items_in_department'] /\n new_features['week_no'].nunique()\n )\n items_in_department = items_in_department.drop(['items_in_department'], axis=1)\n item_features = item_features.merge(items_in_department, on=['department'], how='left')\n\n\t# Количество продаж и среднее количество продаж товара\n item_qnt = new_features.groupby(['item_id'])['quantity'].count().reset_index()\n item_qnt.rename(columns={'quantity': 'quantity_of_sales'}, inplace=True)\n\n item_qnt['sales_count_per_week'] = item_qnt['quantity_of_sales'] / new_features['week_no'].nunique()\n item_features = item_features.merge(item_qnt, on='item_id', how='left')\n\n # sub_commodity_desc\n items_in_department = new_features.groupby('sub_commodity_desc')['item_id'].count().reset_index().sort_values(\n 'item_id', ascending=False\n )\n items_in_department.rename(columns={'item_id': 'items_in_sub_commodity_desc'}, inplace=True)\n\n sales_count_per_dep = new_features.groupby(['sub_commodity_desc'])[\n 'quantity'].count().reset_index().sort_values(\n 'quantity', ascending=False\n )\n sales_count_per_dep.rename(columns={'quantity': 'qnt_of_sales_per_sub_commodity_desc'}, inplace=True)\n\n items_in_department = items_in_department.merge(sales_count_per_dep, on='sub_commodity_desc')\n items_in_department['qnt_of_sales_per_item_per_sub_commodity_desc_per_week'] = (\n items_in_department['qnt_of_sales_per_sub_commodity_desc'] /\n items_in_department['items_in_sub_commodity_desc'] /\n new_features['week_no'].nunique()\n )\n items_in_department = items_in_department.drop(['items_in_sub_commodity_desc'], axis=1)\n item_features = item_features.merge(items_in_department, on=['sub_commodity_desc'], how='left')\n\n return item_features\t\n\ndef extend_user_item_new_features(data, train, recommender, item_features, user_features, items_emb_df, users_emb_df, N=50):\n\n target = get_targets_sec_level(data, train, recommender, N)\n user_features = extend_new_user_features(data, user_features, users_emb_df)\n item_features = extend_new_item_features(data, item_features, items_emb_df)\n item_features = data.merge(item_features, on='item_id', how='left')\n\n new_data = item_features.merge(user_features, on='user_id', how='left')\n\n # коэффициент количества покупок товаров в данной категории к среднему количеству покупок\n count_perch = new_data.groupby(['user_id', 'commodity_desc', 'week_no']).agg({'quantity': 'mean'}) \\\n .reset_index().rename(columns={'quantity': 'count_purchases_week_dep'})\n\n mean_count_perch = new_data.groupby(['commodity_desc', 'week_no']).agg({'quantity': 'sum'}) \\\n .reset_index().rename(columns=({'quantity': 'mean_count_purchases_week_dep'}))\n\n coef = count_perch.merge(mean_count_perch, on=['commodity_desc', 'week_no'], how='left')\n coef['count_purchases_week_mean'] = coef['count_purchases_week_dep'] / coef['mean_count_purchases_week_dep']\n coef = coef[['user_id', 'commodity_desc', 'count_purchases_week_mean']]\n\n temp = coef.groupby(['user_id', 'commodity_desc']).agg({'count_purchases_week_mean': 'mean'}) \\\n .reset_index()\n\n new_data = new_data.merge(temp, on=['user_id', 'commodity_desc'], how='left')\n\n \"\"\"коэффициент отношения суммы покупок товаров в данной категории к средней сумме\"\"\"\n count_perch = new_data.groupby(['user_id', 'commodity_desc', 'week_no']).agg({'price': 'sum'}) \\\n .reset_index().rename(columns={'price': 'price_week'})\n\n mean_count_perch = new_data.groupby(['commodity_desc', 'week_no']).agg({'price': 'sum'}) \\\n .reset_index().rename(columns=({'price': 'mean_price_week'}))\n\n coef = count_perch.merge(mean_count_perch, on=['commodity_desc', 'week_no'], how='left')\n coef['sum_purchases_week_mean'] = coef['price_week'] / coef['mean_price_week']\n coef = coef[['user_id', 'commodity_desc', 'sum_purchases_week_mean']]\n\n temp = coef.groupby(['user_id', 'commodity_desc']).agg({'sum_purchases_week_mean': 'mean'}) \\\n .reset_index()\n\n new_data = new_data.merge(temp, on=['user_id', 'commodity_desc'], how='left')\n\n new_data = new_data.merge(target, on=['item_id', 'user_id'], how='left')\n new_data = new_data.fillna(0)\n\n return new_data\n\t\ndef get_important_features(model, X_train, y_train):\n \"\"\"Возвращает важные фичи\"\"\"\n\t\n model.fit(X_train, y_train)\n feature = list(zip(X_train.columns.tolist(), model.feature_importances_))\n feature = pd.DataFrame(feature, columns=['feature', 'value'])\n features = feature.loc[feature.value > 0, 'feature'].tolist()\n return features\n\t\ndef get_popularity_recommendations(data, n=5):\n \"\"\"Топ-n популярных товаров\"\"\"\n\n popular = data.groupby('item_id')['quantity'].count().reset_index()\n popular.sort_values('quantity', ascending=False, inplace=True)\n popular = popular[popular['item_id'] != 999999]\n recs = popular.head(n).item_id\n return recs.tolist()\n\ndef filter_by_diff_cat(list_recommendations, item_info):\n \"\"\"Получение списка товаров из уникальных категорий\"\"\"\n\t\n final_recommendations = []\n\n categories_used = []\n\n for item in list_recommendations:\n category = item_info.loc[item_info['item_id'] == item, 'sub_commodity_desc'].values[0]\n\n if category not in categories_used:\n final_recommendations.append(item)\n categories_used.append(category)\n\n return final_recommendations\n\n\ndef postfilter_items(row, item_info, train_1, price, list_pop_rec, N=5):\n \"\"\"Пост-фильтрация товаров\n Input\n -----\n row: строка датасета\n item_info: pd.DataFrame\n Датафрейм с информацией о товарах\n train_1: pd.DataFrame\n обучающий датафрейм\n \"\"\"\n recommend = row['recomendations']\n purchased_goods = train_1.loc[train_1['user_id'] == row['user_id']]['item_id'].unique()\n\n if recommend == 0:\n recommend = list_pop_rec\n\n # Unique\n unique_recommendations = []\n [unique_recommendations.append(item) for item in recommend if item not in unique_recommendations]\n\n # More then 1$\n price_recommendations = []\n [price_recommendations.append(item) for item in unique_recommendations if price \\\n .loc[price['item_id'] == item]['price'].values > 1]\n\n # 1 товар > 7 $\n expensive_items = []\n [expensive_items.append(item) for item in price_recommendations if price. \\\n loc[price['item_id'] == item]['price'].values > 7]\n\n if len(expensive_items) ==0:\n [expensive_items.append(item) for item in list_pop_rec if price. \\\n loc[price['item_id'] == item]['price'].values > 7]\n\n # товар который юзер не покупал\n new_items = []\n [new_items.append(item) for item in price_recommendations if item not in purchased_goods]\n\n # Промежуточный итог\n rec = []\n rec.append(expensive_items[0] if len(expensive_items) > 0 else list_pop_rec[0])\n rec += new_items\n rec = filter_by_diff_cat(rec, item_info=item_info)[0:3]\n rec += price_recommendations\n final_recommendations = filter_by_diff_cat(rec, item_info=item_info)\n\n n_rec = len(final_recommendations)\n if n_rec < N:\n final_recommendations.extend(list_pop_rec[:N - n_rec])\n else:\n final_recommendations = final_recommendations[:N]\n\n assert len(final_recommendations) == N, 'Количество рекомендаций != {}'.format(N)\n\t\n return final_recommendations\n\ndef get_final_recomendations(X_test, test_preds_proba, val_2, train_1, item_features):\n \"\"\"Финальный список рекомендованных товаров\"\"\"\n\t\n X_test['predict_proba'] = test_preds_proba\n\n X_test.sort_values(['user_id', 'predict_proba'], ascending=False, inplace=True)\n recs = X_test.groupby('user_id')['item_id']\n recomendations = []\n for user, preds in recs:\n recomendations.append({'user_id': user, 'recomendations': preds.tolist()})\n\n recomendations = pd.DataFrame(recomendations)\n\n result_2 = val_2.groupby('user_id')['item_id'].unique().reset_index()\n result_2.columns = ['user_id', 'actual']\n\n result = result_2.merge(recomendations, how='left')\n result['recomendations'] = result['recomendations'].fillna(0)\n\n price = train_1.groupby('item_id')['price'].mean().reset_index()\n\n pop_rec = get_popularity_recommendations(train_1, n=500)\n list_pop_rec = []\n [list_pop_rec.append(item) for item in pop_rec if price \\\n .loc[price['item_id'] == item]['price'].values > 1]\n\n result['recomendations'] = result.progress_apply \\\n (lambda x: postfilter_items(x, item_info=item_features, train_1=train_1, price=price, list_pop_rec=list_pop_rec, N=5), axis=1)\n\n return result\n","sub_path":"final/src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"582625856","text":"from common import getLogging\nimport ConfigParser\n\nlog = getLogging()\nconfig = ConfigParser.ConfigParser()\nconfig.read(\"etc/credentials.ini\")\n\nclass BrokerAbstract(object):\n def getPrice(self):\n raise Exception(\"implement the method\")\n\n def getBook(self):\n raise Exception(\"implement the method\")\n\n def sell(self, qty, price):\n raise Exception(\"implement the method\")\n\n def buy(self, qty, price):\n raise Exception(\"implement the method\")\n\n def getBalance(self):\n raise Exception(\"implement the method\")\n\n def compare(self, broker, qty):\n# delta = abs(self.getPrice() - broker.getPrice())/min([self.getPrice(),broker.getPrice()])\n if self.getPriceBuyNow(qty) < broker.getPriceSellNow(qty):\n priceBuy = self.getPriceBuyNow(qty)\n priceSell = broker.getPriceSellNow(qty)\n buy = self.CODE\n sell = broker.CODE\n elif broker.getPriceBuyNow(qty) < self.getPriceSellNow(qty):\n priceBuy = broker.getPriceBuyNow(qty)\n priceSell = self.getPriceSellNow(qty)\n buy = broker.CODE\n sell = self.CODE\n else:\n log.info(\"BROKER A - PRECO DE COMPRA: %s\" % self.getPriceBuyNow(qty))\n log.info(\"BROKER B - PRECO DE VENDA: %s\" % broker.getPriceSellNow(qty))\n log.info(\"BROKER B - PRECO DE COMPRA: %s\" % broker.getPriceBuyNow(qty))\n log.info(\"BROKER A - PRECO DE VENDA: %s\" % self.getPriceSellNow(qty))\n return False\n\n real_delta = (priceSell - priceBuy)/priceBuy\n\n return {\n# 'delta': delta,\n 'real_delta': real_delta,\n# 'delta_perc': \"%.2f%%\" % (delta*100),\n 'real_delta_perc': \"%.2f%%\" % (real_delta*100),\n \"buy\": buy,\n \"sell\": sell,\n 'buy_per': priceBuy,\n 'sell_per': priceSell,\n }\n\n def getPriceBuyNow(self, qty):\n orderbook = self.getBook()\n price = 0\n for order in orderbook['sell']:\n price = order[0]\n qty = qty-order[1]\n if qty <= 0:\n break\n return price\n\n def getPriceSellNow(self, qty):\n orderbook = self.getBook()\n price = 0\n for order in orderbook['buy']:\n price = order[0]\n qty = qty-order[1]\n if qty <= 0:\n break\n return price\n\n def initialize(self):\n self.price = None\n self.orderbook = None\n\n def getSecret(self):\n return config.get(self.CODE,'secret')\n\n def getKey(self):\n return config.get(self.CODE,'key')\n\n def getSummarize(self):\n balance = self.getBalance()\n btc_qty = balance['total'] - balance['reais']\n log.info(\"%s --- BTC: R$%.2f (%.2f%%) - Reais: R$%.2f (%.2f%%) - Total: R$%.2f\" % (self.CODE, btc_qty, 100*(btc_qty/balance['total']), balance['reais'], 100*(balance['reais']/balance['total']), balance['total']))\n","sub_path":"broker/abstract.py","file_name":"abstract.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"549077923","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\n# Example of a double ended singly linked list in Python.\r\n\r\nimport random\r\n\r\n\r\nclass List:\r\n class _Node:\r\n def __init__(self, data):\r\n self.data = data\r\n self.next = None\r\n\r\n class Iterator:\r\n def __init__(self, node):\r\n self._node = node\r\n\r\n def __iter__(self):\r\n return self\r\n\r\n def __next__(self):\r\n if self._node is None:\r\n raise StopIteration\r\n data = self._node.data\r\n self._node = self._node.next\r\n return data\r\n\r\n def __init__(self, items=None):\r\n self._head = self._tail = None\r\n self._length = 0\r\n if items:\r\n self += items\r\n\r\n def __iadd__(self, other):\r\n for item in other:\r\n self.append(item)\r\n return self\r\n\r\n def __iter__(self):\r\n return List.Iterator(self._head)\r\n\r\n def __len__(self):\r\n return self._length\r\n\r\n def __repr__(self):\r\n return '[' + ', '.join(repr(item) for item in self) + ']'\r\n\r\n def front(self):\r\n return self._head.data\r\n\r\n def back(self):\r\n return self._tail.data\r\n\r\n def append(self, data):\r\n node = self._Node(data)\r\n if self._head:\r\n self._tail.next = node\r\n else:\r\n self._head = node\r\n self._tail = node\r\n self._length += 1\r\n\r\n def pop(self):\r\n data = self._head.data\r\n self._head = self._head.next\r\n if not self._head:\r\n self._tail = None\r\n self._length -= 1\r\n return data\r\n\r\n def reverse(self):\r\n prev, curr = None, self._head\r\n while curr:\r\n nxt = curr.next\r\n curr.next = prev\r\n prev, curr = curr, nxt\r\n self._head, self._tail = self._tail, self._head\r\n\r\n\r\nif __name__ == '__main__':\r\n lst = List(random.randrange(0, 51) for _ in range(20))\r\n\r\n print('Length =', len(lst))\r\n print('Head =', lst.front())\r\n print('Tail =', lst.back())\r\n print('Min =', min(lst))\r\n print('Max =', max(lst))\r\n\r\n s = sum(lst)\r\n print('Sum =', s)\r\n print('Average =', s // len(lst))\r\n print('Contains ', 0, ': ', 0 in lst, sep='')\r\n\r\n print(lst)\r\n\r\n lst.reverse()\r\n print(lst)\r\n\r\n while lst:\r\n print(lst.pop(), end=' ')\r\n","sub_path":"ctci/python/ch2_linked_lists/ex_singly_linked_list.py","file_name":"ex_singly_linked_list.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"198483948","text":"import os\nfrom pyln.testing.fixtures import * # noqa: F401,F403\n\nplugin_path = os.path.join(os.path.dirname(__file__), \"donations.py\")\n\n\ndef test_donation_starts(node_factory):\n l1 = node_factory.get_node()\n # Test dynamically\n l1.rpc.plugin_start(plugin_path)\n l1.rpc.plugin_stop(plugin_path)\n l1.rpc.plugin_start(plugin_path)\n l1.stop()\n # Then statically\n l1.daemon.opts[\"plugin\"] = plugin_path\n l1.start()\n\n\ndef test_donation_server(node_factory):\n pluginopt = {'plugin': plugin_path}\n l1, l2 = node_factory.line_graph(2, opts=pluginopt)\n l1.rpc.donationserver()\n l1.daemon.wait_for_logs('plugin-donations.py: Process server on port 8088')\n msg = l1.rpc.donationserver(\"stop\")\n assert msg.startswith(f'stopped server on port 8088')\n","sub_path":"donations/test_donations.py","file_name":"test_donations.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"458580214","text":"n = int(input())\n\nnotas = [int(i) for i in input().split()]\n\nm = [0 for x in range(101)]\n\nfor i in notas:\n m[i]+=1\n \npos=0\nmaior=0\n\nfor i in range(101):\n if maior <= m[i]:\n maior = m[i]\n pos = i\n \nprint(pos)\n","sub_path":"2469.py","file_name":"2469.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"57184212","text":"# 网路编程 TCP\nimport socket\n\n#AF_INET指定使用IPv4协议,如果要用更先进的IPv6,就指定为AF_INET6\n#SOCK_STREAM指定使用面向流的TCP协议\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# 80端口是Web服务的标准端口\ns.connect(('www.sina.com.cn', 80))\n\ns.send(b'GET / HTTP/1.1\\r\\nHost: www.sina.com.cn\\r\\nConnection: close\\r\\n\\r\\n')\n\nbuffer = []\nwhile True:\n\td = s.recv(1024)\n\tif d: #直到recv()返回空数据,表示接收完毕\n\t\tbuffer.append(d)\n\telse:\n\t\tbreak\ndata = b''.join(buffer)\n\ns.close()\n\n#处理结果\nhead, html = data.split(b'\\r\\n\\r\\n', 1)\nprint(head.decode('utf-8'))\nwith open('sina.html', 'wb') as f:\n\tpass\n\t# f.write(html)\n\n\n# 服务器\n# 一个Socket依赖4项:服务器地址、服务器端口、客户端地址、客户端端口来唯一确定一个Socket\nsService = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsService.bind(('127.0.0.1', 9999)) #绑定监听地址和端口, 127这个是本机地址\nsService.listen(5) #5指最大连接数\nprint('wating for you /....')\n\ndef tcplink(sock, addr):\n\tprint('accept new connetion, from %s : %s...' % addr)\n\tsock.send(b'Welcome')\n\twhile True:\n\t\tdata = sock.recv(1024)\n\t\ttime.sleep(1)\n\t\tif not data or data.decode('utf-8') == 'exit':\n\t\t\tbreak\n\t\tsock.send(('hello, %s!' % data.decode('utf-8')).encode('utf-8'))\n\tsock.close()\n\tprint('connetion from %s : %s closed' % addr)\n\nwhile True:\n\t\n\tsock, addr = sService.accept()\n\tt = treading.Tread(target=tcplink, args=(sock, addr))\n\tt.start()\n\n\n# 同一个端口,被一个Socket绑定了以后,就不能被别的Socket绑定了","sub_path":"py22.py","file_name":"py22.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"402686148","text":"\"\"\"Bootstrap code for a Python engine. \"\"\"\n\nboot = \"\"\"\\\nfrom onlinelab.service.engine.python.runtime import PythonEngine\nPythonEngine().run(port=%(port)d)\n\"\"\"\n\ndef builder(port):\n \"\"\"Build command-line for running Python engine. \"\"\"\n return [\"python\", \"-c\", boot % {'port': port}]\n\n","sub_path":"onlinelab/service/engine/python/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"516586193","text":"import requests\nimport json\nimport os\nimport csv\nimport sys\nimport uuid\nfrom DACS import stamp2DACS, iso2DACS\nfrom datetime import datetime\n\n#for debugging\ndef pp(output):\n\tprint (json.dumps(output, indent=2))\ndef serializeOutput(filename, output):\n\t__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\tf = open(os.path.join(__location__, filename + \".json\"), \"w\")\n\tf.write(json.dumps(output, indent=2))\n\tf.close\n\t\n#logging\ndef log(logMsg):\n\tprint (logMsg)\n\t__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\tlog = open(os.path.join(__location__, \"webArchives.log\"), \"a\")\n\tlog.write(\"\\n\" + str(datetime.now()) + \" -- \" + logMsg)\n\tlog.close()\ntry:\n\n\t__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n\t#get config from webArchives.ini\n\tif sys.version_info[0] < 3:\n\t\timport ConfigParser\n\t\tconfig = ConfigParser.ConfigParser()\n\telse:\n\t\timport configparser\n\t\tconfig = configparser.ConfigParser()\n\tconfig.read(os.path.join(__location__, \"webArchives.ini\"))\n\tuser = config.get('config_data', 'Username')\n\tpw = config.get('config_data', 'Password')\n\taspaceURL = config.get('config_data', 'Backend_URL')\n\tpaginatedResults = config.get('config_data', 'Paginated_Results')\n\tupdateParentRecords = config.get('config_data', 'Update_Parents')\n\tdateExpressions = config.get('config_data', 'Date_Expressions')\n\twebExtentType = config.get('custom_labels', 'Web_Extents')\n\twebDatesLabel = config.get('custom_labels', 'Web_Dates_Label')\n\tpublishNotes = config.get('custom_labels', 'Publish_Notes')\n\tacqinfoLabel = config.get('custom_labels', 'Archive-It_Acqinfo')\n\tacqinfoLabelIA = config.get('custom_labels', 'InternetArchive_Acqinfo')\n\twarcLabel = config.get('custom_labels', 'WARC_Label')\n\tdaoTitleAIT = config.get('custom_labels', 'ArchiveIT_Object_Title')\n\tdaoTitleIA = config.get('custom_labels', 'InternetArchive_Object_Title')\n\n\t#get acqinfo from webArchivesData.csv\n\tcsv.register_dialect('piper', delimiter='|', quoting=csv.QUOTE_NONE)\n\tcsvFile = open(os.path.join(__location__, \"webArchivesData.csv\"), \"r\")\n\tcsvObject = csv.reader(csvFile, delimiter='|')\n\tcsvData = list(list(csvObject) for csvObject in csv.reader(csvFile, delimiter='|'))\n\tcsvFile.close()\n\n\tdef UpdateWebRecord(webObjectList):\n\t\tfor webObject in webObjectList:\n\t\t\t#serializeOutput(\"object\", webObject)\n\t\t\tobjectID = webObject[\"uri\"].split(\"/archival_objects/\")[1]\n\t\t\tobjectURI = webObject[\"uri\"]\n\t\t\tif \"external_documents\" in webObject:\n\t\t\t\twebInfo = webObject[\"external_documents\"]\n\t\t\t\tcheckStatus = False\n\t\t\t\tcheckURL = False\n\t\t\t\tfor exDoc in webInfo:\n\t\t\t\t\tif exDoc[\"title\"].lower().strip() == \"status\":\n\t\t\t\t\t\twebStatus = exDoc[\"location\"].lower().strip()\n\t\t\t\t\t\tif webStatus == \"inactive\":\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\telif webStatus == \"initial\":\n\t\t\t\t\t\t\tinitialCheck = False\n\t\t\t\t\t\t\tfor date in webObject[\"dates\"]:\n\t\t\t\t\t\t\t\tif date[\"label\"] == webDatesLabel:\n\t\t\t\t\t\t\t\t\tif \"end\" in date:\n\t\t\t\t\t\t\t\t\t\tinitalDate = date[\"end\"]\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tinitalDate = date[\"begin\"]\n\t\t\t\t\t\t\t\t\tinitialCheck = True\n\t\t\t\t\t\t\t\t\tcheckStatus = True\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcheckStatus = True\n\t\t\t\t\t\t\t#serializeOutput(\"object\", webObject)\n\t\t\t\t\tif exDoc[\"title\"].lower().strip() == \"url\":\n\t\t\t\t\t\twebURL = exDoc[\"location\"].lower().strip()\n\t\t\t\t\t\tif not webURL.startswith(\"http\"):\n\t\t\t\t\t\t\twebURL = \"http://\" + webURL\n\t\t\t\t\t\tcheckURL = True\n\t\t\t\t#check for necessary data\n\t\t\t\tif checkStatus == True and checkURL == True:\n\t\t\t\t\tlog(\"\tUpdating record for \" + webObject[\"display_string\"])\n\t\t\t\t\t\t\n\t\t\t\t\t#loop though the CSV file and get list of collections\n\t\t\t\t\trowCount = 0\n\t\t\t\t\tcollectionList = []\n\t\t\t\t\tfor row in csvData:\n\t\t\t\t\t\trowCount = rowCount + 1\t\t\t\n\t\t\t\t\t\tif rowCount == 2:\n\t\t\t\t\t\t\tif row[1].lower() == \"true\":\n\t\t\t\t\t\t\t\tinternetArchive = True\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tinternetArchive = False\n\t\t\t\t\t\t\tif len(row[2]) > 1:\n\t\t\t\t\t\t\t\tacqinfoIA = True\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tacqinfoIA = False\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tint(row[0])\n\t\t\t\t\t\t\tcollectionList.append(row[0])\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\n\t\t\t\t\t#variable to count number of captures:\n\t\t\t\t\tcaptureCountAIT = 0\n\t\t\t\t\tcollectionNumber = \"\"\n\t\t\t\t\tdateType = \"\"\n\t\t\t\t\tdateTypeIA = \"\"\n\t\t\t\t\tinternetArchiveCaptures = False\n\t\t\t\t\tfor aiCollection in collectionList:\n\t\t\t\t\t\trequestURL = \"http://wayback.archive-it.org/\" + aiCollection + \"/timemap/cdx?url=\" + webURL\n\t\t\t\t\t\tresponse = requests.get(requestURL)\n\t\t\t\t\t\tif len(response.text) > 5:\n\t\t\t\t\t\t\tresponseLines = response.text.split(\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfirstPage = responseLines[0]\n\t\t\t\t\t\t\tlastPage = \"\"\n\t\t\t\t\t\t\tcaptureCountCollection = 0\n\t\t\t\t\t\t\tfor textLine in responseLines:\n\t\t\t\t\t\t\t\tif len(textLine) > 5:\n\t\t\t\t\t\t\t\t\tif webStatus == \"initial\" and initialCheck == True:\n\t\t\t\t\t\t\t\t\t\tcheckDisplay, checkNormal = stamp2DACS(textLine.split(\" \")[1])\n\t\t\t\t\t\t\t\t\t\tif checkNormal <= initalDate:\n\t\t\t\t\t\t\t\t\t\t\tcaptureCountCollection = captureCountCollection + 1\n\t\t\t\t\t\t\t\t\t\t\tlastPage = textLine\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tcaptureCountCollection = captureCountCollection + 1\n\t\t\t\t\t\t\t\t\t\tlastPage = textLine\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif len(lastPage) > 0:\n\t\t\t\t\t\t\t\t#get date range of captures\n\t\t\t\t\t\t\t\tfirstDate = firstPage.split(\" \")[1]\n\t\t\t\t\t\t\t\tlastDate = lastPage.split(\" \")[1]\n\t\t\t\t\t\t\t\tif firstDate == lastDate:\n\t\t\t\t\t\t\t\t\t#only one capture\n\t\t\t\t\t\t\t\t\tdateType = \"single\"\n\t\t\t\t\t\t\t\t\t#get DACS and normal dates\n\t\t\t\t\t\t\t\t\tfirstDisplay, firstNormal = stamp2DACS(firstDate)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tdateType = \"inclusive\"\n\t\t\t\t\t\t\t\t\t#get DACS and normal dates\n\t\t\t\t\t\t\t\t\tfirstDisplay, firstNormal = stamp2DACS(firstDate)\n\t\t\t\t\t\t\t\t\tlastDisplay, lastNormal = stamp2DACS(lastDate)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif captureCountCollection > captureCountAIT:\n\t\t\t\t\t\t\t\t\tcaptureCountAIT = captureCountCollection\n\t\t\t\t\t\t\t\t\tcollectionNumber = aiCollection\n\t\t\t\t\t\t\n\t\t\t\t\tcaptureCountIA = 0\n\t\t\t\t\tif internetArchive == True:\n\t\t\t\t\t\trequestIA = \"https://web.archive.org/cdx/search/cdx?url=\" + webURL\n\t\t\t\t\t\tresponseIA = requests.get(requestIA)\n\t\t\t\t\t\tif len(responseIA.text) > 5:\n\t\t\t\t\t\t\tresponseIALines = responseIA.text.split(\"\\n\")\n\t\t\t\t\t\t\tfirstPage = responseIALines[0]\n\t\t\t\t\t\t\tlastPage = \"\"\n\t\t\t\t\t\t\tfor textLine in responseIALines:\n\t\t\t\t\t\t\t\tif len(textLine) > 5:\n\t\t\t\t\t\t\t\t\tif webStatus == \"initial\" and initialCheck == True:\n\t\t\t\t\t\t\t\t\t\tcheckDisplay, checkNormal = stamp2DACS(textLine.split(\" \")[1])\n\t\t\t\t\t\t\t\t\t\tif checkNormal <= initalDate:\n\t\t\t\t\t\t\t\t\t\t\tinternetArchiveCaptures = True\n\t\t\t\t\t\t\t\t\t\t\tcaptureCountIA = captureCountIA + 1\n\t\t\t\t\t\t\t\t\t\t\tlastPage = textLine\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tinternetArchiveCaptures = True\n\t\t\t\t\t\t\t\t\t\tcaptureCountIA = captureCountIA + 1\n\t\t\t\t\t\t\t\t\t\tlastPage = textLine\n\t\t\t\t\t\t\tif internetArchiveCaptures == True:\n\t\t\t\t\t\t\t\tfirstDateIA = firstPage.split(\" \")[1]\n\t\t\t\t\t\t\t\tlastDateIA = lastPage.split(\" \")[1]\n\t\t\t\t\t\t\t\tif firstDateIA == lastDateIA:\n\t\t\t\t\t\t\t\t\tdateTypeIA = \"single\"\n\t\t\t\t\t\t\t\t\tfirstDisplayIA, firstNormalIA = stamp2DACS(firstDateIA)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tdateTypeIA = \"inclusive\"\n\t\t\t\t\t\t\t\t\tfirstDisplayIA, firstNormalIA = stamp2DACS(firstDateIA)\n\t\t\t\t\t\t\t\t\tlastDisplayIA, lastNormalIA = stamp2DACS(lastDateIA)\n\t\t\t\t\tcaptureCountTotal = captureCountAIT + captureCountIA\n\t\t\t\t\t\n\t\t\t\t\t#function to make Acquisition info notes\n\t\t\t\t\tdef makeNote(noteType, webObject, row, label, subnotes):\n\t\t\t\t\t\tif row[1].lower() == \"true\":\n\t\t\t\t\t\t\tnoteExist = False\n\t\t\t\t\t\t\tfor note in webObject[\"notes\"]:\n\t\t\t\t\t\t\t\tif note[\"type\"] == noteType:\n\t\t\t\t\t\t\t\t\tif \"label\" in note:\n\t\t\t\t\t\t\t\t\t\tif note[\"label\"] == label:\n\t\t\t\t\t\t\t\t\t\t\tnoteExist = True\n\t\t\t\t\t\t\t\t\t\t\tif subnotes == True:\n\t\t\t\t\t\t\t\t\t\t\t\tsubnotes = []\n\t\t\t\t\t\t\t\t\t\t\t\tcellCount = 0\n\t\t\t\t\t\t\t\t\t\t\t\tfor cell in row:\n\t\t\t\t\t\t\t\t\t\t\t\t\tcellCount = cellCount + 1\n\t\t\t\t\t\t\t\t\t\t\t\t\tif cellCount > 2:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif len(cell) > 1:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif publishNotes.lower() == \"true\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnewPara = {\"content\": cell, \"publish\": True, \"jsonmodel_type\": \"note_text\"}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnewPara = {\"content\": cell, \"publish\": False, \"jsonmodel_type\": \"note_text\"}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsubnotes.append(newPara)\n\t\t\t\t\t\t\t\t\t\t\t\tnote[\"subnotes\"] = subnotes\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tcellCount = 0\n\t\t\t\t\t\t\t\t\t\t\t\tcontentText = \"\"\n\t\t\t\t\t\t\t\t\t\t\t\tfor cell in row:\n\t\t\t\t\t\t\t\t\t\t\t\t\tcellCount = cellCount + 1\n\t\t\t\t\t\t\t\t\t\t\t\t\tif cellCount > 2:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif len(cell) > 1:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontentText = contentText + \"\\n\\n\" + cell\n\t\t\t\t\t\t\t\t\t\t\t\tnote[\"content\"] = [contentText]\n\t\t\t\t\t\t\t\t\t\t\tif publishNotes.lower() == \"true\":\n\t\t\t\t\t\t\t\t\t\t\t\tnote[\"publish\"] = True\n\t\t\t\t\t\t\tif noteExist == False:\n\t\t\t\t\t\t\t\t#possible uid collision here, but very unlikely, right?\n\t\t\t\t\t\t\t\tnoteID = str(uuid.uuid4()).replace(\"-\", \"\")\n\t\t\t\t\t\t\t\tif subnotes == True:\n\t\t\t\t\t\t\t\t\tnewNote = {\"type\": noteType, \"persistent_id\": noteID, \"jsonmodel_type\": \"note_multipart\", \"publish\": False}\n\t\t\t\t\t\t\t\t\tsubnotes = []\n\t\t\t\t\t\t\t\t\tcellCount = 0\n\t\t\t\t\t\t\t\t\tfor cell in row:\n\t\t\t\t\t\t\t\t\t\tcellCount = cellCount + 1\n\t\t\t\t\t\t\t\t\t\tif cellCount > 2:\n\t\t\t\t\t\t\t\t\t\t\tif len(cell) > 1:\n\t\t\t\t\t\t\t\t\t\t\t\tif publishNotes.lower() == \"true\":\n\t\t\t\t\t\t\t\t\t\t\t\t\tnewPara = {\"content\": cell, \"publish\": True, \"jsonmodel_type\": \"note_text\"}\n\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\tnewPara = {\"content\": cell, \"publish\": False, \"jsonmodel_type\": \"note_text\"}\n\t\t\t\t\t\t\t\t\t\t\t\tsubnotes.append(newPara)\n\t\t\t\t\t\t\t\t\tnewNote[\"subnotes\"] = subnotes\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tnewNote = {\"type\": noteType, \"persistent_id\": noteID, \"jsonmodel_type\": \"note_digital_object\", \"publish\": False}\n\t\t\t\t\t\t\t\t\tcellCount = 0\n\t\t\t\t\t\t\t\t\tcontentText = \"\"\n\t\t\t\t\t\t\t\t\tfor cell in row:\n\t\t\t\t\t\t\t\t\t\tcellCount = cellCount + 1\n\t\t\t\t\t\t\t\t\t\tif cellCount > 2:\n\t\t\t\t\t\t\t\t\t\t\tif len(cell) > 1:\n\t\t\t\t\t\t\t\t\t\t\t\tcontentText = contentText + \"\\n\\n\" + cell\n\t\t\t\t\t\t\t\t\tnewNote[\"content\"] = [contentText]\n\t\t\t\t\t\t\t\tif publishNotes.lower() == \"true\":\n\t\t\t\t\t\t\t\t\tnewNote[\"publish\"] = True\n\t\t\t\t\t\t\t\tnewNote[\"label\"] = label\n\t\t\t\t\t\t\t\twebObject[\"notes\"].append(newNote)\n\t\t\t\t\t\treturn webObject\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t#acquisition notes\n\t\t\t\t\tfor row in csvData:\n\t\t\t\t\t\tif row[0] == collectionNumber:\n\t\t\t\t\t\t\tif captureCountAIT > 0:\n\t\t\t\t\t\t\t\twebObject = makeNote(\"acqinfo\", webObject, row, acqinfoLabel, True)\n\t\t\t\t\t\tif row[0].lower() == \"warc\":\n\t\t\t\t\t\t\tif captureCountAIT > 0:\n\t\t\t\t\t\t\t\twebObject = makeNote(\"accessrestrict\", webObject, row, warcLabel, True)\n\t\t\t\t\tif internetArchiveCaptures == True:\n\t\t\t\t\t\tif len(csvData[1][2]) > 1:\n\t\t\t\t\t\t\twebObject = makeNote(\"acqinfo\", webObject, csvData[1], acqinfoLabelIA, True)\n\t\t\t\t\t\t\t\n\t\t\t\t\t#add Web Archives PhysTech note\n\t\t\t\t\tdef addPhystech(webObject):\n\t\t\t\t\t\tphystechExist = False\n\t\t\t\t\t\tfor note in webObject[\"notes\"]:\n\t\t\t\t\t\t\tif note[\"type\"] == \"phystech\":\n\t\t\t\t\t\t\t\tif \"subnotes\" in note:\n\t\t\t\t\t\t\t\t\tfor subnote in note[\"subnotes\"]:\n\t\t\t\t\t\t\t\t\t\tif subnote[\"content\"].lower() == \"web archives\":\n\t\t\t\t\t\t\t\t\t\t\tphystechExist = True\n\t\t\t\t\t\tif phystechExist == False:\n\t\t\t\t\t\t\t#possible uid collision here, but very unlikely, right?\n\t\t\t\t\t\t\tnoteID = str(uuid.uuid4()).replace(\"-\", \"\")\n\t\t\t\t\t\t\tnewSubnote = {\"content\": \"Web Archives\", \"jsonmodel_type\": \"note_text\", \"publish\": False}\n\t\t\t\t\t\t\tnewPhystech = {\"type\": \"phystech\", \"persistent_id\": noteID, \"subnotes\": [newSubnote], \"jsonmodel_type\": \"note_multipart\", \"publish\": False}\n\t\t\t\t\t\t\twebObject[\"notes\"].append(newPhystech)\n\t\t\t\t\taddPhystech(webObject)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tif len(dateType) > 0:\n\t\t\t\t\t\tif dateType == \"inclusive\":\n\t\t\t\t\t\t\tbeginAIT = firstNormal\n\t\t\t\t\t\t\tendAIT = lastNormal\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tbeginAIT = firstNormal\n\t\t\t\t\t\t\tendAIT = \"\"\n\t\t\t\t\tif len(dateTypeIA) > 0:\n\t\t\t\t\t\tif dateTypeIA == \"inclusive\":\n\t\t\t\t\t\t\tbeginIA = firstNormalIA\n\t\t\t\t\t\t\tendIA = lastNormalIA\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tbeginIA = firstNormalIA\n\t\t\t\t\t\t\tendIA = \"\"\n\t\t\t\t\t\n\t\t\t\t\t#get the total date range for both IA and AIT\n\t\t\t\t\tnewEnd = \"\"\n\t\t\t\t\tif len(dateType) > 0 or len(dateTypeIA) > 0:\n\t\t\t\t\t\tif len(dateType) > 0:\n\t\t\t\t\t\t\tnewBegin = firstNormal\n\t\t\t\t\t\t\tif dateType == \"inclusive\":\n\t\t\t\t\t\t\t\tnewEnd = lastNormal\n\t\t\t\t\t\tif len(dateTypeIA) > 0:\n\t\t\t\t\t\t\tif len(dateType) > 0:\n\t\t\t\t\t\t\t\tif firstNormalIA < newBegin:\n\t\t\t\t\t\t\t\t\tnewBegin = firstNormalIA\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tnewBegin = firstNormalIA\n\t\t\t\t\t\t\tif dateTypeIA == \"inclusive\":\n\t\t\t\t\t\t\t\tif len(dateType) > 0:\n\t\t\t\t\t\t\t\t\tif lastNormalIA > newEnd:\n\t\t\t\t\t\t\t\t\t\tnewEnd = lastNormalIA\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tnewEnd = lastNormalIA\n\t\t\t\t\t\t\n\t\t\t\t\t\tdef updateDates(webObject, newBegin, newEnd, dateType, dateTypeIA, webDatesLabel):\n\t\t\t\t\t\t\tupdateTime = datetime.now().isoformat(\"T\")[:-4] + \"Z\"\t\t\t\t\t\n\t\t\t\t\t\t\tif \"dates\" in webObject:\n\t\t\t\t\t\t\t\tsameDateType = False\n\t\t\t\t\t\t\t\tfor date in webObject[\"dates\"]:\n\t\t\t\t\t\t\t\t\tif date[\"label\"].lower() == webDatesLabel.lower():\n\t\t\t\t\t\t\t\t\t\tsameDateType = True\n\t\t\t\t\t\t\t\t\t\tif newBegin < date[\"begin\"]:\n\t\t\t\t\t\t\t\t\t\t\tdate[\"begin\"] = newBegin\n\t\t\t\t\t\t\t\t\t\tif dateType == \"inclusive\" or dateTypeIA == \"inclusive\":\n\t\t\t\t\t\t\t\t\t\t\tdate[\"date_type\"] = \"inclusive\"\n\t\t\t\t\t\t\t\t\t\t\tif not \"end\" in date:\n\t\t\t\t\t\t\t\t\t\t\t\tdate[\"end\"] = newEnd\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tif newEnd > date[\"end\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\tdate[\"end\"] = newEnd\n\t\t\t\t\t\t\t\t\t\tif \"expression\" in date or dateExpressions.lower().strip() == \"true\":\n\t\t\t\t\t\t\t\t\t\t\tif date[\"date_type\"] == \"inclusive\":\n\t\t\t\t\t\t\t\t\t\t\t\tdate[\"expression\"] = iso2DACS(date[\"begin\"]) + \"-\" + iso2DACS(date[\"end\"])\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tdate[\"expression\"] = iso2DACS(date[\"begin\"])\n\t\t\t\t\t\t\t\tif sameDateType == False:\n\t\t\t\t\t\t\t\t\tif dateType == \"inclusive\" or dateTypeIA == \"inclusive\":\n\t\t\t\t\t\t\t\t\t\tnewDates = {\"lock_version\": 0, \"system_mtime\": updateTime, \"begin\": newBegin, \"end\": newEnd, \"jsonmodel_type\": \"date\", \"date_type\": \"inclusive\", \"user_mtime\": updateTime, \"last_modified_by\": user, \"label\": webDatesLabel.lower(), \"create_time\": updateTime, \"created_by\": user}\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tnewDates = {\"lock_version\": 0, \"system_mtime\": updateTime, \"begin\": newBegin, \"jsonmodel_type\": \"date\", \"date_type\": \"single\", \"user_mtime\": updateTime, \"last_modified_by\": user, \"label\": webDatesLabel.lower(), \"create_time\": updateTime, \"created_by\": user}\n\t\t\t\t\t\t\t\t\tif dateExpressions.lower().strip() == \"true\":\n\t\t\t\t\t\t\t\t\t\tif dateType == \"inclusive\" or dateTypeIA == \"inclusive\":\n\t\t\t\t\t\t\t\t\t\t\tnewDates[\"expression\"] = iso2DACS(newDates[\"begin\"]) + \"-\" + iso2DACS(newDates[\"end\"])\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tnewDates[\"expression\"] = iso2DACS(newDates[\"begin\"])\n\t\t\t\t\t\t\t\t\twebObject[\"dates\"].append(newDates)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif dateType == \"inclusive\" or dateTypeIA == \"inclusive\":\n\t\t\t\t\t\t\t\t\tnewDates = {\"lock_version\": 0, \"system_mtime\": updateTime, \"begin\": newBegin, \"end\": newEnd, \"jsonmodel_type\": \"date\", \"date_type\": \"inclusive\", \"user_mtime\": updateTime, \"last_modified_by\": user, \"label\": webDatesLabel.lower(), \"create_time\": updateTime, \"created_by\": user}\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tnewDates = {\"lock_version\": 0, \"system_mtime\": updateTime, \"begin\": newBegin, \"jsonmodel_type\": \"date\", \"date_type\": \"single\", \"user_mtime\": updateTime, \"last_modified_by\": user, \"label\": webDatesLabel.lower(), \"create_time\": updateTime, \"created_by\": user}\n\t\t\t\t\t\t\t\tif \"expression\" in newDates or dateExpressions.lower().strip() == \"true\":\n\t\t\t\t\t\t\t\t\tif dateType == \"inclusive\" or dateTypeIA == \"inclusive\":\n\t\t\t\t\t\t\t\t\t\tnewDates[\"expression\"] = iso2DACS(newDates[\"begin\"]) + \"-\" + iso2DACS(date[\"end\"])\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tnewDates[\"expression\"] = iso2DACS(newDates[\"begin\"])\n\t\t\t\t\t\t\t\twebObject[\"dates\"] = newDates\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tdef updateExtent(webObject, captureCountTotal):\n\t\t\t\t\t\tupdateTime = datetime.now().isoformat(\"T\")[:-4] + \"Z\"\n\t\t\t\t\t\tif \"extents\" in webObject:\n\t\t\t\t\t\t\tcaptureExtent = False\n\t\t\t\t\t\t\tfor extent in webObject[\"extents\"]:\n\t\t\t\t\t\t\t\tif extent[\"extent_type\"].lower() == webExtentType.lower():\n\t\t\t\t\t\t\t\t\tcaptureExtent = True\n\t\t\t\t\t\t\t\t\tif captureCountTotal > int(extent[\"number\"]):\n\t\t\t\t\t\t\t\t\t\textent[\"number\"] = str(captureCountTotal)\n\t\t\t\t\t\t\t\t\textent[\"extent_type\"] = webExtentType\n\t\t\t\t\t\t\tif captureExtent == False:\n\t\t\t\t\t\t\t\tnewExtent = {\"lock_version\": 0, \"system_mtime\": updateTime, \"jsonmodel_type\": \"extent\", \"user_mtime\": updateTime, \"number\": str(captureCountTotal), \"last_modified_by\": user, \"portion\": \"whole\", \"create_time\": updateTime, \"created_by\": user, \"extent_type\": webExtentType}\n\t\t\t\t\t\t\t\twebObject[\"extents\"].append(newExtent)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tnewExtent = {\"lock_version\": 0, \"system_mtime\": updateTime, \"jsonmodel_type\": \"extent\", \"user_mtime\": updateTime, \"number\": str(captureCountTotal), \"last_modified_by\": user, \"portion\": \"whole\", \"create_time\": updateTime, \"created_by\": user, \"extent_type\": webExtentType}\n\t\t\t\t\t\t\twebObject[\"extents\"] = newExtent\n\t\t\t\t\t\t\n\t\t\t\t\t#recursive function for updating parents\n\t\t\t\t\tdef updateParents(object, parentCount):\n\t\t\t\t\t\tif \"parent\" in object:\n\t\t\t\t\t\t\tparentCount = parentCount + 1\n\t\t\t\t\t\t\tlog(\"\t\tUpdating parent \" + str(parentCount) + \"...\")\n\t\t\t\t\t\t\tparentID = object[\"parent\"][\"ref\"]\n\t\t\t\t\t\t\tparentObject = requests.get(aspaceURL + parentID, headers=headers).json()\n\t\t\t\t\t\t\t#serializeOutput(\"parentRecord\", parentObject)\n\t\t\t\t\t\t\t#updateExtent(parentObject, captureCountTotal)\n\t\t\t\t\t\t\tupdateDates(parentObject, newBegin, newEnd, dateType, dateTypeIA, webDatesLabel)\n\t\t\t\t\t\t\taddPhystech(parentObject)\n\t\t\t\t\t\t\t#serializeOutput(\"parentRecord2\", parentObject)\n\t\t\t\t\t\t\tnewParent = json.dumps(parentObject)\n\t\t\t\t\t\t\tpostParent = requests.post(aspaceURL + parentID, headers=headers, data=newParent)\n\t\t\t\t\t\t\tif postParent.status_code != 200:\n\t\t\t\t\t\t\t\traise ValueError(\"Error posting updated parent record to ArchivesSpace: \" + postParent.text)\n\t\t\t\t\t\t\tupdateParents(parentObject, parentCount)\n\t\t\t\t\t\t\t\n\t\t\t\t\tif captureCountTotal > 0:\n\t\t\t\t\t\tupdateExtent(webObject, captureCountTotal)\n\t\t\t\t\t\tupdateDates(webObject, newBegin, newEnd, dateType, dateTypeIA, webDatesLabel)\n\t\t\t\t\t\tif updateParentRecords.lower() == \"true\":\n\t\t\t\t\t\t\tupdateParents(webObject, 0)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t#update resource record\n\t\t\t\t\t\t\tif \"resource\" in webObject:\n\t\t\t\t\t\t\t\tresourceID = webObject[\"resource\"][\"ref\"]\n\t\t\t\t\t\t\t\tlog(\"\t\tUpdating resource...\")\n\t\t\t\t\t\t\t\tresourceObject = requests.get(aspaceURL + resourceID, headers=headers).json()\n\t\t\t\t\t\t\t\t#serializeOutput(\"parentResource\", resourceObject)\n\t\t\t\t\t\t\t\t#updateExtent(resourceObject, captureCountTotal)\n\t\t\t\t\t\t\t\tupdateDates(resourceObject, newBegin, newEnd, dateType, dateTypeIA, webDatesLabel)\n\t\t\t\t\t\t\t\taddPhystech(resourceObject)\n\t\t\t\t\t\t\t\t#serializeOutput(\"parentResource2\", resourceObject)\n\t\t\t\t\t\t\t\tnewResource = json.dumps(resourceObject)\n\t\t\t\t\t\t\t\tpostResource = requests.post(aspaceURL + resourceID, headers=headers, data=newResource)\n\t\t\t\t\t\t\t\tif postResource.status_code != 200:\n\t\t\t\t\t\t\t\t\traise ValueError(\"Error posting updated resource record to ArchivesSpace: \" + postResource.text)\n\t\t\t\t\t\t\n\t\t\t\t\t#Update Digital Objects\n\t\t\t\t\tif captureCountAIT > 0:\n\t\t\t\t\t\tarchiveItLink = \"http://wayback.archive-it.org/\" + collectionNumber + \"/*/\" + webURL\n\t\t\t\t\twaybackLink = \"https://web.archive.org/web/*/\" + webURL\n\t\t\t\t\tobjectAIT = False\n\t\t\t\t\tobjectIA = False\n\t\t\t\t\tlog(\"\t\tUpdating digital objects...\")\n\t\t\t\t\tfor instance in webObject[\"instances\"]:\n\t\t\t\t\t\tif instance[\"instance_type\"] == \"digital_object\":\n\t\t\t\t\t\t\tdigObURI = instance[\"digital_object\"][\"ref\"]\n\t\t\t\t\t\t\tdigitalObject = requests.get(aspaceURL + digObURI, headers=headers).json()\n\t\t\t\t\t\t\t#serializeOutput(\"digitalObject\", digitalObject)\n\t\t\t\t\t\t\tfor file in digitalObject[\"file_versions\"]:\n\t\t\t\t\t\t\t\tif file[\"file_uri\"].strip() == archiveItLink:\n\t\t\t\t\t\t\t\t\tobjectAIT = True\n\t\t\t\t\t\t\t\t\tif captureCountAIT > 0:\n\t\t\t\t\t\t\t\t\t\tfile[\"publish\"] = True\n\t\t\t\t\t\t\t\t\t\tfile[\"is_representative\"] = False\n\t\t\t\t\t\t\t\t\t\tupdateExtent(digitalObject, captureCountAIT)\n\t\t\t\t\t\t\t\t\t\tupdateDates(digitalObject, beginAIT, endAIT, dateType, dateTypeIA, webDatesLabel)\n\t\t\t\t\t\t\t\t\t\tdigitalObject[\"title\"] = daoTitleAIT\n\t\t\t\t\t\t\t\t\t\tdigitalObject[\"publish\"] = True\n\t\t\t\t\t\t\t\t\t\tfor row in csvData:\n\t\t\t\t\t\t\t\t\t\t\tif row[0] == collectionNumber:\n\t\t\t\t\t\t\t\t\t\t\t\tdigitalObject = makeNote(\"acqinfo\", digitalObject, row, acqinfoLabel, False)\n\t\t\t\t\t\t\t\t\t\t\tif row[0].lower() == \"warc\":\n\t\t\t\t\t\t\t\t\t\t\t\tdigitalObject = makeNote(\"accessrestrict\", digitalObject, row, warcLabel, False)\n\t\t\t\t\t\t\t\t\t\t#serializeOutput(\"digitalObjectAIT\", digitalObject)\n\t\t\t\t\t\t\t\t\t\tnewDaoAIT = json.dumps(digitalObject)\n\t\t\t\t\t\t\t\t\t\tpostDao = requests.post(aspaceURL + digObURI, headers=headers, data=newDaoAIT)\n\t\t\t\t\t\t\t\t\t\tif postDao.status_code != 200:\n\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"Error posting updated Archive-It digital object record to ArchivesSpace: \" + postDao.text)\n\t\t\t\t\t\t\t\telif file[\"file_uri\"] == waybackLink:\n\t\t\t\t\t\t\t\t\tobjectIA = True\n\t\t\t\t\t\t\t\t\tif captureCountIA > 0:\n\t\t\t\t\t\t\t\t\t\tfile[\"publish\"] = True\n\t\t\t\t\t\t\t\t\t\tfile[\"is_representative\"] = False\n\t\t\t\t\t\t\t\t\t\tupdateExtent(digitalObject, captureCountIA)\n\t\t\t\t\t\t\t\t\t\tupdateDates(digitalObject, beginIA, endIA, dateType, dateTypeIA, webDatesLabel)\n\t\t\t\t\t\t\t\t\t\tdigitalObject[\"title\"] = daoTitleIA\n\t\t\t\t\t\t\t\t\t\tdigitalObject[\"publish\"] = True\n\t\t\t\t\t\t\t\t\t\tfor row in csvData:\n\t\t\t\t\t\t\t\t\t\t\tif len(row[0]) > 0:\n\t\t\t\t\t\t\t\t\t\t\t\tif row[0].lower() == \"internet archive\":\n\t\t\t\t\t\t\t\t\t\t\t\t\tdigitalObject = makeNote(\"acqinfo\", digitalObject, row, acqinfoLabel, False)\n\t\t\t\t\t\t\t\t\t\t#serializeOutput(\"digitalObjectIA\", digitalObject)\n\t\t\t\t\t\t\t\t\t\tnewDaoIA = json.dumps(digitalObject)\n\t\t\t\t\t\t\t\t\t\tpostDao = requests.post(aspaceURL + digObURI, headers=headers, data=newDaoIA)\n\t\t\t\t\t\t\t\t\t\tif postDao.status_code != 200:\n\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"Error posting updated Internet Archive digital object record to ArchivesSpace: \" + postDao.text)\n\t\t\t\t\tupdateTime = datetime.now().isoformat(\"T\")[:-4] + \"Z\"\t\n\t\t\t\t\tnewDigitalObject = {\"jsonmodel_type\": \"digital_object\", \"publish\": True, \"linked_instances\": [{\"ref\": objectURI}], \"title\": \"\", \"subjects\": [], \"extents\": [], \"external_documents\": [], \"linked_agents\": [], \"repository\": [{\"ref\": objectURI.split(\"/archival_objects/\")[0]}], \"file_versions\": [], \"rights_statements\": [], \"linked_events\": [], \"external_ids\": [], \"suppressed\": False, \"restrictions\": False, \"dates\": [], \"notes\": []}\n\t\t\t\t\tnewFile = {\"lock_version\": 0, \"system_mtime\": updateTime, \"jsonmodel_type\": \"file_version\", \"file_uri\": \"\", \"user_mtime\": updateTime, \"last_modified_by\": user, \"create_time\": updateTime, \"created_by\": user, \"is_representative\": False, \"publish\": True}\n\t\t\t\t\tif captureCountAIT > 0 and objectAIT == False:\n\t\t\t\t\t\tnewAIT = newDigitalObject\n\t\t\t\t\t\tnewFileAIT = newFile\n\t\t\t\t\t\tnewFileAIT[\"file_uri\"] = archiveItLink\n\t\t\t\t\t\tnewAIT[\"file_versions\"] = [newFileAIT]\n\t\t\t\t\t\tupdateExtent(newAIT, captureCountAIT)\n\t\t\t\t\t\tupdateDates(newAIT, beginAIT, endAIT, dateType, dateTypeIA, webDatesLabel)\n\t\t\t\t\t\tnewAIT[\"title\"] = daoTitleAIT\n\t\t\t\t\t\tnewAIT[\"publish\"] = True\n\t\t\t\t\t\tfor row in csvData:\n\t\t\t\t\t\t\tif row[0] == collectionNumber:\n\t\t\t\t\t\t\t\tnewAIT = makeNote(\"acqinfo\", newAIT, row, acqinfoLabel, False)\n\t\t\t\t\t\t\tif row[0].lower() == \"warc\":\n\t\t\t\t\t\t\t\tnewAIT = makeNote(\"accessrestrict\", newAIT, row, warcLabel, False)\n\t\t\t\t\t\tdaoID = str(uuid.uuid4()).replace(\"-\", \"\")\n\t\t\t\t\t\tnewAIT[\"digital_object_id\"] = daoID\n\t\t\t\t\t\t#serializeOutput(\"newDaoAIT\", newAIT)\n\t\t\t\t\t\tnewDaoAIT = json.dumps(newAIT)\n\t\t\t\t\t\tpostDao = requests.post(aspaceURL + objectURI.split(\"/archival_objects/\")[0] +\"/digital_objects\", headers=headers, data=newDaoAIT)\n\t\t\t\t\t\tif postDao.status_code != 200:\n\t\t\t\t\t\t\traise ValueError(\"Error posting new Archive-It digital object record to ArchivesSpace: \" + postDao.text)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tdaoLink = postDao.json()[\"id\"]\n\t\t\t\t\t\tnewInstance = {\"lock_version\": 0, \"system_mtime\": updateTime, \"jsonmodel_type\": \"instance\", \"digital_object\": {\"ref\": objectURI.split(\"/archival_objects/\")[0] + \"/digital_objects/\" + str(daoLink)}, \"user_mtime\": updateTime, \"last_modified_by\": user, \"instance_type\": \"digital_object\", \"create_time\": updateTime, \"created_by\": user, \"is_representative\": False}\n\t\t\t\t\t\twebObject[\"instances\"].append(newInstance)\n\t\t\t\t\tif captureCountIA > 0 and objectIA == False:\n\t\t\t\t\t\tnewIA = newDigitalObject\n\t\t\t\t\t\tnewFileIA = newFile\n\t\t\t\t\t\tnewFileIA[\"file_uri\"] = waybackLink\n\t\t\t\t\t\tnewIA[\"file_versions\"] = [newFileIA]\n\t\t\t\t\t\tupdateExtent(newIA, captureCountIA)\n\t\t\t\t\t\tupdateDates(newIA, beginIA, endIA, dateType, dateTypeIA, webDatesLabel)\n\t\t\t\t\t\tnewIA[\"title\"] = daoTitleIA\n\t\t\t\t\t\tnewIA[\"publish\"] = True\n\t\t\t\t\t\tfor row in csvData:\n\t\t\t\t\t\t\tif len(row[0]) > 0:\n\t\t\t\t\t\t\t\tif row[0].lower() == \"internet archive\":\n\t\t\t\t\t\t\t\t\tdigitalObject = makeNote(\"acqinfo\", newIA, row, acqinfoLabel, False)\n\t\t\t\t\t\tdaoID = str(uuid.uuid4()).replace(\"-\", \"\")\n\t\t\t\t\t\tnewIA[\"digital_object_id\"] = daoID\n\t\t\t\t\t\t#serializeOutput(\"newDaoIA\", newIA)\n\t\t\t\t\t\tnewDaoIA = json.dumps(newIA)\n\t\t\t\t\t\tpostDao = requests.post(aspaceURL + objectURI.split(\"/archival_objects/\")[0] +\"/digital_objects\", headers=headers, data=newDaoIA)\n\t\t\t\t\t\tif postDao.status_code != 200:\n\t\t\t\t\t\t\traise ValueError(\"Error posting new Internet Archive digital object record to ArchivesSpace: \" + postDao.text)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tdaoLink = postDao.json()[\"id\"]\n\t\t\t\t\t\tnewInstance = {\"lock_version\": 0, \"system_mtime\": updateTime, \"jsonmodel_type\": \"instance\", \"digital_object\": {\"ref\": objectURI.split(\"/archival_objects/\")[0] + \"/digital_objects/\" + str(daoLink)}, \"user_mtime\": updateTime, \"last_modified_by\": user, \"instance_type\": \"digital_object\", \"create_time\": updateTime, \"created_by\": user, \"is_representative\": False}\n\t\t\t\t\t\twebObject[\"instances\"].append(newInstance)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t#change inital records to inactive\n\t\t\t\t\tif webStatus == \"initial\" and initialCheck == True:\n\t\t\t\t\t\tfor extDoc in webObject[\"external_documents\"]:\n\t\t\t\t\t\t\tif extDoc[\"title\"].lower() == \"status\":\n\t\t\t\t\t\t\t\textDoc[\"location\"] = \"inactive\"\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t#Post the updated record back to ArchivesSpace\n\t\t\t\t\tif captureCountTotal > 0 or len(dateType) > 0:\n\t\t\t\t\t\tlog(\"\t\tPosting updated archival object back to ASpace...\")\n\t\t\t\t\t\tupdateID = webObject[\"uri\"].split(\"/archival_objects/\")[1]\n\t\t\t\t\t\tnewObject = json.dumps(webObject)\n\t\t\t\t\t\tupdateObject = requests.post(aspaceURL + repoPath + \"/archival_objects/\" + updateID, headers=headers, data=newObject)\n\t\t\t\t\t\tif updateObject.status_code != 200:\n\t\t\t\t\t\t\traise ValueError(\"Error posting updated record to ArchivesSpace: \" + updateObject.text)\n\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\n\t#recursive function to find records with web archives\n\tdef webRecords(children):\n\t\tfor child in children:\n\t\t\tif child[\"level\"].lower() == \"web archives\":\n\t\t\t\tif child[\"has_children\"] == True:\n\t\t\t\t\t#serializeOutput(\"parent\", child)\n\t\t\t\t\twebRecords(child[\"children\"])\n\t\t\t\telse:\n\t\t\t\t\t#serializeOutput(\"child\", child)\n\t\t\t\t\tobjectID = str(child[\"id\"])\n\t\t\t\t\twebObject = requests.get(aspaceURL + repoPath + \"/archival_objects?id_set=\" + objectID, headers=headers).json()\n\t\t\t\t\t#lowest level web record\n\t\t\t\t\tUpdateWebRecord(webObject)\n\t\t\n\tdef findWebRecords(resources):\n\t\t#serializeOutput(\"resources\", resources)\n\t\tcount = 0\n\t\twebCount = 0\n\t\tfor record in resources[\"results\"]:\n\t\t\t#pp(record)\n\t\t\t#print (record[\"ead_id\"] + \" -- \" + record[\"title\"])\n\t\t\tcount = count + 1\n\t\t\t#if record[\"ead_id\"] == \"nam_apap104\":\n\t\t\tresourceID = record[\"uri\"].split(\"/resources/\")[1]\n\t\t\tnotes = record[\"notes\"]\n\t\t\tfor note in notes:\n\t\t\t\tif \"type\" in note:\n\t\t\t\t\tif note[\"type\"] == \"phystech\":\n\t\t\t\t\t\tsubnotes = note[\"subnotes\"]\n\t\t\t\t\t\tfor subnote in subnotes:\n\t\t\t\t\t\t\tif \"web archives\" in subnote[\"content\"].lower():\n\t\t\t\t\t\t\t\tlog(\"found Web Archives in resource ---> \" + record[\"title\"])\n\t\t\t\t\t\t\t\twebCount = webCount + 1\n\t\t\t\t\t\t\t\twebCollection = requests.get(aspaceURL + repoPath + \"/resources/\" + resourceID + \"/tree\", headers=headers).json()\n\t\t\t\t\t\t\t\t#serializeOutput(\"tree\", webCollection)\n\t\t\t\t\t\t\t\twebRecords(webCollection[\"children\"])\t\n\t\tlog(\"found and updated \" + str(webCount) + \" web archives resource in \" + str(count) + \" total resources.\")\n\n\t#function to loop through paginated results\n\tdef getResults(pageCount):\n\t\tresources = requests.get(aspaceURL + repoPath + \"/resources?page=\" + str(pageCount) + \"&page_size=\" + str(paginatedResults), headers=headers).json()\n\t\tlastPage = resources[\"last_page\"]\n\t\tlog(\"Requesting resource results page \" + str(pageCount) + \" of \" + str(lastPage))\n\t\tfindWebRecords(resources)\n\t\tif lastPage > pageCount:\n\t\t\tpageCount = pageCount + 1\n\t\t\tgetResults(pageCount)\n\t\t\t\t\t\t\t\t\t\n\t#inital request for session\n\tr = requests.post(aspaceURL + \"/users/\" + user + \"/login\", data = {\"password\":pw})\n\n\tif r.status_code == \"200\":\n\t\tlog(\"Connection Successful\")\n\n\tsessionID = r.json()[\"session\"]\n\theaders = {'X-ArchivesSpace-Session':sessionID}\n\n\trepos = requests.get(aspaceURL + \"/repositories\", headers=headers).json()\n\tfor repo in repos:\n\t\tlog(\"Looking for Web Archives Records in \" + repo[\"name\"])\n\t\trepoPath = repo[\"uri\"]\n\t\t\n\t\t#get paginated results\n\t\tgetResults(1)\n\nexcept Exception as errorMsg:\n\ttry:\n\t\tprint (sys.exc_info())\n\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\tlineNum = exc_tb.tb_lineno\n\t\timport smtplib\n\t\t#get config from webArchives.ini\n\t\tif sys.version_info[0] < 3:\n\t\t\timport ConfigParser\n\t\t\tconfig = ConfigParser.ConfigParser()\n\t\telse:\n\t\t\timport configparser\n\t\t\tconfig = configparser.ConfigParser()\n\t\tconfig.read(os.path.join(__location__, \"webArchives.ini\"))\n\t\terrorEmail = config.get('error_email', 'sendErrorEmail')\n\t\tsender = config.get('error_email', 'sender')\n\t\tpw = config.get('error_email', 'pw')\n\t\treceiver = config.get('error_email', 'receiver')\n\t\temailHost = config.get('error_email', 'emailHost')\n\t\tportNum = config.get('error_email', 'port')\n\t\tsubject = \"Error Updating Web Archives Records in ArchivesSpace\"\n\t\t\n\t\tif errorEmail.lower() == \"true\":\n\t\t\temailMsg = \"Sent Error Email\"\n\t\telse:\n\t\t\temailMsg = \"Email errors turned off\"\n\t\tbody = \"**********************************************************************************************************\\nERROR: Line: \" + str(lineNum) + \"\\n\" + emailMsg + \"\\n\" + str(errorMsg) + \"\\n**********************************************************************************************************\\n\"\n\t\tmessage = 'Subject: %s\\n\\n%s' % (subject, body)\n\t\tsmtpObj = smtplib.SMTP(host=emailHost, port=int(portNum))\n\t\tsmtpObj.ehlo()\n\t\tsmtpObj.starttls()\n\t\tsmtpObj.ehlo()\n\t\tsmtpObj.login(sender,pw)\n\t\tsmtpObj.sendmail(sender, receiver, message)\n\t\tsmtpObj.quit()\n\t\tlog(message)\n\texcept Exception as error:\n\t\tlog(\"**********************************************************************************************************\\nERROR: Line: \" + str(lineNum) + \"\\\\nFailed to send error email.\\n\" + str(error) + \"\\n\" + str(errorMsg) + \"\\n**********************************************************************************************************\\n\")\n\tsys.exit()\n\n \n","sub_path":"webArchives.py","file_name":"webArchives.py","file_ext":"py","file_size_in_byte":29831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"396873955","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 27 13:23:30 2021\r\n\r\n@author: sliakat\r\n\"\"\"\r\n\r\n#How to use, and notes:\r\n#FIRST: CHANGE THE NAME FOR 'expToLoad' (line 106) TO A VALID EXPERIMENT FILE ON YOUR PC\r\n#**If you don't change the name and use an experiment name that is not on your PC, it will crash**\r\n#\r\n#When you've changed the experiment accordingly, run script with all 3 functions in main commendted (so only the 'pass' line is active)\r\n#This will open up an automation bridge to LightField that will be controllable via the Pyhton\r\n#thread until the instance is disposed.\r\n#\r\n#Next, run ONLY the line in main calling 'Background'. This will create a BG file and save in\r\n#the default save directory as 'Background.spe'.\r\n#\r\n#Next, run ONLY the line in main calling 'Reference'. This will create the reference file using LF\r\n#BG subtraction w/ the file created by 'Background'.\r\n#\r\n#Finally, run ONLY the 'Transmitted' line to arm LightField with the desired formula. After this line is run, you can hit\r\n#'Run' or 'Acquire in LF with all parameters armed.\r\n#\r\n#This script is meant to be an example of what is possible with the automation interface for this absorbance application.\r\n#You can turn into a GUI by making buttons that call the 'Background', 'Reference', and 'Tramsitted' options.\r\n\r\n\r\nimport clr\r\n\r\n# Import python sys module\r\nimport sys\r\n\r\n# Import modules\r\nimport os\r\n\r\nfrom System.Threading import AutoResetEvent\r\n\r\n# Import c compatible List and String\r\nfrom System import String\r\nfrom System.Collections.Generic import List\r\n\r\n# Add needed dll references\r\nsys.path.append(os.environ['LIGHTFIELD_ROOT'])\r\nsys.path.append(os.environ['LIGHTFIELD_ROOT']+\"\\\\AddInViews\")\r\nclr.AddReference('PrincetonInstruments.LightFieldViewV5')\r\nclr.AddReference('PrincetonInstruments.LightField.AutomationV5')\r\nclr.AddReference('PrincetonInstruments.LightFieldAddInSupportServices')\r\n\r\n# PI imports\r\nfrom PrincetonInstruments.LightField.Automation import Automation\r\nfrom PrincetonInstruments.LightField.AddIns import ExperimentSettings\r\nfrom PrincetonInstruments.LightField import AddIns\r\n\r\ndef acquisitionFinished(sender, event_args):\r\n signal.Set()\r\n exp.ExperimentCompleted -= acquisitionFinished\r\n \r\ndef Acquire():\r\n exp.ExperimentCompleted += acquisitionFinished\r\n exp.Acquire()\r\n signal.WaitOne()\r\n\r\ndef SetFilenames(name):\r\n exp.SetValue(ExperimentSettings.FileNameGenerationBaseFileName, name)\r\n exp.SetValue(ExperimentSettings.FileNameGenerationAttachDate, False)\r\n exp.SetValue(ExperimentSettings.FileNameGenerationAttachTime, False)\r\n exp.SetValue(ExperimentSettings.FileNameGenerationAttachIncrement, False)\r\n \r\ndef SetFilenamesWithDate(name):\r\n exp.SetValue(ExperimentSettings.FileNameGenerationBaseFileName, name)\r\n exp.SetValue(ExperimentSettings.FileNameGenerationAttachDate, True)\r\n exp.SetValue(ExperimentSettings.FileNameGenerationAttachTime, True)\r\n exp.SetValue(ExperimentSettings.FileNameGenerationAttachIncrement, False)\r\n\r\ndef Background(expName):\r\n exp.SetValue(ExperimentSettings.OnlineCorrectionsBackgroundCorrectionEnabled,False) #unchecks BG correction box\r\n accums = exp.GetValue(ExperimentSettings.OnlineProcessingFrameCombinationFramesCombined)\r\n if accums < 5:\r\n exp.SetValue(ExperimentSettings.OnlineProcessingFrameCombinationFramesCombined,5)\r\n exp.SetValue(ExperimentSettings.OnlineProcessingFrameCombinationMethod, AddIns.FrameCombinationMethod.Average)\r\n exp.SetValue(ExperimentSettings.AcquisitionFramesToStore,1) #takes 1 frame for BG\r\n SetFilenames('Background')\r\n bgPath = exp.GetValue(ExperimentSettings.FileNameGenerationDirectory) + '\\\\Background.spe'\r\n Acquire()\r\n exp.Load(expName) #reload original experiment to bring back previous settings after acquiring BG\r\n return bgPath\r\n \r\ndef Reference(expName,background,numAccums):\r\n exp.SetValue(ExperimentSettings.OnlineCorrectionsBackgroundCorrectionEnabled,True) #auto BG correction enabled\r\n exp.SetValue(ExperimentSettings.OnlineCorrectionsBackgroundCorrectionReferenceFile,background)\r\n exp.SetValue(ExperimentSettings.OnlineProcessingFrameCombinationFramesCombined,numAccums)\r\n exp.SetValue(ExperimentSettings.OnlineProcessingFrameCombinationMethod, AddIns.FrameCombinationMethod.Average)\r\n exp.SetValue(ExperimentSettings.AcquisitionFramesToStore,1)\r\n SetFilenames('Reference')\r\n refPath = exp.GetValue(ExperimentSettings.FileNameGenerationDirectory) + '\\\\Reference.spe'\r\n Acquire()\r\n exp.Load(expName)\r\n return refPath\r\n\r\ndef Transmitted(reference):\r\n exp.SetValue(ExperimentSettings.OnlineProcessingFormulasEnabled, True)\r\n formula = 'reference = \\\"' + reference + '\\\"\\ntransmitted = input\\n' + 'output = Log10(reference/transmitted)\\n'\r\n exp.SetValue(ExperimentSettings.OnlineProcessingFormulasCustomFormula,formula)\r\n \r\nexpToLoad = 'ProDemo'\r\n\r\nauto = Automation(True, List[String]())\r\nexp = auto.LightFieldApplication.Experiment\r\nexp.Load(expToLoad)\r\nsignal = AutoResetEvent(False)\r\n\r\nif __name__ == '__main__':\r\n pass\r\n #bgPath = Background(expToLoad)\r\n #refPath = Reference(expToLoad,bgPath,10) #change the 3rd parameter (integer) to input number of averaged accums\r\n #Transmitted(refPath)\r\n \r\n ","sub_path":"LFAutomation/PythonWebinar/referenceFuncs.py","file_name":"referenceFuncs.py","file_ext":"py","file_size_in_byte":5301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"337315097","text":"import sys\n\nn = int(sys.argv[1])\n\n# Compute v as the largest power of 2 <= n.\nv = 1\nwhile v <= n // 2:\n v = v * 2\n\n# Cast out powers of 2 in decreasing order.\nwhile v > 0:\n if n < v:\n print(0)\n else:\n print(1)\n n = n -v\n v = v // 2\n \nprint()\n","sub_path":"introCS/python/binary.py","file_name":"binary.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"196991571","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\n\nimport sys,time\n\nclass DigitalClock(QMainWindow):\n def __init__(self,parent=None):\n super(DigitalClock,self).__init__(parent)\n\n\n self.time=QTimer()\n self.time.timeout.connect(self.run)\n self.time.start(1000)\n\n self.number=0\n\n self.clock=QLCDNumber(self)\n self.clock.setDigitCount(8)\n\n self.setCentralWidget(self.clock)\n\n\n self.menucrate()\n self.resize(350,150)\n self.show()\n\n\n def run(self):\n self.number+=1\n\n self.hour = time.localtime().tm_hour\n self.minute = time.localtime().tm_min\n self.second = time.localtime().tm_sec\n\n if(len(str(self.hour)))==1:\n self.hour=str(\"0\"+str(self.hour))\n if (len(str(self.minute))) == 1:\n self.minute = str(\"0\" + str(self.minute))\n if (len(str(self.second))) == 1:\n self.second = str(\"0\" + str(self.second))\n\n self.clock.display(\"{0}:{1}:{2}\".format(str(self.hour),str(self.minute),str(self.second)))\n\n if self.number==60:\n self.number=0\n self.time.stop()\n self.time.start(1000)\n\n def menucrate(self):\n\n menus=QMenuBar()\n self.setMenuBar(menus)\n\n\n colorselect=QAction(\"COLOR SELECT\",self)\n colorselect.triggered.connect(self.colorclick)\n\n menu=menus.addMenu(\"MENU\")\n menu.addAction(colorselect)\n\n\n def colorclick(self):\n diyalog=QColorDialog()\n if diyalog.exec():\n self.clock.setStyleSheet(\"color:{};\".format(diyalog.currentColor().name()))\n\n\n\n\n\n\nuyg=QApplication(sys.argv)\nwindow=DigitalClock()\nsys.exit(uyg.exec())","sub_path":"digital_clock/digitalclock.py","file_name":"digitalclock.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"408218151","text":"import hashlib\nimport uuid\n\nfrom django.conf import settings\nfrom django.db.models import Model\n\nfrom base import Client, Encoder, SolitudeError\n\nfrom amo.helpers import absolutify, urlparams\nfrom amo.urlresolvers import reverse\n\nclient = None\n\n\ndef model_to_uid(model):\n return ':'.join((settings.DOMAIN.replace('-', '.'),\n model.__class__._meta.db_table,\n str(model.pk))).lower()\n\n\nclass ZamboniEncoder(Encoder):\n\n def default(self, v):\n if isinstance(v, Model):\n return model_to_uid(v)\n return super(ZamboniEncoder, self).default(v)\n\n\nclass ZamboniClient(Client):\n\n Error = SolitudeError\n\n def lookup_buyer_paypal(self, buyer):\n res = self.get_buyer(filters={'uuid': model_to_uid(buyer)})\n count = res['meta']['total_count']\n if count == 1:\n return res['objects'][0]['paypal']\n else:\n raise ValueError('Get returned %s buyers.' % count)\n\n def create_buyer_if_missing(self, buyer):\n \"\"\"\n Checks to see if the buyer exists in solitude. If not we'll create\n it so that solitude can store the pre-approval data for that buyer.\n \"\"\"\n res = self.get_buyer(filters={'uuid': model_to_uid(buyer)})\n if res['meta']['total_count'] == 0:\n self.post_buyer(data={'uuid': buyer})\n\n def create_seller_paypal(self, seller):\n \"\"\"\n Will see if the user exists. If it does, will see if paypal exists, if\n it doesn't it will create a paypal record. It will then return the\n paypal pk, so we can do calls to it.\n \"\"\"\n res = self.get_seller(filters={'uuid': model_to_uid(seller)})\n count = res['meta']['total_count']\n if count == 0:\n # There's no seller data, so create the seller objects.\n sel = self.post_seller(data={'uuid': seller})\n return self.post_seller_paypal(data={'seller':\n sel['resource_uri']})\n elif count == 1:\n sel = res['objects'][0]\n paypal = sel['paypal']\n if not paypal:\n # There is no PayPal object. Create one.\n return self.post_seller_paypal(data={'seller':\n sel['resource_uri']})\n # The resource_pk is there in the first results, just save it.\n return paypal\n else:\n raise ValueError('Get returned %s sellers.' % count)\n\n def create_seller_for_pay(self, addon):\n \"\"\"\n A temporary method to populate seller data, when a data migration\n is completed, this can be removed.\n \"\"\"\n obj = client.create_seller_paypal(addon)\n if not obj['paypal_id']:\n client.patch_seller_paypal(pk=obj['resource_pk'],\n data={'paypal_id': addon.paypal_id})\n\n def make_uuid(self):\n return hashlib.md5(str(uuid.uuid4())).hexdigest()\n\n def pay(self, data):\n \"\"\"Add in uuid and urls on the way.\"\"\"\n uuid = self.make_uuid()\n rt = data['seller'].get_purchase_url(action='done', args=['complete'])\n ca = data['seller'].get_purchase_url(action='done', args=['cancel'])\n\n data.update({\n 'ipn_url': absolutify(reverse('amo.paypal')),\n 'return_url': absolutify(urlparams(rt, uuid=uuid)),\n 'cancel_url': absolutify(urlparams(ca, uuid=uuid)),\n 'uuid': uuid,\n })\n return self.post_pay(data=data)\n\n\ndef get_client():\n # If you haven't specified a seclusion host, we can't do anything.\n if settings.SECLUSION_HOSTS:\n config = {\n # TODO: when seclusion can cope with multiple hosts, we'll pass\n # them all through and let seclusion do its magic.\n 'server': settings.SECLUSION_HOSTS[0],\n 'key': settings.SECLUSION_KEY,\n 'secret': settings.SECLUSION_SECRET,\n 'timeout': settings.SECLUSION_TIMEOUT\n }\n client = ZamboniClient(config)\n client.encoder = ZamboniEncoder\n return client\n\nif not client:\n client = get_client()\n","sub_path":"lib/pay_server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"153909322","text":"import datetime\n\nfrom Cinema.models import PaiDang, ORDERED_PAYED, ORDERED_NOT_PAY\nfrom Viewer.models import ViewerOrder\n\n\ndef get_valid_seats(paidang_id, order_id=0):\n paidang = PaiDang.objects.get(pk=paidang_id)\n\n h_seats = paidang.p_hall.h_seats\n\n # orders_payed = paidang.viewerorder_set.filter(v_status=ORDERED_PAYED)\n orders_payed = ViewerOrder.objects.filter(v_paidang_id=paidang_id).filter(v_status=ORDERED_PAYED)\n\n # orders_locked = paidang.viewerorder_set.filter(v_status=ORDERED_NOT_PAY).filter(v_expire__gt=datetime.datetime.now())\n orders_locked = ViewerOrder.objects.filter(v_paidang_id=paidang_id).filter(v_status=ORDERED_NOT_PAY).filter(v_expire__gt=datetime.datetime.now())\n\n if order_id != 0:\n print(\"排除自己\")\n orders_locked = orders_locked.exclude(pk=order_id)\n\n h_seat_list = h_seats.split(\"#\")\n\n orders_payed_seats = []\n\n for order_payed in orders_payed:\n orders_payed_seats += order_payed.v_seats.split(\"#\")\n\n orders_locked_seats = []\n\n for order_locked in orders_locked:\n orders_locked_seats += order_locked.v_seats.split(\"#\")\n\n print(h_seat_list)\n print(\"付款座位\",orders_payed_seats)\n print(\"锁定座��\",orders_locked_seats)\n\n valid_seats = list(set(h_seat_list) - set(orders_payed_seats) - set(orders_locked_seats))\n\n print(\"可用座位\",valid_seats)\n\n return valid_seats","sub_path":"Viewer/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"129784730","text":"class Network:\n def __init__(self):\n self.inputNeurons = {}\n self.neurons = {}\n self.conns = {}\n self.activity = {}\n\n def reset(self):\n for name, _ in self.activity.items():\n self.activity[name] = []\n\n def addInputNeuron(self, neuron):\n self.inputNeurons[neuron.name] = neuron\n self.conns[neuron.name] = []\n\n def addNeuron(self, neuron):\n self.neurons[neuron.name] = NetworkNeuron(neuron, [])\n self.activity[neuron.name] = []\n self.conns[neuron.name] = []\n\n def addConnection(self, neuronFromName, neuronToName, weight):\n self.neurons[neuronToName].addDep(neuronFromName)\n if neuronFromName in self.conns:\n self.conns[neuronFromName].append((neuronToName, weight))\n else:\n self.conns[neuronFromName] = [(neuronToName, weight)]\n\n def runRound(self, round_, inputs):\n for _, neuron in self.inputNeurons.items():\n children = self.conns[neuron.name]\n fired = 1 if neuron.name in inputs else 0\n\n for (childName, weight) in children:\n self.fire(round_, fired, weight, childName)\n\n def fire(self, round_, input_, weightIn, neuronName):\n networkNeuron = self.neurons[neuronName]\n fired = networkNeuron.fire(round_, input_, weightIn)\n if fired == None:\n return\n\n self.activity[neuronName].append(fired)\n children = self.conns[neuronName]\n for (child, weightOut) in children:\n self.fire(round_, fired, weightOut, child)\n\n\nclass NetworkNeuron:\n def __init__(self, neuron, deps):\n self.neuron = neuron\n self.deps = deps\n self.round = 0\n self.inputs = []\n self.weights = []\n\n def addDep(self, dep):\n self.deps.append(dep)\n\n def fire(self, round_, input_, weight):\n if self.round != round_:\n self.round = round_\n self.inputs = []\n self.weights = []\n\n self.inputs.append(input_)\n self.weights.append(weight)\n\n if len(self.inputs) == len(self.deps):\n return self.neuron.fire(self.inputs, self.weights)\n","sub_path":"FigS7E_gca-errs/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"217240932","text":"#coding=utf-8\n\nimport unittest\n\n\"\"\"\n146. LRU Cache\nDescriptionHintsSubmissionsDiscussSolution\nDiscuss Pick One\nDesign and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: \nget and put.\n\nget(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.\nput(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it \nshould invalidate the least recently used item before inserting a new item.\n\nFollow up:\nCould you do both operations in O(1) time complexity?\n\nExample:\n\nLRUCache cache = new LRUCache( 2 /* capacity */ );\n\ncache.put(1, 1);\ncache.put(2, 2);\ncache.get(1); // returns 1\ncache.put(3, 3); // evicts key 2\ncache.get(2); // returns -1 (not found)\ncache.put(4, 4); // evicts key 1\ncache.get(1); // returns -1 (not found)\ncache.get(3); // returns 3\ncache.get(4); // returns 4\n\nDifficulty:Hard\nTotal Accepted:131K\nTotal Submissions:742K\nContributor: LeetCode\nSubscribe to see which companies asked this question.\n\nRelated Topics \nDesign \nSimilar Questions \nLFU Cache Design In-Memory File System Design Compressed String Iterator\n\n\"\"\"\n\n\nclass DoubleLinkedNode(object):\n def __init__(self, key, val):\n self.key = key\n self.val = val\n self.pre = None\n self.next = None\n\n\nclass DoubledLinkedList(object):\n def __init__(self, head):\n self.head = head\n self.tail = head\n\n def move_to_head(self, node):\n old_pre = node.pre\n old_next = node.next\n old_pre.next = old_next\n if old_next:\n old_next.pre = old_pre\n else:\n self.tail = old_pre\n self.insert(node)\n\n def remove_tail(self):\n tmp = self.tail\n old_pre = self.tail.pre\n old_pre.next = None\n self.tail.pre = None\n self.tail = old_pre\n return tmp.key\n\n def insert(self, node):\n tmp = self.head.next\n self.head.next = node\n node.pre = self.head\n node.next = tmp\n if tmp:\n tmp.pre = node\n else:\n self.tail = node\n\n\nclass LRUCache(object):\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.max_cnt = capacity\n self.cnt = 0\n self.vals = {}\n dummy = DoubleLinkedNode('dummy', -1)\n self.linked_list = DoubledLinkedList(dummy)\n\n def get(self, key):\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n node = self.vals.get(key, None)\n if node:\n self.linked_list.move_to_head(node)\n return node.val # don't forget this\n return -1\n\n def put(self, key, value):\n \"\"\"\n :type key: int\n :type value: int\n :rtype: void\n \"\"\"\n node = self.vals.get(key, None)\n if node:\n # should update the key, val here, old same key might have new val!!!\n node.val = value # !!!important\n self.linked_list.move_to_head(node)\n return # no need to return, but should return to quit !!!!\n # return node.val # no need to return\n node = DoubleLinkedNode(key, value)\n if self.cnt >= self.max_cnt:\n old_key = self.linked_list.remove_tail()\n #print(\"old_key\", old_key)\n del self.vals[old_key]\n self.cnt -= 1\n self.vals[key] = node\n self.linked_list.insert(node)\n self.cnt += 1\n\n####################################################################################\n\nclass LRUCache1(object):\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n if capacity <= 0:\n raise ValueError(\"Capacity should be positive integer.\")\n self.vals = {}\n self.cnt = 0\n self.capacity = capacity\n self.visit_list = None\n\n def get(self, key):\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n if key in self.vals:\n target = self.vals[key]\n # update the list\n self.visit_list.remove(target)\n self.visit_list.add_head(target)\n return target.val\n else:\n return -1\n\n def put(self, key, value):\n \"\"\"\n need to think about \n 1) when key already existes in dict, maybe need to update value, maybe not\n 2) adjust the node to head\n 3) if not exist, create new node and update, a) capcity not full, b) capacity full, then need to delete tail\n :type key: int\n :type value: int\n :rtype: void\n \"\"\"\n if key in self.vals:\n node = self.vals[key]\n self.visit_list.remove(node)\n self.visit_list.add_head(node)\n node.val = value\n else:\n node = ListNode(key, value)\n self.vals[key] = node\n # self.visit_list.add_head(node) # when empty list, AttributeError: 'NoneType' object has no attribute 'add_head'\n if not self.visit_list:\n self.visit_list = DoubleList(node)\n else:\n self.visit_list.add_head(node)\n self.cnt += 1\n if self.cnt > self.capacity: # should not have >=, only use > here\n old_key = self.visit_list.tail.key\n self.visit_list.remove_tail()\n del self.vals[old_key]\n self.cnt -= 1\n\n\nclass ListNode(object):\n def __init__(self, key, val):\n self.key = key # looks like key is also necessary, when need to remove tail node and del key in cache\n self.val = val\n self.pre = None\n self.post = None\n\n\nclass DoubleList(object):\n def __init__(self, head):\n self.head = head\n self.tail = head\n\n def remove(self, node):\n if self.head == self.tail:\n self.head, self.tail = None, None\n node.next, node.pre = None, None\n return\n if node == self.head:\n self.head = node.next\n self.head.pre = None\n node.next, node.pre = None, None\n return\n if node == self.tail:\n self.tail = node.pre\n self.tail.next = None\n node.next, node.pre = None, None\n return\n pre, post = node.pre, node.next\n pre.next = post\n post.pre = pre\n node.next, node.pre = None, None\n\n def add_head(self, node):\n if not self.head:\n self.head = node\n self.tail = node\n return\n node.next = self.head\n self.head.pre = node\n self.head = node\n\n def remove_tail(self):\n node = self.tail\n self.remove(node)\n\n\n# Your LRUCache object will be instantiated and called as such:\n# obj = LRUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)\n\n\nclass SolutionTester(unittest.TestCase):\n def setUp(self):\n self.cache = LRUCache(2)\n self.cache.put(1,1)\n self.cache.put(2,2)\n\n def test_case1(self):\n answer = 1\n result = self.cache.get(1)\n self.assertEqual(answer, result)\n\n def test_case2(self):\n self.cache.get(1)\n self.cache.put(3,3) # evict 2\n result = self.cache.get(2)\n answer = -1\n self.assertEqual(answer, result)\n\n def test_case3(self):\n self.cache.get(1)\n self.cache.put(3,3) # evict 2\n self.cache.get(2)\n self.cache.put(4, 4) # evicts 1\n result = self.cache.get(1)\n answer = -1\n self.assertEqual(answer, result)\n\n def test_case4(self):\n self.cache.get(1)\n self.cache.put(3,3) # evict 2\n self.cache.get(2)\n self.cache.put(4, 4) # evicts 1\n self.cache.get(1)\n result = [self.cache.get(3), self.cache.get(4)]\n answer = [3,4]\n self.assertEqual(answer, result)\n\n\ndef main():\n suite = unittest.TestLoader().loadTestsFromTestCase(SolutionTester)\n unittest.TextTestRunner(verbosity=2).run(suite)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n#-*- coding:utf-8 -*-\n\n\"\"\"\n\nhttp://www.cnblogs.com/zuoyuan/p/3701572.html\n\n\n原题地址:http://oj.leetcode.com/problems/lru-cache/\n\n题意:设计LRU Cache\n\n参考文献:http://blog.csdn.net/hexinuaa/article/details/6630384 这篇博文总结的很到位。\n\n     https://github.com/Linzertorte/LeetCode-in-Python/blob/master/LRUCache.py 代码参考的github人写的,思路非常清晰,\n写的也很好。\n\nCache简介:\n\nCache(高速缓存), 一个在计算机中几乎随时接触的概念。CPU中Cache能极大提高存取数据和指令的时间,让整个存储器(Cache+内存)既有Cache的高速度,\n又能有内存的大容量;操作系统中的内存page中使用的Cache能使得频繁读取的内存磁盘文件较少的被置换出内存,从而提高访问速度;数据库中数据查询也\n用到Cache来提高效率;即便是Powerbuilder的DataWindow数据处理也用到了Cache的类似设计。Cache的算法设计常见的有FIFO(first in first out)\n和LRU(least recently used)。根据题目的要求,显然是要设计一个LRU的Cache。\n\n解题思路:\n\nCache中的存储空间往往是有限的,当Cache中的存储块被用完,而需要把新的数据Load进Cache的时候,我们就需要设计一种良好的算法来完成数据块的替\n换。LRU的思想是基于“最近用到的数据被重用的概率比较早用到的大的多”这个设计规则来实现的。\n\n为了能够快速删除最久没有访问的数据项和插入最新的数据项,我们双向链表连接Cache中的数据项,并且保证链表维持数据项从最近访问到最旧访问的顺序。\n每次数据项被查询到时,都将此数据项移动到链表头部(O(1)的时间复杂度)。这样,在进行过多次查找操作后,最近被使用过的内容就向链表的头移动,而\n没有被使用的内容就向链表的后面移动。当需要替换时,链表最后的位置就是最近最少被使用的数据项,我们只需要将最新的数据项放在链表头部,当Cache满\n时,淘汰链表最后的位置就是了。\n\n 注: 对于双向链表的使用,基于两个考虑。首先是Cache中块的命中可能是随机的,和Load进来的顺序无关。其次,双向链表插入、删除很快,可以灵活的\n 调整相互间的次序,时间复杂度为O(1)。\n\n 查找一个链表中元素的时间复杂度是O(n),每次命中的时候,我们就需要花费O(n)的时间来进行查找,如果不添加其他的数据结构,这个就是我们能实\n 现的最高效率了。目前看来,整个算法的瓶颈就是在查找这里了,怎么样才能提高查找的效率呢?Hash表,对,就是它,数据结构中之所以有它,就是因\n 为它的查找时间复杂度是O(1)。\n\n梳理一下思路:对于Cache的每个数据块,我们设计一个数据结构来储存Cache块的内容,并实现一个双向链表,其中属性next和prev是双向链表的两个指针,\nkey用于存储对象的键值,value用于存储cache块对象本身。\n\nCache的接口:\n\n查询:\n\n根据键值查询hashmap,若命中,则返回节点key值对应的value,否则返回-1。\n从双向链表中删除命中的节点,将其重新插入到表头。\n所有操作的复杂度均为O(1)。\n插入:\n\n将新的节点关联到Hashmap\n如果Cache满了,删除双向链表的尾节点,同时删除Hashmap对应的记录\n将新的节点插入到双向链表中头部\n更新:\n\n和查询相似\n删除:\n\n从双向链表和Hashmap中同时删除对应的记录。\n双向链表示意图:\n\n\n\n代码:\n\n复制代码\nclass Node:                          #双向链表中节点的定义\n def __init__(self,k,x):\n self.key=k\n self.val=x\n self.prev=None\n self.next=None\n\nclass DoubleLinkedList:            ��      #双向链表是一个表头,head指向第一个节点,tail指向最后一个节点\n def __init__(self):\n self.tail=None\n self.head=None\n \n def isEmpty():                      #如果self.tail==None,那么说明双向链表为空\n return not self.tail\n def removeLast(self):                  #删除tail指向的节点\n self.remove(self.tail)\n \n def remove(self,node):                  #具体双向链表节点删除操作的实现\n if self.head==self.tail:\n self.head,self.tail=None,None\n return\n if node == self.head:\n node.next.prev=None\n self.head=node.next\n return\n if node ==self.tail:\n node.prev.next=None\n self.tail=node.prev\n return\n node.prev.next=node.next\n node.next.prev=node.prev\n \n def addFirst(self,node):                 #在双向链表的第一个节点前面再插入一个节点  \n if not self.head:\n self.head=self.tail=node\n node.prev=node.next=None\n return\n node.next=self.head\n self.head.prev=node\n self.head=node\n node.prev=None\n\nclass LRUCache:\n\n # @param capacity, an integer\n def __init__(self, capacity):              #初始化LRU Cache\n self.capacity=capacity                #LRU Cache的容量大小             \n self.size=0                      #LRU Cache目前占用的容量\n self.P=dict()                     #dict为文章中提到的hashmap,加快搜索速度,{key:对应节点的地址}\n self.cache=DoubleLinkedList()\n # @return an integer\n def get(self, key):                    #查询操作\n if (key in self.P) and self.P[key]:        #如果key在字典中\n self.cache.remove(self.P[key])         #将key对应的指针指向的节点删除\n self.cache.addFirst(self.P[key])        #然后将这个节点添加到双向链表头部\n return self.P[key].val              #并返回节点的value\n else: return -1\n\n # @param key, an integer\n # @param value, an integer\n # @return nothing\n def set(self, key, value):                #设置key对应的节点的值为给定的value值\n if key in self.P:                   #如果key在字典中\n self.cache.remove(self.P[key])         #先删掉key对应的节点\n self.cache.addFirst(self.P[key])        #然后将这个节点插入到表的头部\n self.P[key].val=value               #将这个节点的值val改写为value\n else:                          #如果key不在字典中\n node=Node(key,value)               #新建一个Node节点,val值为value\n self.P[key]=node                  #将key和node的对应关系添加到字典中\n self.cache.addFirst(node)            #将这个节点添加到链表表头\n self.size +=1                   #容量加1\n if self.size > self.capacity:         #如果链表的大小超过了缓存的大小,删掉最末尾的节点,\n self.size -=1                 #并同时删除最末尾节点key值和末节点在字典中的对应关系\n del self.P[self.cache.tail.key]\n self.cache.removeLast()\n复制代码\n\n\n\"\"\"","sub_path":"freq/LRU_cache.py","file_name":"LRU_cache.py","file_ext":"py","file_size_in_byte":16236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"82434142","text":"import csv\nresult = []\nwith open(\"matematicos.csv\",encoding=\"Latin1\") as f:\n lector = csv.reader(f)\n for linea in lector:\n result.append(linea)\n\nwith open('office.csv', 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerows(sorted(result,key=lambda x: x[2]))\n","sub_path":"sort_mathematician.py","file_name":"sort_mathematician.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"368370930","text":"from lucyparser import parse\nfrom lucyparser.exceptions import BaseLucyException\nfrom lucyparser.tree import BaseNode\n\nfrom ..utils import LuceneSearchException\n\n\nclass BaseLuceneParserMixin:\n @classmethod\n def parse(cls, raw_expression: str):\n \"\"\"\n Parses raw expression to query tree\n \"\"\"\n\n try:\n tree = parse(string=raw_expression)\n except BaseLucyException:\n raise LuceneSearchException()\n\n parsed_tree = cls._parse_tree(tree=tree)\n\n if parsed_tree is None:\n raise LuceneSearchException()\n\n return parsed_tree\n\n @classmethod\n def _parse_tree(cls, tree: BaseNode):\n \"\"\"\n Parses lucyparsers tree to query tree\n \"\"\"\n raise NotImplementedError()\n","sub_path":"src/parser/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"87496247","text":"from django.contrib.auth.models import User\nfrom run_core.models import AddmDev, ADDMCommands\nfrom octo_tku_patterns.models import TestLast, TestHistory\nfrom octo_tku_upload.models import TkuPackagesNew as TkuPackages\nfrom octo_tku_upload.models import UploadTestsNew as UploadTests\nfrom rest_framework import routers, serializers, viewsets\n\n\n# Serializers define the API representation.\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'is_staff')\n\n\nclass TestLastSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = TestLast\n fields = (\n 'tkn_branch',\n 'pattern_library',\n 'pattern_folder_name',\n 'test_py_path',\n 'tst_name',\n 'tst_module',\n 'tst_class',\n 'tst_message',\n 'tst_status',\n 'fail_message',\n 'addm_name',\n 'addm_group',\n 'addm_v_int',\n 'addm_host',\n 'addm_ip',\n 'time_spent_test',\n 'test_date_time',\n )\n\n\nclass TestHistorySerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = TestHistory\n fields = (\n 'tkn_branch',\n 'pattern_library',\n 'pattern_folder_name',\n 'test_py_path',\n 'tst_name',\n 'tst_module',\n 'tst_class',\n 'tst_message',\n 'tst_status',\n 'fail_message',\n 'addm_name',\n 'addm_group',\n 'addm_v_int',\n 'addm_host',\n 'addm_ip',\n 'time_spent_test',\n 'test_date_time',\n )\n\n\nclass TkuPackagesSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = TkuPackages\n fields = (\n 'zip_file_path',\n 'zip_file_name',\n 'package_type',\n 'tku_type',\n 'zip_type',\n 'addm_version',\n 'tku_name',\n 'tku_addm_version',\n 'tku_build',\n 'tku_date',\n 'tku_month',\n 'tku_pack',\n )\n\n\nclass UploadTestsSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = UploadTests\n fields = (\n 'test_case_key',\n 'test_mode',\n 'mode_key',\n 'test_date',\n 'test_time',\n 'upload_test_status',\n 'upload_test_str_stdout',\n 'upload_test_str_stderr',\n 'important_out',\n 'all_errors',\n 'all_warnings',\n 'upload_warnings',\n 'upload_errors',\n 'tku_statuses',\n 'time_spent_test',\n 'tested_zips',\n 'addm_name',\n 'addm_v_int',\n 'addm_host',\n 'addm_ip',\n 'addm_version',\n 'tku_type',\n 'package_type',\n 'tku_build',\n 'tku_date',\n 'tku_month',\n )\n\n\nclass AddmDevSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = AddmDev\n fields = (\n 'addm_host',\n 'addm_name',\n 'tideway_user',\n 'tideway_pdw',\n 'addm_ip',\n 'addm_v_int',\n 'addm_full_version',\n 'addm_group',\n 'disables',\n )\n\nclass ADDMCommandsSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = ADDMCommands\n fields = (\n 'command_key',\n 'command_value',\n 'private',\n 'interactive',\n 'description',\n 'created_at',\n )\n\n# ViewSets define the view behavior.\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass TestLastViewSet(viewsets.ModelViewSet):\n queryset = TestLast.objects.all()\n serializer_class = TestLastSerializer\n\n\nclass TestHistoryViewSet(viewsets.ModelViewSet):\n queryset = TestHistory.objects.all()\n serializer_class = TestHistorySerializer\n\n\nclass TkuPackagesViewSet(viewsets.ModelViewSet):\n queryset = TkuPackages.objects.all()\n serializer_class = TkuPackagesSerializer\n\n\nclass UploadTestsViewSet(viewsets.ModelViewSet):\n queryset = UploadTests.objects.all()\n serializer_class = UploadTestsSerializer\n\n\nclass AddmDevViewSet(viewsets.ModelViewSet):\n queryset = AddmDev.objects.all()\n serializer_class = AddmDevSerializer\n\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\n\nrouter.register(r'tku_packages', TkuPackagesViewSet)\n\nrouter.register(r'tests_last', TestLastViewSet)\nrouter.register(r'tests_history', TestHistoryViewSet)\nrouter.register(r'upload_tests', UploadTestsViewSet)\n\nrouter.register(r'addm_dev', AddmDevViewSet)\n","sub_path":"octo/octo_serializers.py","file_name":"octo_serializers.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"42152715","text":"import matplotlib\nmatplotlib.use('Agg')\n\nimport sys\nsys.path.append(\"/home/hrushikesh/dl4cv/preprocessing\")\nsys.path.append(\"/home/hrushikesh/dl4cv/callbacks\")\nsys.path.append(\"/home/hrushikesh/dl4cv/io\")\nsys.path.append(\"/home/hrushikesh/dl4cv/fer2013\")\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nos.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\nfrom config import emotion_config as config\nfrom emotionvggnet import EmotionVGGNet\nfrom imagetoarraypreprocessor import ImageToArrayPreprocessor\nfrom trainingmonitor import TrainingMonitor\nfrom epochcheckpoint import EpochCheckpoint\nfrom hdf5datasetgenerator import HDF5DatasetGenerator\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.optimizers import SGD \nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import load_model\nimport tensorflow.keras.backend as K\nimport argparse\nfrom sklearn.metrics import classification_report\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-c\", \"--checkpoints\", required=True, help=\"path to output checkpoint directory\")\nap.add_argument(\"-m\", \"--model\", type=str, help=\"path to *specific* model checkpoint to load\")\nap.add_argument(\"-s\", \"--start_epoch\", type=int, default=0, help=\"epoch to restart training at\")\nargs = vars(ap.parse_args())\n\n# construct the training and testing image generators for data augmentation,then initialize the image preprocessors\ntrainAug = ImageDataGenerator(horizontal_flip=True, rescale=1/ 225.0)#, zoom_range=0.1, rotation_range=10, rescale=1/ 255.0) \nvalAug = ImageDataGenerator(rescale=1/ 255.0)\niap = ImageToArrayPreprocessor()\n\n# initalize the training and validation dataset generators\ntrainGen = HDF5DatasetGenerator(config.TRAIN_HDF5, config.BATCH_SIZE, aug=trainAug, preprocessors=[iap], classes=config.NUM_CLASSES)\nvalGen = HDF5DatasetGenerator(config.VAL_HDF5, config.BATCH_SIZE, aug=valAug, preprocessors=[iap], classes=config.NUM_CLASSES)\n\n# if there is no specific model checkpoint supplied, then initalize the network and compile the model\nif args[\"model\"] is None:\n print(\"[INFO] compiling model...\")\n model = EmotionVGGNet.build(width=48, height=48, depth=1, classes=config.NUM_CLASSES)\n #opt = Adam(lr=1e-3)\n opt = SGD(lr=1e-2, momentum=0.9, nesterov=True)\n model.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n# otherwise load the checkpoint from disk\nelse:\n print(\"[INFO] loading {}...\".format(args[\"model\"]))\n model = load_model(args[\"model\"])\n\n # update the learning rate\n print(\"[INFO] old learning rate: {}\".format(K.get_value(model.optimizer.lr)))\n K.set_value(model.optimizer.lr, 1e-3)\n print(\"[INFO] new learning rate:{}\".format(K.get_value(model.optimizer.lr)))\n \n# construct the set of callbacks\nfigPath = os.path.sep.join([config.OUTPUT_PATH, \"vggnet_emotion.png\"])\njsonPath = os.path.sep.join([config.OUTPUT_PATH, \"vggnet_emotion.json\"])\ncallbacks = [\n EpochCheckpoint(args[\"checkpoints\"], every=5, startAt=args[\"start_epoch\"]),\n TrainingMonitor(figPath, jsonPath=jsonPath, startAt=args[\"start_epoch\"])]\n# train the network\nmodel.fit_generator(\n trainGen.generator(),\n steps_per_epoch = trainGen.numImages // config.BATCH_SIZE,\n validation_data = valGen.generator(),\n validation_steps = valGen.numImages // config.BATCH_SIZE,\n epochs = 70,\n max_queue_size = config.BATCH_SIZE * 2,\n initial_epoch = args[\"start_epoch\"],\n callbacks = callbacks, verbose = 2)\n\n# close the databases\ntrainGen.close()\nvalGen.close()\n\n","sub_path":"fer2013/emotion_recognition/train_recognizer.py","file_name":"train_recognizer.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"300156258","text":"# A number's summationo is the sum of all positive numbers\r\n# less than or equal to the number. For example, the summation\r\n# of 3 is 6 because 1 + 2 + 3 = 6.\r\n#\r\n# Write a method summation_sequence that takes in a two numbers:\r\n# start and length. The method should return an array containing\r\n# length total elements. The first number of the sequence should\r\n# be the start number. At any point, to generate the next element\r\n# of the sequence, we take the summation of the previous element.\r\n# You can assume length is not zero.\r\n\r\ndef summation(number):\r\n return sum(range(1, number + 1))\r\n\r\ndef summation_sequence(start, length):\r\n if(length < 1):\r\n return []\r\n \r\n arr = [start]\r\n for _ in range(length - 1):\r\n arr.append(summation(arr[len(arr) - 1]))\r\n \r\n return arr\r\n\r\nif __name__ == \"__main__\":\r\n print(summation_sequence(3, 4))\r\n print(summation_sequence(5, 3))","sub_path":"Intro_To_Ruby_Programming_II/Advanced_Problems/Summation_Sequence.py","file_name":"Summation_Sequence.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"135251158","text":"# Files needed\nprefix = \"configs/\"\nenduros_json = prefix + \"enduros.json\"\nupdates_txt = prefix + \"updates.txt\"\nall_activities_json = prefix + \"all_activities.json\"\nmtb_ride_activities_json = prefix + \"mtb_ride_activities.json\"\nenduro_attempts_json = prefix + \"enduro_attempts.json\"\ndetailed_segments_json = prefix + \"detailed_segments.json\"\nenduro_attempts_pickle = prefix + \"enduro_attempts.p\"\n\n# Strava Athlete information\nathlete_id = '33719269'\n# Strava Information\nstrava_info = {\n 'client_id' : '65128',\n 'client_secret' : '5c5310cdc850bbb385539831b6c07d7d19cc2730',\n 'refresh_token' : 'ae87c5d5b420a4019007a66815324b74dcd0f11d',\n 'grant_type' : 'refresh_token'\n}\n\n# Storage Types\nPICKLE = \"PICKLE\"\nDATABASE = \"DATABASE\"\nJSON = \"JSON\"\nDEFAULT_STORAGE_TYPE = PICKLE\n","sub_path":"consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"539310479","text":"import platform\nimport subprocess\nimport sys\n\nsystem = platform.system()\n_system_calls = ['restart', 'sleep']\n\n\ndef invoke_system_call(type_):\n assert type_ in _system_calls\n subprocess.call(['osascript', '-e', 'tell app \"System Events\" to %s' % type_])\n\n\ndef imply_extensions_from_system():\n if system == 'Windows':\n return '.exe'\n elif system == 'Darwin':\n return '.dmg'\n else:\n raise SystemError('Unsupported OS system.')\n\n\ndef open_program(data):\n app = ''.join(data[1:])\n ext = imply_extensions_from_system()\n cmd = '%s' % app + ext\n return app, cmd\n\n\ndef restart(request):\n return request.update(\n {\n 'action': 'os restart',\n 'response': 'Restarting your system.',\n 'queue': lambda x: invoke_system_call('restart')\n }\n )\n\n\ndef gideon_quit(request):\n return request.update(\n {\n 'action': 'quit',\n 'response': 'Assistant stopping now.',\n 'queue': lambda x: sys.exit()\n }\n )\n\n\ndef sleep(request):\n return request.update(\n {\n 'action': 'os sleep',\n 'response': 'Putting your system to sleep.',\n 'queue': lambda x: invoke_system_call('sleep')\n }\n )\n\n\ndef unable_to_process(request):\n return request.update(\n {\n 'action': 'unable to process',\n 'response': 'Did not understand your request.',\n }\n )\n","sub_path":"core/plugins/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"235268783","text":"import requests\nfrom bs4 import BeautifulSoup\n\ncmc_url = 'https://coinmarketcap.com/all/views/all/'\n\nrequest_url = requests.get(cmc_url)\npage_decoded = request_url.content.decode('utf-8')\nsoup = BeautifulSoup(page_decoded, \"lxml\")\nfor link in soup.find_all('a', {\"class\": \"currency-name-container link-secondary\"}):\n currency = link.string\n with open('coin_list.txt', 'a') as file:\n file.write(currency + '\\n')\n","sub_path":"cmc_coin_list.py","file_name":"cmc_coin_list.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"334587515","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1675]:\n\n\nimport pandas\nimport numpy as np\n#for chisquare\nfrom scipy.stats import chi2\n\n#we are reading the csv\ntotaldataset = pandas.read_csv(\"training.csv\", header=None)\n\n\n# In[1676]:\n\n\n#coverting the DataFrame to a Numpy array\ndataset_numpy = totaldataset.to_numpy()\n#deleting the first column \nmatrix = np.delete(dataset_numpy, 0, 1)\n#splitting the dna into 60 and appending labels to that list forming a list of 61 elements\nreshape_numpy = []\nfor row in matrix:\n dna_seq = row[0]\n dna_list = list(dna_seq)\n dna_list.append(row[1])\n reshape_numpy.append(dna_list)\n\nnp_dataset = np.array(reshape_numpy)\n\n\n# In[1677]:\n\n\ndef gini_index(column): #function to find impurity via gini_index at parent\n # we find all the unique lables and their counts\n labels, num_labels = np.unique(column,return_counts = True)\n total_gini = 0\n gini_label = 0\n #for each label we find the gini, sum them up and do 1 - the sum\n for i in range(len(num_labels)):\n percentage_of_label = num_labels[i] / len(column)\n gini_label += percentage_of_label**2\n total_gini = 1 - gini_label\n return total_gini\n\n\n# In[1678]:\n\n\ndef misclassification_error(column): #function to find impurity via misclassification_error at parent\n # we find all the unique lables and their counts\n labels, num_labels = np.unique(column,return_counts = True)\n total_misclass = 0\n percentage_of_label=[]\n #for each label we find misclassication_error and do 1 - the maximum \n for i in range(len(num_labels)):\n ind_percentage_of_label = num_labels[i] / len(column)\n percentage_of_label.append(ind_percentage_of_label)\n misclass_label = np.max(percentage_of_label)\n total_misclass = 1 - misclass_label\n return total_misclass\n\n\n# In[1679]:\n\n\ndef entropy(column): #function to find impurity via entropy at parent\n # we find all the unique lables and their counts \n labels, num_labels = np.unique(column,return_counts = True)\n total_entropy = 0\n #for each label we find entropy and sum them up\n for i in range(len(num_labels)):\n percentage_of_label = num_labels[i] / len(column)\n entropy_label = (-1) * percentage_of_label * np.log2(percentage_of_label)\n total_entropy += entropy_label\n return total_entropy\n\n\n# In[1680]:\n\n\ndef InformationGain(current_dataset, column_name, class_label, method=\"gini\"): #function to find information gain via diff methods.\n \n #We created a nested dictionary that holds the values and counts of the char_val i.e.., 'A','G'...and the char_class_label i.e.., 'N', 'IE', 'EI'\n \n hash_map = {}\n for index, char_val in np.ndenumerate(current_dataset[:, column_name]):\n value_index = index[0]\n char_class_label = current_dataset[:, class_label][value_index]\n if char_val not in hash_map:\n hash_map[char_val] = {}\n if char_class_label not in hash_map[char_val]:\n hash_map[char_val][char_class_label] = 1\n else:\n hash_map[char_val][char_class_label] += 1\n else:\n if char_class_label not in hash_map[char_val]:\n hash_map[char_val][char_class_label] = 1\n else:\n hash_map[char_val][char_class_label] += 1\n \n #Based on the method called one of entropy, gini, or misclass will be executed.\n if method == \"gini\":\n total_gini = gini_index(current_dataset[:, class_label])\n sum_gini =0\n # for each char in the map, we find the gini and sum it all up\n for char in hash_map.keys():\n labels_counts = hash_map[char].values()\n char_gini = 0\n gini_char_label = 0\n for char_label_count in labels_counts:\n percentage_char_label = char_label_count / sum(labels_counts)\n gini_char_label+= percentage_char_label**2 \n char_gini = 1- gini_char_label\n sum_gini += sum(labels_counts)/ len(current_dataset[:, column_name]) * char_gini\n Information_Gain = total_gini - sum_gini\n return Information_Gain\n \n elif method == \"entropy\":\n total_entropy = entropy(current_dataset[:, class_label])\n sum_entropy = 0\n # for each char in the map, we find the entropy and sum it all up\n for char in hash_map.keys():\n labels_counts = hash_map[char].values()\n char_entropy = 0\n for char_label_count in labels_counts:\n percentage_char_label = char_label_count / sum(labels_counts)\n entropy_char_label = (-1) * percentage_char_label * np.log2(percentage_char_label)\n char_entropy += entropy_char_label\n sum_entropy += sum(labels_counts)/ len(current_dataset[:, column_name]) * char_entropy\n Information_Gain = total_entropy - sum_entropy\n return Information_Gain\n \n else:\n if method ==\"misclass\":\n total_misclass = misclassification_error(current_dataset[:, class_label])\n sum_misclass =0\n # for each char in the map, we find the misclass and sum it all up\n for char in hash_map.keys():\n labels_counts = hash_map[char].values()\n char_misclass = 0\n percentage_char_label=[]\n for char_label_count in labels_counts:\n ind_percentage_char_label = char_label_count / sum(labels_counts)\n percentage_char_label.append(ind_percentage_char_label)\n misclass_char_label = np.max(percentage_char_label)\n char_misclass =1-misclass_char_label\n sum_misclass += sum(labels_counts)/ len(current_dataset[:, column_name]) * char_misclass\n Information_Gain = total_misclass - sum_misclass\n return Information_Gain\n\n\n# In[1681]:\n\n\ndef ChiSquare(current_dataset, column_name, class_label=60): #find chiSquare for a column\n result_chi = 0\n unique_chars = np.unique(current_dataset[:, column_name]) #find unique chars ('A','G'..) \n for char in unique_chars:\n branch_dataset = current_dataset[current_dataset[:, column_name] == char] #take a certain char to loop through\n branch_class_names, branch_class_counts = np.unique(branch_dataset[:, class_label], return_counts=True) #collect all the counts of unique labels of that char\n for cls in branch_class_names:\n cls_index = list(branch_class_names).index(cls)\n cls_count = branch_class_counts[cls_index]\n real_n_count = cls_count #get the real count of labels that belong to char\n left_expected = len(branch_dataset) # total branch length\n parent_cls_names, parent_cls_count = np.unique(current_dataset[:, class_label], return_counts=True)\n parent_n_index = list(parent_cls_names).index(cls)\n right_expected = parent_cls_count[parent_n_index] / len(current_dataset)\n expected = left_expected * right_expected\n chi = (real_n_count - expected) ** 2 / expected\n result_chi += chi\n \n freedom = (len(unique_chars) - 1 ) * (len(np.unique(current_dataset[:, class_label])) -1 )\n critical_value = chi2.ppf(0.99, freedom) #calc crit value based on freedom and confidence\n if result_chi > critical_value:\n keep_building = True\n else:\n keep_building = False\n return keep_building\n\n\n# In[1682]:\n\n\ndef ID3Algorithm(current_dataset, completedataset, characteristics, labels_column=60, upper_node_label = \"N\"): #we are considering each column positon as a characteristics\n #for the current data if there is only one label in the 60th column, then return that\n if len(np.unique(current_dataset[:, labels_column])) <= 1:\n return np.unique(current_dataset[:, labels_column])[0]\n #if the len of the data is zero then return label which has the highest count in the complete data\n elif len(current_dataset)==0:\n return np.unique(completedataset[:, labels_column])[\n np.argmax(np.unique(completedataset[:, \n labels_column],return_counts=True)[1])]\n #if there are no more features, then we return the label of the parent node\n elif len(characteristics) ==0:\n return upper_node_label\n else:\n upper_node_label = np.unique(current_dataset[:, labels_column])[\n np.argmax(np.unique(current_dataset[:, labels_column],return_counts=True)[1])]\n #ig_set has the list of all IG of all characteristics\n ig_set = [InformationGain(current_dataset,characteristic,labels_column,\"misclass\") for characteristic in characteristics]\n #top_characteristic_index has the index of the highest value of ig_set\n top_characteristic_index = np.argmax(ig_set)\n #we find the top_characteristic from the list using index\n top_characteristic = characteristics[top_characteristic_index]\n #we add that characteristic to a dictionary\n tree = {top_characteristic:{}}\n #A list characteristics puts in the characteristics as long as it's not equal to the best characteristic\n characteristics = [i for i in characteristics if i != top_characteristic]\n #Check is it is noteworthy to keep building the tree by running the chisquare test\n if (ChiSquare(current_dataset, top_characteristic)):\n for col_value in np.unique(current_dataset[:, top_characteristic]):\n col_value = col_value\n sub_dataset = current_dataset[current_dataset[:, top_characteristic] == col_value] \n subtree = ID3Algorithm(sub_dataset, completedataset, \n characteristics, labels_column, upper_node_label) \n tree[top_characteristic][col_value] = subtree\n return(tree)\n else:\n upper_label_node = np.unique(current_dataset[:, labels_column])[\n np.argmax(np.unique(current_dataset[:, \n labels_column],return_counts=True)[1])]\n return(upper_label_node)\n\n\n# In[1683]:\n\n\ndef predict(instance, tree):\n attribute = list(tree.keys())[0]\n if instance[attribute] in list(tree[attribute].keys()):\n result = tree[attribute][instance[attribute]]\n if isinstance(result, dict):\n return predict(instance, result)\n elif result is not None:\n return result\n else:\n return \"N\"\n else:\n return \"N\"\n\n\n# In[1684]:\n\n\ntree = ID3Algorithm(np_dataset, np_dataset, [i for i in range(0, 60)])\n\n\n# In[1685]:\n\n\ntest_dataset = pd.read_csv(\"testing.csv\", header=None).to_numpy()\n\nresult = [[row[0], predict(row[1], tree)] for row in test_dataset]\n\npandas_frame = pd.DataFrame(result)\n\npandas_frame.to_csv(\"cs529_dna_test_misclass_edited_chi2_2_final.csv\")\n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":10892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"130522365","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 20 12:47:58 2019\n\n@author: George\n\"\"\"\n\nimport numpy as np\nimport tifffile\nimport os\nfrom os import listdir\nfrom os.path import expanduser, isfile, join\nfrom matplotlib import pyplot as plt\n\nvolume_path = r'C:\\Users\\George\\Dropbox\\UCI\\shared\\volume\\light_sheet_vols0'\n\ndef get_permutation_tuple(src, dst):\n \"\"\"get_permtation_tuple(src, dst)\n\n Parameters:\n src (list): The original ordering of the axes in the tiff.\n dst (list): The desired ordering of the axes in the tiff.\n\n Returns:\n result (tuple): The required permutation so the axes are ordered as desired.\n \"\"\"\n result = []\n for i in dst:\n result.append(src.index(i))\n result = tuple(result)\n return result\n\ndef openTiff(filename):\n Tiff = tifffile.TiffFile(str(filename))\n A = Tiff.asarray()\n Tiff.close()\n axes = [tifffile.AXES_LABELS[ax] for ax in Tiff.series[0].axes]\n if set(axes) == set(['series', 'height', 'width']): # single channel, multi-volume\n target_axes = ['series', 'width', 'height']\n perm = get_permutation_tuple(axes, target_axes)\n A = np.transpose(A, perm)\n return A\n\nA_list = []\n\n#get volume files in folder\nvols = [f for f in listdir(volume_path) if isfile(join(volume_path, f))]\n#add volumes to volume list\nfor i in range(len(vols)):\n file = join(volume_path, vols[i])\n A_list.append(openTiff(file))\n \nfilename =r'C:\\Users\\George\\Desktop\\UCI\\stackforGeorge_150slice_step2.tif'\noriginal = openTiff(filename)\n\ntest = A_list[0]\n\ntest1 = A_list[0][0,::]\ntest2 = A_list[0][10,::]\n\nnewdisplayImage = A_list[0][0,::]\n\nfor i in np.arange(1,len(A_list)):\n newdisplayImage = np.dstack((newdisplayImage, A_list[i][0,::]))\n\n\n\n\n\n\n#plt.figure(1)\n#fig1 = plt.imshow(test1)\n#plt.figure(2)\n#fig2 = plt.imshow(test2)\n#plt.show()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"openTiff.py","file_name":"openTiff.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"430145279","text":"from pyparsing import *\n\nclass BibKV(object):\n def __init__(self, kv_list):\n self._ind = {}\n self._backing_list = kv_list\n for i in range(0, len(kv_list)):\n self._ind[kv_list[i][0].lower()] = i\n def __getitem__(self, key):\n key = key.lower()\n if key not in self._ind:\n raise KeyError()\n return self._kv_ref(key)[1]\n def __setitem__(self, key, value):\n key = key.lower()\n if key not in self._ind:\n raise KeyError()\n self._kv_ref(key)[1] = value\n def _kv_ref(self, key):\n return self._backing_list[self._ind[key]]\n def __contains__(self, key):\n return key.lower() in self._ind\n def __iter__(self):\n return iter([ kv[0] for kv in self._backing_list ])\n\nclass BibWrapper(object):\n def __init__(self, type, ident, kv):\n self.type = type\n self.ident = ident\n self.kv = kv\n def filter_mapping(self, l):\n new_kv = []\n for k in self.kv:\n if not l(k):\n continue\n new_kv.append([k, self.kv[k]])\n self.kv = BibKV(new_kv)\n\nlit_open = Suppress('{')\nlit_close = Suppress('}')\nlit_comma = Suppress(',')\nequals = Suppress('=')\n\nno_comma = Regex(r\"[^,]+\")\nkey = Word(alphas + \"_\")\nnon_brace = Regex(r\"[^{}]+\")\nbrace_value = Forward().addParseAction(lambda s: \"\".join(s.asList()))\nbrace_delim = (Literal(\"{\") + ZeroOrMore(brace_value) + Literal(\"}\"))\nbrace_value <<= (brace_delim | non_brace)\nvalue = brace_delim.addParseAction(lambda s: \"\".join(s.asList())) | no_comma\n\nkey_item = Group(key + equals + Group(value).addParseAction(lambda s: s.asList()[0]))\n\nkey_item_list = Group(delimitedList(key_item, delim=',') + Optional(Suppress(\",\")))\n\ntype_start = Suppress(\"@\") + non_brace\n\nbib_item = Group(type_start + lit_open + no_comma + lit_comma + key_item_list + lit_close)\n\nitems = OneOrMore(bib_item) + StringEnd()\n\ndef parse_items(blob):\n return [ BibWrapper(item[0], item[1], BibKV(item[2])) for item in \\\n items.parseString(blob).asList() ]\n","sub_path":"bibparse.py","file_name":"bibparse.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"396773961","text":"from tkinter import messagebox\nfrom tkinter import Listbox\nimport sqlalchemy\nimport pandas as pd\nimport os\n\nBASE_DIR = os.path.abspath('.')\nBASE_DIR = os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) )\nDATA_DIR = os.path.join( BASE_DIR, 'data' )\nSQL_DIR = os.path.join( BASE_DIR, 'sql' )\n\ndef connect_db():\n '''Função para conectar automaticamente ao banco de dados.'''\n return sqlalchemy.create_engine('sqlite:///' + os.path.join(DATA_DIR, 'data.db'))\n\ndef insert_value( value, value_type ):\n '''Função para realizar insert de novo tipo de categoria/cor/etc no banco de dados.\n É realizada a validação se o valor já existe'''\n\n field = 'ds_' + value_type if type(value) == str else 'nr_' + value_type\n cod_field = 'cod_' + value_type\n tb_field = 'tb_' + value_type\n \n con = connect_db()\n try:\n query_exists_values = 'SELECT DISTINCT {field} AS {field} FROM tb_{value_type}'.format(field=field, value_type=value_type )\n exists_values = pd.read_sql_query( query_exists_values, con)[field]\n exists_values = [ i.lower() for i in exists_values ]\n\n if value.lower() in exists_values:\n messagebox.showinfo( \"Erro\", \"Esse(a) {value_type} já existe!\".format(value_type=value_type) )\n return None\n\n query_cod = \"SELECT MAX({cod_field}) AS {cod_field} FROM tb_{value_type}\".format(cod_field=cod_field, value_type = value_type)\n cod_value = pd.read_sql_query( query_cod, con)[cod_field][0] + 1\n \n except:\n cod_value = 1\n\n df = pd.DataFrame( {field: [value], cod_field: [cod_value] } )\n df.to_sql( tb_field, con, index=False, if_exists='append' )\n messagebox.showinfo(\"Sucesso!\", \"{value_type} cadastrado(a) com sucesso!\".format( value_type = value_type ) )\n\ndef insert_material(data, update=False):\n \n if type(data) == type(None):\n messagebox.showinfo(\"Erro!\", \"Descrição não pode ser nula\")\n return None\n\n con = connect_db()\n\n try:\n lista_material = pd.read_sql_query( \"SELECT DISTINCT ds_descricao AS ds_descricao FROM tb_materiais\", con )[\"ds_descricao\"]\n lista_material = [ i.lower() for i in lista_material.tolist()]\n\n if data[\"ds_descricao\"][0].lower() in lista_material and not update:\n messagebox.showinfo(\"Erro\", \"Você está inserindo um produto que já possui essa descrição!\")\n return None\n\n elif data[\"ds_descricao\"][0].lower() in lista_material and update:\n delete_from_db( data[\"ds_descricao\"][0], \"descricao\", 'tb_materiais', verbose=False )\n\n cod_material = pd.read_sql_query( 'SELECT MAX(cod_material) as cod_material FROM tb_materiais', con )['cod_material'].tolist()[0]\n data[\"cod_material\"] = cod_material + 1\n except:\n data[\"cod_material\"] = 1\n\n data.to_sql( \"tb_materiais\", con, if_exists=\"append\", index=False )\n messagebox.showinfo(\"Sucesso!\", \"Material Cadastrado com sucesso!\")\n\n\ndef import_materiais(file_name):\n '''Realiza a importação de um arquivo xlsx ou csv para um conjunto de materiais'''\n\n if file_name.endswith(\".csv\"):\n data = pd.read_csv( file_name, sep=\";\", decimal=\",\" )\n\n elif file_name.endswith(\".xlsx\"):\n data = pd.read_excel( file_name )\n\n columns = ['ds_descricao', 'ds_categoria', 'ds_cor', 'nr_largura', 'nr_comprimento', 'nr_altura', 'nr_peso']\n data = data[columns]\n\n con = connect_db()\n try:\n cod_material = pd.read_sql_query( 'SELECT MAX(cod_material) as cod_material FROM tb_materiais', con )['cod_material'].tolist()[0]\n data[\"cod_material\"] = data.index + 1 + cod_material\n except:\n data[\"cod_material\"] = data.index + 1\n\n data.to_sql( \"tb_materiais\", con, if_exists='append', index=False )\n messagebox.showinfo(\"Sucesso!\", \"Base importada com sucesso!\")\n\ndef delete_from_db( value, value_type, tb, verbose = True):\n field = 'ds_' + value_type if type(value) == str else 'nr_' + value_type\n query = '''DELETE FROM {tb} WHERE {field} = '{value}';'''.format( tb=tb, field=field, value=value )\n con = connect_db()\n con.execute( query )\n if verbose:\n messagebox.showinfo(\"Sucesso!\", \"Registro deletado com sucesso!\")\n","sub_path":"src/dbtools.py","file_name":"dbtools.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"26546178","text":"\"\"\"\nGiven an array arr of integer elements, the task is to find the range and coefficient of range of the given array where: \nRange: Difference between the maximum value and the minimum value in the distribution. \nCoefficient of Range: (Max – Min) / (Max + Min).\nExamples: \n \n\nInput: arr[] = {15, 16, 10, 9, 6, 7, 17} \nOutput: Range : 11 \nCoefficient of Range : 0.478261 \nMax = 17, Min = 6 \nRange = Max – Min = 17 – 6 = 11 \nCoefficient of Range = (Max – Min) / (Max + Min) = 11 / 23 = 0.478261\nInput: arr[] = {5, 10, 15} \nOutput: Range : 10 \nCoefficient of Range : 0.5 \n\"\"\"\nimport sys\ndef solution(arr):\n min_v=sys.maxsize\n max_v=0\n for item in arr:\n if(item>max_v):\n max_v=item\n if(item> 64)\n the_vertex['_key'] = v.upper() + \"-\" + the_vertex['node_id']\n node_val_ids[v][row_val] = the_vertex['_key']\n\n self.load_vertex_attributes(row, the_vertex, v )\n\n vertex_colls[v].insert(the_vertex)\n record_vertex_keys[v] = node_val_ids[v][row_val]\n\n #insert the edges\n for ename in edge_names:\n from_vertex = self.edge_dict[ename]['from']\n to_vertex = self.edge_dict[ename]['to']\n edge_key = record_vertex_keys[from_vertex] + \"-\" + \\\n record_vertex_keys[to_vertex]\n the_edge = {\"_key\" : edge_key,\\\n \"_from\": from_vertex + \"/\" + record_vertex_keys[from_vertex],\\\n \"_to\": to_vertex + \"/\" + record_vertex_keys[to_vertex]}\n edge_colls[ename].insert(the_edge)\n\n\n\n except Exception as e:\n traceback.print_exc()\n breakpoint()\n\n #breakpoint()\n\n\n t1 = time.time()\n et = float((t1 -t0) / 60)\n et = round(et, 2)\n print(\"Data load took \" + str(et) + \" minutes!.\")\n print(\"Done loading data!\")\n\n return\n\n def load_vertex_attributes(self, row, the_vertex, vertex_name):\n\n if vertex_name == 'incident':\n self.load_incident_attributes(row, the_vertex)\n if vertex_name == 'customer':\n self.load_customer_attributes(row, the_vertex)\n if vertex_name == 'support_org':\n self.load_support_org_attributes(row, the_vertex)\n if vertex_name == 'vendor':\n self.load_vendor_attributes(row, the_vertex)\n\n return\n\n def load_incident_attributes(self, row, the_vertex):\n subset_dict = row[self.feature_dict['incident']].to_dict()\n\n\n for a in subset_dict:\n the_vertex[a] = subset_dict[a]\n\n return\n\n def load_customer_attributes(self, row, the_vertex):\n\n subset_dict = row[self.feature_dict['customer']].to_dict()\n\n for a in subset_dict:\n the_vertex[a] = subset_dict[a]\n\n return\n\n def load_support_org_attributes(self, row, the_vertex):\n\n subset_dict = row[self.feature_dict['support_org']].to_dict()\n\n for a in subset_dict:\n the_vertex[a] = subset_dict[a]\n\n return\n\n def load_vendor_attributes(self, row, the_vertex):\n\n subset_dict = row[self.feature_dict['vendor']].to_dict()\n\n for a in subset_dict:\n the_vertex[a] = subset_dict[a]\n\n return\n\n def load_num_mods(self, row, the_vertex):\n\n return\n\n\n def load_data_from_db(self):\n query = 'FOR doc in incident\\\n FOR s IN 1..1 OUTBOUND doc `incident-support_org`\\\n FOR c IN 1..1 OUTBOUND doc `incident-customer`\\\n FOR v IN 1..1 OUTBOUND doc `incident-vendor`\\\n RETURN { incident: doc, support_org: s, customer: c, vendor: v,\\\n reassigned: doc.reassigned}'\n\n cursor = self.db.aql.execute(query)\n sgdata = {ename : nx.DiGraph() for ename in self.edge_dict}\n rsgdata = {ename : nx.DiGraph() for ename in self.edge_dict}\n labels = []\n for doc in cursor:\n node_data = {v: dict() for v in self.vertex_list}\n edge_data = {ename: list() for ename in self.edge_dict}\n labels.append(doc['reassigned'])\n for v in self.vertex_list:\n a_vdata = doc[v]\n a_vattrib = dict()\n for k,val in a_vdata.items():\n if not k.startswith('_'):\n a_vattrib[k] = a_vdata[k]\n node_info = node_data[v]\n node_info['node_id'] = a_vdata['node_id']\n node_info['attrib'] = a_vattrib\n # done with vertices, set up edges now\n for ename in self.edge_dict:\n from_vertex = self.edge_dict[ename]['from']\n to_vertex = self.edge_dict[ename]['to']\n node_id_from = node_data[from_vertex]['node_id']\n node_id_to = node_data[to_vertex]['node_id']\n\n edge_data[ename].append((node_id_from, node_id_to))\n # set the networkx graph for this doc\n sg = sgdata[ename]\n node_attr_from = node_data[from_vertex]['attrib']\n node_attr_to = node_data[to_vertex]['attrib']\n self.feature_data[from_vertex][node_id_from] = node_attr_from\n self.feature_data[to_vertex][node_id_to] = node_attr_to\n sg.add_node(node_id_from, bipartite = 0)\n #import ipdb; ipdb.set_trace()\n sg.add_node(node_id_to, bipartite = 1)\n sg.nodes[node_id_to].update(node_attr_to)\n sg.add_edge(node_id_from, node_id_to)\n rsg = rsgdata[ename]\n rsg.add_node(node_id_from, attr_dict = node_attr_from, bipartite = 1)\n rsg.nodes[node_id_from].update(node_attr_from)\n rsg.add_node(node_id_to, attr_dict = node_attr_to, bipartite = 0)\n rsg.nodes[node_id_to].update(node_attr_to)\n rsg.add_edge(node_id_to, node_id_from)\n #construct the dgl hetero graph\n dict_desc = dict()\n for ename in self.edge_dict:\n tokens = ename.split('-')\n rename = tokens[1] + '-' + tokens[0]\n fgk = ( tokens[0], ename, tokens[1] )\n rgk = (tokens[1], rename, tokens[0])\n dict_desc[fgk] = sgdata[ename]\n dict_desc[rgk] = rsgdata[ename]\n\n g = dgl.heterograph(dict_desc)\n print(\"Preparing Node feature data... \")\n np_node_data = self.trim_node_data()\n print(\"Setting node feature data...\")\n\n for v in self.vertex_list:\n v_data = th.from_numpy(np_node_data[v].values)\n g.nodes[v].data['f'] = v_data\n\n print(\"Done setting feature data in dgl graph!\")\n\n\n\n return labels, g\n\n\n\n\n","sub_path":"tutorials/models/hetro-graph-with-node-features/ITSM_data_loader.py","file_name":"ITSM_data_loader.py","file_ext":"py","file_size_in_byte":13065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"493251711","text":"from application.model import GroupModel\nfrom application.service import group_service\n\n\ndef test_enroll_user(group_factory, fixture_user):\n # given\n group = group_factory()\n created_goal = group.create_goal(\n criteria='일주일에 책 한권을 읽습니다. 그러지않으면 만원!!!',\n started_date='2018-08-01',\n ended_date='2018-08-30'\n )\n\n (group, goal, achievements) = group_service.enroll_user(\n group_id=group.id,\n user_id=fixture_user.id\n )\n\n assert group.id is group.id\n assert goal.id == created_goal.id\n\n days = (created_goal.ended_date - created_goal.started_date).days + 1\n\n assert days == 30\n\n # 시작과 끝일만큼\n assert len(achievements) == days\n\n\ndef test_create_group():\n title = '그룹 이름입니다.'\n description = '그룹 설명입니다'\n criteria = '목표의 기준입니다.'\n\n group: GroupModel = group_service.create(\n title,\n description,\n criteria,\n )\n\n assert group.id > 0\n assert group.title == title\n assert group.description == description\n assert group.goal.group_id == group.id\n assert group.goal.criteria == criteria\n","sub_path":"tests/application/service/test_group_service.py","file_name":"test_group_service.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"460150619","text":"from sklearn import naive_bayes, model_selection\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nimport pandas as pd\nimport time\nfrom sklearn.svm import SVC\nfrom sklearn.utils import shuffle\n\nstart_time = time.time()\npd.set_option('display.max_columns', 500)\n#create dataframe\n# df = pd.read_csv('./all datasets processed/fake_news_1.csv')\ndf = pd.read_csv('analyses.csv')\n\n#Extract Target Feature\ndf = shuffle(df)\ndf.fillna(0, inplace =True)\ntargetLabels = df['fake_news']\n\ndf.drop(['fake_news','news_no','user_no',\"user_spread_news_no_times\",'following_accounts_number',\n 'user_total_real_news_spread','user_total_news_spread','user_total_fake_news_spread',\n 'user_number_of_followers',\n ],axis=1, inplace=True)\n\n#--------------------------------------------\n# Hold-out Test Set + Confusion Matrix\n#--------------------------------------------\n#define naive bayes model using Gaussian based information \ngnb = SVC(gamma=0.001)\n#Split the data: 80% training : 20% test set\n\ninstances_train, instances_test, target_train, target_test = train_test_split(df, targetLabels, test_size=0.2, random_state=0)\n#fit the model using just the test set\ngnb.fit(instances_train, target_train)\n#Use the model to make predictions for the test set queries\npredictions = gnb.predict(instances_test)\n# print(instances_test)\nprint(\"--------------------------------------------------\")\n# print(target_test)\n''\n#Output the accuracy score of the model on the test set\nprint(\"Accuracy= \" + str(accuracy_score(target_test, predictions, normalize=True)))\n#Output the confusion matrix on the test set\nconfusionMatrix = confusion_matrix(target_test, predictions)\nprint(confusionMatrix)\nprint(\"\\n\\n\")\n \n#Draw the confusion matrix\n\n#--------------------------------------------\n# Cross-validation to Compare to Models\n#--------------------------------------------\n#run a 10 fold cross validation on this model using the full chrum data\nscores=model_selection.cross_val_score(gnb, instances_train, target_train, cv=10)\n#the cross validaton function returns an accuracy score for each fold\nprint(\"Dec Tree based Model:\")\nprint(\"Score by fold: \" + str(scores))\n#we can output the mean accuracy score and standard deviation as follows:\nprint(\"Accuracy: %0.4f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\nprint(\"\\n\\n\")\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n","sub_path":"Python/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"360724025","text":"from django.conf import settings\nfrom django.db import connection as _connection\nfrom models import SoftwareVersion\n\ndef connection(request):\n total_time = 0.0\n for query in _connection.queries:\n total_time += float(query.get('time', 0))\n return {\n 'connection': _connection, \n 'queries_time': total_time,\n 'HONEYPOT_URL': settings.HONEYPOT_URL\n }\n\ndef version(request):\n versions = SoftwareVersion.objects.all().order_by('-id')\n if versions:\n version = versions[0]\n else:\n version = SoftwareVersion(state='v', major=1, minor=1)\n return {'software_version': version.__unicode__()}\n","sub_path":"general/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"554813749","text":"\"\"\"\n236. Lowest Common Ancestor of a Binary Tree\n\nGiven a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.\n\nAccording to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node\nin T that has both p and q as descendants (where we allow a node to be a descendant of itself).”\n\n\n\nExample 1:\n\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\nOutput: 3\nExplanation: The LCA of nodes 5 and 1 is 3.\nExample 2:\n\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\nOutput: 5\nExplanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.\nExample 3:\n\nInput: root = [1,2], p = 1, q = 2\nOutput: 1\n\n\nConstraints:\n\nThe number of nodes in the tree is in the range [2, 105].\n-109 <= Node.val <= 109\nAll Node.val are unique.\np != q\np and q will exist in the tree.\n\n\"\"\"\n\n\nclass LowestCommonAncestor:\n\n\n \"\"\"\n Approach 1: Recursive Approach\n Intuition\n\n The approach is pretty intuitive. Traverse the tree in a depth first manner. The moment you encounter either of the nodes p or q, return some boolean flag. The flag helps to determine if we found the required nodes in any of the paths. The least common ancestor would then be the node for which both the subtree recursions return a True flag. It can also be the node which itself is one of p or q and for which one of the subtree recursions returns a True flag.\n\n Let us look at the formal algorithm based on this idea.\n\n Algorithm\n\n Start traversing the tree from the root node.\n If the current node itself is one of p or q, we would mark a variable mid as True and continue the search for the other node in the left and right branches.\n If either of the left or the right branch returns True, this means one of the two nodes was found below.\n If at any point in the traversal, any two of the three flags left, right or mid become True, this means we have found the lowest common ancestor for the nodes p and q.\n Let us look at a sample tree and we search for the lowest common ancestor of two nodes 9 and 11 in the tree.\n\n Complexity Analysis\n\n Time Complexity: O(N)O(N), where NN is the number of nodes in the binary tree. In the worst case we might be visiting all the nodes of the binary tree.\n\n Space Complexity: O(N)O(N). This is because the maximum amount of space utilized by the recursion stack would be NN since the height of a skewed binary tree could be NN.\n\n \"\"\"\n def doit(self, root, p, q):\n\n ans = None\n\n def dfs(n):\n nonlocal ans\n if not n:\n return 0\n\n left, right = dfs(n.left), dfs(n.right)\n mid = n == p or n == q\n\n if mid + right + left >= 2:\n ans = n\n\n return mid or left or right\n\n dfs(root)\n return ans\n\n \"\"\"\n Approach 2: Iterative using parent pointers\n Intuition\n \n If we have parent pointers for each node we can traverse back from p and q to get their ancestors. The first common node we get during this traversal would be the LCA node. \n We can save the parent pointers in a dictionary as we traverse the tree.\n \n Algorithm\n \n Start from the root node and traverse the tree.\n Until we find p and q both, keep storing the parent pointers in a dictionary.\n Once we have found both p and q, we get all the ancestors for p using the parent dictionary and add to a set called ancestors.\n Similarly, we traverse through ancestors for node q. If the ancestor is present in the ancestors set for p, \n this means this is the first ancestor common between p and q (while traversing upwards) and hence this is the LCA node.\n\n \"\"\"\n def doit(self, root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n\n # Stack for tree traversal\n stack = [root]\n\n # Dictionary for parent pointers\n parent = {root: None}\n\n # Iterate until we find both the nodes p and q\n while p not in parent or q not in parent:\n\n node = stack.pop()\n\n # While traversing the tree, keep saving the parent pointers.\n if node.left:\n parent[node.left] = node\n stack.append(node.left)\n if node.right:\n parent[node.right] = node\n stack.append(node.right)\n\n # Ancestors set() for node p.\n ancestors = set()\n\n # Process all ancestors for node p using parent pointers.\n while p:\n ancestors.add(p)\n p = parent[p]\n\n # The first ancestor of q which appears in\n # p's ancestor set() is their lowest common ancestor.\n while q not in ancestors:\n q = parent[q]\n return q","sub_path":"PythonLeetcode/leetcodeM/236_LowestCommonAncestorOfBinaryTree.py","file_name":"236_LowestCommonAncestorOfBinaryTree.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"234439260","text":"'''\nstudying bitcoin opcodes/Script\n\nreference: https://en.bitcoin.it/wiki/Script\n'''\n\nimport struct\nfrom copy import deepcopy\nfrom binascii import hexlify, unhexlify\nfrom hashlib import sha1, sha256\nimport hashlib\nfrom script_stack import ScriptStack\nfrom btc_ecdsa import bin2pubkey, der2sig, verifiers\nfrom btc_block import txDict2rawBytes\nfrom btc_utils import l2ui as l2i\nfrom btc_utils import ui2l as i2l\nfrom btc_utils import ui2b as i2b\nfrom btc_utils import b2ui as b2i\n\nclass WTF(Exception): pass\n\nbitcoin_opcode_data = (\n # (decimal dec-code, short-name, validity, function)\n\n # meaning of 'validity'... \n # True: this is an enabled opcode, \n # None: invalidates transaction if occurring in an executed branch,\n # False = invalidates transaction if used anywhere in script.\n\n (0, '0', True, lambda x: x.stack.append(i2l(0,1))),\n (0, 'false', True, lambda x: x.stack.append(i2l(0,1))), # duplicate\n (1, 'push1', True, lambda x: x.rpush(1)),\n (2, 'push2', True, lambda x: x.rpush(2)),\n (3, 'push3', True, lambda x: x.rpush(3)),\n (4, 'push4', True, lambda x: x.rpush(4)),\n (5, 'push5', True, lambda x: x.rpush(5)),\n (6, 'push6', True, lambda x: x.rpush(6)),\n (7, 'push7', True, lambda x: x.rpush(7)),\n (8, 'push8', True, lambda x: x.rpush(8)),\n (9, 'push9', True, lambda x: x.rpush(9)),\n (10, 'push10', True, lambda x: x.rpush(10)),\n (11, 'push11', True, lambda x: x.rpush(11)),\n (12, 'push12', True, lambda x: x.rpush(12)),\n (13, 'push13', True, lambda x: x.rpush(13)),\n (14, 'push14', True, lambda x: x.rpush(14)),\n (15, 'push15', True, lambda x: x.rpush(15)),\n (16, 'push16', True, lambda x: x.rpush(16)),\n (17, 'push17', True, lambda x: x.rpush(17)),\n (18, 'push18', True, lambda x: x.rpush(18)),\n (19, 'push19', True, lambda x: x.rpush(19)),\n (20, 'push20', True, lambda x: x.rpush(20)),\n (21, 'push21', True, lambda x: x.rpush(21)),\n (22, 'push22', True, lambda x: x.rpush(22)),\n (23, 'push23', True, lambda x: x.rpush(23)),\n (24, 'push24', True, lambda x: x.rpush(24)),\n (25, 'push25', True, lambda x: x.rpush(25)),\n (26, 'push26', True, lambda x: x.rpush(26)),\n (27, 'push27', True, lambda x: x.rpush(27)),\n (28, 'push28', True, lambda x: x.rpush(28)),\n (29, 'push29', True, lambda x: x.rpush(29)),\n (30, 'push30', True, lambda x: x.rpush(30)),\n (31, 'push31', True, lambda x: x.rpush(31)),\n (32, 'push32', True, lambda x: x.rpush(32)),\n (33, 'push33', True, lambda x: x.rpush(33)),\n (34, 'push34', True, lambda x: x.rpush(34)),\n (35, 'push35', True, lambda x: x.rpush(35)),\n (36, 'push36', True, lambda x: x.rpush(36)),\n (37, 'push37', True, lambda x: x.rpush(37)),\n (38, 'push38', True, lambda x: x.rpush(38)),\n (39, 'push39', True, lambda x: x.rpush(39)),\n (40, 'push40', True, lambda x: x.rpush(40)),\n (41, 'push41', True, lambda x: x.rpush(41)),\n (42, 'push42', True, lambda x: x.rpush(42)),\n (43, 'push43', True, lambda x: x.rpush(43)),\n (44, 'push44', True, lambda x: x.rpush(44)),\n (45, 'push45', True, lambda x: x.rpush(45)),\n (46, 'push46', True, lambda x: x.rpush(46)),\n (47, 'push47', True, lambda x: x.rpush(47)),\n (48, 'push48', True, lambda x: x.rpush(48)),\n (49, 'push49', True, lambda x: x.rpush(49)),\n (50, 'push50', True, lambda x: x.rpush(50)),\n (51, 'push51', True, lambda x: x.rpush(51)),\n (52, 'push52', True, lambda x: x.rpush(52)),\n (53, 'push53', True, lambda x: x.rpush(53)),\n (54, 'push54', True, lambda x: x.rpush(54)),\n (55, 'push55', True, lambda x: x.rpush(55)),\n (56, 'push56', True, lambda x: x.rpush(56)),\n (57, 'push57', True, lambda x: x.rpush(57)),\n (58, 'push58', True, lambda x: x.rpush(58)),\n (59, 'push59', True, lambda x: x.rpush(59)),\n (60, 'push60', True, lambda x: x.rpush(60)),\n (61, 'push61', True, lambda x: x.rpush(61)),\n (62, 'push62', True, lambda x: x.rpush(62)),\n (63, 'push63', True, lambda x: x.rpush(63)),\n (64, 'push64', True, lambda x: x.rpush(64)),\n (65, 'push65', True, lambda x: x.rpush(65)),\n (66, 'push66', True, lambda x: x.rpush(66)),\n (67, 'push67', True, lambda x: x.rpush(67)),\n (68, 'push68', True, lambda x: x.rpush(68)),\n (69, 'push69', True, lambda x: x.rpush(69)),\n (70, 'push70', True, lambda x: x.rpush(70)),\n (71, 'push71', True, lambda x: x.rpush(71)),\n (72, 'push72', True, lambda x: x.rpush(72)),\n (73, 'push73', True, lambda x: x.rpush(73)),\n (74, 'push74', True, lambda x: x.rpush(74)),\n (75, 'push75', True, lambda x: x.rpush(75)),\n (76, 'pushData1', True, lambda x: x.readlenrpush(1)),\n (77, 'pushData2', True, lambda x: x.readlenrpush(2)),\n (78, 'pushData4', True, ),#lambda x: x.readlenrpush(4)),\n (79, '1negate', True, ),#lambda x: x.stack.append(l2i(-1,4))),\n (81, '1', True, lambda x: x.stack.append(i2l(1,1))),\n (81, 'true', True, lambda x: x.stack.append(i2l(1,1))), # duplicate\n (82, '2', True, lambda x: x.stack.append(i2l(2,1))),\n (83, '3', True, lambda x: x.stack.append(i2l(3,1))),\n (84, '4', True, lambda x: x.stack.append(i2l(4,1))),\n (85, '5', True, lambda x: x.stack.append(i2l(5,1))),\n (86, '6', True, lambda x: x.stack.append(i2l(6,1))),\n (87, '7', True, lambda x: x.stack.append(i2l(7,1))),\n (88, '8', True, lambda x: x.stack.append(i2l(8,1))),\n (89, '9', True, lambda x: x.stack.append(i2l(9,1))),\n (90, '10', True, lambda x: x.stack.append(i2l(10,1))),\n (91, '11', True, lambda x: x.stack.append(i2l(11,1))),\n (92, '12', True, lambda x: x.stack.append(i2l(12,1))),\n (93, '13', True, lambda x: x.stack.append(i2l(13,1))),\n (94, '14', True, lambda x: x.stack.append(i2l(14,1))),\n (95, '15', True, lambda x: x.stack.append(i2l(15,1))),\n (96, '16', True, lambda x: x.stack.append(i2l(16,1))),\n\n # flow\n (97, 'nop', True, lambda x: x.nop()),\n (99, 'if', True, ),#lambda x: x.if_(True)),\n (100, 'notIf', True, ),#lambda x: x.if_(False)),\n (103, 'else', True, ),#lambda x: x.else_()),\n (104, 'endIf', True, ),#lambda x: x.endif()),\n (105, 'verify', True, lambda x: x.verify()),\n (106, 'return', True, ),#lambda x: x.return_()),\n\n # stack\n (107, 'toAltStack', True, lambda x: x.toAltStack()),\n (108, 'fromAltStack', True, ),#lambda x: x.fromAltStack()),\n (109, '2drop', True, lambda x: x.stack.drop(2)),\n (110, '2dup', True, ),#lambda x: x.stack.dup(2)),\n (111, '3dup', True, ),#lambda x: x.stack.dup(3)),\n (112, '2over', True, ),#lambda x: x.stack.over(2)),\n (113, '2rot', True, ),#lambda x: x.stack.rot(2)),\n (114, '2swap', True, ),#lambda x: x.stack.swap(2)),\n (115, 'ifDup', True, ),#lambda x: x.ifDup()),\n (116, 'depth', True, ),#lambda x: x.depth()),\n (117, 'drop', True, lambda x: x.stack.drop(1)),\n (118, 'dup', True, lambda x: x.stack.dup(1)),\n (119, 'nip', True, ),#lambda x: x.stack.nip()),\n (120, 'over', True, ),#lambda x: x.stack.over(1)),\n (121, 'pick', True, ),#lambda x: x.stack.pick()),\n (122, 'roll', True, ),#lambda x: x.stack.roll()),\n (123, 'rot', True, ),#lambda x: x.stack.rot()),\n (124, 'swap', True, ),#lambda x: x.stack.swap(1)),\n (125, 'tuck', True, ),#lambda x: x.stack.tuck()),\n\n # splice\n (126, 'cat', False, ),\n (127, 'substr', False, ),\n (128, 'left', False, ),\n (129, 'right', False, ),\n (130, 'size', True, ),#lambda x: x.size()),\n\n # bitwise\n (131, 'invert', False, ),\n (132, 'and', False, ),\n (133, 'or', False, ),\n (134, 'xor', False, ),\n (135, 'equal', True, lambda x: x.equal()),\n (136, 'equalVerify', True, lambda x: x.equalVerify()),\n\n # arithmetic\n (139, '1add', True, ),#lambda x: x.add(1)),\n (140, '1sub', True, ),#lambda x: x.sub(1)),\n (141, '2mul', False, ),\n (142, '2div', False, ),\n (143, 'negate', True, ),#lambda x: x.negate()),\n (144, 'abs', True, ),#lambda x: x.abs()),\n (145, 'not', True, ),#lambda x: x.not_()),\n (146, '0notEqual', True, ),#lambda x: x.zeroNotEqual()),\n (147, 'add', True, ),#lambda x: x.add()),\n (148, 'sub', True, ),#lambda x: x.sub()),\n (149, 'mul', False, ),\n (150, 'div', False, ),\n (151, 'mod', False, ),\n (152, 'lshift', False, ),\n (153, 'rshift', False, ),\n (154, 'boolAnd', True, ),#lambda x: x.bool('AND')),\n (155, 'boolOr', True, ),#lambda x: x.bool('OR')),\n (156, 'numEqual', True, ),#lambda x: x.numCompare('==')),\n (157, 'numEqualVerify', True, ),#lambda x: x.numEqualVerify()),\n (158, 'numNotEqual', True, ),#lambda x: x.numCompare('!=')),\n (159, 'lessThan', True, ),#lambda x: x.numCompare('<')),\n (160, 'greaterThan', True, ),#lambda x: x.numCompare('>')),\n (161, 'lessThanOrEqual', True, ),#lambda x: x.numCompare('<=')),\n (162, 'greaterThanOrEqual', True, ),#lambda x: x.numCompare('>=')),\n (163, 'min', True, lambda x: x.min()),\n (164, 'max', True, ),#lambda x: x.max()),\n (165, 'within', True, ),#lambda x: x.numCompare('WITHIN')),\n\n # crypto\n (166, 'ripemd160', True, ),#lambda x: x.hash_('RIPEMD160')),\n (167, 'sha1', True, ),#lambda x: x.hash_('SHA1')),\n (168, 'sha256', True, lambda x: x.hash_('SHA256')),\n (169, 'hash160', True, lambda x: x.hash_('HASH160')),\n (170, 'hash256', True, ),#lambda x: x.hash_('HASH256')),\n (171, 'codeSeparator', True, lambda x: x.codeSeparator()),\n (172, 'checkSig', True, lambda x: x.checkSig()),\n (173, 'checkSigVerify', True, ),#lambda x: x.checkSigVerify()),\n (174, 'checkMultiSig', True, lambda x: x.checkMultiSig()),\n (175, 'checkMultiSigVerify', True, ),#lambda x: x.checkSigVerify()),\n\n # locktime\n # not fucking cool, but in eb3b82c0884e3efa6d8b0be55b4915eb20be124c9766245bcc7f34fdac32bccb\n # long before checklocktimeverify implemented, i imagine it was nop2 before.\n (177, 'checkLockTimeVerify', True, lambda x: x.nop()), \n (178, 'checkSequenceVerify', True, ),\n\n # pseudo\n (253, 'pubKeyHash', False, ),\n (254, 'pubKey', False, ),\n (255, 'invalidOpCode', False, ),\n\n # reserved\n (80, 'reserved', None, ),\n (98, 'ver', None, ),\n (101, 'verIf', False, ),\n (102, 'verNotIf', False, ),\n (137, 'reserved1', None, ),\n (138, 'reserved2', None, ),\n (176, 'nop1', True, lambda x: x.nop()),\n (179, 'nop4', True, lambda x: x.nop()),\n (180, 'nop5', True, lambda x: x.nop()),\n (181, 'nop6', True, lambda x: x.nop()),\n (182, 'nop7', True, lambda x: x.nop()),\n (183, 'nop8', True, lambda x: x.nop()),\n (184, 'nop9', True, lambda x: x.nop()),\n (185, 'nop10', True, lambda x: x.nop()),\n )\n\n#def i2l(anInt, length): \n# return struct.pack(' maxlen: raise Exception\n# else: return int(hexlify(unhexlify(hexlify(aByteStr))[::-1]),16)\ndef ripemd160(input_):\n h = hashlib.new('ripemd160')\n h.update(input_)\n return h\n\nclass BitcoinOpCode:\n def __str__(self): return '%s %s' % (self.word, self.hex)\n def __repr__(self): return repr(self.__dict__)\n def __init__(self, code, name, validity, function=None):\n if 0 <= code <= 255 and type(code) == type(0):\n self.dec = code\n self.hex = hex(self.dec)\n self.byte = i2l(self.dec, 1)\n else: raise TypeError('invalid code: %s' % code)\n self.name = name\n self.word = 'OP_' + name.upper()\n if validity in (True, None, False): self.validity = validity\n else: raise TypeError('invalid validity: %s' % validity)\n self.function = function\n\nclass BitcoinOpCodes(dict):\n def __getattr__(self, name):\n keys = [x.word for x in self.values() if x.word==name.upper() or x.name==name]\n if len(keys) == 1: return self[keys[0]]\n else: raise AttributeError\n def __missing__(self, key):\n keys = [x.word for x in self.values() if x.dec==key]\n if 0 < len(keys) <= 2: return self[keys[0]] # OP_0/False and OP_1/True are duplicated\n else: raise KeyError\n\nopcodes = BitcoinOpCodes({\n 'OP_%s' % k.upper(): BitcoinOpCode(*v) \n for k,v in [(x[1], x) for x in bitcoin_opcode_data]\n })\n\nclass InvalidTransaction(Exception): pass\n\nclass BitcoinScript:\n\n flow_control_ops = ('OP_IF', 'OP_NOTIF', 'OP_ELSE', 'OP_ENDIF')\n hash_funcs = ('RIPEMD160', 'SHA1', 'SHA256', 'HASH160', 'HASH256')\n\n def __init__(self, txDict, blockTime, blockHeight, asHex=False, verbose=False):\n self.txDict = txDict\n self.blockTime = blockTime\n self.blockHeight = blockHeight\n if asHex: self.convert, self.unconvert = lambda x: unhexlify(x), lambda x: hexlify(x)\n else: self.convert, self.unconvert = lambda x: x, lambda x: x\n self.verbose = verbose\n\n def evaluate(self):\n self.valid, self.errors = None, []\n self.lock_time = self.txDict['lock_time']\n try:\n for i, aDict in enumerate(self.txDict['tx_in']):\n self.inDict = aDict\n self._evaluate_script()\n if not self.valid: break\n except Exception as e:\n self.valid = False\n self.errors.append(e)\n raise\n if self.errors: \n self.errors.append('txid: %s' % self.txDict['TxId'])\n return self.valid, self.errors\n\n def _evaluate_script(self):\n self.script = self.convert(self.inDict['sig_script'] + self.inDict['prev_out_pk_script'])\n self.sequence = self.inDict['sequence']\n self.last_codesep = 0\n self.cursor = 0\n self.stack = ScriptStack([b''])\n self.altstack = ScriptStack([b''])\n self.tokens = []\n self.execute = [True]\n try: \n while self.cursor < len(self.script):\n op = opcodes[l2i(self._read())]\n if self.execute[-1] or op.word in self.flow_control_ops:\n if op.validity == True:\n if op.function:\n if self.verbose: print('executing: %s' % op)\n op.function(self)\n else: \n raise InvalidTransaction('opcode not yet implemented: %s' % op)\n else: \n raise InvalidTransaction('invalid opcode in execution path: %s' % op)\n else: \n if self.verbose: print('skipping: %s' % op)\n if op.validity == False:\n raise InvalidTransaction('invalid opcode in script: %s' % op)\n\n if self.execute != [True]:\n raise InvalidTransaction('unfinished flow control in script: %s' % self.execute)\n except Exception as e:\n self.valid = False\n self.errors.append(e)\n self._debug(e)\n raise\n # up until feb28'12, strict 'must be OP_TRUE' as top stack item was a good rule\n #self.valid = self.stack.pop() == '\\x01' # script valid if OP_TRUE on top\n # txid:3a5e0977cc64e601490a761d83a4ea5be3cd03b0ffb73f5fe8be6507539be76c txin:0,\n # block:168910, 20120228 pushed True and 20bytes then finished\n self.valid = self.stack.pop() != '\\x00' # script valid if OP_FALSE not on top\n if self.verbose:\n self._debug('_evaluate_script() done')\n\n def _debug(self, error=None):\n print(error)\n print(' valid: %s\\n errors: %s\\n tokens: %s\\n stack: %s\\n altstack: %s\\n execute: %s\\n' % (\n self.valid, self.errors, \n [hexlify(x) for x in self.tokens], [hexlify(x) for x in self.stack], \n self.altstack, self.execute)\n )\n\n def _read(self, length=1):\n length = abs(length)\n answer = self.script[self.cursor:self.cursor+length]\n self.cursor += length\n self.tokens.append(answer)\n return answer\n\n # constants\n def rpush(self, length): \n self.stack.append(self._read(length))\n\n def readlenrpush(self, length):\n '''\n txid:968a692ab98b1f275c635c76be003ab1db9740d0b62f338b270115342ca42f5b txin:0\n block:177618, 20120428, pushdata1\n txid:c705ec760f828063461630048d7e372005a6dc9cba054b1524bf469eb3117de4 txin:0\n block: 177660, 20120429, pushdata2\n '''\n length = l2i(self._read(length))\n self.rpush(length)\n\n # flow\n def nop(self): \n pass\n\n def if_(self):\n if set(self.execute) == set((True)):\n if self.stack.pop() != '': self.execute.append(True)\n else: self.execute.append(False)\n else: self.execute.append(False)\n\n def notif(self):\n if set(self.execute) == set((True)):\n if self.stack.pop() == '': self.execute.append(True)\n else: self.execute.append(False)\n else: self.execute.append(False)\n\n def else_(self):\n if set(self.execute[:-1]) == set((True)): self.execute[-1] = not self.execute[-1]\n\n def endif(self):\n self.execute.pop()\n\n def verify(self):\n if l2i(self.stack.pop()) == 0:\n raise InvalidTransaction('verify() aborting. stack.pop() == 0')\n\n def return_(self):\n raise InvalidTransaction('return() aborting.')\n\n # stack\n def toAltStack(self):\n self.altstack.append(self.stack.pop())\n\n def fromAltStack(self):\n self.stack.append(self.altstack.pop())\n\n def ifDup(self):\n if self.stack[-1] != '': self.stack.append(self.stack[-1])\n\n def depth(self): \n self.stack.append(i2l(len(self.stack), 4))\n\n # splice\n '''\n def cat(self): raise InvalidTransaction\n def substr(self): raise InvalidTransaction\n def left(self): raise InvalidTransaction\n def right(self): raise InvalidTransaction\n '''\n def size(self): \n self.stack.append(i2l(len(self.stack[-1]), 4))\n\n # bitwise\n '''\n def invert(self): raise InvalidTransaction\n def and(self): raise InvalidTransaction\n def or(self): raise InvalidTransaction\n def xor(self): raise InvalidTransaction\n '''\n def equal(self): \n if self.stack.pop() == self.stack.pop(): self.stack.append(i2l(1, 1))\n else: self.stack.append(i2l(0, 1))\n\n def equalVerify(self):\n self.equal()\n self.verify()\n\n # arithmetic\n '''\n def mul(self): raise InvalidTransaction\n def div(self): raise InvalidTransaction\n def mod(self): raise InvalidTransaction\n def lshift(self): raise InvalidTransaction\n def rshift(self): raise InvalidTransaction\n '''\n def negate(self): \n self.stack[-1] = i2l(l2i(self.stack[-1]) * -1, 4)\n\n def abs(self): \n self.stack[-1] = abs(i2l(l2i(self.stack[-1]), 4))\n\n def not_(self): \n if l2i(self.stack[-1]) == 0: self.stack[-1] = i2l(1, 4)\n else: self.stack[-1] = i2l(0, 4)\n\n def zeroNotEqual(self): \n if l2i(self.stack[-1]) == 0: self.stack[-1] = i2l(0, 4)\n else: self.stack[-1] = i2l(1, 4)\n\n def add(self, a=None):\n b = l2i(self.stack.pop())\n if a == None: a = l2i(self.stack.pop())\n self.stack.append(i2l(a + b, 4))\n\n def sub(self, a=None):\n b = l2i(self.stack.pop())\n if a == None: a = l2i(self.pop())\n self.stack.append(i2l(a - b, 4))\n\n def bool(self, and_or):\n if and_or not in ('AND', 'OR'): \n raise WTF('bool(%s) invalid' % and_or)\n b, a = self.stack.pop(), self.stack.pop()\n if and_or == 'AND' and (a != '' and b != ''): self.stack.append(i2l(1, 4))\n if and_or == 'OR' and (a != '' or b != ''): self.stack.append(i2l(1, 4))\n else: self.stack.append(i2l(0, 4))\n\n def numCompare(self, operator):\n if operator not in ('==', '!=', '>', '<', '>=', '<=', 'WITHIN'):\n raise WTF('numCompare(%s) invalid' % operator)\n b, a = l2i(self.stack.pop()), l2i(self.stack.pop())\n if operator == '==' and a == b: self.stack.append(i2l(1, 4))\n elif operator == '!=' and a != b: self.stack.append(i2l(1, 4))\n elif operator == '>' and a > b: self.stack.append(i2l(1, 4))\n elif operator == '<' and a < b: self.stack.append(i2l(1, 4))\n elif operator == '>=' and a >= b: self.stack.append(i2l(1, 4))\n elif operator == '<=' and a <= b: self.stack.append(i2l(1, 4))\n elif operator == 'WITHIN' and a <= l2i(self.stack.pop()) < b:\n self.stack.append(i2l(1, 4))\n else:\n self.stack.append(i2l(0, 4))\n\n def numEqualVerify(self):\n self.numCompare('==')\n self.verify()\n\n def min(self):\n '''\n txid: 3ee060fb1856f111859fb108d079635a2d225ef68d5ae5250ce70d39ac2a2dc4 txin:0\n block:170977, 20120313\n '''\n b, a = self.stack.pop(), self.stack.pop()\n self.stack.append(min(a, b))\n\n def max(self):\n b, a = self.stack.pop(), self.stack.pop()\n self.stack.append(max(a, b))\n\n # crypto\n def _ripemd160(self, x): return ripemd160(x)\n def _sha1(self, x): return sha1(x)\n def _sha256(self, x): return sha256(x)\n def hash_(self, hashFunc):\n if hashFunc not in self.hash_funcs: raise WTF('hashFunc unknown %s' % hashFunc)\n preImage = self.stack.pop()\n if hashFunc == 'RIPEMD160': \n self.stack.append(self._ripemd160(preImage).digest())\n elif hashFunc == 'SHA1':\n self.stack.append(self._sha1(preImage).digest())\n elif hashFunc == 'SHA256':\n '''\n txid:81b0bb7be25a496cb12ed5acf834cbaebb8e5dfaffc9c996f33fe24f0f54c883 \n txin:0, block:165642, 20120206\n '''\n self.stack.append(self._sha256(preImage).digest())\n elif hashFunc == 'HASH160':\n self.stack.append(self._ripemd160(self._sha256(preImage).digest()).digest())\n elif hashFunc == 'HASH256':\n self.stack.append(self._sha256(self._sha256(preImage).digest()).digest())\n\n def codeSeparator(self): \n self.last_codesep = self.cursor\n\n def _serializeTxCopy4signature(self, derhashtype_list, recipe=None):\n '''\n node has stopped processing because hashtype:02 not yet implemented\n txid:599e47a8114fe098103663029548811d2651991b62397e057f0c863c2bc9f9ea txin:0\n\n it appears that the recipe for building subscript has not always been consistent.\n 1: subscript is the prev_out_pk_script\n txid:f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16 txin:0, blk:170, 20090112\n txid:10c61e258e0a2b19b245a96a2d0a1538fe81cd4ecd547e0a3df7ed6fd3761ada txin:0, blk:165335, 20120204\n 2: subscript starts after latest codesep, finishes after current executing opcode\n txid:eb3b82c0884e3efa6d8b0be55b4915eb20be124c9766245bcc7f34fdac32bccb txin:1, blk:163685, 20120124\n txid:0157f2eec7bf856d66714856182a146998910dc6fa576bec200a9fa8039459e7 txin:0, blk:168216, 20120224\n 3: subscript starts after dersig, finishes at end of script (so even op0 multisig bug is removed)\n txid:60a20bd93aa49ab4b28d514ec10b06e1829ce6818ec06cd3aabd013ebcdc4bb1 txin:0, blk:165084, 20120203\n txid:10c61e258e0a2b19b245a96a2d0a1538fe81cd4ecd547e0a3df7ed6fd3761ada txin:0, blk:165335, 20120204\n '''\n if recipe == 1: subscript = self.convert(self.inDict['prev_out_pk_script']) # skips extra ops in sig_script\n elif recipe == 2: subscript = self.script[self.last_codesep:self.cursor] # skips any remaining ops\n elif recipe == 3: subscript = self.script[1:self.cursor] # skips the op0-multisig bug as sig_script prefix\n else: subscript = self.script[self.last_codesep:] # now this actually makes sense!\n \n # remove the signature from the subscript since subscript does get signed\n for derhashtype in derhashtype_list:\n derhashtype = i2b(len(derhashtype), 1) + derhashtype\n if derhashtype in subscript:\n ix = subscript.index(derhashtype)\n subscript = subscript[:ix] + subscript[ix+len(derhashtype):]\n txCopy = deepcopy(self.txDict)\n for inDict in txCopy['tx_in']:\n if inDict['sig_script'] == self.inDict['sig_script']:\n inDict['sig_script'] = self.unconvert(subscript)\n else:\n inDict['sig_script'] = ''\n #if derhashtype_list[i] in ('\\x02', '\\x03', '\\x80'):\n # inDict['sequence'] = '00' * 4\n inDict['len_sig_script'] = self.unconvert(i2l(len(self.convert(inDict['sig_script'])), 1))\n #if derhashtype_list[i] in ('\\x02'):\n # txCopy['tx_out_count'] = '00'\n # txCopy['tx_out'] = []\n return self.convert(txDict2rawBytes(txCopy))\n\n def checkSig(self): \n # needs cleanup, works a/o 20180729\n bpubkey = self.stack.pop()\n pubkey = bin2pubkey(bpubkey)\n derhashtype = self.stack.pop()\n sig = der2sig(derhashtype[:-1], tolerant=True)\n hashtype = derhashtype[-1] + '\\x00'*3\n rawBytes = self._serializeTxCopy4signature([derhashtype], recipe=1)\n msg = self._sha256(self._sha256(rawBytes + hashtype).digest()).digest()\n verified = verifiers[1](sig, b2i(msg), pubkey)\n if verified: \n self.stack.append(i2l(1,1))\n else: \n self.stack.append(i2l(0,1))\n self.errors.append(\n 'checkSig failed! der+hashtype: %s, rawtx: %s, pubkey: %s' % (\n repr(hexlify(derhashtype)), repr(hexlify(rawBytes)), \n repr(hexlify(bpubkey))))\n\n #def checkSigVerify(self): \n # self.checkSig()\n # self.verify()\n\n def checkMultiSig(self):\n # txid: eb3b82c0884e3efa6d8b0be55b4915eb20be124c9766245bcc7f34fdac32bccb, height: 163685\n N = b2i(self.stack.pop())\n bpubkeys = []\n for i in range(N):\n bpubkeys.append(self.stack.pop())\n M = b2i(self.stack.pop())\n assert M <= N\n derhashtypes = []\n for i in range(M):\n derhashtypes.append(self.stack.pop())\n assert self.stack.pop() == '\\x00'\n verified, n = 0, -1\n rawBytes = []\n for m in range(M):\n rawBytes.append(self._serializeTxCopy4signature(derhashtypes, recipe=2))\n sig = der2sig(derhashtypes[m][:-1], tolerant=True)\n hashtype = derhashtypes[m][-1] + '\\x00'*3\n msg = self._sha256(self._sha256(rawBytes[-1] + hashtype).digest()).digest()\n for n in range(n+1, N):\n pubkey = bin2pubkey(bpubkeys[n])\n if verifiers[1](sig, b2i(msg), pubkey):\n verified += 1\n break\n if verified == M: \n self.stack.append(i2l(1,1))\n else: \n self.stack.append(i2l(0,1))\n self.errors.append(\n 'checkMultiSig failed! derhashtypes: %s, rawBytes: %s, bpubkeys: %s' % (\n repr([hexlify(x) for x in derhashtypes]), \n repr([hexlify(x) for x in rawBytes]), \n repr([hexlify(x) for x in bpubkeys])))\n\n #def checkMultiSigVerify(self):\n # self.checkMultiSig()\n # self.verify()\n\n # locktime\n #def checkLocktimeVerify(self): pass # will need access to tx[txns]locktime\n #def checkSequenceVerify(self): pass # will need access to tx.tx_in\n # pseudo\n # reserved\n","sub_path":"btc_script.py","file_name":"btc_script.py","file_ext":"py","file_size_in_byte":27211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"28168293","text":"import pytest\nimport hypothesis.strategies as st\n\n\n@st.composite\ndef reals(draw, min_value=None, max_value=None, allow_infinity=True):\n if min_value is not None and max_value is not None:\n allow_infinity = False\n return draw(st.floats(\n min_value=min_value, max_value=max_value,\n allow_nan=False, allow_infinity=allow_infinity\n ))\n\n\n@st.composite\ndef coefficients(draw, min_value=None, max_value=None):\n return draw(st.floats(\n min_value=min_value, max_value=max_value,\n allow_nan=False, allow_infinity=False,\n ))\n\n\nclass PlaceholderExpression(object):\n depth = 0\n","sub_path":"tests/unit/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"546308613","text":"import os\nimport time\n\ns = 600\nwhile True:\n time.sleep(1)\n os.system('clear') # ← windows では 'cls'\n if s > 0:\n print(f'再開まで {s} 秒')\n elif s % 2 == 0:\n print(' 講義を再開します ')\n else:\n print('>講義を再開します<')\n s -= 1","sub_path":"step3/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"264239049","text":"def Gene2TF(inF1, inF2):\n D = {}\n inFile = open(inF1)\n for line in inFile:\n line = line.strip()\n fields = line.split('\\t')\n for item in fields[2:]:\n gene = item.split(':')[1]\n D.setdefault(gene, [])\n if fields[0] not in D[gene]:\n D[gene].append(fields[0])\n inFile.close()\n \n inFile = open(inF2)\n ouFile = open(inF2.split('.txt')[0] + '_TF.txt', 'w')\n for line in inFile:\n line = line.strip()\n if line in D:\n ouFile.write(line + '\\t' + str(len(D[line])) +'\\t'+ '\\t'.join(D[line]) + '\\n')\n inFile.close()\n ouFile.close()\nGene2TF('Human_GRCh37_TF_Genes', 'BloodVesselDevelopment.txt')\n","sub_path":"Data/FactorBook/BloodVessel/01-Gene2TF.py","file_name":"01-Gene2TF.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"554935845","text":"from MPVisitor import MPVisitor\nfrom MPParser import MPParser\nfrom AST import *\nfrom functools import reduce\n#flatten_mix\ndef flatten(l):\n return list(reduce(lambda x, y: x + y if(isinstance(y, list)) else x + [y], l, []))\nclass ASTGeneration(MPVisitor):\n def visitProgram(self,ctx:MPParser.ProgramContext):\n return Program(flatten([self.visit(x) for x in ctx.manydeclares()]))\n def visitManydeclares(self, ctx:MPParser.ManydeclaresContext):\n if ctx.varde():\n return self.visit(ctx.varde())\n if ctx.funcde():\n return self.visit(ctx.funcde())\n if ctx.procede():\n return self.visit(ctx.procede())\n\n def visitCompostate(self,ctx:MPParser.CompostateContext):\n return flatten([self.visit(x) for x in ctx.statement()])\n\n def visitVarde(self, ctx:MPParser.VardeContext):\n return flatten([self.visit(x) for x in ctx.var_list()])\n\n def visitVar_list(self, ctx:MPParser.Var_listContext):\n _type = self.visit(ctx.vartype())\n _id = self.visit(ctx.idlist())\n return list(map(lambda x: VarDecl(x,_type),_id))\n\n def visitProcede(self, ctx:MPParser.ProcedeContext):\n if ctx.varde():\n local = flatten([self.visit(ctx.varde())])\n else:\n local = []\n cpstmt = self.visit(ctx.compostate())\n id = Id(ctx.procede1().ID().getText())\n param = self.visit(ctx.procede1())\n return FuncDecl(id,\n param,\n local,\n cpstmt)\n def visitProcede1(self, ctx:MPParser.Procede1Context):\n if (ctx.parade()):\n return flatten([self.visit(ctx.parade())])\n return []\n\n def visitParade(self, ctx:MPParser.ParadeContext):\n return flatten([self.visit(x) for x in ctx.parade1()])\n\n def visitParade1(self, ctx:MPParser.Parade1Context):\n _type = self.visit(ctx.vartype())\n _id = self.visit(ctx.idlist())\n return list(map(lambda x: VarDecl(x,_type),_id))\n\n def visitIdlist(self, ctx:MPParser.IdlistContext):\n return [Id(x.getText()) for x in ctx.ID()]\n\n def visitVartype(self, ctx:MPParser.VartypeContext):\n if (ctx.primtype()):\n return self.visit(ctx.primtype())\n else:\n return self.visit(ctx.arrtype())\n\n def visitPrimtype(self, ctx:MPParser.PrimtypeContext):\n if ctx.BOOLEAN():\n return BoolType()\n if ctx.INTEGER():\n return IntType()\n if ctx.REAL():\n return FloatType()\n if ctx.STRING():\n return StringType()\n\n def visitArrtype(self, ctx:MPParser.ArrtypeContext):\n eleType = self.visit(ctx.primtype())\n lower = int(ctx.intt(0).INTLIT().getText())\n upper = int(ctx.intt(1).INTLIT().getText())\n if ctx.intt(0).SUBNE() is not None:\n lower = lower*(-1)\n if ctx.intt(1).SUBNE() is not None:\n upper = upper*(-1)\n return ArrayType(lower, upper, eleType)\n\n def visitIntt(self, ctx:MPParser.InttContext):\n return\n\n def visitFuncde(self, ctx:MPParser.FuncdeContext):\n cpstmt = self.visit(ctx.compostate())\n id = Id(ctx.funcde1().ID().getText())\n param = self.visit(ctx.funcde1())\n varType = self.visit(ctx.vartype())\n if ctx.varde():\n local = flatten([self.visit(ctx.varde())])\n else:\n local = []\n return FuncDecl(id,\n param,\n local,\n cpstmt,\n varType)\n\n def visitFuncde1(self, ctx:MPParser.Funcde1Context):\n if (ctx.parade()):\n return flatten([self.visit(ctx.parade())])\n return []\n\n def visitStatement(self, ctx:MPParser.StatementContext):\n if (ctx.semistatement()):\n return self.visit(ctx.semistatement())\n else:\n return self.visit(ctx.nomistatement())\n\n def visitSemistatement(self, ctx:MPParser.SemistatementContext):\n if (ctx.assignstate()):\n return self.visit(ctx.assignstate())\n elif (ctx.breakstate()):\n return self.visit(ctx.breakstate())\n elif (ctx.contstate()):\n return self.visit(ctx.contstate())\n elif (ctx.returnsate()):\n return self.visit(ctx.returnsate())\n else:\n return self.visit(ctx.callstate())\n\n def visitNomistatement(self, ctx:MPParser.NomistatementContext):\n if (ctx.ifstate()):\n return self.visit(ctx.ifstate())\n elif (ctx.forstate()):\n return self.visit(ctx.forstate())\n elif (ctx.whilestate()):\n return self.visit(ctx.whilestate())\n elif (ctx.compostate()):\n return self.visit(ctx.compostate())\n else:\n return self.visit(ctx.withstate())\n\n def visitAssignstate(self, ctx:MPParser.AssignstateContext):\n lhs = flatten([self.visit(x) for x in ctx.lhs()])\n exp = self.visit(ctx.expression())\n lhs.append(exp)\n a=[]\n for i in range(0,len(lhs)-1,1):\n a.append(Assign(lhs[i],lhs[i+1]))\n a.reverse()\n return a\n\n # def visitAssignstate1(self, ctx:MPParser.Assignstate1Context):\n # if ctx.assignstate1():\n # a= [self.visit (ctx.assignstate1())]\n # if ctx.expression():\n # a=[self.visit(ctx.expression())]\n # a.append(self.visit(ctx.lhs()))\n # b=reduce (lambda x,y: Assign(y,x), list(a))\n # return b\n\n def visitLhs(self, ctx:MPParser.LhsContext):\n if (ctx.ID()):\n return Id(ctx.ID().getText())\n else:\n return self.visit(ctx.indexexpre())\n\n def visitIndexexpre(self, ctx:MPParser.IndexexpreContext):\n b = [self.visit(i) for i in ctx.expression()]\n a = self.visit(ctx.factor())\n c=ArrayCell(a,b[0])\n for i in range(1,len(b),1):\n c=ArrayCell(c,b[i])\n return c\n\n # explist= [self.visit(x) for x in ctx.expression()]\n # Inexxep = ArrayCell(self.visit(ctx.factor()), explist[0])\n # for i in explist[1:]:\n # Inexxep = ArrayCell(Inexxep, explist[i])\n # return Inexxep\n\n def visitFactor(self, ctx:MPParser.FactorContext):\n if (ctx.LB() and ctx.RB()):\n return self.visit(ctx.exp1())\n elif (ctx.ID()):\n return Id(ctx.ID().getText())\n elif (ctx.INTLIT()):\n return IntLiteral(int(ctx.INTLIT().getText()))\n elif (ctx.boollit()):\n return self.visit(ctx.boollit())\n elif (ctx.REALLIT()):\n return FloatLiteral(float(ctx.REALLIT().getText()))\n elif (ctx.STRINGLIT()):\n return StringLiteral(ctx.STRINGLIT().getText())\n else:\n return self.visit(ctx.invoexpre())\n\n def visitBoollit(self, ctx:MPParser.BoollitContext):\n return BooleanLiteral(True) if ctx.TRUE() else BooleanLiteral(False)\n\n def visitExp1(self, ctx:MPParser.Exp1Context):\n if (ctx.AND() and ctx.THEN()):\n return BinaryOp(\"andthen\",self.visit(ctx.exp1()),self.visit(ctx.exp2()))\n elif (ctx.OR() and ctx.ELSE()):\n return BinaryOp(\"orelse\",self.visit(ctx.exp1()),self.visit(ctx.exp2()))\n else:\n return self.visit(ctx.exp2())\n\n def visitExp2(self, ctx:MPParser.Exp2Context):\n if (ctx.EQ()):\n return BinaryOp(\"=\",self.visit(ctx.exp3(0)),self.visit(ctx.exp3(1)))\n elif (ctx.NOTEQ()):\n return BinaryOp(\"<>\",self.visit(ctx.exp3(0)),self.visit(ctx.exp3(1)))\n elif (ctx.LESSTN()):\n return BinaryOp(\"<\",self.visit(ctx.exp3(0)),self.visit(ctx.exp3(1)))\n elif (ctx.GRETN()):\n return BinaryOp(\">\",self.visit(ctx.exp3(0)),self.visit(ctx.exp3(1)))\n elif (ctx.GREEQ()):\n return BinaryOp(\">=\",self.visit(ctx.exp3(0)),self.visit(ctx.exp3(1)))\n elif (ctx.LESSEQ()):\n return BinaryOp(\"<=\",self.visit(ctx.exp3(0)),self.visit(ctx.exp3(1)))\n else:\n return self.visit(ctx.exp3(0))\n\n def visitExp3(self, ctx:MPParser.Exp3Context):\n if (ctx.ADD()):\n return BinaryOp(\"+\",self.visit(ctx.exp3()),self.visit(ctx.exp4()))\n elif (ctx.SUBNE()):\n return BinaryOp(\"-\",self.visit(ctx.exp3()),self.visit(ctx.exp4()))\n elif (ctx.OR()):\n return BinaryOp(ctx.OR().getText(),self.visit(ctx.exp3()),self.visit(ctx.exp4()))\n else:\n return self.visit(ctx.exp4())\n\n def visitExp4(self, ctx:MPParser.Exp4Context):\n if (ctx.DIVSI()):\n return BinaryOp(\"/\",self.visit(ctx.exp4()),self.visit(ctx.exp5()))\n elif (ctx.MUL()):\n return BinaryOp(\"*\",self.visit(ctx.exp4()),self.visit(ctx.exp5()))\n elif (ctx.MOD()):\n mod = ctx.MOD().getText()\n return BinaryOp(mod,self.visit(ctx.exp4()),self.visit(ctx.exp5()))\n elif (ctx.AND()):\n return BinaryOp(ctx.AND().getText(),self.visit(ctx.exp4()),self.visit(ctx.exp5()))\n elif (ctx.DIV()):\n return BinaryOp(ctx.DIV().getText(),self.visit(ctx.exp4()),self.visit(ctx.exp5()))\n else:\n return self.visit(ctx.exp5())\n\n def visitExp5(self, ctx:MPParser.Exp5Context):\n if (ctx.NOT()):\n return UnaryOp(ctx.NOT().getText(),self.visit(ctx.exp5()))\n elif (ctx.SUBNE()):\n return UnaryOp(\"-\",self.visit(ctx.exp5()))\n else:\n return self.visit(ctx.exp6())\n\n def visitExp6(self, ctx:MPParser.Exp6Context):\n if (ctx.factor()):\n return self.visit(ctx.factor())\n else:\n return self.visit(ctx.indexexpre())\n\n def visitInvoexpre(self, ctx:MPParser.InvoexpreContext):\n method = Id(ctx.ID().getText())\n param = []\n if ctx.exprlist():\n param = flatten([self.visit(ctx.exprlist())])\n return CallExpr(method, param)\n\n def visitExprlist(self, ctx:MPParser.ExprlistContext):\n return [self.visit(x) for x in ctx.expression()]\n\n def visitExpression(self, ctx:MPParser.ExpressionContext):\n if (ctx.indexexpre()):\n return self.visit(ctx.indexexpre())\n elif (ctx.invoexpre()):\n return self.visit(ctx.invoexpre())\n else:\n return self.visit(ctx.exp1())\n\n def visitBreakstate(self, ctx:MPParser.BreakstateContext ):\n return Break()\n\n def visitContstate(self, ctx:MPParser.ContstateContext):\n return Continue()\n\n def visitReturnsate(self, ctx:MPParser.ReturnsateContext):\n if (ctx.returnexp()):\n return self.visit(ctx.returnexp())\n else:\n return self.visit(ctx.returnnoexp())\n\n def visitReturnexp(self, ctx:MPParser.ReturnexpContext):\n return Return(self.visit(ctx.expression()))\n\n def visitReturnnoexp(self, ctx:MPParser.ReturnnoexpContext):\n return Return()\n\n def visitCallstate(self, ctx:MPParser.CallstateContext):\n method = Id(ctx.ID().getText())\n if ctx.expression(0) is not None:\n param = [self.visit(x) for x in ctx.expression()]\n else:\n param = []\n return CallStmt(method, param)\n\n def visitIfstate(self, ctx:MPParser.IfstateContext):\n expr = self.visit(ctx.exp1())\n thenStmt = flatten([self.visit(ctx.statement(0))])\n if (ctx.statement(1)) is not None:\n elseStmt = flatten([self.visit(ctx.statement(1))])\n return If(expr, thenStmt, elseStmt)\n else:\n return If(expr, thenStmt)\n\n def visitForstate(self, ctx:MPParser.ForstateContext):\n id = Id(ctx.ID().getText())\n expr1 = self.visit(ctx.expression(0))\n expr2 = self.visit(ctx.expression(1))\n loop = flatten([self.visit(ctx.statement())])\n if (ctx.TO()):\n up = \"True\"\n else:\n up = \"False\"\n return For(id, expr1, expr2, up, loop)\n\n def visitWhilestate(self, ctx:MPParser.WhilestateContext):\n sl = flatten([self.visit(ctx.statement())])\n exp = self.visit(ctx.expression())\n return While(exp, sl)\n\n def visitWithstate(self, ctx:MPParser.WithstateContext):\n decl = flatten([self.visit(ctx.parade2())])\n stmt = flatten([self.visit(ctx.statement())])\n return With(decl, stmt)\n\n def visitParade2(self, ctx:MPParser.Parade2Context):\n return self.visit(ctx.parade())\n","sub_path":"src/main/mp/astgen/ASTGeneration.py","file_name":"ASTGeneration.py","file_ext":"py","file_size_in_byte":12409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"448266611","text":"class Solution(object):\n def __init__(self):\n self.queens = None # global variable\n self.res = []\n self.n = 0\n\n def solveNQueens(self, n):\n \"\"\"\n :type n: int\n :rtype: List[List[str]]\n \"\"\"\n self.queens = [2*n]*n\n self.n = n\n self.NQueens(0)\n return self.res\n\n def NQueens(self, k):\n if k == self.n:\n self.genSolution()\n\n for i in range(self.n):\n if self.placeQueen(k, i):\n self.NQueens(k+1)\n\n def placeQueen(self, k, l):\n '''Place queen in row k, col l'''\n for i in range(k):\n if self.queens[i] == l:\n return False\n if abs(self.queens[i]-l) == abs(i-k):\n return False\n self.queens[k] = l\n return True\n\n def genSolution(self):\n '''Add solution to self.res'''\n solution = []\n for i in range(self.n):\n basic_solution = '.'*self.queens[i] + 'Q' + '.'*(self.n-self.queens[i]-1)\n solution.append(basic_solution)\n self.res.append(solution)\n\nif __name__ == '__main__':\n s = Solution()\n s.solveNQueens(3)\n print(s.res)\n","sub_path":"python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"351887890","text":"\"\"\"\n Module: irony.data\n Author: Lubin Maxime \n Date: 2013-05-13\n This module is part of the code I wrote for my master research project at Keio University (Japan).\n\n \n Export:\n _PATH_TO_DATA: default path to the different data objects used in the package\n get_ressources: list available ressources (e.g. get_ressources(\"corpus\") will list available corpora)\n save: save an object into the ressource store (e.g save(foo, \"corpus/bar\"))\n load: load an objet of the ressource store (e.g. load(\"corpus/sarcasm\"))\n load_chunk: return an iterator on chunk of data (necessary for large corpora)\n \n \n __all__(modules):\n analyzer\n preprocessing\n \n \n For more information, see respective modules.\n \n\"\"\"\nfrom os import listdir\nfrom pandas import load as pandas_load\nfrom pandas import read_csv\nimport cPickle\n\n_PATH_TO_DATA_LINUX = \"/usr/home/maxime/hilbert_home/virony_data/\"\n\nlistdir(_PATH_TO_DATA_LINUX)\n_PATH_TO_DATA = _PATH_TO_DATA_LINUX\n\n\n__all__ = [\"save\", \"load\", \"load_chunk\", \"get_ressources\",'_PATH_TO_DATA']\n\n\ndef get_ressources(group_name):\n \"\"\"\n List all the files within the specified group_name folder.\n \n >>> get_ressources(\"corpus\")\n Return a list of all avaiable corpora.\n \"\"\"\n \n return listdir(_PATH_TO_DATA+group_name)\n \ndef save(obj, path):\n \"\"\"\n Save an object in the store at the given location.\n Example: save(new_corpus, \"corpus/new_corpus\")\n \"\"\"\n try:\n obj.to_csv(_PATH_TO_DATA+path, encoding=\"utf-8\")\n except:\n with open(_PATH_TO_DATA+path, \"wb\") as fout:\n cPickle.dump(obj, fout)\n \ndef load(path):\n \"\"\"\n Load an object off the store.\n \n Example:\n >>> load(\"wordlist/emoticon\")\n will load the emoticon DataFrame.\n \"\"\"\n try:\n with open(_PATH_TO_DATA+path, \"rb\") as fin:\n obj = cPickle.load(fin)\n if obj==None:\n return pandas_load(_PATH_TO_DATA+path)\n else:\n return obj\n except:\n return pandas_load(_PATH_TO_DATA+path)\n \ndef load_chunk(path, chunksize, n_iter=1):\n \"\"\"Same as load, but for large files (csv only). Load only a part of the data.\n \n Args:\n str::path: store address of the resource to load\n Int::chunksize: how many rowsto load at the same time\n Int:: n_iter: number of times to iterate over the whole file\n Return:\n Iterator(DataFrame):: iterator over chunks of data\n \"\"\"\n \n for _ in xrange(n_iter):\n for chunk in read_csv(_PATH_TO_DATA+path, header=0, index_col=0, encoding=\"utf-8\", chunksize=chunksize):\n yield chunk\n \n","sub_path":"virony/data/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"640189883","text":"import sys\nimport math\nfrom collections import defaultdict\n\n\"\"\"\n Given a set of distinct numbers, find all subsets of this set.\n\"\"\"\ndef subset(s):\n if not s or len(s) == 1:\n return s if len(s) == 1 else []\n\n res = []\n subset_help(s, 0, [], res)\n return res\n\n\ndef subset_help(s, idx, curr, res):\n n = len(s)\n\n if idx == n:\n res.append(list(curr))\n return\n\n curr.append(idx)\n subset_help(s, idx + 1, curr, res)\n curr.pop()\n subset_help(s, idx + 1, curr, res)\n\n\n\"\"\"\n Subset without recursion\n\"\"\"\ndef subset_iterative(s):\n if not s or len(s) == 1:\n return s if len(s) == 1 else []\n\n res = [[]]\n for num in s:\n new_res = []\n for curr in res:\n new_set = list(curr)\n new_set.append(num)\n new_res.append(new_set)\n res.extend(new_res)\n return res\n\n\n\n#s = [1, 2, 3, 4, 5]\n#print len(subset(list(s)))\n#print '-' * 100\n#print len(subset_iterative(list(s)))\n","sub_path":"Py_leetcode/071_subset.py","file_name":"071_subset.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"216161969","text":"import os\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport imageio\nimport matplotlib.pyplot as plt\nimport tfmodel\n\nDATA_NAME = 'Data'\nTRAIN_SOURCE = \"Train\"\nTEST_SOURCE = 'Test'\nRUN_NAME = \"SELU_Run_step16500_batch6\"\nOUTPUT_NAME = 'Output'\nCHECKPOINT_FN = 'model.ckpt'\n\nWORKING_DIR = os.getcwd()\n\nTRAIN_DATA_DIR = os.path.join(WORKING_DIR, DATA_NAME, TRAIN_SOURCE)\nTEST_DATA_DIR = os.path.join(WORKING_DIR, DATA_NAME, TEST_SOURCE)\n\nROOT_LOG_DIR = os.path.join(WORKING_DIR, OUTPUT_NAME)\nLOG_DIR = os.path.join(ROOT_LOG_DIR, RUN_NAME)\nCHECKPOINT_FL = os.path.join(LOG_DIR, CHECKPOINT_FN)\n\nTRAIN_WRITER_DIR = os.path.join(LOG_DIR, TRAIN_SOURCE)\nTEST_WRITER_DIR = os.path.join(LOG_DIR, TEST_SOURCE)\n\nNUM_EPOCHS = 10\nMAX_STEP = 16500\nBATCH_SIZE = 1\n\nLEARNING_RATE = 1e-04\n\nSAVE_RESULTS_INTERVAL = 5\nSAVE_CHECKPOINT_INTERVAL = 100\n\n\ndef main():\n\n test_data = tfmodel.GetData(TEST_DATA_DIR)\n #print(\"test_data:\", test_data)\n\n g = tf.Graph()\n\n with g.as_default():\n\n images, labels = tfmodel.placeholder_inputs(batch_size=BATCH_SIZE)\n\n logits, softmax_logits = tfmodel.inference(images, class_inc_bg=2)\n\n tfmodel.add_output_images(images=images, logits=logits, labels=labels)\n\n loss = tfmodel.loss_calc(logits=logits, labels=labels)\n\n global_step = tf.Variable(0, name='global_step', trainable=False)\n\n train_op = tfmodel.training(loss=loss, learning_rate=1e-04, global_step=global_step)\n\n accuracy = tfmodel.evaluation(logits=logits, labels=labels)\n\n summary = tf.summary.merge_all()\n\n init = tf.global_variables_initializer()\n\n saver = tf.train.Saver(tf.global_variables())\n\n sm = tf.train.SessionManager(graph=g)\n\n with sm.prepare_session(\"\", init_op=init, saver=saver, checkpoint_dir=LOG_DIR) as sess:\n\n sess.run(tf.local_variables_initializer())\n\n try:\n\n count = 0\n while True:\n\n if (count > 279):\n break\n\n else:\n #images_batch, labels_batch = test_data.next_batch(BATCH_SIZE)\n\n images_batch, labels_batch, fname = test_data.get_one_image()\n feed_dict = {images: images_batch[None, ...], labels: labels_batch[None, ...]}\n print('image_data1:', images_batch[None, ...].shape)\n\n image_data = sess.run(logits, feed_dict=feed_dict)\n print('image_data2:', image_data.shape)\n\n image = np.argmax(image_data, axis=-1)[0, ...]\n #image = np.reshape(image)\n print('image:', image.shape)\n\n plt.imsave(os.path.join((r'C:\\Users\\Yun\\Documents\\GitHub\\SegNetCMR\\result_images\\SELU_Run_step16500_batch6'), fname), image, cmap='gray')\n count = count + 1\n\n\n except Exception as e:\n print('Exception')\n print(e)\n\n print(\"Stopping\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"289428875","text":"import argparse\nimport os\nimport sqlite3\nimport time\nfrom contextlib import contextmanager\nfrom shutil import rmtree\n\nimport pytest\n\nfrom backuppy.blob import apply_diff\nfrom backuppy.cli.backup import main as backup\nfrom backuppy.cli.restore import main as restore\nfrom backuppy.io import IOIter\nfrom backuppy.util import file_walker\nfrom backuppy.util import path_join\nfrom itests.conftest import _TestFileData\nfrom itests.conftest import BACKUP_ARGS\nfrom itests.conftest import BACKUP_DIR\nfrom itests.conftest import clean_up_temp_directories\nfrom itests.conftest import get_latest_manifest\nfrom itests.conftest import ITEST_CONFIG\nfrom itests.conftest import itest_setup\nfrom itests.conftest import RESTORE_DIR\n\ntest_file_history = dict() # type: ignore\nRESTORE_ARGS = argparse.Namespace(\n disable_compression=True,\n disble_encryption=True,\n before='now',\n config=ITEST_CONFIG,\n dest=RESTORE_DIR,\n name='data1_backup',\n sha=None,\n like='',\n preserve_scratch_dir=True,\n yes=False,\n)\n\n\n@pytest.fixture(autouse=True, scope='module')\ndef init():\n clean_up_temp_directories()\n\n\n@pytest.fixture(autouse=True)\ndef clear_restore():\n try:\n rmtree(RESTORE_DIR)\n time.sleep(1) # give the filesystem some time to catch up since we do this for every test\n except FileNotFoundError:\n pass\n\n\ndef get_backup_dir_state():\n backup_dir_state = dict()\n if not os.path.exists(BACKUP_DIR):\n return dict()\n\n for f in file_walker(BACKUP_DIR):\n backup_dir_state[f] = os.stat(f).st_mtime\n return backup_dir_state\n\n\ndef assert_backup_store_correct():\n latest_manifest = get_latest_manifest()\n manifest_conn = sqlite3.connect(latest_manifest)\n manifest_conn.row_factory = sqlite3.Row\n manifest_cursor = manifest_conn.cursor()\n for path, history in test_file_history.items():\n latest = history[-1]\n\n manifest_cursor.execute(\n 'select * from manifest where abs_file_name=? order by commit_timestamp',\n (os.path.abspath(latest.path),),\n )\n rows = manifest_cursor.fetchall()\n if 'dont_back_me_up' in path:\n assert len(rows) == 0\n continue\n else:\n deduped_history = []\n [deduped_history.append(i) for i in history if i not in deduped_history]\n assert len(rows) == len(deduped_history)\n for row in rows:\n assert (row['sha'], row['mode']) in [(e.sha, e.mode) for e in deduped_history]\n\n if latest.backup_path:\n manifest_cursor.execute(\n 'select * from base_shas where sha=?',\n (latest.sha,),\n )\n row = manifest_cursor.fetchone()\n with IOIter(latest.backup_path) as n:\n if not row or not row[1]:\n assert n.fd.read() == latest.contents\n else:\n orig_file_path = path_join(BACKUP_DIR, row[1][:2], row[1][2:4], row[1][4:])\n with IOIter(orig_file_path) as o, IOIter() as tmp:\n apply_diff(o, n, tmp)\n tmp.fd.seek(0)\n assert tmp.fd.read() == latest.contents\n\n\ndef assert_restore_correct():\n itest_restore_root = os.path.join(RESTORE_DIR, 'data1_backup')\n for f in file_walker(itest_restore_root):\n abs_file_name = f[f.find(itest_restore_root) + len(itest_restore_root):]\n with open(f) as restore_file, open(abs_file_name) as orig_file:\n assert restore_file.read() == orig_file.read()\n\n\ndef check_backup_restore(dry_run):\n BACKUP_ARGS.dry_run = dry_run\n original_state = get_backup_dir_state()\n backup(BACKUP_ARGS)\n if dry_run:\n assert original_state == get_backup_dir_state()\n else:\n assert_backup_store_correct()\n restore(RESTORE_ARGS)\n assert_restore_correct()\n\n\n@contextmanager\ndef initial_backup_files():\n with itest_setup(\n test_file_history,\n _TestFileData('foo', 'asdf'),\n _TestFileData('bar', 'hjkl'),\n _TestFileData('baz/buz', 'qwerty'),\n _TestFileData('dont_back_me_up_1', 'secrets!'),\n _TestFileData('baz/dont_back_me_up_2', 'moar secrets!'),\n _TestFileData('fizzbuzz', 'I am a walrus', data_dir_index=1),\n ):\n yield\n\n\n@contextmanager\ndef unchanged():\n with itest_setup(test_file_history):\n yield\n\n\n@contextmanager\ndef contents_changed():\n with itest_setup(\n test_file_history,\n _TestFileData('foo', 'adz foobar'),\n _TestFileData('bar', 'hhhhh'),\n ):\n yield\n\n\n@contextmanager\ndef file_deleted():\n with itest_setup(\n test_file_history,\n _TestFileData('foo', None),\n ):\n yield\n\n\n@contextmanager\ndef file_restored():\n with itest_setup(\n test_file_history,\n _TestFileData('foo', 'adz foobar'),\n ):\n yield\n\n\n@contextmanager\ndef mode_changed():\n with itest_setup(\n test_file_history,\n _TestFileData('foo', 'adz foobar', mode=0o100755),\n ):\n yield\n\n\n@contextmanager\ndef contents_changed_after_delete():\n with itest_setup(\n test_file_history,\n _TestFileData('foo', 'adfoo blah blah blah blah blah'),\n ):\n yield\n\n\n@contextmanager\ndef new_file_same_contents():\n with itest_setup(\n test_file_history,\n _TestFileData('new_file', 'adz foobar'), # this points at a diff\n ):\n yield\n\n\n@contextmanager\ndef old_file_same_contents():\n with itest_setup(\n test_file_history,\n _TestFileData('bar', 'I am a walrus'), # this points at an original\n ):\n yield\n\n\n@pytest.mark.parametrize('dry_run', [True, False])\n@pytest.mark.parametrize('fixture', [\n initial_backup_files,\n unchanged,\n contents_changed,\n file_deleted,\n file_restored,\n mode_changed,\n contents_changed_after_delete,\n new_file_same_contents,\n old_file_same_contents,\n])\ndef test_initial_backup(dry_run, fixture):\n with fixture():\n check_backup_restore(dry_run)\n","sub_path":"itests/backup_restore_test.py","file_name":"backup_restore_test.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"603321696","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n###############################################################################\n# File : samplenetldap1.py\n# Description : Sample script using python-ldap. Script performs an\n# anonymous query against the Enterprise Directory\n# and returns results.\n#\n# Requires : python-ldap Python module installed on script host\n# Author : Paul Watson\n# Date : 2008-02-13\n# Documentation : http://python-ldap.sourceforge.net/\n###############################################################################\nimport sys\nimport ldap\n\nhost = 'ldap://hpe-pro-ods-ed.infra.hpecorp.net:389'\nbase = 'o=hp.com'\nscope = ldap.SCOPE_SUBTREE\n\n# print(sys.argv)\nfilter = ('(uid='+sys.argv[1]+')')\nattrs = ['cn', 'mail', 'uid']\n\nl = ldap.initialize(host)\nr = l.search_s(base, scope, filter, attrs)\nprint(r)\n# for dn, entry in r:\n# print('dn=', repr(dn))\n# for k in entry.keys():\n# print('\\t', k, '=', entry[k])\n\nsys.exit(0)\n","sub_path":"backend/ldap3.py","file_name":"ldap3.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"266794788","text":"#python_repos.py\nimport requests\nimport pygal\n\n#执行API调用并存储响应\nurl='https://api.github.com/search/repositories?q=language:python&sort=stars'\n\n#获得响应对象\nr=requests.get(url)\n\n#获得状态码\nprint(\"status code:\",r.status_code)\n\n#将API响应存储在一个变量中,这个API返回JSON格式的信息,使用方法json把这些信息转换为一个python字典\nresponse_dict=r.json()\nprint(\"Total repositories:\",response_dict['total_count'])\n\n#探索有关仓库的信息\nrepo_dicts=response_dict['items']\nprint(\"Repositories returned:\",len(repo_dicts))\n\nprint(\"\\nSelected information about each repository:\")\nfor repo_dict in repo_dicts:\n print('\\nName:',repo_dict['name'])\n print('Owner:',repo_dict['owner']['login'])\n print('Stars:',repo_dict['stargazers_count'])\n print('Repository:',repo_dict['html_url'])\n print('Description:',repo_dict['description'])\n\n #探索有关仓库的信息\nrepo_dicts=response_dict['items']\n\nnames,stars=[],[]\nfor repo_dict in repo_dicts:\n names.append(repo_dict['name'])\n stars.append(repo_dict['stargazers_count'])\n\n#可视化\nmy_style=LS('#333366',base_style=LCS)\n\n#创建pygal类的config实例,通过修改其属性,可定制图表��观\nmy_config=pygal.Config()\n\n#让标签绕x轴旋转45度\nmy_config.x_label_rotation=45\n#隐藏了图例\nmy_config.show_legend=False\n\n#设置图表标题、副标签和主标签的字体大小\nmy_config.title_font_size=24\nmy_config.label_font_size=14\nmy_config.major_label_font_size=18\n\n#将较长的项目名缩短为15个字符\nmy_config.truncate_label=15\n\n#隐藏图表中的水平线,设置自定义宽度\nmy_config.show_y_guides=False\nmy_config.width=1000\n\nchart=pygal.Bar(my_config,style=my_style)\nchart.title='Most-starred Python Projects on GitHub'\nchart.x_labels=names\n\nchart.add('',stars)\nchart.render_to_file('python_repos.svg')\n\nfor repo_dict in repo_dicts:\n names.append(repo_dict['name'])\n plot_dict={\n 'value':repo_dict['stargazers_count'],\n 'label':repo_dict['description'],\n 'xlink':repo_dict['html_url']\n }\n plot_dicts.append(plot_dict)\n\nchart.add('',plot_dicts)","sub_path":"API学习/API学习.py","file_name":"API学习.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"303408333","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport json\nimport get_point\nfrom PIL import Image\n\n'''\nhttp://47.95.70.97:8950/captcha/captcha/captchaImage post 获取dataToken参数\n\nhttp://47.95.70.97:8950/captcha/captcha/checkCaptcha post 获取token参数\n\nhttp://bulletin.cebpubservice.com/xxfbcmses/search/bulletin.html get 获取数据\n\nhttp://47.95.70.97:8950/captcha/captcha/image/big_source_60_65ded5353c5ee48d.png get 验证码图片残缺\n\n'''\n\n\ndef save_img(bigImgName, sourceImgName):\n img_url = 'http://47.95.70.97:8950/captcha/captcha/image/'\n with open('img/bigImgName.png', 'wb')as f_wb:\n f_wb.write(session.get(url=img_url + bigImgName, headers=headers).content)\n\n with open('img/sourceImgName.png', 'wb')as f_wb:\n f_wb.write(session.get(url=img_url + sourceImgName, headers=headers).content)\n\n\nsession = requests.session()\n\nurl1 = 'http://47.95.70.97:8950/captcha/captcha/captchaImage'\n\nheaders = {\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Content-Length': '0',\n 'Host': '47.95.70.97:8950',\n 'Origin': 'http://bulletin.cebpubservice.com',\n 'Pragma': 'no-cache',\n 'Referer': 'http://bulletin.cebpubservice.com/VerificationCode/login.html?id=88&url=http://bulletin.cebpubservice.com/xxfbcmses/search/bulletin.html?searchDate=1995-06-24&dates=300&categoryId=88&industryName=&area=&status=&publishMedia=&sourceInfo=&showStatus=&word=',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',\n\n}\n\nres1 = session.post(url=url1, headers=headers)\nres_data = json.loads(res1.text)\ndataToken = res_data['dataToken']\n\nbigImgName = res_data['bigImgName']\nsourceImgName = res_data['sourceImgName']\n\nsave_img(bigImgName, sourceImgName)\n\nimg1 = Image.open('img/sourceImgName.png')\nimg2 = Image.open('img/bigImgName.png')\n\npoint = get_point.get_gap(img1, img2)\nurl2 = 'http://47.95.70.97:8950/captcha/captcha/checkCaptcha'\n\ndata = {\n 'dataToken': dataToken,\n 'point': point-7,\n}\n\nres2 = session.post(url=url2, headers=headers, data=data)\ntoken = json.loads(res2.text)['data']\ndata_url = 'http://bulletin.cebpubservice.com/xxfbcmses/search/bulletin.html?searchDate=1995-06-24&dates=300&categoryId=88&industryName=&area=&status=&publishMedia=&sourceInfo=&showStatus=&word=&token={}'.format(token)\nheaders.update({'Host': 'bulletin.cebpubservice.com'})\nres3 = session.get(data_url, headers=headers)\nprint(res3.text)\n","sub_path":"投标平台/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"86958962","text":"from django.contrib import admin\nfrom .models import *\nfrom adminfilters.filters import RelatedFieldCheckBoxFilter\nfrom slides.models import Slide\n# АДМИНКА #\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass SlaPartOnTimeAdmin(admin.ModelAdmin):\n list_display = ('report','part_on_time','target','planned','week',)\n list_filter = (('report',RelatedFieldCheckBoxFilter),)\n list_editable = ('part_on_time','target','planned','week',)\n\n\n\n\n\nclass SlaPartOnTimeExploitationAdmin(admin.ModelAdmin):\n list_display = ('report','implemented_overdue','implemented_on_time','on_time','week',)\n list_filter = (('report',RelatedFieldCheckBoxFilter),)\n list_editable = ('implemented_overdue','implemented_on_time','on_time','week',)\n\n\n\n\n\nclass SlaXSAdmin(admin.ModelAdmin):\n list_display = ('report','part_on_time','target','planned','week',)\n list_filter = (('report',RelatedFieldCheckBoxFilter),)\n list_editable = ('part_on_time','target','planned','week',)\n\n\n\n\n\nclass SlaPreAnalysisAdmin(admin.ModelAdmin):\n list_display = ('report','part_standart','target','week',)\n list_filter = (('report',RelatedFieldCheckBoxFilter),)\n list_editable = ('part_standart','target','week',)\n\n\n\n\n\nclass SlaAverageDurationAdmin(admin.ModelAdmin):\n list_display = ('report','average_duration','standard','count_rfc','week',)\n list_filter = (('report',RelatedFieldCheckBoxFilter),)\n list_editable = ('average_duration','standard','count_rfc','week',)\n\n\n\n\nclass SlaReachGf1Admin(admin.ModelAdmin):\n list_display = ('report','payments','self_service','billing','control_services','sales','max_target','middle_target','min_target','week',)\n list_filter = (('report',RelatedFieldCheckBoxFilter),)\n list_display_links = ('report',)\n list_editable = ('payments','self_service','billing','control_services','sales','max_target','middle_target','min_target','week',)\n\n\n\n\n\nclass SlaReachGf2Admin(admin.ModelAdmin):\n list_display = ('report','payments','self_service','billing','control_services','sales','max_target','middle_target','min_target','week',)\n list_filter = (('report',RelatedFieldCheckBoxFilter),)\n list_display_links = ('report',)\n list_editable = ('payments','self_service','billing','control_services','sales','max_target','middle_target','min_target','week',)\n\n\n\nclass SlaReachGf3Admin(admin.ModelAdmin):\n list_display = ('report','service','max_target','middle_target','min_target','week',)\n list_filter = (('report',RelatedFieldCheckBoxFilter),)\n list_display_links = ('report',)\n list_editable = ('service','max_target','middle_target','min_target','week',)\n\n\n\nclass SlideInline(admin.StackedInline):\n model = Slide\n extra = 0\n\n\nclass ReportAdmin(admin.ModelAdmin):\n list_display = ('title',)\n inlines = [SlideInline]\n\n #hightchart editor\n class Media:\n js = ('/static/highcharts_editor/highstock.js',\n '/static/highcharts_editor/map.js',\n '/static/highcharts_editor/codemirror.min.js',\n 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.18.2/mode/javascript/javascript.min.js',\n '/static/highcharts_editor/highcharts-more.js',\n '/static/highcharts_editor/highcharts-3d.js',\n '/static/highcharts_editor/data.js',\n '/static/highcharts_editor/exporting.js',\n '/static/highcharts_editor/funnel.js',\n '/static/highcharts_editor/solid-gauge.js',\n '/static/highcharts_editor/highcharts-editor.complete.js',\n\n )\n css = {\n 'all': ('/static/highcharts_editor/css/codemirror.min.css',\n '/static/highcharts_editor/css/neo.min.css',\n '/static/highcharts_editor/css/highcharts-editor.min.css',\n )\n }\n\n\n\nadmin.site.register(Report,ReportAdmin)\nadmin.site.register(SlaPartOnTime, SlaPartOnTimeAdmin)\nadmin.site.register(SlaPartOnTimeExploitation, SlaPartOnTimeExploitationAdmin)\nadmin.site.register(SlaXS, SlaXSAdmin)\nadmin.site.register(SlaPreAnalysis, SlaPreAnalysisAdmin)\nadmin.site.register(SlaAverageDuration, SlaAverageDurationAdmin)\nadmin.site.register(SlaReachGf1,SlaReachGf1Admin)\nadmin.site.register(SlaReachGf2,SlaReachGf2Admin)\nadmin.site.register(SlaReachGf3,SlaReachGf3Admin)\nadmin.site.register(Months)\nadmin.site.register(Sections)\nadmin.site.register(SlaCrashGfA2A3)\n","sub_path":"charts_generator/main/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"377928089","text":"from logic import confighandler as cfg\nfrom logic import decode\nfrom logic import open_logging\n\nimport os\nimport logging\nfrom logging import handlers\nimport datetime\nimport sqlite3\n\n__DATABASE_NAME = \"weather_info.db\"\n\n__database_path = None\n__table_name = \"weather_info\"\n# MAYBE create .db for every city\n\n__newest_data = {}\n\nlogger = logging.getLogger(__name__)\nsql_logger = logging.getLogger(__name__ + \"_sql\")\n\n\nsql_format = logging.Formatter('[%(asctime)s / %(levelname)s] %(message)s')\nfile_handler = logging.handlers.RotatingFileHandler('open_weather_database.log')\nfile_handler.setLevel(logging.DEBUG)\nfile_handler.setFormatter(sql_format)\n\nsql_logger.addHandler(file_handler)\n\n\ndef execute_sql(cursor, command):\n sql_logger.debug(command)\n cursor.execute(command)\n\n\ndef get_newest_data_date(city_id):\n return __newest_data[city_id]\n\n\ndef setup_database():\n global __database_path\n\n __save_path = cfg.get_save_dir()\n if not os.path.isdir(__save_path):\n os.makedirs(__save_path)\n\n __database_path = cfg.get_save_dir() + \"\\\\\" + __DATABASE_NAME\n\n check_table_existence()\n check_integrity()\n\n\ndef reset_database():\n logger.info(\"DAT - Resetting database\")\n os.remove(__database_path)\n check_table_existence()\n\n\ndef check_table_existence():\n global __database_path\n\n connection = sqlite3.connect(__database_path)\n cursor = connection.cursor()\n execute_sql(cursor, \"SELECT name FROM sqlite_master WHERE type='table' AND name='\" + __table_name + \"'\")\n\n if cursor.fetchone() is None:\n execute_sql(cursor, \"CREATE TABLE \" + __table_name + \" (city_id NUMERIC, entry_date TEXT, entry_time TEXT, cur_temp NUMERIC, temp_max NUMERIC, temp_min NUMERIC, pressure NUMERIC, humidity NUMERIC, wind_spd NUMERIC, wind_deg NUMERIC, clouds NUMERIC, rain_vol NUMERIC,snow_vol NUMERIC, PRIMARY KEY (city_id, entry_date, entry_time))\")\n connection.commit()\n logger.warning(\"DAT - Table didn't exist '%s' newly created\" % __table_name)\n\n else:\n logger.info(\"DAT - Table '%s' loaded\" % __table_name)\n\n connection.close()\n\n\ndef check_integrity():\n connection = sqlite3.connect(__database_path)\n cursor = connection.cursor()\n execute_sql(cursor, \"PRAGMA table_info(\" + __table_name + \")\")\n\n columns = cursor.fetchall()\n\n # check primary keys\n try:\n if columns[0] != (0, 'city_id', 'NUMERIC', 0, None, 1):\n cursor.close()\n connection.close()\n logger.error(\"DAT - Key column 'city_id' wasn't found\")\n reset_database()\n return\n if columns[1] != (1, 'entry_date', 'TEXT', 0, None, 2):\n logger.error(\"DAT - Key column 'entry_date' wasn't found\")\n cursor.close()\n connection.close()\n reset_database()\n return\n if columns[2] != (2, 'entry_time', 'TEXT', 0, None, 3):\n logger.error(\"DAT - Key column 'entry_time' wasn't found\")\n cursor.close()\n connection.close()\n reset_database()\n return\n\n except:\n logger.exception(\"DAT - Exception during key column check\")\n cursor.close()\n connection.close()\n reset_database()\n return\n\n # check normal columns\n connection.row_factory = sqlite3.Row\n execute_sql(cursor, 'SELECT * FROM ' + __table_name)\n names = [description[0] for description in cursor.description]\n\n if len(names) < 13:\n logger.warning(\"DAT - Detected missing columns\")\n cursor.close()\n connection.close()\n add_missing_columns(names)\n return\n\n cursor.close()\n connection.close()\n\n\ndef add_missing_columns(old_columns):\n logger.info(\"DAT - Recreating table with all columns and transferring old data\")\n\n connection = sqlite3.connect(__database_path)\n cursor = connection.cursor()\n\n columns_str = ', '.join(old_columns)\n\n execute_sql(cursor, \"ALTER TABLE \" + __table_name + \" RENAME TO TempOldTable\")\n connection.commit()\n check_table_existence()\n execute_sql(cursor, \"INSERT INTO \" + __table_name + \" (\" + columns_str + \") SELECT \" + columns_str + \" FROM TempOldTable\")\n connection.commit()\n execute_sql(cursor, \"DROP TABLE TempOldTable\")\n connection.commit()\n\n cursor.close()\n connection.close()\n\n\ndef get_specific(city_id, log_time):\n connection = sqlite3.connect(__database_path)\n cursor = connection.cursor()\n execute_sql(cursor, \"SELECT * FROM \" + __table_name + \" WHERE city_id = '\" + str(city_id) + \"' and entry_date = '\" + str(log_time.date()) + \"' and entry_time = '\" + str(log_time.time()) + \"'\")\n\n return cursor.fetchone()\n\n\ndef get_date(city_id, log_time):\n connection = sqlite3.connect(__database_path)\n cursor = connection.cursor()\n execute_sql(cursor, \"SELECT * FROM \" + __table_name + \" WHERE city_id = '\" + str(city_id) + \"' and entry_date = '\" + str(log_time.date()) + \"'\")\n\n return cursor.fetchall()\n\n\ndef get_city(city_id):\n connection = sqlite3.connect(__database_path)\n cursor = connection.cursor()\n execute_sql(cursor, \"SELECT * FROM \" + __table_name + \" WHERE city_id = '\" + str(city_id) + \"'\")\n\n return cursor.fetchall()\n\n\ndef get_custom(where_str, request_row='*'):\n connection = sqlite3.connect(__database_path)\n cursor = connection.cursor()\n execute_sql(cursor, \"SELECT \" + request_row + \" FROM \" + __table_name + \" WHERE \" + where_str)\n\n return cursor.fetchall()\n\n\ndef execute_custom(execute_str):\n connection = sqlite3.connect(__database_path)\n cursor = connection.cursor()\n execute_sql(cursor, execute_str)\n\n return cursor.fetchall()\n\n\ndef insert_fetched_data(city_id, log_time, cur_temp, temp_max, temp_min, pressure, humidity, wind_spd, wind_deg, clouds, rain_vol, snow_vol):\n entry_date = log_time.date()\n entry_time = log_time.time()\n\n weather_info = [str(city_id), str(entry_date), str(entry_time), str(cur_temp), str(temp_max), str(temp_min), str(pressure), str(humidity), str(wind_spd),\n str(wind_deg), str(clouds), str(rain_vol), str(snow_vol)]\n\n connection = sqlite3.connect(__database_path)\n cursor = connection.cursor()\n\n try:\n execute_sql(cursor, \"INSERT INTO \" + __table_name + \" VALUES (\" + str(weather_info).strip(\"[]\") + \")\")\n except sqlite3.IntegrityError:\n logger.warning(\"DAT - Entry already exists\")\n except:\n logger.exception(\"DAT - Error during insert\")\n\n\n __newest_data[city_id] = log_time\n connection.commit()\n cursor.close()\n connection.close()\n\n\ndef process_fetched_data(fetched_data):\n dec = decode.Decoder(fetched_data)\n data_list = dec.get_all_values()\n\n city_id = data_list['city_id']\n log_time = datetime.datetime.fromtimestamp(data_list['response_time'])\n cur_temp = data_list['cur_temp']\n temp_max = data_list['temp_max']\n temp_min = data_list['temp_min']\n pressure = data_list['pressure']\n humidity = data_list['humidity']\n wind_spd = data_list['wind_spd']\n wind_deg = data_list['wind_deg']\n clouds = data_list['clouds']\n rain_vol = data_list['rain_vol']\n snow_vol = data_list['snow_vol']\n\n insert_fetched_data(city_id, log_time, cur_temp, temp_max, temp_min, pressure, humidity, wind_spd,\n wind_deg, clouds, rain_vol, snow_vol)\n\n\nif __name__ == \"__main__\":\n open_logging.init_logging()\n cfg.read_config()\n setup_database()\n with open(\"C:\\\\Users\\\\Saint\\\\PycharmProjects\\\\OpenWeather\\\\docs\\\\example_response.json\") as f:\n c = f.read()\n process_fetched_data(c)\n print(get_date(\"2950159\", datetime.datetime(2016, 8, 22, 21, 40, 45)))\n","sub_path":"logic/datastore.py","file_name":"datastore.py","file_ext":"py","file_size_in_byte":7629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"35127982","text":"# -*- coding: utf-8 -*-\nfrom unittest import TestCase, main\n\nfrom pygerber.drawing_state import DrawingState\nfrom pygerber.exceptions import InvalidCommandFormat\nfrom pygerber.validators.struct_validator import StructValidator\nfrom pygerber.validators.validator import Validator\n\n\nclass DispatcherTest(TestCase):\n def test_dispatcher(self):\n class ARGS_dispatcher(StructValidator):\n VALUE = Validator()\n\n validator1 = ARGS_dispatcher(r\"(?P[a-z]+)\")\n\n cleaned1 = validator1(None, DrawingState(), \"foo\")\n cleaned2 = validator1(None, DrawingState(), \"bar\")\n self.assertEqual(cleaned1.VALUE, \"foo\")\n self.assertEqual(cleaned2.VALUE, \"bar\")\n\n def test_dispatcher_fail(self):\n class ARGS_dispatcher(StructValidator):\n VALUE = Validator()\n\n validator1 = ARGS_dispatcher(r\"(?P[a-z]+)\")\n\n self.assertRaises(\n InvalidCommandFormat, lambda: validator1(None, DrawingState(), \"346\")\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tests/test_validators/test_dispatcher.py","file_name":"test_dispatcher.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"512891834","text":"\"\"\"\napi.clients\n~~~~~~~~~~~\n\nThis module implements the API clients.\n\n:copyright: (c) 2019 by Elliott Maguire, SmartRecruiters\n\"\"\"\n\nimport os\nimport time\nimport json\n\nfrom api.models import Account, Contact\n\nimport requests\nimport simple_salesforce\n\n\nclass SalesforceClient:\n \"\"\" Client for the Salesforce API.\n\n :param creds: a dictionary of Salesforce credentials\n \"\"\"\n def __init__(self, **creds):\n self.api = simple_salesforce.Salesforce(**creds)\n\n def get_accounts(self):\n \"\"\" Collects enrichment requests from Salesforce.\n\n :return accounts: a list of dictionaries of account data\n \"\"\"\n sql = \"\"\"\n SELECT\n Id, DSCORGPKG__DiscoverOrg_ID__c, Name, Phone, Website,\n Notes__c, OB_Company_Name_Normalized__c,\n Prospecting_EBR__c, Enrichment_Requested_Date__c\n FROM\n Account\n WHERE\n Enrichment_Requested__c = True\n AND\n Enrichment_Complete__c = False\n \"\"\"\n\n accounts = []\n records = self.api.query(sql)['records']\n for record in records:\n account = {\n 'sfid': record['Id'],\n 'doid': record['DSCORGPKG__DiscoverOrg_ID__c'] or '',\n 'prep': record['Prospecting_EBR__c'] or '0050V000006j7Jj',\n 'name': record['OB_Company_Name_Normalized__c'],\n 'domain': record['Website'],\n 'phone': record['Phone'],\n 'insight': record['Notes__c'],\n 'status': 'enrich'}\n\n accounts.append(account)\n\n return accounts\n\n def get_contacts(self, account):\n \"\"\" Collects contacts for an account.\n\n :param account: an Account object\n :return contacts: a list of dictionaries of contact data\n \"\"\"\n sql = \"\"\"\n SELECT\n Id, Name, Title,\n Phone, MobilePhone, Email\n FROM\n Contact\n WHERE\n AccountId = '{sfid}'\n \"\"\".format(sfid=account.sfid)\n\n contacts = []\n records = self.api.query(sql)['records']\n for record in records:\n contact = {\n 'account': account,\n 'sfid': record['Id'],\n 'name': record['Name'],\n 'title': record['Title'],\n 'office': account.phone,\n 'direct': record['Phone'],\n 'mobile': record['MobilePhone'],\n 'email': record['Email'],\n 'ctype': 'old',\n 'status': 'upload'}\n\n contacts.append(contact)\n\n return contacts\n\n def create_contact(self, contact):\n \"\"\" Creates a new contact in Salesforce.\n\n :param contact: a Contact object\n \"\"\"\n for f in contact.account._meta.fields:\n if getattr(contact.account, f.name) is None:\n setattr(contact.account, f.name, '')\n\n for f in contact._meta.fields:\n if getattr(contact, f.name) is None:\n setattr(contact, f.name, '')\n\n self.api.Contact.create({\n 'AccountId': contact.account.sfid,\n 'DSCORGPKG__DiscoverOrg_ID__c': contact.account.doid,\n 'OwnerId': contact.account.prep,\n 'FirstName': contact.name.split()[0],\n 'LastName': contact.name.split()[1],\n 'Title': contact.title,\n 'Phone': contact.direct,\n 'MobilePhone': contact.mobile,\n 'Email': contact.email})\n\n def update_contact(self, contact):\n \"\"\" Updates a contact in Salesforce.\n\n :param contact: a Contact object\n \"\"\"\n data = {\n 'OwnerId': contact.account.prep,\n 'Title': contact.title,\n 'Phone': contact.direct or contact.account.phone,\n 'MobilePhone': contact.mobile or ''}\n\n self.api.Contact.update(contact.sfid, data)\n\n def complete_account(self, account):\n \"\"\" Marks enrichment as complete.\n\n :param account: an Account object\n \"\"\"\n data = {\n 'Notes__c': account.insight,\n 'Enrichment_Complete__c': True}\n\n self.api.Account.update(account.sfid, data)\n\n\nclass LushaClient:\n \"\"\" Implements a Lusha API client.\n\n :param token: an API token\n \"\"\"\n def __init__(self, token):\n self.token = token\n\n def enrich(self, contact):\n \"\"\" Enriches a contact object.\n\n :param contact: a Contact object\n \"\"\"\n name = contact.name.split()\n if len(name) < 2:\n return\n elif len(name) == 3:\n name.pop(1)\n elif len(name) > 3:\n name = [name[0], name[1]]\n\n response = requests.get(\n 'https://api.lusha.co/person',\n headers={\n 'api_key': self.token},\n params={\n 'firstName': name[0],\n 'lastName': name[1],\n 'company': contact.account.name,\n 'property': 'phoneNumbers'})\n\n if 'errors' in response:\n return\n else:\n data = json.loads(response.text)\n\n numbers = data['phoneNumbers'] if 'phoneNumbers' in data else None\n emails = data['emailAddresses'] if 'emailAddresses' in data else None\n\n if numbers:\n contact.direct = numbers[0]['localizedNumber']\n if len(numbers) > 1:\n contact.mobile = numbers[1]['localizedNumber']\n else:\n return\n\n if emails:\n contact.email = emails[0]['email']\n\n contact.save()\n\n\nclass DiscoverOrgClient:\n \"\"\" Implements a DiscoverOrg API client.\n\n :param username: a DiscoverOrg username\n :param password: a DiscoverOrg password\n :param key: a DiscoverOrg API partner key\n \"\"\"\n def __init__(self, username, password, key):\n self.base = 'https://papi.discoverydb.com/papi'\n\n self.username = username\n self.password = password\n self.key = key\n\n self.session = self._get_session()\n\n def _get_session(self):\n \"\"\" Gets a session key.\n\n :return session: a session key\n \"\"\"\n url = ''.join([self.base, '/login'])\n headers = {\n 'Content-Type': 'application/json'}\n data = {\n 'username': self.username,\n 'password': self.password,\n 'partnerKey': self.key}\n\n response = requests.post(url, headers=headers, data=json.dumps(data))\n session = response.headers['X-AUTH-TOKEN']\n\n return session\n\n def get_contacts(self, account):\n \"\"\" Searches for contacts under an account.\n\n :param account: an Account object\n :return contacts: a list of dictionaries of contact data\n \"\"\"\n response = requests.post(\n url=''.join([self.base, '/v1/search/persons']),\n headers={\n 'X-PARTNER-KEY': self.key,\n 'X-AUTH-TOKEN': self.session,\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'},\n data=json.dumps({\n 'companyCriteria': {\n 'websiteUrls': [account.domain]}}))\n\n data = json.loads(response.text)\n\n contacts = []\n results = data['content']\n for result in results:\n contact = {\n 'doid': result['id'],\n 'name': result['fullName'],\n 'title': (\n result['title']\n if 'title' in result\n else None),\n 'direct': (\n result['officeTelNumber']\n if 'officeTelNumber' in result\n else None),\n 'mobile': (\n result['mobileTelNumber']\n if 'mobileTelNumber' in result\n else None),\n 'email': (\n result['email']\n if 'email' in result\n else None),\n 'ctype': 'new',\n 'status': 'enrich'}\n\n contacts.append(contact)\n\n return contacts\n\n def get_hierarchy(self, account):\n \"\"\" Gets an org heirarchy graph for an account.\n\n :param account: an Account object\n :return hierarchy: a dictionary representing org hierarchy\n \"\"\"\n if not account.doid:\n return 'Unavailable'\n\n response = requests.get(\n url=''.join([self.base, f\"/v1/companies/{account.doid}/orgchart/7\"]),\n headers={\n 'X-PARTNER-KEY': self.key,\n 'X-AUTH-TOKEN': self.session})\n\n data = json.loads(response.text)\n hierarchy = data['nodes'] or 'Unknown'\n\n return hierarchy\n\n","sub_path":"smartrecruiters/era_2/applications/leadr/api/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":8824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"636221136","text":"\ndef find_trios(arr, M):\n arr = sorted(arr)\n lens= len(arr)\n cnt = 0\n for i in range(lens-2):\n for j in range(i+1, lens-1):\n for k in range(j+1, lens):\n if (arr[i]+arr[j]+arr[k])%M==0:\n cnt += 1\n return cnt \n \nnoe, M = [int(x) for x in input().split()] \narr = [int(x) for x in input().split()] \nprint(find_trios(arr, M))\n \n \n \n \n","sub_path":"HackerEarth/divisible_trio.py","file_name":"divisible_trio.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"304344990","text":"import json\nimport sys\n\ninput = open(sys.argv[1], \"r\")\n\ntbl = {}\n\nfor line in input:\n\ttry:\n\t\tvalues = line.split()\n\t\tfv = []\n\t\tfor v in values:\n\t\t\tfv.append(float(v))\n\t\ttbl[(fv[0], fv[1], fv[2])] = [fv[3], fv[4]]\n\texcept:\n\t\tpass\n\t\t\nres = {}\n\t\nres[\"divider\"] = 1\nres[\"accuracy\"] = 0.02\nres[\"gridSize\"] = [50, 50, 50]\nres[\"table\"] = []\n\nfor i in tbl:\n\tdif = tbl[i]\n\tres[\"table\"].append({\"coordinate\":[i[0], i[1], i[2]],\"deviation\":[dif[0], dif[1], 0]})\n\nres[\"origin\"] = [float(sys.argv[3]), float(sys.argv[4]), float(sys.argv[5])]\n\noutput = open(sys.argv[2], \"w\")\njson.dump(res, output, indent=4,sort_keys=True)\n\n","sub_path":"scripts/convert2json.py","file_name":"convert2json.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"378647068","text":"import numpy as np\nimport scipy.interpolate as spi\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\n\n#Reto 2 Analisis Numerico\n#Santiago Fernandez - Mariana Galavis - German Velasco\n#Principales referencias durante el desarrollo del codigo:\n#https://numpy.org/\n#https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html\n#https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splprep.html#scipy.interpolate.splprep\n#https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splev.html#scipy.interpolate.splev\n#https://pandas.pydata.org/\n#https://matplotlib.org/\n#https://www.fisicalab.com/apartado/errores-absoluto-relativos\n\ndef cambio_punto_coma(df, col_name):\n df[col_name] = df[col_name].apply(lambda x: float(x.replace(',', '.')))\n return df\n\ndef creacion_data(df, columns):\n df = df.pipe(cambio_punto_coma, 'Temp. Interna (ºC)')\n df_dht = df[:][columns]\n data = df_dht.to_numpy()\n return data\n\ndef eliminacion_porcentaje(data, p):\n tam = int(np.ceil(len(data) * p))\n restantes = np.zeros((tam, 4))\n for i in range(0, tam):\n r = np.random.randint(0, len(data) - i)\n restantes[i] = data[r]\n data = np.delete(data, r, 0)\n return (data, restantes)\n\n#Lectura y transformacion de archivos\ndf_pen = pd.read_csv('/Users/safer/Desktop/Quinto Semestre Ingeniería de Sistemas/Análisis Numérico/Referencias/Quixada.csv', encoding='utf-8', sep=';')\ndf_sga = pd.read_csv('/Users/safer/Desktop/Quinto Semestre Ingeniería de Sistemas/Análisis Numérico/Referencias/Quixera.csv', encoding='utf-8', sep=';')\nn, m = df_pen[df_pen.columns[0]].count(), df_sga[df_sga.columns[0]].count()\n#Creacion indices\nindices_1 = np.arange(n)\nindices_2 = np.arange(m)\n#Anexo nueva columna\ndf_pen.insert(24, 'Indice', indices_1, False)\ndf_sga.insert(24, 'Indice', indices_2,False)\ndata_pen = df_pen.pipe(creacion_data, ['Dia Juliano', 'Hora', 'Temp. Interna (ºC)','Indice'])\ndata_sga = df_sga.pipe(creacion_data, ['Dia Juliano', 'Hora', 'Temp. Interna (ºC)','Indice'])\n#Establecer una copia de cada conjunto de datos\norg_dp = data_pen\norg_ds = data_sga\n#Eliminacion del 20% de datos de forma aleatoria\np = 0.2\ndata_pen, elm_pen = eliminacion_porcentaje(data_pen, p)\ndata_sga, elm_sga = eliminacion_porcentaje(data_sga, p)\n#Creacion de splines para primera estacion\ns_pen = spi.splrep(data_pen[:, 3], data_pen[:, 2])\nxn_pen = data_pen[:, 3]\nyn_pen = spi.splev(xn_pen, s_pen)\n#Creacion de interpolacion lineal para primera estacion\nf_pen = spi.interp1d(data_pen[:, 3], data_pen[:, 2])\n#Grafica de datos originales (primera parte)\nplt.plot(org_dp[:, 3], org_dp[:, 2], 'k-')\n#Grafica de spline cubico (primera parte)\nplt.plot(xn_pen, yn_pen, 'r--')\n#Grafica de interpolacion lineal (primera parte)\nplt.plot(xn_pen, f_pen(xn_pen), 'm-.')\n#Instancia de graficas (primera parte)\nplt.xlabel(\"Índice Calculado\")\nplt.ylabel(\"Temperatura Interna\")\nplt.title(\"Primer Punto - Estacion Quixadá\")\nplt.legend(['Datos originales', 'Splines Cubicos', 'Interpolacion Lineal'])\nplt.show()\n#Ajuste de datos de segunda estacion\ndata_n = np.empty(((len(data_sga)), 4), float)\n\nfor i in range(0, len(data_sga)):\n for j in range(0, len(org_dp)):\n if data_sga[i][0] == org_dp[j][0] and data_sga[i][1] == org_dp[j][1]:\n data_n[i] = org_dp[j]\n data_n[i][3] = data_sga[i][3]\n break\n\n#Creacion de splines para segunda estacion\ns_sga = spi.splrep(data_n[:, 3], data_n[:, 2])\nxn_sga = data_n[:, 3]\nyn_sga = spi.splev(xn_sga, s_sga)\n#Creacion de interpolacion lineal para segunda estacion\nf_sga = spi.interp1d(data_n[:, 3], data_n[:, 2])\n#Grafica de datos originales (segunda parte)\nplt.plot(org_ds[:, 3], org_ds[:, 2], 'b-')\n#Grafica de interpolacion lineal (segunda parte)\nplt.plot(xn_sga, yn_sga, 'g--')\n#Grafica de interpolacion lineal (segunda parte)\nplt.plot(xn_sga, f_pen(xn_sga), 'c-.')\n#Instancia de graficas (segunda parte)\nplt.xlabel(\"Índice Calculado\")\nplt.ylabel(\"Temperatura Interna\")\nplt.title(\"Segundo Punto - Estacion Quixeramobim\")\nplt.legend(['Datos originales', 'Splines Cubicos', 'Interpolacion Lineal'])\nplt.show()\n#Calculo de errores\nerrorL = np.zeros(len(elm_pen))\nerrorS = np.zeros(len(elm_pen))\nerrorEMC_L = 0\nerrorEMC_S = 0\n\nfor k in range (0, len(elm_pen)):\n er = abs(elm_pen[k][2]-f_pen(elm_pen[k][3]))\n errorL[k] = er\n errorEMC_L += math.pow(er, 2)\n erS = abs(elm_pen[k][2]-spi.splev(elm_pen[k][3], s_pen))\n errorS[k] = erS\n errorEMC_S += math.pow(erS,2)\n\nerrorL_2 = np.zeros(len(elm_sga))\nerrorS_2 = np.zeros(len(elm_sga))\nerrorEMC_L2 = 0\nerrorEMC_S2 = 0\n\nfor k in range (0, len(elm_sga)):\n er = abs(elm_sga[k][2]-f_sga(elm_sga[k][3]))\n errorL_2[k] = er\n errorEMC_L2 += math.pow(er, 2)\n erS = abs(elm_sga[k][2]-spi.splev(elm_sga[k][3], s_sga))\n errorS_2[k] = erS\n errorEMC_S2 += math.pow(erS, 2)\n\n#CALCULO DE ERRORES DE PRIMER PUNTO\n\nprint(\"ERRORES PRIMER PUNTO\")\n\n#Impresion de errores - Lineal\nprint(\"ERROR MAXIMO LINEAL {}\".format(np.amax(errorL)))\nprint(\"ERROR MINIMO LINEAL {}\".format(np.amin(errorL)))\nmedia = np.sum(errorL)/len(errorL)\nprint (\"ERROR MEDIA LINEAL {}\".format(media))\nabsoluto = 0\nfor k in range (0, len(errorL)):\n absoluto += abs(media-errorL[k])\nabsoluto = absoluto/len(errorL)\nprint(\"ERROR ABSOLUTO LINEAL {}\".format(absoluto))\nprint(\"ERROR MEDIO CUADRADO LINEAL {}\".format(math.sqrt(errorEMC_L/len(elm_pen))))\n\nprint(\"----------------------------------------------\")\n\n#Impresion de errores Spline\nprint(\"ERROR MAXIMO SPLINE {}\".format(np.amax(errorS)))\nprint(\"ERROR MINIMO SPLINE {}\".format(np.amin(errorS)))\nmedia = np.sum(errorS)/len(errorS)\nprint(\"ERROR MEDIA SPLINE {}\".format(media))\nabsoluto = 0\nfor k in range (0,len(errorS)):\n absoluto += abs(media-errorS[k])\nabsoluto = absoluto/len(errorS)\nprint(\"ERROR ABSOLUTO SPLINE {}\".format(absoluto))\nprint(\"ERROR MEDIO CUADRADO SPLINE {}\".format(math.sqrt(errorEMC_S/len(elm_pen))))\n\nprint(\"--------------------------------------------------------------------------------------------------------------------------\")\n\n#CALCULO DE ERRORES DE SEGUNDO PUNTO\n\nprint(\"ERRORES SEGUNDO PUNTO\")\n\n#Impresion de errores - Lineal\nprint(\"ERROR MAXIMO LINEAL {}\".format(np.amax(errorL_2)))\nprint(\"ERROR MINIMO LINEAL {}\".format(np.amin(errorL_2)))\nmedia = np.sum(errorL_2)/len(errorL_2)\nprint (\"ERROR MEDIA LINEAL {}\".format(media))\nabsoluto = 0\nfor k in range (0, len(errorL_2)):\n absoluto += abs(media-errorL_2[k])\nabsoluto = absoluto/len(errorL_2)\nprint(\"ERROR ABSOLUTO LINEAL {}\".format(absoluto))\nprint(\"ERROR MEDIO CUADRADO LINEAL {}\".format(math.sqrt(errorEMC_L2/len(elm_sga))))\n\nprint(\"----------------------------------------------\")\n\n#Impresion de errores Spline\nprint(\"ERROR MAXIMO SPLINE {}\".format(np.amax(errorS_2)))\nprint(\"ERROR MINIMO SPLINE {}\".format(np.amin(errorS_2)))\nmedia = np.sum(errorS_2)/len(errorS_2)\nprint(\"ERROR MEDIA SPLINE {}\".format(media))\nabsoluto = 0\nfor k in range (0,len(errorS_2)):\n absoluto += abs(media-errorS_2[k])\nabsoluto = absoluto/len(errorS_2)\nprint(\"ERROR ABSOLUTO SPLINE {}\".format(absoluto))\nprint(\"ERROR MEDIO CUADRADO SPLINE {}\".format(math.sqrt(errorEMC_S2/len(elm_sga))))","sub_path":"Retos/Reto 2/Reto 2.py","file_name":"Reto 2.py","file_ext":"py","file_size_in_byte":7163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"95875545","text":"'''Transmedia Delivery Script:\n\nThis script was developed in order to help streamline Transmedia HUB deliveries to EA.\n\n'''\n\nimport arcpy \nimport os\nimport datetime \n\n#Arcmap Settings\narcpy.env.overwriteOutput = True \narcpy.env.addOutputsToMap = False\n\n#Script input parameters\n\n#HUB for transmedia delivery\nHUB = arcpy.GetParameterAsText (0)\n\n#Excel sheet for HLD Route join\nexcelSheet = arcpy.GetParameterAsText (1)\n\n#Output folder path\nfolderPath = arcpy.GetParameterAsText (2)\n\n#Database Connection\nexistingDataPath = arcpy.GetParameterAsText (3) \n\n#Path to FC template in West Coast GDB\ntemplatePath = '{0}\\\\xxxxxx'.format(existingDataPath)\n\n#Path to HLD Route\nHLDroute = '{0}\\\\xxxxxx'.format(existingDataPath)\n\n#Variable to store proper SQL expression\nexpressionSQL = \"HUB = '{0}'\".format(HUB)\n\n#Select input HUB and use in SQL expression to export HLD Route\nHLDexport = arcpy.Select_analysis(HLDroute, \"in_memory\\\\HLDexport\" , expressionSQL)\n\n#Make lyr file for table join\nHLDlyr = arcpy.MakeFeatureLayer_management(HLDexport, \"in_memory\\\\HLDlyr\")\n\n#Excel to Table\nmyTable = arcpy.ExcelToTable_conversion(excelSheet, \"in_memory\\\\myTable\")\n\n#Join\njoined = arcpy.AddJoin_management(HLDlyr, \"SEGMENT_\", myTable, \"Segment_Name\", \"KEEP_COMMON\")\n\n#copy the FC stored in the joined variable and export to its own FC\nnewFC = arcpy.CopyFeatures_management(joined, \"in_memory\\\\newFC\")\n\n#Apply correct projection to HLDexport\nHLDproject = arcpy.Project_management(newFC, \"HLDproject\", \n\"PROJCS['NAD_1983_StatePlane_California_V_FIPS_0405_Feet',GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic'],PARAMETER['False_Easting',6561666.666666666],PARAMETER['False_Northing',1640416.666666667],PARAMETER['Central_Meridian',-118.0],PARAMETER['Standard_Parallel_1',34.03333333333333],PARAMETER['Standard_Parallel_2',35.46666666666667],PARAMETER['Latitude_Of_Origin',33.5],UNIT['Foot_US',0.3048006096012192]]\", \n\"WGS_1984_(ITRF00)_To_NAD_1983\", \n\"PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]\", \n\"NO_PRESERVE_SHAPE\", \"\", \"NO_VERTICAL\")\n\ndataPath = HLDproject\n\n#Fields in HLD Route needed for calculating new fields and formatting\ncalcList = [\"HLDexport_SEGMENT_\",\"HLDexport_HUB\",\"HLDexport_ROUTETYPE\",\"HLDexport_FIBERSIZE\",\"HLDexport_NETWORKTYPE\",\"HLDexport_NF_ID\",\n\"myTable_DYEA_permit_number\",\"myTable_Site_name\",\"SHAPE@\"]\n\n# New fields for delivery\nnewList = ['none',\"HUB\",\"Type_Name\", \"NumberOfFibers\",\"Network_Type\",\"Cluster_Ring_NFID\",\"Site_Span_NFID\",\n\"Permits\", \"WorkOrderID\",\"SHAPE@\"]\n\n#Search cursor to retrieve necessary records from table\ncursor = arcpy.da.SearchCursor(dataPath, calcList)\n\n#Empty dictionary to write to\nmyDict = {}\t\t\t\t\t\t\t\t\t\t\t\t\npermDict = {}\t\t\t\t\t\t\t\t\t\t\t\nwoDict = {}\t\t\t\t\t\t\t\t\t\t\t\t\nuseWO = {}\t\t\t\t\t\t\t\t\t\t\t\t\n\n#for loop to create nested dictionary w/segment name & permit as key & cursor row as values\n#also edits entries so they are calculated/formatted properly\nfor row in cursor:\n\t# collect permit numbers for each segment\n\tseg = row[0]\n\tperm = row[6]\n\tdKey = \"{0}, {1}\".format(seg, perm)\t\t\t\t\t\n\tmyDict [dKey] = {}\t\t\t\t\t\t\t\t\t \n\tif seg not in permDict :\t\t\t\t\t\t\t\n\t\tpermDict[seg] = [perm]\t\t\t\t\t\t\t \n\telse :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\tmyList = permDict[seg]\t \n\t\t\t\t\t\t\t\t\t\t\t\n\t\tmyList.append(perm)\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\n\t\tpermDict[seg] = myList\t\t\t\t\t\t\t\n\t\t\n\t#Calculate and format Type_Name field\n\ttypeName = row[2]\n\ttypeName = typeName.replace(\"New Underground\", \"BURIED\")\n\ttypeName = typeName.replace(\"New Aerial\", \"AERIAL\")\n\t#Calculate and format NumberofFibers field\n\tfibers = row[3]\n\t#Calculate and format Network_Type field\n\tnetworkType = row[4]\n\tnetworkType = networkType.replace(\"Lateral\", \"Fronthaul\")\n\t#Calculate and format Cluster_Ring_NFID field\n\tcluster = row[5]\n\tcluster = cluster[:-4]\n\t#Calculate and format Site_Span_NFID field\n\tsiteSpan = row[5]\n\t#Calculate and format WorkOrderID field\n\tworkID = \"LSA_N_{}_{}_LLD\".format(row[5],row[7])\n\tworkID = workID.replace(\".\",\"_\")\n\tworkID = workID.replace(\"-\",\"_\")\n\tworkID = workID.replace(\" \",\"_\")\n\t###Now we can populate the empty dictionary with the new values###\n\tmyDict [dKey][newList[2]] = typeName\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t \n\tmyDict [dKey][newList[3]] = fibers\t\t\t\t\t\n\t\n\tmyDict [dKey][newList[4]] = networkType\n\t\n\tmyDict [dKey][newList[5]] = cluster\n\t\n\tmyDict [dKey][newList[6]] = siteSpan\n\t\n\tmyDict [dKey][newList[8]] = workID\n\t\n\t#HUB\n\tmyDict [dKey][newList[1]] = row[1]\n\t\n\t#SHAPE@\n\tmyDict [dKey][newList[9]] = row[8]\n\t\n\t# count fronthaul segments for each workorder\n\tif networkType == 'Fronthaul' :\t\t\t\t\t\t\n\t\tif workID in woDict :\t\t\t\t\t\t\t\n\t\t\t\n\t\t\twoDict[workID] = woDict[workID] + 1\t\t\t\n\t\t\t\n\t\t\tuseWO[workID] = \"yes\"\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t \n\t\telse :\n\t\t\twoDict[workID] = 1\n\t\t\tuseWO[workID] = \"no\"\t\t\t\t\t\t\n\t\n#always delete cursor after you're done\ndel cursor \n\n###Now these new values/dictionary(s) can be used to populate the template FC###\n\n###create folder and GDB for Transmedia deliverable###\n\n#create datetime object for folder naming\ntime = datetime.datetime.now()\ntimeString = str(time.strftime(\"%m%d%Y\"))\n\n#Make folder for Transmedia delivery \nos.chdir(folderPath)\nos.mkdir('{0}_Transmedia_{1}'.format(HUB, timeString))\n\ntransmediaFolder = '{0}\\\\{1}_Transmedia_{2}'.format(folderPath, HUB, timeString)\n\n#Create file GDB and set as workspace\narcpy.CreateFileGDB_management (transmediaFolder, 'Sub_Transmedia_{0}'.format(timeString))\nnewGDB = r'{0}\\Sub_Transmedia_{1}.gdb'.format(transmediaFolder, timeString)\n\narcpy.env.workspace = newGDB \n\n#Copy and export to new FC in corresponding GDB\narcpy.FeatureClassToFeatureClass_conversion(templatePath, newGDB, \"Sub_Transmedia\")\n#list of fields in template FC\nFCfields = [\"SHAPE@\",\"Type_Name\", \"NumberOfFibers\", \"Network_Type\", \"Cluster_Ring_NFID\", \"Site_Span_NFID\", \n\"Permits\", \"WorkOrderID\",\"Segment_\", \"HUB\", \"SHAPE_Length\"]\n\n#use update cursor and for loop to iterate over records and input into new FC\ninsertCursor = arcpy.da.InsertCursor(\"Sub_Transmedia\", FCfields)\n\n#To control \"Fronthaul\" WO naming\nwoDict[workID] = woDict[workID] - 1\n\nfor segment in myDict:\n\tgeometry = myDict[segment][\"SHAPE@\"]\t\t\t\t\t\n\tgeo = geometry.length\t\t\t\t\t\t\t\t\t\n\tpermKey = segment.split(\",\")[0]\t\t\t\t\t\t\t \n\tpermits = \",\".join(permDict[permKey])\t\t\t\t\t\n\t# check for multiple fronthaul segs in workorder\n\two = myDict[segment][\"WorkOrderID\"]\t\t\t\t\t\t\n\tif myDict[segment][\"Network_Type\"] == \"Fronthaul\" and useWO[wo] == \"yes\" :\t\n\t\tif woDict[wo] > 9 :\n\t\t\tnewWO = wo[:-3] + \"{0}_\".format(woDict[wo]) + wo[-3:]\t\n\t\telif woDict[wo] == 0 :\n\t\t\tnewWO = wo\t\t\t\t\t\t\t\t\t\t\t\t\n\t\telse :\n\t\t\tnewWO = wo[:-3] + \"0{0}_\".format(woDict[wo]) + wo[-3:] \n\t\twoDict[wo] = woDict[wo] - 1\t\t\t\t\t\t\t\n\telse :\n\t\tnewWO = wo\t\t\t\t\t\t\t\t\t\t\t\n\t# create new row using list\n\tnRow = [myDict[segment][\"SHAPE@\"],\t\t\t\t\t\t\n\t myDict[segment][\"Type_Name\"],\t\t\t\t\t\t\t\n\t myDict[segment][\"NumberOfFibers\"],\n\t myDict[segment][\"Network_Type\"],\n\t myDict[segment][\"Cluster_Ring_NFID\"],\n\t myDict[segment][\"Site_Span_NFID\"],\n\t permits,\n\t newWO,\n\t permKey,\n\t myDict[segment][\"HUB\"],\n\t geometry.length]\n\t#use insert cursor to populate new row in FC\n\tinsertCursor.insertRow(nRow)\ndel insertCursor\n\n\n### EOlson 12/2018 ###\n### rosemary.erin.o@gmail.com ###\n","sub_path":"transmedaiHUB.py","file_name":"transmedaiHUB.py","file_ext":"py","file_size_in_byte":7558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569894715","text":"n = int(input())\ngrid = [list(map(int, input().split())) for x in range(n)]\n\ndef isGood(grid):\n if sorted(grid[0]) != grid[0]: return False\n a = list(zip(*grid))[0]\n if list(a) != sorted(a): return False\n return True \n\ndef rotate(grid):\n return [list(x) for x in zip(*reversed(grid))]\n\nwhile not isGood(grid):\n grid = rotate (grid)\n\nfor x in grid:\n for y in x:\n print(y, end = \" \")\n print()\n\n","sub_path":"CCC Problems/CCC18S2.py","file_name":"CCC18S2.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"158135957","text":"import pytest\n\nfrom resolvelib.structs import DirectedGraph\n\n\n@pytest.fixture()\ndef graph():\n return DirectedGraph()\n\n\ndef test_simple(graph):\n \"\"\"\n a -> b -> c\n | ^\n +---------+\n \"\"\"\n graph.add(\"a\")\n graph.add(\"b\")\n graph.add(\"c\")\n graph.connect(\"a\", \"b\")\n graph.connect(\"b\", \"c\")\n graph.connect(\"a\", \"c\")\n assert set(graph) == {\"a\", \"b\", \"c\"}\n assert set(graph.iter_edges()) == {(\"a\", \"b\"), (\"a\", \"c\"), (\"b\", \"c\")}\n\n \"\"\"\n a -> b -> c d\n | ^\n +------------+\n \"\"\"\n graph.add(\"d\")\n assert graph.connected(\"b\", \"c\") is True\n assert graph.connected(\"b\", \"d\") is False\n\n with pytest.raises(ValueError) as ctx:\n graph.add(\"d\")\n assert str(ctx.value) == \"vertex exists\"\n\n assert set(graph.iter_children(\"a\")) == {\"b\", \"c\"}\n assert set(graph.iter_parents(\"b\")) == {\"a\"}","sub_path":"tests/test_structs.py","file_name":"test_structs.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"145099522","text":"from pub_data import publish\nimport psutil\n\ncpu = psutil.cpu_percent()\nprint(cpu)\n\nram = psutil.virtual_memory().percent\nprint(ram)\n\ndisk = psutil.disk_usage('/').percent\nprint(disk)\n\ndata = {\n \"cpu\" : cpu,\n \"ram\" : ram,\n \"disk\": disk\n }\n\npublish(\"piSystemUsage\", data)\n","sub_path":"pi_hub_python/pi_monitoring_scripts/systemUsage.py","file_name":"systemUsage.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"390160059","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\ndf = pd.read_csv(\"C:/Users/user/Desktop/DATASETS/crime_data.csv\")\r\ndf.describe() #gives iqr and std values.\r\ndf.info()\r\ndf1 = df.drop(['Unnamed: 0'],axis = 1)\r\n\r\n#creating normalization function \r\ndef norm_func(i):\r\n x = (i-i.min())/(i.max()-i.min())\r\n return (x)\r\n\r\n# Normalized data frame (considering the numerical part of data)\r\ndf_norm = norm_func(df1)\r\ndf_norm.describe()\r\n\r\n\r\n# for creating dendrogram \r\nfrom scipy.cluster.hierarchy import linkage\r\nimport scipy.cluster.hierarchy as sch\r\n\r\nz = linkage(df_norm, method='single',metric= 'euclidean')\r\n\r\n#dendrogram\r\nplt.figure(figsize=(14,6));plt.title('h-clustering');plt.xlabel('index');plt.ylabel('distance')\r\nsch.dendrogram(z);plt.show()\r\n\r\n\r\n# Now applying AgglomerativeClustering choosing 4 as clusters from the above dendrogram\r\nfrom sklearn.cluster import AgglomerativeClustering\r\n\r\nh_complete = AgglomerativeClustering(n_clusters = 4, linkage = 'complete', affinity = \"euclidean\").fit(df_norm);plt.show() \r\nh_complete.labels_\r\n\r\ncluster_labels = pd.Series(h_complete.labels_)\r\n\r\ndf['cluster'] = cluster_labels # creating a new column and assigning it to new column \r\ndf.describe()\r\ndf = df.iloc[:, [5,0,1,2,3,4]] #bring cluster column to 0th index\r\ndf.head()\r\n\r\n# Aggregate mean of each cluster\r\ndf.iloc[:, 2:].groupby(df.cluster).mean()\r\n# creating a csv file \r\ndf.to_csv(\"crimedata.csv\", encoding = \"utf-8\")\r\n\r\nimport os\r\nos.getcwd()\r\n","sub_path":"hclust-2.py","file_name":"hclust-2.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"19477948","text":"\r\nimport flask\r\nimport sys\r\nfrom flask import Flask, Response\r\nimport json\r\nimport requests\r\nfrom functools import wraps\r\nfrom dutil.log import logger\r\nfrom dutil.utility import CJsonEncoder, decrypt_sentences\r\nimport os\r\nCURPATH = os.path.dirname(os.path.realpath(__file__))\r\nPARPATH = os.path.dirname(CURPATH)\r\nsys.path.append(os.path.join(PARPATH, \"dmp/gongan/address_formula_release\" ))\r\nsys.path.append(os.path.join(PARPATH, \"dmp/gongan/address_match_release\" ))\r\nsys.path.append(os.path.join(PARPATH, \"dmp/gongan/address_formula_release/src\" ))\r\nsys.path.append(os.path.join(PARPATH, \"dmp/gongan/address_match_release/src\" ))\r\nimport dmp.gongan.address_match_release.src.init_data\r\nimport dmp.gongan.address_formula_release.src.reghelper\r\nimport dmp.gongan.address_match_release.src.activity_match\r\nsys.path.extend(dmp.gongan.address_formula_release.src.__path__)\r\nsys.path.extend(dmp.gongan.address_match_release.src.__path__)\r\n\r\nprint(sys.path[-1])\r\nprint(CURPATH,PARPATH)\r\nsys.path.append(PARPATH)\r\nsys.path.append(CURPATH)\r\nimport pdb\r\n\r\nmatchInstance = dmp.gongan.address_match_release.src.activity_match.ActiMatch()\r\nformularInstance = dmp.gongan.address_formula_release.src.reghelper.RegHelper()\r\n\r\nclass IbaResponse(Response):\r\n default_mimetype = 'application/json'\r\n\r\nclass IbaFlask(Flask):\r\n response_class = IbaResponse\r\n\r\napp = IbaFlask(__name__)\r\n\r\nchild_sys_id = 'ADD_FORMULA'\r\n\r\ndef log_event(param, event, interface_name, log_level='info'):\r\n log_message = {'child_sys_id': child_sys_id, 'host_no': flask.request.remote_addr,\r\n 'monitor_name': '{0}计算'.format(interface_name),\r\n 'business_no': param['messageid'] if 'messageid' in param else None,\r\n 'business_name': '{0}接口'.format(interface_name), }\r\n if log_level == 'error':\r\n logger.error('{0}{1}'.format(interface_name, event), log_message)\r\n else:\r\n logger.info('{0}{1}'.format(interface_name, event), log_message)\r\n\r\n\r\ndef param_error(param, interface_name):\r\n log_event(param, '接口参数错误', interface_name, 'error')\r\n result = {\r\n 'messageid': param['messageid'] if 'messageid' in param else None,\r\n 'clientid': param['clientid'] if 'clientid' in param else None,\r\n 'resultcode': '010'\r\n }\r\n return result\r\n\r\n\r\ndef heartbeat_test(param, interface_name):\r\n log_event(param, '接口心跳测试', interface_name)\r\n result = {\r\n 'messageid': param['messageid'] if 'messageid' in param else None,\r\n 'clientid': param['clientid'] if 'clientid' in param else None,\r\n 'resultcode': '001'\r\n }\r\n return result\r\n\r\n\r\ndef log_service(interface_name, key_params=['user_id', 'model_id', 'messageid', 'clientid']):\r\n def decorator(func):\r\n @wraps(func)\r\n def wrapped():\r\n logger.debug(flask.request.data)\r\n param = json.loads(flask.request.data.decode())\r\n if 'action' in param and param['action'] == 'test':\r\n result = heartbeat_test(param, interface_name)\r\n return json.dumps(result, ensure_ascii=False)\r\n for key_param in key_params:\r\n if key_param not in param:\r\n result = param_error(param, interface_name)\r\n return json.dumps(result, ensure_ascii=False)\r\n log_event(param, '计算开始...', interface_name)\r\n logger.debug(json.dumps(param, indent=2, ensure_ascii=False))\r\n result = func(param)\r\n log_event(param, '计算完成', interface_name)\r\n return json.dumps(result, ensure_ascii=False, cls=CJsonEncoder)\r\n return wrapped\r\n return decorator\r\n\r\n@app.route('/normalization/addr-normal', methods=['POST', 'GET'])\r\n@log_service('addr-normal', ['messageid', 'clientid', 'encrypt', 'text'])\r\ndef addr_formula(param=None):\r\n predict_str = param['text']\r\n encrypt = param['encrypt']\r\n predict_str = decrypt_sentences(predict_str, encrypt)\r\n predict_result = formularInstance.address_formula(predict_str)\r\n result = {\r\n 'messageid': param['messageid'],\r\n 'clientid': param['clientid'],\r\n 'resultcode': '000',\r\n 'result': predict_result,\r\n }\r\n return result\r\n\r\n@app.route('/normalization/mode-match', methods=['POST', 'GET'])\r\n@log_service('addr-normal', ['messageid', 'clientid', 'encrypt', 'text'])\r\ndef mode_match(param=None):\r\n predict_str = param['text']\r\n encrypt = param['encrypt']\r\n predict_str = decrypt_sentences(predict_str, encrypt)\r\n predict_result = matchInstance.mode_match(predict_str,7)\r\n result = {\r\n 'messageid': param['messageid'],\r\n 'clientid': param['clientid'],\r\n 'resultcode': '000',\r\n 'result': predict_result,\r\n }\r\n return result\r\n\r\n@app.route('/normalization/search', methods=['POST', 'GET'])\r\n@log_service('addr-normal', ['messageid', 'clientid', 'encrypt', 'text'])\r\ndef search(param=None):\r\n predict_str = param['text']\r\n encrypt = param['encrypt']\r\n predict_str = decrypt_sentences(predict_str, encrypt)\r\n predict_result = matchInstance.search(predict_str)\r\n result = {\r\n 'messageid': param['messageid'],\r\n 'clientid': param['clientid'],\r\n 'resultcode': '000',\r\n 'result': predict_result,\r\n }\r\n return result\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host='0.0.0.0', debug=True, port=7944, use_reloader=True, threaded=True)\r\n\r\n","sub_path":"srv/yunyan_baotou/src/web/dap/gz_address_match_release.py","file_name":"gz_address_match_release.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"635087467","text":"from django.conf.urls.defaults import *\n\n#from milestoness.feeds import AllMilestoneFeed\n\n\n\n#milestone_feed_dict = {\"feed_dict\": {\n# \"all\": AllMilestoneFeed,\n#}}\n\n\n\nurlpatterns = patterns(\"\",\n url(r\"^$\", \"milestones.views.milestones\", name=\"milestone_list\"),\n \n url(r\"^add/$\", \"milestones.views.add_milestone\", name=\"milestone_add\"),\n #url(r\"^$\", \"milestones.views.milestones\", name=\"milestone_new\"),\n# url(r\"^add/$\", \"milestones.views.add_milestone\", name=\"milestone_add\"),\n url(r\"^milestone/edit/(?P\\d+)/$\", \"milestones.views.milestone_edit\",\n name=\"milestone_edit\"),\n url(r\"^milestone/(?P\\d+)/$\", \"milestones.views.milestone_detail\", name=\"milestone_detail\"),\n \n # feeds\n #(r\"^feeds/(.*)/$\", \"django.contrib.syndication.views.feed\", tasks_feed_dict),\n)\n","sub_path":"apps/milestones/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"289783675","text":"import urllib.request\nimport pprint\nfrom json import loads as json_loads, dump as json_dump\n\ndef take_data():\n link = f\"http://api.travelpayouts.com/v2/prices/latest?origin=MOW&page=2&limit=28&show_to_affiliates=true&sorting=price&token=[my_token]\"\n request = urllib.request.urlopen(link)\n requestResult = request.read()\n data = json_loads(requestResult)\n return data\n\n\nif __name__ == '__main__':\n\n data = take_data()\n\n filename = '/Users/grifosh/Downloads/TestApp/1.one_way/cache/data.json'\n with open(str(filename), \"w+\") as fp:\n json_dump(obj=data,fp=fp)\n\n filename = '/Users/grifosh/Downloads/TestApp/1.one_way/cache/data.txt'\n with open(str(filename), \"w+\") as fp:\n json_dump(obj=data,fp=fp)\n\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":"1_Data_Download.py","file_name":"1_Data_Download.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"266199556","text":"# Copyright 2021 Google 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# https://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\"\"\"GlobalDeviceArray serialization and deserialization.\"\"\"\n\nimport asyncio\nimport re\nfrom typing import Callable\n\nimport jax\nfrom jax._src.util import prod\nfrom jax.experimental import global_device_array as gda\nfrom jax.experimental.maps import Mesh\nimport jax.numpy as jnp\nimport numpy as np\nimport tensorstore as ts\n\n\nasync def create_async_gda_from_callback(\n global_shape: gda.Shape,\n global_mesh: Mesh,\n mesh_axes: gda.MeshAxes,\n data_callback: Callable[[gda.Index], asyncio.Future],\n):\n global_idx_rid = gda.get_shard_indices_replica_ids(\n global_shape, global_mesh, mesh_axes)\n local_devices = global_mesh.local_devices\n future_arrays = [data_callback(global_idx_rid[d][0])\n for d in local_devices]\n # Pause here and come back to `from_async_callback()` when future_arrays are\n # ready. device_put cannot happen with future_arrays.\n local_arrays = await asyncio.gather(*future_arrays)\n\n dbs = [jax.device_put(array, device)\n for array, device in zip(local_arrays, local_devices)]\n return gda.GlobalDeviceArray(global_shape, global_mesh, mesh_axes, dbs,\n gda._GdaFastPathArgs(global_idx_rid, local_devices))\n\n\ndef _get_metadata(gda):\n if gda.dtype == jnp.bfloat16:\n # Tensorstore uses 'bfloat16', not ' prod(t.shape)\n\n if requires_padding:\n new_shard_shape = gda.get_shard_shape(shape, mesh, mesh_axes)\n\n async def cb(index):\n if requires_padding:\n # This is needed because the shape the array was saved with is smaller\n # than the requested shape of the array in which it will be reloaded. So\n # the extra values will be filled with 0s.\n out = np.zeros(new_shard_shape, dtype=t.dtype.numpy_dtype)\n requested_domain = ts.IndexTransform(input_shape=shape)[index].domain\n restricted_domain = t.domain.intersect(requested_domain)\n await ts.array(out)[ts.d[:].translate_to[requested_domain.origin]][restricted_domain].write(t[restricted_domain])\n return out\n else:\n return await t[index].read()\n\n return await create_async_gda_from_callback(shape, mesh, mesh_axes, cb)\n\n\ndef run_deserialization(global_meshes, mesh_axes, tensorstore_specs,\n global_shapes=None):\n async def _run_deserializer():\n future_gdas = jax.tree_map(\n async_deserialize, global_meshes, mesh_axes, tensorstore_specs,\n [None] * len(tensorstore_specs) if global_shapes is None else global_shapes)\n return await asyncio.gather(*future_gdas)\n return asyncio.run(_run_deserializer())\n","sub_path":"jax/experimental/gda_serialization/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":5413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"434360027","text":"import PyPDF2\nimport random\nimport os\nfrom experiment import selection\n\n# 前半の選択\nslc = []\n# 後半の選択\nslc2 = []\n\nresult_path = os.path.join(os.getcwd(), \"result\")\n\ndict_all ={\n\"1_security\": 1,\n\"2_hardware\" : 2,\n\"2_software\": 3,\n\"3_database\": 4,\n\"4_network\": 5,\n\"6_PM\": 6,\n\"5_soft_str\": 7,\n\"7_sys_str\": 8,\n\"9_C\": 9,\n\"10_cobol\": 10,\n\"11_java\": 11,\n\"12_assembler\": 12,\n\"13_excel\": 13}\n\n\n# slc1とslc2の初期化\ndef __init__():\n i = 0\n j = 0\n while(i < 100):\n slc1.append(0)\n while(j < 100):\n slc1.append(0)\n\n\n# 入力フォームから、4つの選択問題を選ぶ\ndef input_form1(curr, file_path):\n \"\"\"\n Parameters\n ------\n name : str\n 名前\n\n Returns\n ------\n Hello! とnameの結合結果\n \"\"\"\n\n global slc1\n global slc2\n\n print(\"選択問題を4つ入力してください(記入例:2,3,4,5):\\n\")\n print(\"2.ハードウェア\")\n print(\"3.ソフトウェア\")\n print(\"4.データベース\")\n print(\"5.ネットワーク\")\n print(\"6.PM・サービスマネジメント\")\n print(\"7.ソフトウェア設計(21問)\")\n print(\"8.システム戦略・経営戦略\")\n print(\"-------------------------------\")\n erab1 = input(\"Put 4: \")\n erab1 = erab1.split(\",\")\n if len(erab1) > 5:\n print(\"\\n\\n選択問題が多いです。\\n\\n\")\n input_form1(curr, file_path)\n if len(erab1) < 4:\n print(\"\\n\\n選択問題が少ないです。\\n\\n\")\n\n print(\"選択問題を1つ選んでください:\\n9.C\\n10.Cobol\\n11.java\\n12.assenmbler\\n13.Excel\")\n print(\"-----------------------------\")\n erab2 = input(\"Choose 1: \")\n if len(erab2) == 0:\n print(\"問題を選択しなおしてください\")\n input_form1(curr, file_path)\n else:\n select_1(erab1, erab2, file_path, curr)\n\n\ndef select_1(erab1, erab2, file_path, curr):\n \"\"\"\n ここに函数の説明(どのような処理を行うものかを記述する)\n\n Parameters\n ------\n name : str\n 名前\n\n Returns\n ------\n Hello! とnameの結合結果\n \"\"\"\n\n global slc\n global slc2\n global result_path\n merger = PyPDF2.PdfFileMerger()\n\n erab1.append(erab2)\n print(\"erab1 goes like >>>\", erab1)\n\n path = os.path.join(file_path, \"1_security\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n\n for i in erab1:\n if i == \"2\":\n # 2のファイルを取ってくる。\n path = os.path.join(file_path, \"2_hardware\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n if i == \"3\":\n # 3のファイルを取ってくる。\n path = os.path.join(file_path, \"2_software\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n if i == \"4\":\n # 4のファイルを取ってくる。\n path = os.path.join(file_path, \"3_database\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n if i == \"5\":\n # 5のファイルを取ってくる。\n path = os.path.join(file_path, \"4_network\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n if i == \"6\":\n # 7のファイルを取ってくる。\n path = os.path.join(file_path, \"6_PM\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n if i == \"7\":\n # 6のファイルを取ってくる。\n path = os.path.join(file_path, \"5_soft_str\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n if i == \"8\":\n # 8のファイルを取ってくる。\n path = os.path.join(file_path, \"7_sys_str\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n\n path = os.path.join(file_path, \"8_algo\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n\n # リストとして保持している\n if erab2 == \"9\":\n # 2のファイルを取ってくる。\n path = os.path.join(file_path, \"9_C\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n if erab2 == \"10\":\n # 3のファイルを取ってくる。\n path = os.path.join(file_path, \"10_cobol\")\n files = os.listdir(path)\n selection(slc, files, path)\n os.chdir(file_path)\n if erab2 == \"11\":\n # 4のファイルを取ってくる。\n path = os.path.join(file_path, \"11_java\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n if erab2 == \"12\":\n # 2のファイルを取ってくる。\n path = os.path.join(file_path, \"12_assembler\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n if erab2 == \"13\":\n # 3のファイルを取ってくる。\n path = os.path.join(file_path, \"13_Excel\")\n files = os.listdir(path)\n selection(slc, files, path)\n merger.append(Q)\n os.chdir(file_path)\n\n # 最後にPDFのアプリ起動させたら嬉しくない?\n\n merger = PyPDF2.PdfFileMerger()\n result_final = os.path.join(result_path, \"result.pdf\")\n # resultファイルは\n merger.write(result_final)\n merger.close()\n\n print(\"今回は、\", str([slc]), \"の問題です\")\n print(\"resultフォルダにあるresult.pdfをみてください\")\n print(\"終了\\n\")\n exit\n\n\nif __name__ == \"__main__\":\n curr_path = os.getcwd()\n curr_path = os.path.join(curr_path)\n file_path = os.path.join(curr_path)\n print(file_path)\n input_form1(curr_path, file_path)\n","sub_path":"duplication.py","file_name":"duplication.py","file_ext":"py","file_size_in_byte":6293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"638996219","text":"from pipeline import *\nfrom utils import *\nimport getopt\nimport warnings\nwarnings.simplefilter('ignore', RuntimeWarning)\n\n\"\"\" \nUsage: %run -i Measure_Centroid.py 'A2465C' -z 0.245 --SN_THRE 2.5 --SUM_TYPE 'mean' --SUB_CONT --LPF --SAVE\n\"\"\"\n\n# Arugument\nname = sys.argv[1]\nsn_thre = 2.0\nsum_type = \"mean\"\nsub_cont = False\nsave = False\n\nmode = \"MMA\"\noutput_dir = './output1'\nLPF = False\n\nif 'A2390' in name: \n z0 = 0.228\n coords_BCG = (328.403512,17.695440)\n double_cluster = False\n\nif 'A2465' in name:\n z0 = 0.245\n coords_BCG = ((339.918680, -5.723983),\n (339.852272, -5.788233))\n cluster_bounds = \"./A2465C/A2465C_bound_v2.fits\"\n double_cluster = True\n \nwavl_mask = [[7950,8006], [8020,8040], [8230,8280]]\n \n# Options\ntry:\n optlists, args = getopt.getopt(sys.argv[2:], \"z:\",\n [\"SN_THRE=\", \"SUM_TYPE=\", \"LPF\",\n \"SAVE\", \"SUB_CONT\", \"OUT_DIR=\"])\n opts = [opt for opt, arg in optlists] \nexcept getopt.GetoptError:\n print('Wrong Option.')\n sys.exit(2)\n \nfor opt, arg in optlists:\n if opt in (\"-z\"):\n z0 = np.float(arg)\n elif opt in (\"--SN_THRE\"):\n sn_thre = np.float(arg)\n elif opt in (\"--SUM_TYPE\"):\n sum_type = arg\n elif opt in (\"--OUT_DIR\"):\n output_dir = arg\nif (\"--LPF\" in opts): LPF = True\nif (\"--SUB_CONT\" in opts): sub_cont = True\nif (\"--SAVE\" in opts): save = True\n\nprint(\"S/N = %.1f\"%(sn_thre))\nprint(\"Emission: %s\"%(sum_type))\nprint(\"Continuum Subtracted?: %s\"%(sub_cont))\nprint(\"Use LPF cube?: %s\"%LPF)\n\n# Suffix\nsuffix = \"_%s_sn%.1f\"%(sum_type, sn_thre)\nif sub_cont:\n suffix += '_contsub'\nif LPF:\n suffix += '_lpf'\n\nsuffix += '_NB'\n\n# Collect File Path\nsave_path = os.path.join(output_dir, name)\ncentroid_path = os.path.join(output_dir, 'centroid', name)\ncheck_save_path(centroid_path)\n \ntable_path = os.path.join(save_path, '%s_%s_lpf.dat'%(name, mode))\nseg_path = os.path.join(save_path, '%s_segm_%s_lpf.fits'%(name, mode))\ndeep_path = os.path.join(save_path, '%s_DF.fits'%(name))\nmask_edge_path = os.path.join(save_path, 'Raw_stack_%s_mask.fits'%name)\nspec_path = os.path.join(save_path, '%s-spec-%s_lpf.fits'%(name, mode))\ntemplate_path = os.path.join(output_dir, 'template')\nCC_res_path = os.path.join(save_path, '%s-cc-%s_lpf.pkl'%(name, mode))\ncandidate_path = os.path.join(save_path, 'pic/candidate_%s_lpf'%mode)\n\nif LPF:\n cube_path = os.path.join(save_path, '%s_cube_lpf.fits'%name)\nelse:\n cube_path = os.path.join(save_path, '%s_cube.fits'%name)\n \n# Read\ndatacube = Read_Datacube(cube_path, name, z0, \n mode=mode, wavl_mask=wavl_mask,\n table=table_path, seg_map=seg_path,\n deep_frame=deep_path,\n mask_edge=mask_edge_path)\n \ndatacube.get_wcs()\ncube_detect_path = os.path.join(save_path, '%s_cube_lpf.fits'%name)\ndatacube.src_map = fits.getdata(cube_detect_path)\ndatacube.read_spec(spec_path)\ndatacube.read_template(template_path, n_intp=2, name=name, verbose=False)\ndatacube.read_cc_result(CC_res_path)\n\n# BCG\ndatacube.assign_BCG_coordinate(coords_BCG)\n\nif double_cluster:\n datacube.read_cluster_boundary(cluster_bounds)\nelse:\n X_BCG, Y_BCG = datacube.wcs.all_world2pix(datacube.coord_BCG.ra,\n datacube.coord_BCG.dec, 0)\n datacube.pos_BCG = (X_BCG, Y_BCG)\n\n# Candidate\ncandidate_path_V = os.path.join(candidate_path,\"V/%s#*.png\"%name)\ndir_V = glob.glob(candidate_path_V)\nNum_V = np.sort(np.array([re.compile(r'\\d+').findall(el)[-1] for el in dir_V]).astype(\"int\"))\n\n# Measure\nprint(\"Measure Centroid...\")\ndatacube.centroid_analysis_all(Num_V, nums_obj=Num_V, centroid_type=\"ISO-D\", sub_cont=sub_cont,\n sn_thre=sn_thre, sum_type=sum_type, morph_cen=False, verbose=False)\n\ndatacube.centroid_analysis_all(Num_V, nums_obj=Num_V, centroid_type=\"ISO-D\",\n sn_thre=sn_thre, sum_type=sum_type, morph_cen=True, verbose=False)\n\n# Save\nif save:\n datacube.save_centroid_measurement(Num_V, save_path=save_path,\n suffix=suffix, ID_field=name[-1])\n\n# Plot histogram\nz_V = datacube.get_CC_result_best('z_best', 'Ha-NII_gauss', Num_V)\n\ndiff_angle_iso_d = datacube.get_centroid_result('diff_angle', 'ISO-D', fill_value=0)\ndiff_angle_std_iso_d = datacube.get_centroid_result('diff_angle_std', 'ISO-D', fill_value=99)\ncen_off_iso_d = datacube.get_centroid_result('cen_offset', 'ISO-D', fill_value=0)\ncen_off_std_iso_d = datacube.get_centroid_result('cen_offset_std', 'ISO-D', fill_value=99)\n\ndiff_angle_iso_dm = datacube.get_centroid_result('diff_angle', 'ISO-Dm', fill_value=0)\ncen_off_iso_dm = datacube.get_centroid_result('cen_offset', 'ISO-Dm', fill_value=0)\ncen_off_std_iso_dm = datacube.get_centroid_result('cen_offset_std', 'ISO-Dm', fill_value=99)\n\ndef condition_1(cen_off, cen_off_std, z_V):\n return (cen_off>0.85) & (cen_off>3*cen_off_std) & (abs(z_V-z0)<0.015)\n\ndef condition_2(cen_off, cen_off_std, z_V):\n return (cen_off>0.85+3*cen_off_std) & (abs(z_V-z0)<0.015)\n\nd_angle_d1 = diff_angle_iso_d[condition_1(cen_off_iso_d, cen_off_std_iso_d, z_V)]\nd_angle_dm1 = diff_angle_iso_dm[condition_1(cen_off_iso_dm, cen_off_std_iso_dm, z_V)]\n\nd_angle_d2 = diff_angle_iso_d[condition_2(cen_off_iso_d, cen_off_std_iso_d, z_V)]\nd_angle_dm2 = diff_angle_iso_dm[condition_2(cen_off_iso_dm, cen_off_std_iso_dm, z_V)]\n\n# Plot\nfig, (ax1,ax2)=plt.subplots(1,2,figsize=(11,4))\nax1.hist(d_angle_d1-2, bins=np.linspace(0,180,8)-2,histtype=\"step\",hatch=\"/\", lw=4, alpha=0.7,label='ISO-1')\nax1.hist(d_angle_dm1, bins=np.linspace(0,180,8),histtype=\"step\", lw=4, hatch=\"\", alpha=0.7,label='morph-1')\nax1.legend()\nax2.hist(d_angle_d2-2, bins=np.linspace(0,180,8)-2,histtype=\"step\",hatch=\"/\", lw=4, alpha=0.7,label='ISO-2')\nax2.hist(d_angle_dm2, bins=np.linspace(0,180,8),histtype=\"step\", lw=4, hatch=\"\", alpha=0.7,label='morph-2')\nax2.legend()\nplt.show()\n","sub_path":"Measure_Centroid.py","file_name":"Measure_Centroid.py","file_ext":"py","file_size_in_byte":6012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"332004674","text":"import libperso as lp, cv2, numpy as np, argparse as ap, time\nfrom keras.models import Model\nfrom keras.layers import Input, Conv2D, MaxPool2D, Dense, Flatten, Dropout, Activation, BatchNormalization as BN, Reshape\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard, EarlyStopping, ModelCheckpoint\nfrom keras.regularizers import l2\nfrom keras.optimizers import Adam\nfrom keras.utils.np_utils import to_categorical as cat\nfrom sklearn.metrics import classification_report as classify\n\nparser = ap.ArgumentParser()\nparser.add_argument('-f', '--features', type=int, default=64, help='Number of features on base convolutionnal layer')\nparser.add_argument('-m', '--model', type=str, default='models/placeholder.h5', help='Path to model (.h5 file) from which weights will be loaded')\nparser.add_argument('-e', '--epochs', type=int, default=1000, help='Epochs for model training')\nparser.add_argument('-i', '--face_height', type=int, default=112, help='Size of the extracted faces')\nargs = vars(parser.parse_args())\n\ndef make_layer_trainable(model, val, name_contains):\n\tfor l in model.layers:\n\t\tif name_contains in l.name:\n\t\t\tl.trainable = val\n\ndef classifier_emo(nb_feat = 64):\n\tcl_input = Input(shape=(inH, inH, dim))\n\n\tx = Conv2D(nb_feat, (3,3), padding='same', kernel_regularizer=l2(0.01), activation='relu', name='l_00_c')(cl_input)\n\tx = Conv2D(2*nb_feat, (7,7), padding='same', activation='relu', strides=2, name='l_01_c')(x)\n\t#x = BN()(x)\n\tx = MaxPool2D((2,2), name='l_02_p')(x)\n\tx = Dropout(.5)(x)\n\n\tx = Conv2D(2*nb_feat, (3,3), padding='same', activation='relu', name='l_03_c')(x)\n\tx = BN()(x)\n\tx = Conv2D(2*2*nb_feat, (5,5), padding='same', activation='relu', strides=2, name='l_04_c')(x)\n\tx = BN()(x)\n\tx = MaxPool2D((2,2), name='l_05_p')(x)\n\tx = Dropout(.5)(x)\n\t\n\tx = Conv2D(2*2*2*nb_feat, (3,3), padding='same', activation='relu', name='l_06_c')(x)\n\tx = BN()(x)\n\tx = Conv2D(2*2*nb_feat, (3,3), padding='same', activation='relu', name='l_07_c')(x)\n\tx = BN()(x)\n\t# = MaxPool2D((2,2), name='l_08_p')(x)\n\tx = Dropout(.5)(x)\n\n\tx = Flatten()(x)\n\t# = kb.transpose(x)\n\n\tx = Dense(nb_feat, activation='relu', name='l_d_00')(x)\n\tx = Dropout(.5)(x)\n\t\n\tx = Dense(int(nb_feat/2), activation='relu', name='l_d_01')(x)\n\tx = Dropout(.5)(x)\n\t\n\tcl_output = Dense(out, activation='softmax', name='l_d_end')(x)\n\t\n\tmodel = Model(cl_input, cl_output)\n\tmodel.compile(optimizer=Adam(lr=.001, beta_1=.9, beta_2=.999, epsilon=1e-7), loss='categorical_crossentropy', metrics=['accuracy'])\n\tmodel.summary()\n\treturn model\n\nw, h, dim, out = 320, 240, 1, 8\ninH = args['face_height']\n\nemo_model = classifier_emo(args['features'])\nemo_model.load_weights(args['model'], by_name=True)\nmake_layer_trainable(emo_model, False, 'c')\nemo_model.compile(optimizer=Adam(lr=.001, beta_1=.9, beta_2=.999, epsilon=1e-7), loss='categorical_crossentropy', metrics=['accuracy'])\nemo_model.summary()\n\nprint('Downloading CK+ dataset...')\ntrain, test, val = lp.load_ck_csv(.1, .1, 'databases/ck_plus_fulldb.csv', w, h)\nx_train, y_train = train\nx_test, y_test = test\nx_val, y_val = val\n\nx_train = x_train.astype('uint8')\nx_test = x_test.astype('uint8')\nx_val = x_val.astype('uint8')\n\ny_train = cat(y_train)\ny_test = cat(y_test)\ny_val = cat(y_val)\n\nprint('done\\nCK+ dataset loaded.')\n\nprint('Extracting faces from images...', end='', flush=True)\nfx_train, fy_train = lp.extract_faces(x_train, y_train, inH)\nfx_test, fy_test = lp.extract_faces(x_test, y_test, inH)\nfx_val, fy_val = lp.extract_faces(x_val, y_val, inH)\n\nfx_train = fx_train.astype('float32')/255.\nfx_test = fx_test.astype('float32')/255.\nfx_val = fx_val.astype('float32')/255.\nprint('done\\nFaces extracted.')\ntime.sleep(1)\n\nlr_reducer = ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=18, verbose=1)\ntensorboard = TensorBoard(log_dir='./logs')\nearly_stopper = EarlyStopping(monitor='val_loss', min_delta=0, patience=45, verbose=1, mode='auto')\ncheckpointer = ModelCheckpoint('./models/emo_transfer_large_lighter.h5', monitor='val_loss', verbose=1, save_best_only=True)\n\nemo_model.fit(fx_train, fy_train, batch_size=64, epochs=args['epochs'],\n\t\tverbose=1, validation_data=(fx_val, fy_val), shuffle=True, callbacks=[lr_reducer, tensorboard, early_stopper, checkpointer])\n\nscores = emo_model.evaluate(fx_test, fy_test, batch_size=64)\nfor i in range(len(scores)):\n\tprint('%10s: %.2f' % (emo_model.metrics_names[i], scores[i]))\n\nnames = ['Neutral', 'Anger', 'Contempt', 'Disgust', 'Fear', 'Happiness', 'Sadness', 'Surprise']\npredictions = emo_model.predict(fx_test)\nprint(classify(fy_test.argmax(axis=1), predictions.argmax(axis=1), target_names=names))","sub_path":"CK+ _clean/scripts_for_CK_transfer/emo_transfer_large_lighter.py","file_name":"emo_transfer_large_lighter.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"462789252","text":"\"\"\"ORF Open Reading Frames\r\n\r\nAn open reading frame (ORF) is one which starts from the start codon and ends by stop codon,\r\nwithout any other stop codons in between.\r\n\"\"\"\r\n\r\ndna_codon_table = {'TTT': 'F', 'CTT': 'L', 'ATT': 'I', 'GTT': 'V', 'TTC': 'F', 'CTC': 'L',\r\n'ATC': 'I', 'GTC': 'V', 'TTA': 'L', 'CTA': 'L', 'ATA': 'I', 'GTA': 'V', 'TTG': 'L', 'CTG': 'L',\r\n'ATG': 'M', 'GTG': 'V', 'TCT': 'S', 'CCT': 'P', 'ACT': 'T', 'GCT': 'A', 'TCC': 'S', 'CCC': 'P',\r\n'ACC': 'T', 'GCC': 'A', 'TCA': 'S', 'CCA': 'P', 'ACA': 'T', 'GCA': 'A', 'TCG': 'S', 'CCG': 'P',\r\n'ACG': 'T', 'GCG': 'A', 'TAT': 'Y', 'CAT': 'H', 'AAT': 'N', 'GAT': 'D', 'TAC': 'Y', 'CAC': 'H',\r\n'AAC': 'N', 'GAC': 'D', 'TAA': 'Stop', 'CAA': 'Q', 'AAA': 'K', 'GAA': 'E', 'TAG': 'Stop',\r\n'CAG': 'Q', 'AAG': 'K', 'GAG': 'E', 'TGT': 'C', 'CGT': 'R', 'AGT': 'S', 'GGT': 'G', 'TGC': 'C',\r\n'CGC': 'R', 'AGC': 'S', 'GGC': 'G', 'TGA': 'Stop', 'CGA': 'R', 'AGA': 'R', 'GGA': 'G', 'TGG': 'W',\r\n'CGG': 'R', 'AGG': 'R', 'GGG': 'G'}\r\n\r\ns = input()\r\nrc_s = s[::-1].translate(str.maketrans('ACGT', 'TGCA'))\r\nproteins = []\r\nfor string in (s, rc_s):\r\n \r\n start_pos = (x for x in range(len(string) - 2) if string[x:x+3] == 'ATG')\r\n \r\n for j in start_pos:\r\n\r\n prot = []\r\n index = j\r\n \r\n while index < len(string) - 2:\r\n acid = dna_codon_table[string[index:index + 3]]\r\n \r\n if acid == 'Stop':\r\n break\r\n \r\n prot.append(acid)\r\n index += 3\r\n else:\r\n continue\r\n proteins.append(''.join(prot))\r\n\r\nfor x in set(proteins):\r\n print(x, end='\\n')\r\n","sub_path":"18_orf.py","file_name":"18_orf.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"149017043","text":"from thehive4py.api import TheHiveApi\nfrom st2common.runners.base_action import Action\n\n__all__ = [\n 'PromoteAlertToCaseAction'\n]\n\n\nclass PromoteAlertToCaseAction(Action):\n def run(self, alert_id, case_template=None):\n api = TheHiveApi(self.config['thehive_url'], self.config['thehive_api_key'])\n # api.promote_alert_to_case(alert_id, case_template)\n # wait for https://github.com/TheHive-Project/TheHive4py/pull/115\n api.promote_alert_to_case(alert_id)\n\n return True\n","sub_path":"actions/promote_alert_to_case.py","file_name":"promote_alert_to_case.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"515679702","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# This is a simple script to prune dangling IP addresses from the account\n# that are not associated with a server.\n#\n\nimport json\nimport os, sys\nimport requests\n\nclass NoCredentialsFound(Exception):\n pass\n\ndef get_token():\n if not os.environ.get('CODEHELPER_SCW_TOKEN'):\n raise NoCredentialsFound()\n return os.environ.get('CODEHELPER_SCW_TOKEN')\n\ndef get_ips():\n headers = {\n 'X-Auth-Token': get_token(),\n 'Content-Type': \"application/json\"\n }\n req = requests.get(\"https://cp-par1.scaleway.com/ips/\", headers=headers)\n return json.loads(req.text)['ips']\n\ndef delete_ip(ip_id):\n headers = {\n 'X-Auth-Token': get_token(),\n 'Content-Type': \"application/json\"\n }\n try:\n req = requests.delete(\"https://cp-par1.scaleway.com/ips/%s\" % ip_id, headers=headers)\n except Exception as e:\n sys.stderr.write(\"%s\\n\" % e)\n sys.stderr.write(\"Unable to delete address with id %s\" % ip_id)\n else:\n print(\"Successfully deleted IP %s\" % ip_id)\n\ndef main():\n ips = get_ips()\n orphaned = [ip['id'] for ip in ips if ip['server'] is None ]\n for ip in orphaned:\n delete_ip(ip)\n\nif __name__ == '__main__':\n main()\n","sub_path":"prune_ips.py","file_name":"prune_ips.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"18434248","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2018/11/13 11:44\n@Author : Li Shanlu\n@File : net_example_for_define_vars.py\n@Software : PyCharm\n@Description: 用一个网络来实践怎么定义重复利用的变量\n\"\"\"\nimport tensorflow as tf\n\n\ndef conv(input, kernel_shape, bias_shape):\n weights = tf.get_variable(name='weights', shape=kernel_shape, initializer=tf.random_normal_initializer())\n biases = tf.get_variable(name='biases', shape=bias_shape, initializer=tf.constant_initializer())\n conv_result = tf.nn.conv2d(input, weights, [1,2,2,1], padding='SAME')\n return tf.nn.relu(tf.add(conv_result, biases))\n\n\ndef net(input):\n with tf.variable_scope('net1'):\n conv1_out = conv(input, [5, 5, 1, 32], [32])\n with tf.variable_scope('net2'):\n conv2_out = conv(conv1_out, [5, 5, 32, 64], [64])\n return None\n\n\nif __name__ == '__main__':\n input = tf.placeholder(tf.float32, shape=[1, 28, 28, 1])\n with tf.variable_scope('test') as scope:\n net(input)\n scope.reuse_variables()\n net(input)\n for var in tf.trainable_variables():\n print(var)\n\n\"\"\"\n>>\n\n\n\n\n____________________________________________________________________________\n总结:\n在net第一次调用时定义了四个变量,通过使用函数reuse_variables(),在第二次调用net的时候,共享了上一次的变量参数。\n\"\"\"","sub_path":"9_net_example_for_define_vars.py","file_name":"9_net_example_for_define_vars.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"189969319","text":"import unittest\r\n\r\nfrom Lesson01 import Square\r\n\r\n\r\nclass SquareTest(unittest.TestCase):\r\n def test_positive_numbers(self):\r\n squares = {\r\n 1: 1,\r\n 2: 4,\r\n 3: 9,\r\n 12: 144,\r\n 100: 10000,\r\n }\r\n\r\n for num, square in squares.items():\r\n self.assertEqual(square, Square.calc(num), \"Squaring {}\".format(num))\r\n","sub_path":"students/JasneetChandok/Lesson01_unittest.py","file_name":"Lesson01_unittest.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"413034451","text":"from math import sqrt\nimport torch\nfrom torch import nn\nfrom utils import to_gpu, get_mask_from_lengths\nfrom .encoder import Encoder\nfrom .decoder import Decoder\nfrom .postnet import Postnet\n\nclass Tacotron2(nn.Module):\n def __init__(self, hparams):\n super(Tacotron2, self).__init__()\n self.mask_padding = hparams.mask_padding\n self.fp16_run = hparams.fp16_run\n self.n_mel_channels = hparams.n_mel_channels\n self.n_frames_per_step = hparams.n_frames_per_step\n\n self.text_embedding = nn.Embedding(\n hparams.n_symbols, hparams.symbols_embedding_dim)\n std = sqrt(2.0 / (hparams.n_symbols + hparams.symbols_embedding_dim))\n val = sqrt(3.0) * std # uniform bounds for std\n self.text_embedding.weight.data.uniform_(-val, val)\n\n self.speaker_embedding = nn.Embedding(\n hparams.n_speakers, hparams.speakers_embedding_dim)\n self.speaker_embedding.weight.data.uniform_(-1e-4, 1e-4)\n\n self.encoder = Encoder(hparams)\n self.decoder = Decoder(hparams)\n self.postnet = Postnet(hparams)\n\n def parse_batch(self, batch):\n text_padded, input_lengths, mel_padded, gate_padded, \\\n output_lengths, speaker_ids = batch\n text_padded = to_gpu(text_padded).long()\n input_lengths = to_gpu(input_lengths).long()\n max_len = torch.max(input_lengths.data).item()\n mel_padded = to_gpu(mel_padded).float()\n gate_padded = to_gpu(gate_padded).float()\n output_lengths = to_gpu(output_lengths).long()\n speaker_ids = to_gpu(speaker_ids).long()\n\n return (\n (text_padded, input_lengths, mel_padded, max_len, output_lengths, speaker_ids),\n (mel_padded, gate_padded))\n\n def parse_output(self, outputs, output_lengths=None):\n if self.mask_padding and output_lengths is not None:\n mask = ~get_mask_from_lengths(output_lengths, self.n_frames_per_step)\n mask = mask.expand(self.n_mel_channels, mask.size(0), mask.size(1))\n mask = mask.permute(1, 0, 2)\n\n outputs[0].data.masked_fill_(mask, 0.0)\n outputs[1].data.masked_fill_(mask, 0.0)\n outputs[2].data.masked_fill_(mask[:, 0, :], 1e3) # gate energies\n\n return outputs\n\n def forward(self, inputs):\n text_inputs, text_lengths, mels, max_len, output_lengths, speaker_ids = inputs\n text_lengths, output_lengths = text_lengths.data, output_lengths.data\n\n embedded_inputs = self.text_embedding(text_inputs).transpose(1, 2)\n embedded_speakers = self.speaker_embedding(speaker_ids) \n\n encoder_outputs = self.encoder(embedded_inputs, text_lengths, embedded_speakers)\n\n mel_outputs, gate_outputs, alignments = self.decoder(\n encoder_outputs, mels, embedded_speakers, memory_lengths=text_lengths)\n\n mel_outputs_postnet = self.postnet(mel_outputs)\n mel_outputs_postnet = mel_outputs + mel_outputs_postnet\n\n return self.parse_output(\n [mel_outputs, mel_outputs_postnet, gate_outputs, alignments],\n output_lengths)\n\n def inference(self, inputs, speaker_ids):\n embedded_inputs = self.text_embedding(inputs).transpose(1, 2)\n embedded_speakers = self.speaker_embedding(speaker_ids) \n\n encoder_outputs = self.encoder.inference(embedded_inputs, embedded_speakers)\n mel_outputs, gate_outputs, alignments = self.decoder.inference(\n encoder_outputs, embedded_speakers)\n\n mel_outputs_postnet = self.postnet(mel_outputs)\n mel_outputs_postnet = mel_outputs + mel_outputs_postnet\n\n outputs = self.parse_output(\n [mel_outputs, mel_outputs_postnet, gate_outputs, alignments])\n\n return outputs\n","sub_path":"tacotron2/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"219963584","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport time\nfrom cap_comm.ship_comm_client.client import ShipCommClient, read_topic, DataType\n# from src.utilities.remaining import get_ip\n\n# use ggplot style for more sophisticated visuals\nplt.style.use('ggplot')\n\n# def live_plotter(x_vec, y_data, ax, identifier='Real-Time Response', pause_time=0.1):\n#\n# if line1 == []:\n# # this is the call to matplotlib that allows dynamic plotting\n# plt.ion()\n# fig = plt.figure(figsize=(13, 6))\n# ax = fig.add_subplot(111)\n# # create a variable for the line so we can later update it\n# plt.ylabel('heading')\n# plt.title('Title: {}'.format(identifier))\n#\n# # after the figure, axis, and line are created, we only need to update the y-data\n# # line1.set_ydata(y_data) # adjust limits if new data goes beyond bounds\n# plt.plot(x_vec, y_data)\n# # if np.min(y_comb) <= line1.axes.get_ylim()[0] or np.max(y_comb) >= line1.axes.get_ylim()[1]:\n# plt.ylim([np.min(y_data) - np.std(y_data)-10, np.max(y_data) + np.std(y_data) +10])\n# # this pauses the data so the figure/axis can catch up - the amount of pause can be altered above\n# plt.pause(pause_time) #maybe take it out # return line so we can update it again in the next iteration\n#\n# return ax\n\nif __name__==\"__main__\":\n sc = ShipCommClient(\"172.16.128.163\",\n local_address='172.16.128.141',\n process_name=\"plotter\")\n sc.init_read_topic('metrics', DataType.Utf8)\n\n x_vec = np.linspace(0, 1, 1000 )[0:-1]\n y_vec = np.zeros((7, len(x_vec)))\n t_init = time.time()\n\n plt.ion()\n fig = plt.figure(figsize=(16, 6))\n ax = fig.add_subplot(211)\n # create a variable for the line so we can later update it\n line_1 = ax.plot(x_vec, y_vec[0, :], '-r', alpha=1)[0]\n line_2 = ax.plot(x_vec, y_vec[1, :], '-b', alpha=1)[0]\n line_3 = ax.plot(x_vec, y_vec[2, :], '-g', alpha=1)[0]\n line_4 = ax.plot(x_vec, y_vec[3, :], '-m', alpha=1)[0]\n line_5 = ax.plot(x_vec, y_vec[4, :], '-k', alpha=1)[0]\n plt.ylabel('Control outputs')\n plt.title('Title: {}'.format('Real-Time Response'))\n plt.legend(['pid_s', 'Pv', 'Iv', 'Dv', 'Fv'])\n plt.ylim([-35, 35])\n ax2 = fig.add_subplot(212)\n line_6 = ax2.plot(x_vec, y_vec[5, :], '-g', alpha=0.8)[0]\n line_7 = ax2.plot(x_vec, y_vec[6, :], '-b', alpha=0.8)[0]\n plt.ylim([-10, 370])\n plt.legend(['Cur_H', 'Des_H'])\n plt.ylabel('Heading')\n plt.show()\n\n while True:\n msg = read_topic('metrics', block=True)\n if msg:\n # print('msg')\n vals = msg.split(':')\n y_vec = np.roll(y_vec, -1)\n # x_vec = np.roll(x_vec, -1)\n # x_vec[-1] = time.time()-t_init\n y_vec[:, -1] = np.array([float(vals[1]), float(vals[3]), float(vals[5]), float(vals[7]),\n float(vals[9]), float(vals[11]), float(vals[13])])\n line_1.set_ydata(y_vec[0, :])\n line_2.set_ydata(y_vec[1, :])\n line_3.set_ydata(y_vec[2, :])\n line_4.set_ydata(y_vec[3, :])\n line_5.set_ydata(y_vec[4, :])\n line_6.set_ydata(y_vec[5, :])\n line_7.set_ydata(y_vec[6, :])\n plt.axes(ax)\n plt.ylim([1.5*np.min(y_vec[0:4, :]), 1.5*np.max(y_vec[0:4, :])])\n fig.canvas.flush_events()\n time.sleep(.01)","sub_path":"Autopilot_light/control/utilities/printcontrol.py","file_name":"printcontrol.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"515403720","text":"# $Id: StrippingBc2JpsiMuX.py,v 1.2 2010-09-06 16:30:22 jhe Exp $\n\n'''\nModule for construction of Bc->Jpsi(MuMu)X\n'''\n\n__author__=['Jibo He']\n__date__ = '02/09/2010'\n__version__= '$Revision: 2.0 $'\n\n\n__all__ = (\n 'Bc2JpsiMuXConf',\n 'makeJpsi2MuMu',\n 'makeBc2JpsiMu'\n )\n\nconfig_default = {\n 'LinePrescale' : 1. ,\n 'LinePostscale' : 1. ,\n \n 'MuonTRCHI2DOF' : 5. , # adimentional \n 'MuonPT' : 1400. , # MeV\n 'MuonP' : -5. , # MeV, not applied now\n 'MuMuParticleName' : \"'J/psi(1S)'\", # Particle Name, like \"'psi(2S)'\"\n 'MuMuMassWindow' : 150. , # MeV, 10 sigma, may decreased to 150\n 'MuMuVtxCHI2' : 9. , # adimentional\n 'MuMuPT' : -10. , # MeV, not applied \n \n 'MuonBcTRCHI2DOF' : 5. , # adimentional \n 'MuonBcPT' : 2500. , # MeV\n 'MuonBcP' : -5. , # MeV, not applied now\n 'BcUpperMass' : 6400. , # MeV, Upper limit for partial rec. \n 'BcLowerMass' : 3200. , # MeV, Lower limit for partial rec.\n 'BcVtxCHI2' : 9. , # adimentional\n 'BcPT' : 6000. # MeV, May incrase up to 5000 MeV if needed \n }\n\n\nfrom Gaudi.Configuration import *\nfrom GaudiConfUtils.ConfigurableGenerators import FilterDesktop, CombineParticles\nfrom PhysSelPython.Wrappers import Selection, DataOnDemand\nfrom StrippingConf.StrippingLine import StrippingLine\nfrom StrippingUtils.Utils import LineBuilder\n\nclass Bc2JpsiMuXConf(LineBuilder):\n \n __configuration_keys__ = (\n 'LinePrescale',\n 'LinePostscale',\n\n 'MuonTRCHI2DOF',\n 'MuonPT',\n 'MuonP',\n 'MuMuParticleName',\n 'MuMuMassWindow',\n 'MuMuVtxCHI2',\n 'MuMuPT',\n \n 'MuonBcTRCHI2DOF', \n 'MuonBcPT',\n 'MuonBcP',\n 'BcVtxCHI2',\n 'BcUpperMass',\n 'BcLowerMass',\n 'BcPT'\n )\n \n def __init__(self, name, config ):\n\n LineBuilder.__init__(self, name, config)\n \n Bc2JpsiMuXName = name\n self.SelJpsi2MuMu = makeJpsi2MuMu( 'Jpsi2MuMuFor'+Bc2JpsiMuXName,\n MuonPT = config['MuonPT'],\n MuonP = config['MuonP'],\n MuonTRCHI2DOF = config['MuonTRCHI2DOF'],\n MuMuParticleName = config['MuMuParticleName'],\n MuMuVtxCHI2 = config['MuMuVtxCHI2'],\n MuMuMassWindow = config['MuMuMassWindow'],\n MuMuPT = config['MuMuPT']\n )\n \n self.SelBc2JpsiMuX = makeBc2JpsiMu( \"Sel_\"+Bc2JpsiMuXName,\n SelJpsi2MuMu = self.SelJpsi2MuMu,\n MuonBcTRCHI2DOF = config['MuonBcTRCHI2DOF'],\n MuonBcPT = config['MuonBcPT'],\n MuonBcP = config['MuonBcP'],\n BcVtxCHI2 = config['BcVtxCHI2'],\n BcUpperMass = config['BcUpperMass'],\n BcLowerMass = config['BcLowerMass'],\n BcPT = config['BcPT'] \n )\n \n self.line = StrippingLine( Bc2JpsiMuXName+\"Line\",\n prescale = config['LinePrescale'],\n postscale = config['LinePostscale'],\n selection = self.SelBc2JpsiMuX \n )\n\n self.registerLine(self.line)\n \n \n \n\ndef makeJpsi2MuMu( name,\n MuonPT,\n MuonP,\n MuonTRCHI2DOF,\n MuMuParticleName, \n MuMuVtxCHI2,\n MuMuMassWindow,\n MuMuPT\n ):\n \n _StdLooseDiMuon = DataOnDemand(Location = \"Phys/StdLooseDiMuon/Particles\")\n \n #MuonCut = \"(MINTREE('mu+'==ABSID,PT) > %(MuonPT)s *MeV) & (MINTREE('mu+'==ABSID,P) > %(MuonP)s *MeV) & (MAXTREE('mu+'==ABSID,TRCHI2DOF) < %(MuonTRCHI2DOF)s)\" % locals()\n MuonCut = \"(CHILDCUT((TRCHI2DOF < %(MuonTRCHI2DOF)s),1)) & (CHILDCUT((TRCHI2DOF < %(MuonTRCHI2DOF)s),2)) & (CHILDCUT((PT > %(MuonPT)s *MeV),1)) & (CHILDCUT((PT > %(MuonPT)s *MeV),2))\" % locals()\n \n MuMuCut = \"(ADMASS(%(MuMuParticleName)s) < %(MuMuMassWindow)s *MeV) & (VFASPF(VCHI2PDOF)< %(MuMuVtxCHI2)s) & (PT > %(MuMuPT)s *MeV)\" % locals()\n \n _MuMu = FilterDesktop( Code = MuonCut + \" & \" + MuMuCut )\n \n return Selection( name + \"_SelP2MuMu\",\n Algorithm = _MuMu,\n RequiredSelections = [ _StdLooseDiMuon ]\n )\n\n\ndef makeBc2JpsiMu( name,\n SelJpsi2MuMu,\n MuonBcTRCHI2DOF,\n MuonBcPT,\n MuonBcP,\n BcVtxCHI2,\n BcUpperMass,\n BcLowerMass,\n BcPT\n ):\n\n #---------------------------\n # Muon\n #--------------------------- \n from StandardParticles import StdAllNoPIDsMuons as NoPIDsMuonsForBc2JpsiMu\n \n # MuBc Cut\n MuonBcCut = \"(PT > %(MuonBcPT)s *MeV) & (P > %(MuonBcP)s *MeV) & (TRCHI2DOF < %(MuonBcTRCHI2DOF)s) & (TRGHOSTPROB<0.4)\" % locals()\n\n _MuonBcFilter = FilterDesktop( Code = MuonBcCut )\n \n SelMuonBc = Selection(\"SelMuonBc_\"+name,\n Algorithm = _MuonBcFilter,\n RequiredSelections = [ NoPIDsMuonsForBc2JpsiMu ])\n \n \n #---------------------------\n # Bc -> J/psi(MuMu) Mu X\n #--------------------------- \n # Comb cut\n combCut = \"(in_range( %(BcLowerMass)s *MeV, AM, %(BcUpperMass)s *MeV))\" % locals()\n \n # Bc Cut\n BcCut = \"(VFASPF(VCHI2PDOF)< %(BcVtxCHI2)s ) & (PT > %(BcPT)s *MeV)\" % locals()\n\n _Bc2JpsiMuX = CombineParticles( DecayDescriptor = \"[ B_c+ -> J/psi(1S) mu+ ]cc\",\n CombinationCut = combCut,\n MotherCut = BcCut,\n ReFitPVs = True )\n \n return Selection( name,\n Algorithm = _Bc2JpsiMuX,\n RequiredSelections = [ SelJpsi2MuMu, SelMuonBc ]\n )\n","sub_path":"DaVinci_v36r1p3/InstallArea/x86_64-slc6-gcc48-opt/python/StrippingArchive/Stripping20r0p2/StrippingBc2JpsiMuXNew.py","file_name":"StrippingBc2JpsiMuXNew.py","file_ext":"py","file_size_in_byte":6734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"471903718","text":"import pprint\n\nclass Abstract:\n def __init__(self):\n self.keywords = []\n self.body = \"\"\n self.authors = []\n self.url = \"\"\n\n def setAuthors(self, authors):\n self.authors = authors\n\n def setKeywords(self, keywords):\n self.keywords = keywords\n\n def setBody(self, body):\n self.body = body\n\n def toString(self):\n pprint.pprint(\"Abstract Body:\", self.body)\n pprint.pprint(\"Keywords:\", self.keywords)\n pprint.pprint(\"Authors:\", self.authors)\n pprint.pprint(\"URL:\", self.url)\n\n def setUrl(self, url):\n self.url = url\n\nclass ScienceDirectParser:\n def __init__(self):\n pass\n\n def parse(self, fileName):\n abstracts = []\n with open(fileName, mode='r', encoding='utf8') as f:\n text = f.read()\n\n ct = 0\n while True:\n ab_index = text.find('Abstract')\n if (ab_index < 0):\n break\n\n ab_index += len('Abstract')\n kw_index = text.find('Keyword')\n abstract = text[ab_index:kw_index].rstrip('\\n')\n if len(abstract) > 1:\n abstracts.append(abstract.replace('Abstract', \"\").replace('abstract', ''))\n\n kw_start = kw_index + len('Keywords:')\n kw_end = text.find('\\n', kw_start)\n keywords = text[kw_start:kw_end].split(';')\n text = text[kw_end:]\n\n ct += 1\n return abstracts\n","sub_path":"GAFinalProject/src/parsers/science_direct_parser.py","file_name":"science_direct_parser.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"558602626","text":"from dearpygui.core import *\nfrom dearpygui.demo import *\n\nadd_font(\"google\", \"../../Resources/NotoSerifCJKjp-Medium.otf\", 20)\nset_font(\"google\", 20)\n\nadd_texture_container(id=\"mvTextureContainer\")\n\nshow_demo()\n\nvp = create_viewport(small_icon=\"../../Resources/dpg_icon_small.ico\", large_icon=\"../../Resources/dpg_icon_large.ico\")\nsetup_dearpygui(viewport=vp)\nshow_viewport(vp)\nwhile(is_dearpygui_running()):\n render_dearpygui_frame() \ncleanup_dearpygui()","sub_path":"DearSandbox/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"196286143","text":"from Utils_folder.Utils_Preprocess import *\nfrom Utils_folder.HN_Constants import ALL_IM_SIZE, ROI_ORDER, DICOM_DIR\nimport pandas as pd\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--preprocess', type=bool, default=True)\n parser.add_argument('--filelist', type=bool, default=False)\n parser.add_argument('--size', type=bool, default=True)\n args = parser.parse_args()\n\n if not os.path.exists('Filelist'):\n os.makedirs('Filelist')\n if args.preprocess:\n print('Resize to ',ALL_IM_SIZE)\n flip = False #switch for enable flip for image for horizontal plane\n print('Flip =',flip)\n preprocess(ALL_IM_SIZE, DICOM_DIR, flip, data_path = 'Data')\n\n if args.filelist:\n print('Generate file list')\n train_filelist('Data', ROI_ORDER)\n print('Done')\n \n if args.size:\n print('Generate size and ratio')\n train_file_lists = pd.read_csv('Filelist/Train_Filelist_ROI.csv')\n size_ratio(train_file_lists, ROI_ORDER)\n print('Done')","sub_path":"Dicom_Preprocess.py","file_name":"Dicom_Preprocess.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"99613623","text":"#####################################################\n# Problem 01\n#####################################################\n\n# user input a number\n# multiply the number from 1 up to 10\n# output should be:\n# 10 x 1 = 10\n# 10 x 2 = 20\n# 10 x 3 = 30\n# -----------\n# -----------\n# 10 x 10 = 100\nnumber = int(input(\"Enter a Number Here: \"))\ncount = 1\nwhile count <= 10:\n print(number, \"x\", count, \"=\", number * count)\n count += 1\n\n#####################################################\n# Problem 02\n#####################################################\nnumber = int(input(\"Enter a Number Here: \"))\ntemp = number\n\nwhile number > 0:\n count = temp\n while count > 0:\n print('*', end='')\n count -= 1\n print()\n number -= 1\n\n#####################################################\n# Problem 03\n#####################################################\n# You have a blank list. After input one by one food items are added in the blank list\n# Once input completed then print the food list\nfood_list = []\nchoice = input(\"Do you want food ? y / n: \")\n\nwhile choice == \"y\":\n food_name = input(\"Enter your item here: \")\n food_list.append(food_name.title())\n print(food_list)\n choice = input(\"Want to add more items ? y / n: \")\nif food_list:\n print(\"Your items are\", food_list)\nelse:\n print(\"You added no items\")\n\n# #####################################################\n# Problem 04\n# #####################################################\n# enter item and item price\n# once shopping completed print a list with item name and total price\nshop_list = []\ntotal_price = 0\n\nchoice = input(\"Do you want to start shopping ? y / n: \")\n\nwhile choice == \"y\":\n item_name = input(\"Enter Item Name Here: \")\n shop_list.append(item_name.title())\n item_price = int(input(\"Enter Item Price Here: \"))\n total_price = item_price + total_price\n choice = input(\"Continue shopping ? y / n: \")\n print(\"Right now your items are\", shop_list, \"and price is\", total_price)\nif shop_list:\n print(\"Your total items are\", shop_list, \"and total price is\", total_price)\nelse:\n print(\"You added no items\")\n\n\n# #####################################################\n# Problem 05\n# #####################################################\nitems_available = [\"Chicken\", \"Vegetables\", \"Plain Rice\", \"Daal\", \"Vorta\", \"Firni\", \"Paan Masala\"]\ncustomer_ordered_item = []\n\nchoice = input(\"Do you want food ? y / n: \")\n\nwhile choice == \"y\":\n food_name = input(\"Choose your items: \")\n if food_name in items_available:\n customer_ordered_item.append(food_name)\n print(customer_ordered_item)\n choice = input(\"Do you want more ? y / n: \")\n else:\n print(food_name, \"is not available\")\nif customer_ordered_item:\n print(\"Your ordered items are\", customer_ordered_item)\nelse:\n print(\"You added no items\")\n","sub_path":"loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"255219982","text":"import random\r\nimport array\r\nfrom reconchess import *\r\nimport os\r\nimport math\r\n\r\n# from attacker_bot.py, used to flip move sequence if player color\r\n# starts as black\r\ndef flipped_move(move):\r\n def flipped(square):\r\n return chess.square(chess.square_file(square), 7 - chess.square_rank(square))\r\n\r\n return chess.Move(from_square=flipped(move.from_square), to_square=flipped(move.to_square),\r\n promotion=move.promotion, drop=move.drop)\r\n \r\n\r\n\r\nclass ZoneBot(Player):\r\n\r\n def handle_game_start(self, color: Color, board: chess.Board):\r\n self.board = board\r\n self.color = color\r\n self.my_piece_captured_square = None\r\n\r\n # initial move sequence for quick attack\r\n self.move_sequence = [chess.Move(chess.B1, chess.C3), chess.Move(chess.C3, chess.B5), chess.Move(chess.B5, chess.D6),\r\n chess.Move(chess.D6, chess.E8)]\r\n\r\n # flip move sequence to opposite side if player is black\r\n if color == chess.BLACK:\r\n self.move_sequence = list(map(flipped_move, self.move_sequence))\r\n \r\n # keep track of turn number for sensing \r\n self.turn_number = 1\r\n # store final move choice\r\n self.selected_move = List[chess.Move]\r\n # keep track of king location\r\n self.king_location = self.board.king(self.color)\r\n\r\n # evaluate board state\r\n def evaluate(self, move_actions: List[chess.Move]):\r\n value = 0\r\n # values of each piece: p, r, n, b, q, k\r\n pieces = [1, 2, 7, 4, 40, 500]\r\n # evaluate current board state based off of move taken\r\n for square, piece in self.board.piece_map().items():\r\n if piece is not None:\r\n if piece.color != self.color:\r\n if piece.piece_type is chess.PAWN:\r\n value += pieces[0]\r\n if piece.piece_type is chess.ROOK:\r\n value += pieces[1]\r\n if piece.piece_type is chess.KNIGHT:\r\n value += pieces[2]\r\n if piece.piece_type is chess.BISHOP:\r\n value += pieces[3]\r\n if piece.piece_type is chess.QUEEN:\r\n value += pieces[4]\r\n if piece.piece_type is chess.KING:\r\n value += pieces[5]\r\n # if pieces are too far from king, calculate reduction\r\n if piece.color == self.color:\r\n if square > self.king_location + 7:\r\n value += 20\r\n return value\r\n\r\n def minimax(self, move_actions: List[chess.Move], isMax, depth, alpha, beta):\r\n # base case\r\n if depth == 0:\r\n return -self.evaluate(move_actions)\r\n \r\n # max player move\r\n if isMax:\r\n bestValue = -math.inf\r\n for move in move_actions:\r\n # push move into board\r\n self.board.push(move)\r\n # recursively calculate value of move and all possible future moves\r\n value = self.minimax(move_actions, False, depth - 1, alpha, beta)\r\n print(\"As Max\", value)\r\n # save the best value and insert the move into the list\r\n if value > bestValue:\r\n bestValue = value\r\n self.selected_move.insert(0, move)\r\n alpha = max(alpha, bestValue)\r\n if beta <= alpha:\r\n break\r\n self.board.pop()\r\n return bestValue\r\n else:\r\n bestValue = math.inf\r\n for move in move_actions:\r\n self.board.push(move)\r\n value = self.minimax(move_actions, True, depth - 1, alpha, beta)\r\n print(\"As Min\", value)\r\n if value < bestValue:\r\n print(\"here\")\r\n bestValue = value\r\n self.selected_move.insert(0, move)\r\n beta = min(beta, bestValue)\r\n if beta <= alpha:\r\n break\r\n self.board.pop()\r\n return bestValue\r\n\r\n\r\n def handle_opponent_move_result(self, captured_my_piece: bool, capture_square: Optional[Square]):\r\n # if the opponent captured our piece, remove it from our board.\r\n self.my_piece_captured_square = capture_square\r\n if captured_my_piece:\r\n self.board.remove_piece_at(capture_square)\r\n\r\n def choose_sense(self, sense_actions: List[Square], move_actions: List[chess.Move], seconds_left: float) -> Square:\r\n # sensing strategy to be implemented:\r\n # first scan front line area for enemy movement\r\n # if no enemies moved in area, scan opposite side next turn\r\n # keep track of expected number of pieces in area\r\n # if missing a piece, swap sides again changing general range\r\n\r\n # if our piece was just captured, sense where it was captured\r\n if self.my_piece_captured_square:\r\n return self.my_piece_captured_square\r\n\r\n # otherwise, just randomly choose a sense action, but don't sense on a square where our pieces are located\r\n for square, piece in self.board.piece_map().items():\r\n if self.turn_number / 5 % 2 == 0:\r\n if piece.color == self.color and piece.piece_type is chess.KING:\r\n return sense_actions(0)\r\n if piece.color == self.color:\r\n sense_actions.remove(square)\r\n return random.choice(sense_actions)\r\n\r\n def handle_sense_result(self, sense_result: List[Tuple[Square, Optional[chess.Piece]]]):\r\n # add the pieces in the sense result to our board\r\n for square, piece in sense_result:\r\n self.board.set_piece_at(square, piece)\r\n\r\n def choose_move(self, move_actions: List[chess.Move], seconds_left: float) -> Optional[chess.Move]:\r\n #while len(self.move_sequence) > 0 and self.move_sequence[0] not in move_actions:\r\n # self.move_sequence.pop(0)\r\n #if len(self.move_sequence) > 0:\r\n # self.turn_number = self.turn_number + 1\r\n # return self.move_sequence.pop(0)\r\n #else:\r\n # add random move onto the stack\r\n self.selected_move = [random.choice(move_actions + [None])]\r\n # calculate best move\r\n self.minimax(move_actions, True, 3, -math.inf, math.inf)\r\n # keep track of king location\r\n if self.board.king(self.color) is not None:\r\n self.king_location = self.board.king(self.color)\r\n return self.selected_move.pop()\r\n\r\n\r\n def handle_move_result(self, requested_move: Optional[chess.Move], taken_move: Optional[chess.Move],\r\n captured_opponent_piece: bool, capture_square: Optional[Square]):\r\n # if a move was executed, apply it to our board\r\n if taken_move is not None:\r\n self.board.push(taken_move)\r\n\r\n def handle_game_end(self, winner_color: Optional[Color], win_reason: Optional[WinReason],\r\n game_history: GameHistory):\r\n pass","sub_path":"reconchess/bots/zone_bot.py","file_name":"zone_bot.py","file_ext":"py","file_size_in_byte":7159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"91488611","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sklearn import svm\n\n\nos.chdir(\"/home/andrew/Git/deeplearning/\")\n\n# read in as pandas DataFrames\ntrain = pd.read_csv('data/train.csv')\ntest = pd.read_csv('data/test.csv')\nlabels = train.iloc[ : , 0]\ntrain.drop('label', axis=1, inplace=True)\n\n# Support Vector Classifier using polynomial kernal of degree 3, parameters C and gamma:\nclf = svm.SVC(C=1.2, gamma = 0.009, kernel='poly', degree=3)\n\n#% time clf.fit(train.iloc[ 0:2000, :], labels.iloc[ 0:2000])\n#% time prediction = clf.predict(test.iloc[ 0:2000, :] ) \n#np.savetxt('prediction.csv', prediction, delimiter=',')\n\n# fit to the training set, predict the test set. Using full dataset (took me ~10 mins to run) : \nclf.fit(train, labels)\nprediction = clf.predict(test) \n\n# write to csv in Kaggle submission format:\nimage_id = np.array(range(1, len(prediction)+1 )) # getting a numpy array and then coverting it to a pandas Dataframe:\nprediction_df = pd.DataFrame( np.transpose(np.array([image_id, prediction])), columns=['ImageID','Label'])\nprediction_df.to_csv('prediction_svm.csv', index=False)\n\nprint('Done \\n')","sub_path":"deeplearning.py","file_name":"deeplearning.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"413377248","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\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.\n\nimport re\n\nimport Logger\nimport Packager\nfrom Component import (PkgUninstallComponent, PkgInstallComponent,\n ComponentBase, RuntimeComponent)\nfrom Util import (DB,\n get_host_ip,\n execute_template)\nfrom Exceptions import (StartException, StopException,\n StatusException, RestartException)\nfrom Shell import (execute)\nfrom Trace import (TraceReader,\n IN_TRACE)\n\nLOG = Logger.getLogger(\"install.db\")\nTYPE = DB\nMYSQL = 'mysql'\nDB_ACTIONS = {\n MYSQL: {\n #hopefully these are distro independent, these should be since they are invoking system init scripts\n 'start': [\"service\", \"mysql\", 'start'],\n 'stop': [\"service\", 'mysql', \"stop\"],\n 'status': [\"service\", 'mysql', \"status\"],\n 'restart': [\"service\", 'mysql', \"status\"],\n #\n 'create_db': ['mysql', '--user=%USER%', '--password=%PASSWORD%', '-e', 'CREATE DATABASE %DB%;'],\n 'drop_db': ['mysql', '--user=%USER%', '--password=%PASSWORD%', '-e', 'DROP DATABASE IF EXISTS %DB%;'],\n 'grant_all': [\n \"mysql\",\n \"--user=%USER%\",\n \"--password=%PASSWORD%\",\n \"-e \\\"GRANT ALL PRIVILEGES ON *.* TO '%USER%'@'%' identified by '%PASSWORD%';\\\"\",\n ],\n #we could do this in python directly, but executing allows us to not have to sudo the whole program\n 'host_adjust': ['perl', '-p', '-i', '-e'] + [\"'s/127.0.0.1/0.0.0.0/g'\", '/etc/mysql/my.cnf'],\n },\n}\n\nBASE_ERROR = 'Currently we do not know how to %s for database type [%s]'\n\n\nclass DBUninstaller(PkgUninstallComponent):\n def __init__(self, *args, **kargs):\n PkgUninstallComponent.__init__(self, TYPE, *args, **kargs)\n\n\nclass DBInstaller(PkgInstallComponent):\n def __init__(self, *args, **kargs):\n PkgInstallComponent.__init__(self, TYPE, *args, **kargs)\n self.runtime = DBRuntime(*args, **kargs)\n\n def _get_download_location(self):\n return (None, None)\n\n def _get_param_map(self, fn=None):\n #this dictionary will be used for parameter replacement\n #in pre-install and post-install sections\n out = dict()\n out['PASSWORD'] = self.cfg.getpw(\"passwords\", \"sql\")\n out['BOOT_START'] = str(True).lower()\n out['USER'] = self.cfg.get(\"db\", \"sql_user\")\n hostip = get_host_ip(self.cfg)\n out['SERVICE_HOST'] = hostip\n out['HOST_IP'] = hostip\n return out\n\n def install(self):\n pres = PkgInstallComponent.install(self)\n #extra actions to ensure we are granted access\n dbtype = self.cfg.get(\"db\", \"type\")\n dbactions = DB_ACTIONS.get(dbtype)\n if(dbactions and dbactions.get('grant_all')):\n #update the DB to give user 'USER'@'%' full control of the all databases:\n grant_cmd = dbactions.get('grant_all')\n params = self._get_param_map()\n cmds = list()\n cmds.append({\n 'cmd': grant_cmd,\n 'run_as_root': False,\n })\n #shell seems to be needed here\n #since python escapes this to much...\n execute_template(*cmds, params=params, shell=True)\n #special mysql actions\n if(dbactions and dbtype == MYSQL):\n cmd = dbactions.get('host_adjust')\n if(cmd):\n execute(*cmd, run_as_root=True, shell=True)\n #restart it to make sure all good\n self.runtime.restart()\n return pres\n\n\nclass DBRuntime(ComponentBase, RuntimeComponent):\n def __init__(self, *args, **kargs):\n ComponentBase.__init__(self, TYPE, *args, **kargs)\n self.tracereader = TraceReader(self.tracedir, IN_TRACE)\n\n def _gettypeactions(self, act, exception_cls):\n pkgsinstalled = self.tracereader.packages_installed()\n if(len(pkgsinstalled) == 0):\n msg = \"Can not %s %s since it was not installed\" % (act, TYPE)\n raise exception_cls(msg)\n #figure out how to do it\n dbtype = self.cfg.get(\"db\", \"type\")\n typeactions = DB_ACTIONS.get(dbtype)\n if(typeactions == None or not typeactions.get(act)):\n msg = BASE_ERROR % (act, dbtype)\n raise NotImplementedError(msg)\n return typeactions.get(act)\n\n def start(self):\n if(self.status().find('start') == -1):\n startcmd = self._gettypeactions('start', StartException)\n execute(*startcmd, run_as_root=True)\n return None\n\n def stop(self):\n if(self.status().find('stop') == -1):\n stopcmd = self._gettypeactions('stop', StopException)\n execute(*stopcmd, run_as_root=True)\n return None\n\n def restart(self):\n restartcmd = self._gettypeactions('restart', RestartException)\n execute(*restartcmd, run_as_root=True)\n return None\n\n def status(self):\n statuscmd = self._gettypeactions('status', StatusException)\n (sysout, stderr) = execute(*statuscmd, run_as_root=True)\n return sysout.strip()\n\n\ndef drop_db(cfg, dbname):\n dbtype = cfg.get(\"db\", \"type\")\n dbactions = DB_ACTIONS.get(dbtype)\n if(dbactions and dbactions.get('drop_db')):\n dropcmd = dbactions.get('drop_db')\n params = dict()\n params['PASSWORD'] = cfg.getpw(\"passwords\", \"sql\")\n params['USER'] = cfg.get(\"db\", \"sql_user\")\n params['DB'] = dbname\n cmds = list()\n cmds.append({\n 'cmd': dropcmd,\n 'run_as_root': False,\n })\n execute_template(*cmds, params=params)\n else:\n msg = BASE_ERROR % ('drop', dbtype)\n raise NotImplementedError(msg)\n\n\ndef create_db(cfg, dbname):\n dbtype = cfg.get(\"db\", \"type\")\n dbactions = DB_ACTIONS.get(dbtype)\n if(dbactions and dbactions.get('create_db')):\n createcmd = dbactions.get('create_db')\n params = dict()\n params['PASSWORD'] = cfg.getpw(\"passwords\", \"sql\")\n params['USER'] = cfg.get(\"db\", \"sql_user\")\n params['DB'] = dbname\n cmds = list()\n cmds.append({\n 'cmd': createcmd,\n 'run_as_root': False,\n })\n execute_template(*cmds, params=params)\n else:\n msg = BASE_ERROR % ('create', dbtype)\n raise NotImplementedError(msg)\n","sub_path":"devstack/Db.py","file_name":"Db.py","file_ext":"py","file_size_in_byte":6903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"356982990","text":"\"\"\"\nCopyright 2014 Sotera Defense Solutions, Inc.\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\nfrom bs4 import BeautifulSoup\nfrom datawake.conf import datawakeconfig as conf\nfrom elasticsearch import Elasticsearch\nfrom pykafka import KafkaClient\n\nimport requests\nimport tangelo\nimport time\n\n\ndef export_rest(service, domain_id, domain_name, cdr):\n try:\n protocol = 'http'\n if service['recipientProtocol']:\n protocol = service['recipientProtocol']\n url = '%s://%s' % (protocol, service['recipientUrl'])\n\n user = ''\n password = ''\n if service['credentials']:\n creds = service['credentials'].split(':')\n user = creds[0]\n password = creds[1]\n\n r = requests.put(url, data=cdr, auth=(user, password))\n tangelo.log('Sending page via REST put to: %s' % r.url)\n if r.status == 200:\n return True\n except Exception as e:\n tangelo.log_error(\"error sending via REST to: %s \" % url, e)\n return False\n return False\n\n\ndef export_kafka(service, cdr):\n try:\n tangelo.log(\"sending kafka to %s %s\" % (service['recipientUrl'], service['recipientIndex']))\n client = KafkaClient(hosts=service['recipientUrl'])\n\n topic = client.topics[service['recipientIndex']]\n producer = topic.get_producer()\n producer.produce(cdr)\n except Exception as e:\n tangelo.log_error(\"error sending via kafka to %s\" % recipientUrl,e)\n return False\n return True\n\n\ndef export_es(service, cdr, domain_name):\n try:\n protocol = 'http'\n cred = ''\n if service['recipientProtocol']:\n protocol = service['recipientProtocol']\n if service['credentials']:\n cred = service['credentials'] + '@'\n es_url = '%s://%s%s' % (protocol, cred, service['recipientUrl'])\n tangelo.log(\"sending ES at %s\" % (es_url))\n tangelo.log(\"index: %s\"%service['recipientIndex'])\n tangelo.log(\"doc_type: %s\"%domain_name)\n tangelo.log(\"cdr: %s\"%cdr)\n es = Elasticsearch(es_url)\n res = es.index(index=service['recipientIndex'], doc_type=domain_name, body=cdr)\n return res['created']\n except Exception as e:\n tangelo.log(e)\n tangelo.log_error(\"error sending via ES to %s\" % service['recipientUrl'],e)\n return False\n return True\n\n\n\ndef build_cdr(url, content, entities, team_id, domain_id, trail_id, domain_name, user_email):\n docid = 'dw-%i-%i-%i-%i' %(team_id, domain_id, trail_id, hash(url))\n soup = BeautifulSoup(content)\n # remove scripts and style\n for script in soup([\"script\", \"style\"]):\n script.extract()\n\n text = soup.get_text(strip=True).encode('ascii', 'ignore')\n crawl_data = {'docid': docid, 'entities': entities, 'full-text': text, 'domain-name': domain_name, 'user-email': user_email}\n return {'url': url, 'timestamp': int(time.time())*1000, 'team': 'sotera', 'crawler': 'datawake', 'content-type': 'full-raw-html', 'raw_content': content, 'crawl_data': crawl_data, 'images':'','videos':''}\n","sub_path":"server/datawake/util/externalTools/externalTool.py","file_name":"externalTool.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"136493321","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Controlador de la portada.\n\"\"\"\nimport os\nfrom werkzeug import url_unquote\nfrom flask import Blueprint, render_template, redirect, url_for, g, make_response, current_app, request, send_from_directory, abort\nfrom flaskext.babel import get_translations, gettext as _\nfrom flaskext.login import current_user\nfrom foofind.forms.files import SearchForm\nfrom foofind.services import *\nfrom foofind.forms.captcha import generate_image\nfrom urlparse import urlparse\nimport urllib\nimport logging\n\nindex = Blueprint('index', __name__, template_folder=\"template\")\n\n# contenidos de la raiz del sitio\n@index.route('/favicon.ico')\ndef favicon():\n return send_from_directory(os.path.join(current_app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')\n\n@index.route('/robots.txt')\ndef robots():\n return send_from_directory(os.path.join(current_app.root_path, 'static'), 'robots.txt')\n\n#@index.route('/sitemap.xml')\ndef sitemap():\n return render_template('sitemap.xml', url_root=request.url_root[:-1], rules=current_app.url_map.iter_rules())\n\n@index.route('//opensearch.xml')\ndef opensearch():\n response = make_response(render_template('opensearch.xml', shortname=\"Foofind\", description=urllib.quote_plus(_(\"opensearch_description\"))))\n response.headers['content-type']='application/opensearchdescription+xml'\n return response\n\n\n@index.route('/')\n@index.route('/')\n@cache.cached(timeout=50)\ndef home():\n '''\n Renderiza la portada.\n '''\n return render_template('index.html',form=SearchForm(),zone=\"home\")\n\n@index.route('//setlang')\ndef setlang():\n '''\n Cambia el idioma\n '''\n # si el idioma esta entre los permitidos y el usuario esta logueado se actualiza en la base de datos\n if g.lang in current_app.config[\"ALL_LANGS\"] and current_user.is_authenticated():\n current_user.set_lang(g.lang)\n usersdb.update_user({\"_id\":current_user.id,\"lang\":g.lang})\n\n # si se puede se redirige a la pagina en la que se estaba\n if request.referrer:\n parts = url_unquote(request.referrer).split(\"/\")\n if parts[0] in (\"http:\",\"https:\"):\n parts = parts[3:]\n return redirect(\"/%s/%s\" % (g.lang, \"/\".join(parts[1:])))\n else:\n return redirect(url_for(\"index.home\"))\n\n@index.route(\"/captcha/\")\ndef captcha(captcha_id):\n try:\n code = cache.get(\"captcha/%s\" % captcha_id)\n if code is None:\n abort(404)\n except BaseException as e:\n logging.error(e)\n abort(404)\n response = make_response(generate_image(code))\n response.headers['Content-Type'] = 'image/png'\n return response\n","sub_path":"foofind/blueprints/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"473608919","text":"# utils.py\n\nimport torch\nfrom torchtext import data\nfrom torchtext.vocab import Vectors\nimport spacy\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import accuracy_score,f1_score\nimport csv\nfrom torch import nn\n\nclass Dataset(object):\n def __init__(self, config):\n self.config = config\n self.train_iterator = None\n self.test_iterator = None\n self.val_iterator = None\n self.vocab = []\n self.word_embeddings = {}\n self.pos_vocab=[]\n \n # def parse_label(self, label):\n # '''\n # Get the actual labels from label string\n # Input:\n # label (string) : labels of the form '__label__2'\n # Returns:\n # label (int) : integer value corresponding to label string\n # '''\n # return int(label.strip()[-1])\n\n def get_pandas_df(self, filename):\n '''\n Load the data into Pandas.DataFrame object\n This will be used to convert data to torchtext object\n '''\n text_li=[]\n label_li=[]\n with open(filename, 'r', encoding='utf-8') as fi:\n next(fi)\n rowes = csv.reader(fi, delimiter='\\t')\n for row in rowes:\n text = row[0]\n text_li.append(text)\n label = row[1]\n label_li.append(label)\n full_df = pd.DataFrame({\"text\": text_li, \"label\": label_li})\n return full_df\n\n # 新增函数\n # df.values.tolist()形如[[text1, label1], [text2, label2], ..., [textn, labeln]]\n # 向train_df.values.tolist()增加了一个特征,也就是复制了一遍text。\n # 返回值read_data形如[[text1, text1, label1], [text2, text2, label2], ..., [textn, textn, labeln]]\n def df_process(self,df):\n df_va=df.values.tolist()\n return [[x[0],x[0],x[1]] for x in df_va]\n #return [[[text, text, label] for text, label in example] for example in df.values.tolist()]\n\n def load_data(self, w2v_file, train_file, test_file, val_file=None):\n '''\n Loads the data from files\n Sets up iterators for training, validation and test data\n Also create vocabulary and word embeddings based on the data\n \n Inputs:\n w2v_file (String): absolute path to file containing word embeddings (GloVe/Word2Vec)\n train_file (String): absolute path to training file\n test_file (String): absolute path to test file\n val_file (String): absolute path to validation file\n '''\n\n NLP = spacy.load('en')\n tokenizer = lambda sent: [x.text for x in NLP.tokenizer(sent) if x.text != \" \"]\n pos_generator = lambda sent: [x.pos_ for x in NLP(sent) if x.text != \" \"]# 新增函数,获取词性特征\n\n # Creating Field for data\n TEXT = data.Field(sequential=True, tokenize=tokenizer, lower=True, fix_length=self.config.max_sen_len)\n # 新增POS Field,这里用pos_generator代替了tokenizer函数对原文进行处理,从而得到词性特征。\n POS = data.Field(sequential=True, tokenize=pos_generator, lower=True,\n fix_length=self.config.max_sen_len)\n LABEL = data.Field(sequential=False, use_vocab=False)\n datafields = [(\"text\",TEXT),(\"pos\",POS),(\"label\",LABEL)]#新增POS Field\n \n # Load data from pd.DataFrame into torchtext.data.Dataset\n train_df = self.get_pandas_df(train_file)\n train_read_data = self.df_process(train_df) # 给数据增加一个特征,也就是复制了一遍text,它在经过pos_generator处理后变成词性特征\n #train_examples = [data.Example.fromlist(i, datafields) for i in train_df.values.tolist()]\n train_examples = [data.Example.fromlist(i, datafields) for i in train_read_data]\n train_data = data.Dataset(train_examples, datafields)\n \n test_df = self.get_pandas_df(test_file)\n test_read_data = self.df_process(test_df)\n test_examples = [data.Example.fromlist(i, datafields) for i in test_read_data]\n test_data = data.Dataset(test_examples, datafields)\n \n # If validation file exists, load it. Otherwise get validation data from training data\n if val_file:\n val_df = self.get_pandas_df(val_file)\n val_read_data = self.df_process(val_df)\n val_examples = [data.Example.fromlist(i, datafields) for i in val_read_data]\n val_data = data.Dataset(val_examples, datafields)\n else:\n train_data, val_data = train_data.split(split_ratio=0.8)\n \n #TEXT.build_vocab(train_data, vectors=Vectors(w2v_file))\n TEXT.build_vocab(train_data, val_data, test_data, vectors=Vectors(w2v_file))#\n\n self.word_embeddings = TEXT.vocab.vectors\n self.vocab = TEXT.vocab\n\n POS.build_vocab(train_data) #不用vectors初始化\n self.pos_vocab = POS.vocab #在__init__里也要加上self.POS_vocab\n\n #print(self.pos_vocab.itos)#统计pos维度---20\n # ['', '', 'noun', 'punct', 'det', 'adj', 'verb', 'aux', 'adp', 'adv', 'pron', 'cconj', 'propn', 'part', 'sconj', 'num', 'sym', 'intj', 'x', 'space']\n\n #self.pos_embeddings=\n \n self.train_iterator = data.BucketIterator(\n (train_data),\n batch_size=self.config.batch_size,\n sort_key=lambda x: len(x.text),\n repeat=False,\n shuffle=True)\n \n self.val_iterator, self.test_iterator = data.BucketIterator.splits(\n (val_data, test_data),\n batch_size=self.config.batch_size,\n sort=False,#这里为了打印label.tsv不改变原始顺序\n repeat=False,\n shuffle=False)\n # #sort_key=lambda x: len(x.text),\n print (\"Loaded {} training examples\".format(len(train_data)))\n print (\"Loaded {} test examples\".format(len(test_data)))\n print (\"Loaded {} validation examples\".format(len(val_data)))\n\n\ndef evaluate_model(model, iterator):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n criterion = torch.nn.CrossEntropyLoss() # 加了torch\n criterion = criterion.to(device)\n\n all_preds = []\n all_y = []\n epoch_loss = 0\n for idx,batch in enumerate(iterator):\n if torch.cuda.is_available():\n x = batch.text.cuda()\n pos = batch.pos.cuda()\n else:\n x = batch.text\n pos = batch.pos\n y_pred = model(x,pos)\n\n loss = criterion(y_pred.view(-1, 5), (batch.label - 1).to(device).view(-1)) # 5是标签种类数\n\n predicted = torch.max(y_pred.cpu().data, 1)[1] + 1\n all_preds.extend(predicted.numpy())\n all_y.extend(batch.label.numpy())\n\n epoch_loss += loss.mean().item()\n\n #print('预测样本数:'+str(len(all_y)))\n accscore = accuracy_score(all_y, np.array(all_preds).flatten())\n macro_f1=f1_score(all_y, np.array(all_preds).flatten(), average='macro')\n return epoch_loss / len(iterator),accscore,macro_f1\n\ndef evaluate_model_te(model, iterator):#有时间得到tensoboard图\n\n all_preds = []\n all_y = []\n all_logits=[]\n for idx,batch in enumerate(iterator):\n if torch.cuda.is_available():\n x = batch.text.cuda()\n pos = batch.pos.cuda()\n else:\n x = batch.text\n pos = batch.pos\n y_pred = model(x,pos)\n predicted = torch.max(y_pred.cpu().data, 1)[1] + 1#[0]是最大值,[1]是最大值的索引\n all_preds.extend(predicted.numpy())\n all_y.extend(batch.label.numpy())\n norm=nn.Softmax(dim=1)#按最后一个维度\n all_logits=np.append(all_logits,norm(y_pred.cpu().data))#每种分类的可能性数组\n np.savetxt('../data/sem/all_logits_bilstm.txt', all_logits.reshape(-1, 5))\n\n accuracy = accuracy_score(all_y, np.array(all_preds).flatten())\n #micro_f1 = f1_score(all_y, np.array(all_preds).flatten(), average='micro')\n #weighted_f1=f1_score(all_y, np.array(all_preds).flatten(), average='weighted')\n macro_f1 = f1_score(all_y, np.array(all_preds).flatten(), average='macro')\n return accuracy, macro_f1, np.array(all_preds).flatten(), all_y\n\n","sub_path":"Model_BiLSTM/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"465036606","text":"#Project Euler Problem 19\n# How many sundays fell on the first of the month in the 20th century?\n# Given that Jan 1 1900 was a monday.\n# Given that April June September and November have 30 days\n# February has 28 unless a leap year which happens in years divisible by 4\n\nimport calendar\nsunday=0\nfor year in range(1901,2001):\n for month in range(1,13):\n \n if calendar.weekday(year,month,1)==6: #6 is the code for sunday\n print (year, month)\n sunday+=1\nprint(sunday)\n\n#Correct!\n","sub_path":"ProjectEulerP19.py","file_name":"ProjectEulerP19.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"147252153","text":"from common_files.sql_functions import create_table\n# this function explodes all mcl columns and creates respective tables\n# This input is a set of columns that need to be exploded\n# no output but tables in postgres are created, tables names are the same as mcl column titles\n\n\ndef explode_column(df, mcl):\n for c in mcl:\n # loop to explode all mcl columns in list\n column = (c + '.label')\n mcl_column = df[[column]]\n mcl_column_exp = mcl_column.explode(column)\n column_name = (\"exploded_\"+column)\n create_table(mcl_column_exp, column_name)\n","sub_path":"step_2_tidy_files/explode_mcl_columns.py","file_name":"explode_mcl_columns.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"171867876","text":"import datetime\n\nright_now = datetime.datetime.now()\nprint(right_now)\n\n# ask for these values?\nbirth_day = datetime.date(year=2014, month=5, day=2)\nthis_day = datetime.date.today()\n\ntil_bd = birth_day - this_day\nprint( \"Cool your birthday is in {0} days\".format(\n til_bd.days\n) )","sub_path":"03_nums_and_collections/bd.py","file_name":"bd.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"447169902","text":"#tricky Q1\ng = lambda x:x+3\n\n\"\"\"\ndef wow(f):\n def boom(g):\n return f(g)\n return boom\n\"\"\"\n\nwow = lambda f: lambda g: f(g) # the two definations of wow are same\nf = wow(g)#f=wow(g)->lambda z:g(z)->lambda z:z+3\n\nf(2)#5\n\ng= lambda x:x*x\nf(3)#6 the change of g doesn't affect the value of f, \n #because g = lambda x:x+3 is part of the inner structure of f\nwow(g)(3) #9 the change of g affects the value of wow(g)(3)\n\n\na = lambda: 5\nb = lambda: lambda x: 3\nc = lambda x, y: x + y\nd = lambda x: c(a(), b()(x))\n\nd(2)#8\n\nb = lambda: lambda x: x\nd(2)#7 the change of b affects the value of d, \n #because b is the input of d not the inner structure\n\n#trick Q2\ndef troy():\n abed = 0\n while abed < 10:\n britta = lambda: abed\n print(\"abed : %d, britta(): %d\"%(abed,britta()))\n abed += 1\n abed = 20\n print(britta())\n return britta\n\njeff = troy()\n#abed : 0, britta(): 0\n#abed : 1, britta(): 1\n#abed : 2, britta(): 2\n#abed : 3, britta(): 3\n#abed : 4, britta(): 4\n#abed : 5, britta(): 5\n#abed : 6, britta(): 6\n#abed : 7, britta(): 7\n#abed : 8, britta(): 8\n#abed : 9, britta(): 9\n#20\n\nshirley = lambda : jeff\npierce = shirley()\npierce()\n#20\n\n#so the free variable in lambda is bound to the environment","sub_path":"lab03/tricky questions.py","file_name":"tricky questions.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"636634680","text":"\n# coding: utf-8\n\n# In[120]:\n\nimport numpy as np\nimport scipy as sp\n# from keras.datasets import mnist\n\nfrom sklearn.decomposition import SparseCoder\nfrom sklearn.decomposition import MiniBatchDictionaryLearning\n\n\n# In[37]:\n\n(train_x, train_y), (test_x, test_y) = mnist.load_data()\n\nnum_codes = 10000\ninput_dim = train_x.shape[1] * train_x.shape[2]\n\n\n# In[38]:\n\ntrain_x = train_x.reshape(train_x.shape[0], input_dim).astype(np.float32)\n\n\n# In[40]:\n\ntrain_x /= 255\n\n\n# In[122]:\n\ndico = MiniBatchDictionaryLearning(n_components=10, alpha=0.01, n_iter=1000)\n\n\n# In[123]:\n\nD = dico.fit(X).components_\n\n\n# In[128]:\n\nD\n\n\n# In[129]:\n\nsparse_coder = SparseCoder(dictionary=D, transform_alpha=0.01)\n\n\n# In[130]:\n\nX_new = sparse_coder.fit_transform(X)\n\n\n# In[133]:\n\nX_new.shape\n\n\n# In[134]:\n\nD.shape\n\n\n# In[135]:\n\nX.shape\n\n\n# In[139]:\n\nnp.dot(X_new, D)\n\n\n# In[140]:\n\nX\n\n\n# In[9]:\n\nget_ipython().magic(u'matplotlib inline')\nimport matplotlib.pyplot as plt\n\n\n# In[10]:\n\nplt.imshow(D[0].reshape(28, 28))\n\n\n# In[37]:\n\nplt.imshow(D[1].reshape(28, 28))\n\n\n# In[1]:\n\nfrom sklearn.datasets import make_blobs\nfrom sklearn.datasets import make_s_curve\n\n\n# In[9]:\n\nX, t = make_s_curve(n_samples=100, noise=0.1)\n\n\n# In[21]:\n\nX, y = make_blobs(n_samples=1000, centers=3, cluster_std=2.5)\n\n\n# In[5]:\n\nget_ipython().magic(u'matplotlib inline')\n\n\n# In[6]:\n\nimport matplotlib.pyplot as plt\n\n\n# In[22]:\n\nplt.scatter(X[:,0], X[:,1])\n\n\n# In[11]:\n\nt\n\n\n# In[12]:\n\nX.shape\n\n\n# In[19]:\n\nfrom sklearn.mixture import GaussianMixture\n\n\n# In[69]:\n\ngm = GaussianMixture(n_components=3, max_iter=1000, covariance_type=\"tied\")\n\n\n# In[70]:\n\ngm.fit(X, y)\n\n\n# In[71]:\n\ny_pred = gm.predict(X)\n\n\n# In[72]:\n\ny_pred\n\n\n# In[73]:\n\nfrom sklearn.metrics import normalized_mutual_info_score\n\n\n# In[74]:\n\nnormalized_mutual_info_score(y, y_pred)\n\n\n# In[75]:\n\nfrom sklearn.datasets import load_iris\n\n\n# In[77]:\n\nX, y = load_iris(return_X_y=True)\n\n\n# In[79]:\n\nX, y\n\n\n# In[80]:\n\niris_gm = GaussianMixture(n_components=3)\n\n\n# In[95]:\n\niris_gm.fit(X)\n\n\n# In[96]:\n\niris_gm.predict(X)\n\n\n# In[97]:\n\nnormalized_mutual_info_score(y, iris_gm.predict(X))\n\n\n# In[90]:\n\nm = np.mean(X, axis=0)\n\n\n# In[91]:\n\nstd = np.std(X, axis=0)\n\n\n# In[93]:\n\nX = (X - m) / std \n\n\n# In[98]:\n\nnp.mean(X, axis=0)\n\n\n# In[101]:\n\nfrom sklearn.decomposition import PCA\n\n\n# In[115]:\n\npca = PCA()\n\n\n# In[116]:\n\npca.fit(X)\n\n\n# In[117]:\n\nY = pca.transform(X)\n\n\n# In[118]:\n\nY\n\n\n# In[119]:\n\npca.explained_variance_ratio_\n\n\n# In[113]:\n\nplt.scatter(Y[y==0,0], Y[y==0,1], c=\"r\")\nplt.scatter(Y[y==1,0], Y[y==1,1], c=\"g\")\nplt.scatter(Y[y==2,0], Y[y==2,1], c=\"b\")\n\n\n# In[114]:\n\nplt.scatter(X[y==0,0], X[y==0,1], c=\"r\")\nplt.scatter(X[y==1,0], X[y==1,1], c=\"g\")\nplt.scatter(X[y==2,0], X[y==2,1], c=\"b\")\n\n\n# In[141]:\n\nfrom sklearn.cluster import KMeans\n\n\n# In[142]:\n\nkmeans = KMeans(n_clusters=3)\n\n\n# In[144]:\n\nY = kmeans.fit_predict(X)\n\n\n# In[145]:\n\nnormalized_mutual_info_score(y, Y)\n\n\n# In[146]:\n\nY\n\n\n# In[147]:\n\nimport networkx as nx\n\n\n# In[148]:\n\nG = nx.karate_club_graph()\n\n\n# In[150]:\n\ndegree = nx.degree(G)\n\n\n# In[154]:\n\nsorted(degree, key=degree.get)[::-1]\n\n\n# In[153]:\n\ndegree\n\n\n# In[164]:\n\nX, y = make_s_curve(n_samples=1000)\n\n\n# In[157]:\n\nfrom sklearn.manifold import LocallyLinearEmbedding\n\n\n# In[158]:\n\nlle = LocallyLinearEmbedding()\n\n\n# In[165]:\n\nY = lle.fit_transform(X)\n\n\n# In[168]:\n\nplt.scatter(Y[:,0], Y[:,1])\n\n\n# In[169]:\n\nX.shape\n\n\n# In[170]:\n\nfrom sklearn.datasets import load_digits\n\n\n# In[196]:\n\nX, y = load_digits(return_X_y=True)\n\n\n# In[176]:\n\nfrom sklearn.manifold import MDS\n\n\n# In[177]:\n\nmds = MDS()\n\n\n# In[200]:\n\nY = mds.fit_transform(X)\n\n\n# In[179]:\n\nY.shape\n\n\n# In[180]:\n\ny\n\n\n# In[201]:\n\nfor i in range(10):\n plt.scatter(Y[y==i,0], Y[y==i,1], c=np.random.rand(3))\n\n\n# In[198]:\n\nX = (X - np.mean(X, axis=0)) / (np.std(X, axis=0) + 1e-8)\n\n\n# In[188]:\n\nlen(np.mean(X, axis=1))\n\n\n# In[190]:\n\nX.shape\n\n\n# In[199]:\n\nX[0]\n\n\n# In[197]:\n\nnp.std(X, axis=0)\n\n\n# In[6]:\n\n####LaBNE\ndef LaBNE(network):\n \n # dictionary of node degrees\n degrees = nx.degree(network)\n \n # mean node degree\n m = np.mean(degrees.values()) / 2\n \n # estimated scaling exponent of the network \n gamma = scaling_exponent(degrees)\n \n # beta \n beta = 1 / (gamma - 1)\n \n # N\n N = len(network)\n \n # R\n R = 2 * np.log(N) - 2 * np.log( 2 * (1 - np.exp(- np.log(N) * (1 - beta))) / (np.pi * m * (1 - beta)) )\n \n # network laplacian\n L = np.array(nx.laplacian_matrix(network).todense())\n \n # eigen-decomposition\n l, U = np.linalg.eigh(L)\n \n # embedding\n Y = U[:,(1, 2)]\n \n # sort nodes decreasingly by degree\n sorted_nodes = np.array(sorted(degrees, key=degrees.get)[::-1])\n \n # argsort and label nodes\n i = sorted_nodes.argsort() + 1\n \n # radial co-ordinates\n r = 2 * beta * np.log(i) + 2 * (1 - beta) * np.log(N)\n \n # compute theta \n theta = np.arctan(Y[:,1] / Y[:,0])\n \n # return (r, theta)\n return r, theta\n\n\n# In[7]:\n\ndef scaling_exponent(degrees):\n \n ##sort nodes by degree\n degrees = np.array([sum(1 for v in degrees.values() if v == i) for i in range(max(degrees.values()))], \n dtype=np.float32)\n \n #probabilities\n probabilities = degrees / np.sum(degrees)\n \n return powerlaw.Fit(probabilities).power_law.alpha\n \n\n\n# In[19]:\n\nget_ipython().magic(u'matplotlib inline')\n\nimport networkx as nx\nimport numpy as np\nimport powerlaw\nimport matplotlib.pyplot as plt\n\n\n# In[20]:\n\nG = nx.karate_club_graph()\n\n\n# In[21]:\n\nr, theta = LaBNE(G)\n\n\n# In[22]:\n\nplt.polar(theta, r, \".\", c=\"k\")\n\n\n# In[23]:\n\nx = r * np.cos(theta)\ny = r * np.sin(theta)\n\n\n# In[26]:\n\nplt.scatter(x, y)\nfor label, i, j in zip(G.nodes(), x, y):\n# if label not in H.nodes():\n# continue\n plt.annotate(\n label,\n xy=(i, j), xytext=(-20, 20),\n textcoords='offset points', ha='right', va='bottom',\n bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),\n arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\n\n\n# In[ ]:\n\n\n\n","sub_path":"sparse_coder_sklearn.py","file_name":"sparse_coder_sklearn.py","file_ext":"py","file_size_in_byte":6008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"537973977","text":"from utils import *\nfrom model import *\nimport sys\nimport torch.optim as optim\nfrom torch import nn\nimport torch\nfrom sklearn.metrics import accuracy_score, classification_report\n\n\ndef calc_true_and_pred(model, iterator):\n all_preds = []\n all_y = []\n for idx,batch in enumerate(iterator):\n if torch.cuda.is_available():\n x = batch.text.cuda()\n else:\n x = batch.text\n y_pred = model(x)\n predicted = torch.max(y_pred.cpu().data, 1)[1] + 1\n all_preds.extend(predicted.numpy())\n all_y.extend(batch.label.numpy())\n return all_y, all_preds\n\n\n\ntrain_file = '../data/booking-rating-train.csv'\ntest_file = '../../Detect-emotion-sentimental/dataset/booking/booking-rating-test.csv'\nval_file = '../data/booking-rating-val.csv'\nw2v_file = '../data/ubercorpus.cased.tokenized.word2vec.300d'\n\n\n\n\nclass Config(object):\n embed_size = 300\n hidden_layers = 2\n hidden_size = 64\n output_size = 5\n max_epochs = 64\n hidden_size_linear = 64\n lr = 0.5\n batch_size = 8\n seq_len = None # Sequence length for RNN\n dropout_keep = 0.8\n\n\nconfig = Config()\ndataset = Dataset(config)\ndataset.load_data(w2v_file, train_file, test_file, val_file)\n\n\n\nmodel = RCNN(config, len(dataset.vocab), dataset.word_embeddings)\nif torch.cuda.is_available():\n model.cuda()\nmodel.train()\noptimizer = optim.SGD(model.parameters(), lr=config.lr)\nNLLLoss = nn.NLLLoss()\nmodel.add_optimizer(optimizer)\nmodel.add_loss_op(NLLLoss)\n\n\n\ntrain_losses = []\nval_accuracies = []\n\nfor i in range(config.max_epochs):\n print(\"Epoch: {}\".format(i))\n train_loss, val_accuracy = model.run_epoch(dataset.train_iterator, dataset.val_iterator, i)\n train_losses.append(train_loss)\n val_accuracies.append(val_accuracy)\n\n\n\nall_y, all_preds = calc_true_and_pred(model, dataset.test_iterator)\n\ntest_acc = accuracy_score(all_y, np.array(all_preds).flatten())\nprint ('Final Test Accuracy: {:.4f}'.format(test_acc))\n\n\nprint(classification_report(all_y, np.array(all_preds).flatten()))\n\n\n\ntorch.save(model.state_dict(), 'rcnn_booking_rating')\n\n\n\n\n","sub_path":"Model_RCNN/train-booking-rating.py","file_name":"train-booking-rating.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"49270976","text":"'''\nCreated on 2016/09/12\n\n@author: kot\n'''\nfrom constants import *\nfrom trader_border import TraderBorder\nfrom libs.common import *\nimport libs.candle as candle\n\nDEBUG = True\n\nclass TraderLine(TraderBorder):\n '''\n Always setups stopLoss and takeProfit according to position of borders\n \n Prerequisits\n analyzer: ChartLines must include peaks line\n '''\n\n\n def __init__(self, **params):\n '''\n Constructor\n '''\n TraderBorder.__init__(self, **params)\n self.set_default_params()\n \n \n def set_default_params(self):\n self.params = {\n \"min_pips_range\":[25, [20, 40], 5],\n \"max_concurrent_trades\":[1, [1, 10], 2],\n \"min_take_profit_pips\":[10, [0, 40], 5],\n \"min_stop_loss_pips\":[5, [0, 30], 5],\n \"wait_candles_no\":[5, [1, 9], 2]\n }\n\n \n \n #task\n # karakasa\n # trend\n def judge_enter(self):\n #if DEBUG:\n # if epoch2str(self.last_clock, NORMAL_DATETIME_FORMAT) >= \"2016-09-23T03:45:00\":\n # print self.last_clock\n \n false_val = (False, \"\", -1)\n chart = self.analyzer.chart\n (j_clocks, j_prices, j_pms, last_peak, peak_clock) = chart.get_peaks(\"bid\")\n if len(j_clocks) <= 0:\n return false_val\n j_idx = chart.get_index(j_clocks[-1])\n last_peak_idx = chart.get_index(peak_clock)\n last_idx = chart.get_index(self.last_clock)\n wait_candles_no = self.get_val(\"wait_candles_no\")\n is_market_follower = True\n side = \"\"\n \n border = self.border[\"bid\"][\"prices\"]\n # bidask, clock, prices, base_price\n last_peak_pos = self.analyzer.get_pos_at(\"bid\", peak_clock, border)\n pos = self.analyzer.get_pos_at(\"bid\", self.last_clock, border)\n \n # [ -3,-2,-1, 0, 1, 2, 3]\n # [-1 0, 1, 2, 3, 4, 5, 6]\n high_pos = 5\n low_pos = 0\n \n #if DEBUG:\n # if self.last_clock == str2epoch(\"2016-09-06T21:25:00\", NORMAL_DATETIME_FORMAT):\n # print self.last_clock\n \n if j_pms[-1] == 1:\n if last_idx - j_idx >= wait_candles_no \\\n and last_peak_pos <= low_pos and pos < high_pos-1:\n side = \"buy\"\n is_market_follower = False\n else:\n side = \"sell\"\n is_market_follower = True\n elif j_pms[-1] == -1:\n if last_idx - j_idx >= wait_candles_no \\\n and last_peak_pos >= high_pos and pos > low_pos+1:\n side = \"sell\"\n is_market_follower = False\n else:\n side = \"buy\"\n is_market_follower = True\n if side == \"buy\":\n bidask = \"ask\"\n elif side == \"sell\":\n bidask = \"bid\"\n else:\n return false_val\n \n \n \n # judge karakasa\n data = chart.get_data()\n data = data[bidask]\n (is_karakasa, is_up_peak) = \\\n candle.judge_karakasa(data[\"open\"], data[\"high\"], data[\"low\"], data[\"close\"], \n last_peak_idx)\n if is_karakasa == False and is_market_follower==False:\n return false_val\n \n # [ -3,-2,-1, 0, 1, 2, 3]\n # [-1 0, 1, 2, 3, 4, 5, 6]\n # judge trend\n if len(j_prices) >= 3 and is_market_follower:\n if side == \"buy\" and (j_prices[-3] > j_prices[-1] or last_peak < j_prices[-2]):\n return false_val\n if side == \"sell\" and (j_prices[-3] < j_prices[-1] or last_peak > j_prices[-2]):\n return false_val\n elif is_market_follower:\n return false_val\n else:\n if last_idx - last_peak_idx >= wait_candles_no:\n return false_val\n \n prices = self.border[bidask][\"prices\"]\n # bidask, clock, prices, base_price\n #last_peak_pos = self.analyzer.get_pos_at(bidask, peak_clock, prices)\n #pos = self.analyzer.get_pos_at(bidask, self.last_clock, prices)\n \n \n (o, h, c, l) = chart.get_data_at(bidask, self.last_clock)\n #if pos == last_peak_pos + j_pm*1:\n # for p in [o, h, c, l]:\n # if pos != self.analyzer.get_pos_at(bidask, self.last_clock, prices, p):\n # return false_val\n \n if pos + 3 > len(prices):\n return false_val\n if pos - 2 < 0:\n return false_val\n \n # [-3,-2,-1, 0, 1, 2, 3]\n # [ 0, 1, 2, 3, 4, 5, 6]\n if side == \"buy\":\n take_profit_pos = min(pos + 3, len(prices)-1)\n stop_loss_pos = max(pos -1, 0)\n if side == \"sell\":\n take_profit_pos = max(pos - 3, 0)\n stop_loss_pos = min(pos + 2, len(prices)-1)\n \n \n \n curr_price = c\n min_take_profit = self.get_val(\"min_take_profit_pips\")\n min_stop_loss = self.get_val(\"min_stop_loss_pips\")\n \n options = {}\n options[\"take_profit_pos\"] = take_profit_pos\n take_profit = prices[take_profit_pos]\n #if abs(take_profit - curr_price) < min_take_profit*0.01:\n # return false_val\n options[\"takeProfit\"] = take_profit\n options[\"stop_loss_pos\"] = stop_loss_pos\n stop_loss = prices[stop_loss_pos]\n #if abs(curr_price - stop_loss) < min_stop_loss*0.01:\n # return false_val\n options[\"stopLoss\"] = stop_loss\n stop_loss_price = prices[stop_loss_pos]\n options[\"stop_loss_price\"] = stop_loss_price\n options[\"trailing_stop_pips\"] = round(abs(curr_price - stop_loss_price)*100)\n options[\"is_market_follower\"] = is_market_follower\n return (True, side, options)\n \n \n def modify_trade(self, trade_id):\n trade = self.trades[trade_id]\n side = trade.get_option(TRADE_SIDE)\n if side == \"sell\":\n prices = self.border[\"ask\"][\"prices\"]\n if side == \"buy\":\n prices = self.border[\"bid\"][\"prices\"]\n options = {\n \"takeProfit\" : prices[trade.get_option(\"take_profit_pos\")],\n \"stopLoss\" : prices[trade.get_option(\"stop_loss_pos\")]\n }\n self.vendor.modify_trade(trade_id, **options)\n \n \n def make_orders(self):\n max_c = self.get_val(\"max_concurrent_trades\")\n if len(self.trades) >= max_c:\n return\n (is_enter_ok, side, options) = self.judge_enter()\n if is_enter_ok:\n self.create_order(side, **options)\n\n\n ","sub_path":"engine/classes/trader_line.py","file_name":"trader_line.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"534771807","text":"\"\"\"\nhomeassistant.components.switch.rpi_gpio\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nAllows to configure a switch using RPi GPIO.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/switch.rpi_gpio/\n\"\"\"\n\nimport logging\nimport homeassistant.components.rpi_gpio as rpi_gpio\nfrom homeassistant.helpers.entity import ToggleEntity\nfrom homeassistant.const import (DEVICE_DEFAULT_NAME)\n\nDEFAULT_INVERT_LOGIC = False\n\nDEPENDENCIES = ['rpi_gpio']\n_LOGGER = logging.getLogger(__name__)\n\n\n# pylint: disable=unused-argument\ndef setup_platform(hass, config, add_devices, discovery_info=None):\n \"\"\" Sets up the Raspberry PI GPIO devices. \"\"\"\n\n invert_logic = config.get('invert_logic', DEFAULT_INVERT_LOGIC)\n\n switches = []\n ports = config.get('ports')\n for port, name in ports.items():\n switches.append(RPiGPIOSwitch(name, port, invert_logic))\n add_devices(switches)\n\n\nclass RPiGPIOSwitch(ToggleEntity):\n \"\"\" Represents a switch that can be toggled using Raspberry Pi GPIO. \"\"\"\n def __init__(self, name, port, invert_logic):\n self._name = name or DEVICE_DEFAULT_NAME\n self._port = port\n self._invert_logic = invert_logic\n self._state = False\n rpi_gpio.setup_output(self._port)\n\n @property\n def name(self):\n \"\"\" The name of the switch. \"\"\"\n return self._name\n\n @property\n def should_poll(self):\n \"\"\" No polling needed. \"\"\"\n return False\n\n @property\n def is_on(self):\n \"\"\" True if device is on. \"\"\"\n return self._state\n\n def turn_on(self):\n \"\"\" Turn the device on. \"\"\"\n rpi_gpio.write_output(self._port, 0 if self._invert_logic else 1)\n self._state = True\n self.update_ha_state()\n\n def turn_off(self):\n \"\"\" Turn the device off. \"\"\"\n rpi_gpio.write_output(self._port, 1 if self._invert_logic else 0)\n self._state = False\n self.update_ha_state()\n","sub_path":"out/production/home-assistant/components/switch/rpi_gpio.py","file_name":"rpi_gpio.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"369754276","text":"\"\"\"Added a token column to the User Model\n\nRevision ID: c79e8f9b9b39\nRevises: 1867107fae82\nCreate Date: 2019-01-03 07:02:03.569253\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c79e8f9b9b39'\ndown_revision = '1867107fae82'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('users', sa.Column('token', sa.String(length=32), nullable=True))\n op.create_unique_constraint(None, 'users', ['token'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'users', type_='unique')\n op.drop_column('users', 'token')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/c79e8f9b9b39_added_a_token_column_to_the_user_model.py","file_name":"c79e8f9b9b39_added_a_token_column_to_the_user_model.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"85940655","text":"from math import inf\nfrom random import randint\n\nclass Heap:\n \"\"\"Implements a heap with some basic operations.\"\"\"\n # A list that will hold the data of the heap\n heap = []\n\n def __init__(self, list):\n \"\"\"Heapify the list\"\"\"\n self.heap = list\n\n # Shift down all the elements (from last to first), takes O(n)\n for i in reversed(range(len(list))):\n self.shiftDown(i)\n\n def add(self, element):\n \"\"\"Add an element to a heap in O(log(n)) - shifts up.\"\"\"\n self.heap.append(element)\n\n i = len(self.heap) - 1 # the last element (the newly added one)\n parent = self.getParent(i) # it's parent\n\n # While the parent is smaller, swap it and the parent\n while(parent[0] < self.heap[i]):\n self.heap[parent[1]], self.heap[i] = self.heap[i], self.heap[parent[1]]\n\n # change i to the index of the parent and the parent of it's parent\n i = parent[1]\n parent = self.getParent(i)\n\n def sorted(self):\n \"\"\"Perform heapsort, return the sorted array. Note that this empties the\n heap.\"\"\"\n array = []\n\n # While there are elements in the heap, pop the biggest one\n while len(self.heap) > 0:\n array.append(self.pop())\n\n return list(reversed(array))\n\n def pop(self):\n \"\"\"Pops the biggest value from the heap in O(log(n)).\"\"\"\n if len(self.heap) == 0:\n return None\n elif len(self.heap) == 1:\n return self.heap.pop()\n\n maxValue = self.heap[0]\n\n self.heap[0] = self.heap.pop()\n self.shiftDown(0)\n\n return maxValue\n\n def peek(self):\n \"\"\"Returns the biggest value from the heap without popping it.\"\"\"\n if len(self.heap) == 0:\n return None\n else:\n return self.heap[0]\n\n def shiftDown(self, i):\n \"\"\"Shifts a number at an index down, until it is in the correct spot.\"\"\"\n mChild = max(self.getChildren(i))\n\n # Swap until our number is not bigger than the biggest of its children\n while self.getValue(i) <= mChild[0]:\n self.heap[i], self.heap[mChild[1]] = self.heap[mChild[1]], self.heap[i]\n\n i = maxChild[1]\n maxChild = max(self.getChildren(i))\n\n def getValue(self, index):\n \"\"\"Returns the value at a specified index of the heap.\"\"\"\n if index < 0:\n # Infinity if it's above the root\n return inf\n elif index >= len(self.heap):\n # -Infinity if it's bigger than the list (would be potential child)\n return -inf\n else:\n # Otherwise it's ok to return the value\n return self.heap[index]\n\n def getChildren(self, index):\n \"\"\"Returns the children of an index.\"\"\"\n return [(self.getValue(2*(index+1)-1), 2*(index+1)-1),\n (self.getValue(2*(index+1)), 2*(index+1))]\n\n def getParent(self, index):\n \"\"\"Returns the parent of an index.\"\"\"\n return [self.getValue((index+1)//2-1), (index+1)//2-1]\n","sub_path":"Programy/17 - Heapsort/heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"398019043","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nfrom scrape_menu_yelp import read_menu\nfrom save_sentences_csv import items_in_sentence, optimize_list\nfrom aylienapiclient import textapi\nfrom nltk.tokenize import sent_tokenize\nfrom pathlib import Path\nimport time\nimport argparse as ap\nimport os, pickle,requests\nimport pandas as pd \n\n# Set up ids and keys from AYLIEN \nids = [\"ca16d389\", \"c1d8b559\", \"223c1a5b\"] \nkeys = [\"7c89bd682b4dddd68404b32e342901fb\", \"d62a26c46dba4da09c526455d2a27055\", \"3772a183fe2fc77774e7448b2d8ff919\"]\n\n\n# count # of reviews \ndef count(userid):\n\turl = \"https://www.yelp.com/user_details?\" + userid\n\tr = requests.get(url)\n\tencoding = r.encoding if 'charset' in r.headers.get('content-type', '').lower() else None\n\tsoup = BeautifulSoup(r.content, from_encoding=encoding) # BeautifulSoup produces HTML of webpage\n\tcount = soup.find('li', attrs={'class' : 'review-count'}).find('strong').get_text()\n\treturn int(count)\n\ndef round_down(num, divisor):\n return num - (num%divisor)\n\n# Pull Yelp HTML \ndef pull_yelp_html(userid, n):\n\turl = \"https://www.yelp.com/user_details_reviews_self?rec_pagestart=\" + str(n) + \"&\" + userid\n\tr = requests.get(url)\n\tencoding = r.encoding if 'charset' in r.headers.get('content-type', '').lower() else None\n\tsoup = BeautifulSoup(r.content, from_encoding=encoding) # BeautifulSoup produces HTML of webpage\n\treturn soup\n\ndef scrape_comments(userid):\n\tdata = []\n\tmaxn = count(userid)\n\tn = 0\n\n\twhile(n < maxn):\n\t\tprint(n)\n\t\tsoup = pull_yelp_html(userid, n)\n\t\tcomments = soup.find_all('p', attrs={'lang': \"en\"})\n\t\tfor comment in comments:\n\t\t\treview_detail = comment.parent.parent.parent\n\t\t\tdate = review_detail.find('span', attrs={'class' : \"rating-qualifier\"}).get_text()\n\t\t\trestaurantCode = review_detail.find('a', attrs={'class' : \"biz-name js-analytics-click\", 'data-analytics-label' : \"biz-name\"}).get('href')[5:]\n\t\t\ttext = comment.get_text()\n\t\t\tdata.append([restaurantCode, text, date])\n\t\tn += 10\n\treturn data\n\ndef write_user(data):\n\tscript_dir = os.path.abspath(os.path.join(__file__ ,\"../..\"))\n\tprint(\"Saving user data at \" + script_dir + \"/output_user/users.txt\")\n\twith open(script_dir + \"/output_user/users.txt\", 'wb') as f:\n\t\tpickle.dump(data, f)\n\ndef read_user():\n\tscript_dir = os.path.abspath(os.path.join(__file__ ,\"../..\"))\n\tfname = script_dir + \"/output_user/users.txt\"\n\tif Path(fname).is_file():\n\t\tprint(\"Reading existing file: output_user/users.txt\")\n\t\twith open(script_dir + \"/output_user/users.txt\", 'rb') as f:\n\t\t\tdata = pickle.load(f)\n\t\treturn data\n\telse:\n\t\tprint(\"File does not exist: \", userid)\n\t\treturn None\n\ndef match_sentence_item(sentence, menu_items, c):\n\tclient = textapi.Client(ids[c], keys[c])\n\n\t# remove sentence if it does not contain a menu item \n\titems_in_given_sentence = items_in_sentence(sentence, menu_items, 2)\n\tif(len(items_in_given_sentence) == 0):\n\t\treturn [], c\n\n\t# call API to gather sentiment analysis \n\ttry:\n\t\tsentiment = client.Sentiment({'text' : sentence})\n\texcept:\n\t\tprint(\"changing client from: \", c)\n\t\tc = (c + 1) % 3\n\t\tprint(\"to: \", c)\n\t\tclient = textapi.Client(ids[c], keys[c])\n\t\ttry:\n\t\t\tsentiment = client.Sentiment({'text': tokenized_sentence})\n\t\texcept: \n\t\t\tprint(\"Error: Too many subjectivity requests from API. Pausing for 5.\")\n\t\t\ttime.sleep(5)\n\t\t\treturn [], c\n\n\t# remove sentence if it is objective or neutral\n\tif(sentiment['subjectivity'] == 'objective'):\n\t\treturn [], c\n\t\t\t\n\t# add single item if list of items is one-item long \n\tif(len(items_in_given_sentence) == 1):\n\t\treturn [next(iter(items_in_given_sentence))], c\n\n\t# add most optimal item out of list of multiple items \n\tif(len(items_in_given_sentence) > 1):\n\t\toptimized_items = optimize_list(items_in_given_sentence, sentence.lower())\n\t\treturn optimized_items, c\n\ndef iterate_restaurants(data, userid, c):\n\toutput = []\n\tfor (restaurantCode, text, date) in data:\t\t\n\t\tmenu_items = read_menu(restaurantCode)\n\t\tif(menu_items == None):\n\t\t\tcontinue \n\n\t\tfor sentence in sent_tokenize(text):\n\t\t\titems, c = match_sentence_item(sentence, menu_items, c)\n\t\t\tif(items == []):\n\t\t\t\tcontinue\n\t\t\tfor item in items:\n\t\t\t\t(month, day, year) = date.split('/')\n\t\t\t\tprint(\"appending: \", sentence)\n\t\t\t\toutput.append(('Yelp', userid, restaurantCode, month, day, year, item, sentence))\n\treturn output\n\ndef iterate_users(data, restaurantCode, c):\n\toutput = []\n\tmenu_items = read_menu(restaurantCode)\n\n\tif(menu_items == None):\n\t\tprint(\"No menus for: \", restaurantCode)\n\t\treturn None\n\n\tfor (userid, text, date) in data:\n\t\tfor sentence in sent_tokenize(text):\n\t\t\titems, c = match_sentence_item(sentence, menu_items, c)\n\t\t\tif(items == []):\n\t\t\t\tcontinue\n\t\t\tfor item in items:\n\t\t\t\t(month, day, year) = date.split('/')\n\t\t\t\tprint(\"appending: \", sentence)\n\t\t\t\toutput.append(('Yelp', userid, restaurantCode, month, day, year, item, sentence)) \n\treturn output\n\nif __name__ == '__main__':\n\tparser = ap.ArgumentParser()\n\tparser.add_argument('-u', '--userid', help='User ID', default='userid=iFadxdXUK118lr-gx6-2tA')\n\tparser.add_argument('-o', '--option', help='0 to scrape by user, 1 to scrape by restaurant', default='0')\n\tparser.add_argument('-t', '--restaurantCode', help='Yelp Restaurant Code', default='girl-and-the-goat-chicago')\n\n\targs = vars(parser.parse_args())\n\tuserid = args['userid']\n\tc = 0\n\to = int(args['option'])\n\trestaurantCode = args['restaurantCode']\n\tclient = textapi.Client(ids[c], keys[c])\n\tscript_dir = os.path.abspath(os.path.join(__file__ ,\"../..\"))\n\tuserids = read_user()\n\n\tif o == 0:\n\t\tdata = scrape_comments(userid)\n\t\toutput = iterate_restaurants(data, userid, c)\t\t\n\t\tif userid not in userids:\n\t\t\tuserids.append(userid)\n\t\t\twrite_user(userids)\n\t\ts = pd.DataFrame(output, index=None, columns=['Source', 'SourceUserCode', 'YelpID', 'Month', 'Day', 'Year', 'Item', 'Sentence']) \n\t\ts.to_csv(script_dir + \"/csvfiles/comments/\" + userid + \".csv\", index=False)\n\telif o == 1:\n\t\twith open(script_dir + \"/output_reviews/\" + restaurantCode + \"-users.txt\", 'rb') as f:\n\t\t\tdata = pickle.load(f)\n\t\toutput = iterate_users(data, restaurantCode, c)\n\t\ts = pd.DataFrame(output, index=None, columns=['Source', 'SourceUserCode', 'YelpID', 'Month', 'Day', 'Year', 'Item', 'Sentence']) \n\t\ts.to_csv(script_dir + \"/csvfiles/comments/\" + restaurantCode + \".csv\", index=False)\n\n\n\n\n\t","sub_path":"scrape_comments.py","file_name":"scrape_comments.py","file_ext":"py","file_size_in_byte":6229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"329595684","text":"from __future__ import division\nimport nltk\nimport numpy\nfrom nltk.tokenize import *\nimport json\nimport re\nimport csv\nimport sys\nimport pickle\nimport string\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import *\nfrom collections import Counter\nimport socket\nimport sys\nimport os\nmodule_dir = os.path.dirname(__file__)\n\ndef bigramReturner(tweetString):\n tweetString = tweetString.lower()\n # tweetString = removePunctuation (tweetString)\n bigramFeatureVector = []\n for item in nltk.bigrams(tweetString.split()):\n bigramFeatureVector.append(' '.join(item))\n return bigramFeatureVector\n\n\nstemmer = SnowballStemmer(\"english\")\n\nstop = stopwords.words('english')\n# ItemID,Sentiment,SentimentSource,SentimentText\n#above is the order in which the tweetdataset columns are\n#reading the csv file\n#csvfile=open('untouched.csv','rb')\n#reader= csv.reader(csvfile)\n\n#unicode encoding stuff\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n#positive tweet words\npos_tweets = []\n#negative tweet words\nneg_tweets = []\n\n#positive words and negative words\npos_words = []\nneg_words = []\n\n#pos_tags to rmove\npos_tags_to_remove = ['DT', 'PRP', 'PRP$', 'IN', 'CD', '-NONE-', 'WRB']\n#pos_tags_to_remove=['NN','DT','NNS','PRP','PRP$','NNP','IN','MD','CD','NNPS','-NONE-']\n#list of uselesswordsee\nuseless_words = ['just', 'very', 'too', 'im', 'amp', 'and', 'am', 'feel', 'is', 'are', 'was', 'for', 'any', 'got',\n 'now', 'http', 'tumblr', 'you', 'twitter', 'quot', 'woot', 'what', 'where', 'how', 'who', 'when',\n 'why']\n\n\ndef islessthan3(word):\n chararray = []\n chararray.extend(word)\n for char in chararray:\n if chararray.count(char) > 3:\n return False\n return True\n\n\ndef hasdigit(word):\n for i in word:\n if i.isdigit() or i in string.punctuation:\n return True\n return False\n\n\nexclude = set(string.punctuation)\n\n#preprocessing block\ndef preprocess(tweets):\n newarray = []\n m = tweets.count('not ')\n y = tweets.count('cant ')\n z = tweets.count('wont ')\n\n if m > 0 or y > 0 or z > 0:\n tweetarray = word_tokenize(tweets.lower())\n wordstoremove = ['not']\n bilist = bigramReturner(tweets)\n #print \"detected bigram\"\n for item in bilist:\n if (item.split()[0] == \"not\"):\n x = item.split()[1]\n #s = ''.join(ch for ch in x if ch not in exclude)\n wordstoremove.append(x)\n s = \"!\" + x\n newarray.append(s)\n for t in tweetarray:\n if t not in wordstoremove and len(t) > 2:\n newarray.append(t)\n return newarray\n\n\n else:\n tweetstoprocess = word_tokenize(tweets.lower())\n for feeling in tweetstoprocess:\n #removing links\n feeling = re.sub(r'^http?:\\/\\/.*[\\r\\n]*', '', feeling, flags=re.MULTILINE)\n feeling = re.sub(r'\\w[&@]\\w', '', feeling)\n feeling = re.sub(r'^&\\w', '', feeling)\n feeling = re.sub(r'^@', '', feeling)\n feeling = re.sub(r'\\w[; -]\\w', '', feeling)\n feeling = re.sub(r'\\w;', '', feeling)\n feeling = re.sub(r'^#\\w', '', feeling)\n feeling = re.sub(r'[^\\x00-\\x7f]', r' ', feeling)\n #feeling=WordNetLemmatizer().lemmatize(feeling)\n temparray = []\n #feelingarray=word_tokenize(feeling.lower())\n #removing words less than 3\n #for feels in feelingarray:\n if len(feeling) > 2 and feeling not in useless_words and islessthan3(feeling) and not hasdigit(feeling):\n temparray = [feeling.lower()]\n #pos tagging words\n postagarray = nltk.pos_tag(temparray)\n #print postagarray\n for (postaggedword, tag) in postagarray:\n if tag not in pos_tags_to_remove:\n newarray.append(str((postaggedword)))\n return newarray\n\n\nposdict = pickle.load(open(os.path.join(module_dir, 'data/unipos100k.p'), \"rb\"))\nnegdict = pickle.load(open(os.path.join(module_dir, 'data/unineg100k.p'), \"rb\"))\n\nposdict_bi = pickle.load(open(os.path.join(module_dir, 'data/bipos1m.p'), \"rb\"))\nnegdict_bi = pickle.load(open(os.path.join(module_dir, 'data/bineg1m.p'), \"rb\"))\n\npositivedictionary = {}\npositivedictionary.update(posdict)\npositivedictionary.update(posdict_bi)\n\nnegativedictionary = {}\nnegativedictionary.update(negdict)\nnegativedictionary.update(negdict_bi)\n\nnum = 30000\nnumofpostweets = 15161\nnumofnegtweets = 14839\nprobofpos = numofpostweets / num\nprobofneg = numofnegtweets / num\n\nFeararray = ['tensed', 'oh my god', 'omg', 'cold-feet', 'afraid', 'angst', 'anxious', 'apprehensive', 'cowardice',\n 'doubt', 'dread', 'dreadful', 'fear', 'fearful', 'fearsome', 'flighty', 'fret', 'fright', 'frightful',\n 'gutless', 'horror', 'jitters', 'kill', 'nervous', 'nightmare', 'panic', 'petrified', 'queasy', 'scare',\n 'scared', 'scary', 'shitless', 'skittish', 'spooky', 'suspicion', 'terror', 'trembling', 'traumatic',\n 'unease', 'uneasy', 'unpleasant', 'unquiet', 'worried', 'worry', 'wreck', 'shitless', 'cold feet',\n 'scared shitless' 'kill me', 'freaking out', 'shit', ':o', 'shocked'];\n\nSadpersonalarray = ['down', 'happy', 'good', 'depressing', 'heartbreaking', 'sad', 'sorrow', 'unhappy', 'upset',\n 'alienated', 'pitiful', 'unpleasant', 'pain', 'lamentable', 'deplorable', 'sorry', 'glum', 'loss',\n 'lost', 'death', 'dying', 'cold', 'dark', 'pout', 'brooding', 'moody', 'melancholy', 'solemn',\n 'blue', 'gloomy', 'down', 'dismal', 'mournful', 'pessimistic', 'lost', 'somber', 'hollow',\n 'wistful', 'bereaved', 'chearless', 'dejected', 'gloomy', 'grief', 'sick', 'weeping', 'morbid',\n 'hurt', 'hurting', 'troubled', 'pensive', 'unpleasant', 'fucked', 'griefstricken', 'grieving',\n 'lonely', 'longing', 'sorrowful', 'victim', 'struck with grief', 'kill me now', 'low spirits',\n 'grief-stricken', 'long-faced', 'low-spirited', 'heart-breaking', 'life', 'tired', 'breakup',\n 'dump', 'dumped', 'broken up', 'heart breaking', 'troubling', 'beat', 'rough spot', 'rough-spot',\n 'shattered', 'bad'];\n\nAngryarray = ['abrasive', 'angry', 'stupid', 'dumb', 'irritating', 'what the hell', 'hell', 'annoyed', 'antagonized',\n 'antagonizing', 'ballistic', 'bitter', 'chagrin', 'contempt', 'crazy', 'disturbed', 'enraged', 'fuming',\n 'furious', 'grudge', 'hateful', 'heated', 'insane', 'irritable', 'mad', 'peevish', 'pissed', 'scowl',\n 'sore', 'storming', 'sullen', 'vexing', 'resent', 'resentful', 'sour', 'wrath', 'unbalanced', 'unhinged',\n 'rage', 'offended', 'turbulent', 'outraged', 'snotty', 'bullshit', 'freakout', 'dirtylook', 'heated',\n 'hotheaded', 'ill temepered', 'freak out', 'kill someone', 'dirty look', 'fired up', 'off the hook',\n 'off the rails', 'worked up', 'hot headed', 'ill-tempered', 'freak-out', 'dirty-look', 'fired-up',\n 'off-the-hook', 'off-the-rails', 'worked-up', 'hot-headed', 'ill temepered', 'freak out', 'kill someone',\n 'dirty look', 'fired up', 'off the hook', 'off the rails', 'worked up', 'hot headed', 'ill-tempered',\n 'freak-out', 'dirty-look', 'fired-up', 'off-the-hook', 'off-the-rails', 'worked-up', 'hot-headed',\n 'angry', 'explode'];\n\nSadprofarray = ['not-a-winner', 'not a winner', 'too big', 'looking down', 'burn', 'catch22', 'crash', 'dejected',\n 'demoralised', 'demoralized', 'dicey', 'disheartened', 'dismay', 'disappointed', 'disappointing',\n 'dispirit', 'doubtful', 'doubting', 'fail', 'failure', 'farce', 'farrago', 'hodgepodge', 'loser',\n 'mishmash', 'monotonous', 'unmotivated', 'uncertain', 'worry', 'work', 'boss', 'goals', 'troublesome',\n 'trouble', 'life is getting nowhere', 'rut', 'getting nowhere', 'difficult to crack', 'implode',\n 'succumb', 'breaking point', 'saturated', 'pushing my limits', 'target', 'sales'];\n\nDepressedarray = ['suicide', 'suicidal', 'kill myself', 'dont want to live', 'depressed', 'distressed',\n 'jump out of the window', 'no reason to live', 'jump out the window']\n\n\ndef mood(tweet):\n #socket\n #conn,addr =s.accept()\n finalprobofpos = 1.0\n finalprobofneg = 1.0\n posnumerator = 1.0\n posdenominator = 1.0\n negnumerator = 1.0\n negdenominator = 1.0\n score = 0.0\n sentiment = \"\"\n #xinput = raw_input(\"enter your feeling:\\n\")\n #we remove user input and take input from php using socket\n #data=conn.recv(100000)\n #xinput=data.decode(\"utf-8\")\n input = tweet.lower()\n #print \"input : \",input\n #feeling = word_tokenize(input.lower())\n feel = preprocess(str(input))\n\n for w in feel:\n\n if w not in positivedictionary:\n cp = numofpostweets\n else:\n cp = positivedictionary[w] #countpos(w)\n if w not in negativedictionary:\n cn = numofnegtweets\n else:\n cn = negativedictionary[w] #countneg(w)\n '''\n\t\tcp=positivedictionary[w]\n\t\tcn=negativedictionary[w]\n\t\t'''\n posnumerator = posnumerator * (cp / len(posdict)) #numofpostweets)\n posdenominator = posdenominator * ((cp + cn) / num)\n\n if posdenominator == 0:\n posdenominator = 1\n finalprobofpos = posnumerator * (0.5 / posdenominator)\n\n #print \"probability of being positive:\",finalprobofpos\n\n negnumerator = 1.0\n negdenominator = 1.0\n for w in feel:\n\n if w not in positivedictionary:\n cp = numofpostweets\n else:\n cp = positivedictionary[w] #countpos(w)\n if w not in negativedictionary:\n cn = numofnegtweets #replaced with 0 ... as other words could still have some prob\n else:\n cn = negativedictionary[w] #countneg(w)\n '''\n\t\tcp=positivedictionary[w]\n\t\tcn=negativedictionary[w]\n\t\t'''\n negnumerator = negnumerator * cn / len(negdict) #numofnegtweets\n negdenominator = negdenominator * ((cn + cp) / num)\n\n if negdenominator == 0:\n negdenominator = 1\n finalprobofneg = negnumerator * (0.5 / negdenominator)\n\n\n #print \"probability of being negative:\",finalprobofneg\n\n if finalprobofneg < finalprobofpos:\n #senddata=conn.send(\"Happy\")\n score = finalprobofpos\n #print \"happy\"\n sentiment = \"happy\"\n else: #if detected negative we further classify\n flag = 0\n score = finalprobofneg * -1\n for depressedword in Depressedarray:\n if input.find(depressedword) != -1:\n #senddata=conn.send(\"Depressed\")\n #print \"depressed\"\n sentiment = \"depressed\"\n flag = 1\n break\n for angryword in Angryarray:\n if input.find(angryword) != -1:\n #senddata=conn.send(\"Anger\")\n #print \"angry\"\n sentiment = \"angry\"\n flag = 1\n break\n for sadprofword in Sadprofarray:\n if input.find(sadprofword) != -1:\n #senddata=conn.send(\"SadProf\")\n #print \"sadprofessional\"\n sentiment = \"sad professional\"\n flag = 1\n break\n for sadpersonalword in Sadpersonalarray:\n if input.find(sadpersonalword) != -1:\n #senddata=conn.send(\"SadPersonal\")\n #print \"sadpersonal\"\n sentiment = \"sad personal\"\n flag = 1\n break\n for fearword in Feararray:\n if input.find(fearword) != -1:\n #senddata=conn.send(\"Fear\")\n #print \"fear\"\n sentiment = \"fear\"\n flag = 1\n break\n if flag == 0:\n #senddata=conn.send(\"SadPersonal\")\n #print \"sadpersonal\"\n sentiment = \"sad personal\"\n\n #score calculation\n\n return (finalprobofpos,finalprobofneg)\n\n\n\n\n\n\n\n","sub_path":"tk/kundli/mood.py","file_name":"mood.py","file_ext":"py","file_size_in_byte":12211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"255156301","text":"# Scrap a single page and get all the metadata.\n\n# Import scrapy library.\nimport scrapy\n\n\nclass MetaSpider(scrapy.Spider):\n\n # The spider's name must be unique in a project.\n name = 'meta_spider'\n\n # Allow crawling only inside these domains.\n # Be careful with the subdomains. Use the www.example.com to restrict on\n # the primary domain.\n allowed_domains = [\n 'example.com',\n ]\n\n # You can have multiple starting points if some areas of the site are not\n # discoverable or you don't want to follow links and specify a list of\n # pages.\n start_urls = [\n 'http://example.com/',\n ]\n\n # The default function `parse(self, response)` called by Scrapy to create\n # the results.\n def parse(self, response):\n\n # Get the URL of the curent page\n page_url = response.url\n # Get the status (200, 301, 404)\n page_status = response.status\n # Get the \n page_title = response.xpath('//title/text()').extract_first()\n # Create list with the <meta> name\n page_meta_list_name = response.xpath('//meta/@name').extract()\n # Create list with the <meta> content\n page_meta_list_value = response.xpath('//meta/@content').extract()\n # Create a joined list like: [[\"meta-name-1\", \"meta-content-1\"],\n # [\"meta-name-1\", \"meta-content-1\"]]\n page_meta_list_array = []\n for i in range(len(page_meta_list_name)):\n page_meta_list_array.append(\n [page_meta_list_name[i], page_meta_list_value[i]])\n # Create a dictionary combining the two metatag lists\n page_meta_list_dictionary = {}\n for i in range(len(page_meta_list_name)):\n page_meta_list_dictionary[\n page_meta_list_name[i]] = page_meta_list_value[i]\n # Get <meta name=\"keywords\"> value\n page_meta_keywords = response.xpath(\n '//meta[@name=\\'keywords\\']/@content').extract_first()\n # Get <meta name=\"non-existing-tag\"> to check what happend when we\n # target something that does not exist\n page_meta_non_existing_tag = response.xpath(\n '//meta[@name=\\'non-existing-tag\\']/@content').extract_first()\n # Get a spesific tag\n page_meta_spesific = response.xpath(\n '/html/head/meta[3]').extract_first()\n\n # `yield` is like `return` but returns a `generator`.\n # for more information:\n # https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/\n # http://stackoverflow.com/a/231855/1692965\n yield {\n 'html': response.body,\n 'url': page_url,\n 'status': page_status,\n 'title': page_title,\n 'meta-list-array': page_meta_list_array,\n 'meta-list-dictionary': page_meta_list_dictionary,\n 'meta-keywords': page_meta_keywords,\n 'meta-non-existing-tag': page_meta_non_existing_tag,\n 'meta-spesific': page_meta_spesific,\n }\n","sub_path":"scrapy_examples/spiders/meta_spider.py","file_name":"meta_spider.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"154738031","text":"class Solution(object):\n def helper(self, root, path, paths):\n if not root:\n return\n \n path += str(root.val)\n\n if not root.left and not root.right:\n paths.append(path)\n return\n \n path += \"->\"\n self.helper(root.left, path, paths)\n self.helper(root.right, path, paths)\n\n def binaryTreePaths(self, root):\n paths = []\n self.helper(root, \"\", paths)\n return paths\n\n\nclass Solution(object):\n def binaryTreePathsHelper(self, root, sol, res):\n if not root.left and not root.right:\n res.append(\"->\".join(map(str, sol)))\n return\n\n if root.left:\n sol.append(root.left.val)\n self.binaryTreePathsHelper(root.left, sol, res)\n sol.pop()\n if root.right:\n sol.append(root.right.val)\n self.binaryTreePathsHelper(root.right, sol, res)\n sol.pop()\n\n def binaryTreePaths(self, root):\n res, sol = [], []\n if not root:\n return res\n\n sol.append(root.val)\n self.binaryTreePathsHelper(root, sol, res)\n sol.pop()\n\n return res\n","sub_path":"algorithms/BinaryTreePaths/BinaryTreePaths.py","file_name":"BinaryTreePaths.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"52424944","text":"from issm.fielddisplay import fielddisplay\nfrom issm.checkfield import checkfield\nfrom issm.WriteData import WriteData\nfrom issm.project3d import project3d\n\nclass SMBgradientsela(object):\n\t\"\"\"\n\tSMBgradientsela Class definition\n\n\t Usage:\n\t SMBgradientsela=SMBgradientsela();\n\t\"\"\"\n\n\tdef __init__(self): # {{{\n\t\tself.ela = float('NaN')\n\t\tself.b_pos = float('NaN')\n\t\tself.b_neg = float('NaN')\n\t\tself.b_max = float('NaN')\n\t\tself.b_min = float('NaN')\n\t\tself.requested_outputs = []\n\t\t#}}}\n\tdef __repr__(self): # {{{\n\t\tstring=\" surface forcings parameters:\"\n\n\t\tstring=\"%s\\n%s\"%(string,fielddisplay(self,'issmbgradientsela','is smb gradients ela method activated (0 or 1, default is 0)'))\n\t\tstring=\"%s\\n%s\"%(string,fielddisplay(self,'ela',' equilibrium line altitude from which deviation is used to calculate smb using the smb gradients ela method [m a.s.l.]'))\n\t\tstring=\"%s\\n%s\"%(string,fielddisplay(self,'b_pos',' vertical smb gradient (dB/dz) above ela'))\n\t\tstring=\"%s\\n%s\"%(string,fielddisplay(self,'b_neg',' vertical smb gradient (dB/dz) below ela'))\n\t\tstring=\"%s\\n%s\"%(string,fielddisplay(self,'b_max',' upper cap on smb rate, default: 9999 (no cap) [m ice eq./yr]'))\n\t\tstring=\"%s\\n%s\"%(string,fielddisplay(self,'b_min',' lower cap on smb rate, default: -9999 (no cap) [m ice eq./yr]'))\n\t\tstring=\"%s\\n%s\"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))\n\n\t\treturn string\n\t\t#}}}\n\tdef extrude(self,md): # {{{\n\n\t\t#Nothing for now\n\t\treturn self\n\t#}}}\n\tdef defaultoutputs(self,md): # {{{\n\t\treturn []\n\t#}}}\n\tdef initialize(self,md): # {{{\n\n\t\t#Nothing for now\n\n\t\treturn self\n\t#}}}\n\tdef checkconsistency(self,md,solution,analyses): # {{{\n\n\t\tif 'MasstransportAnalysis' in analyses:\n\t\t\tmd = checkfield(md,'fieldname','smb.ela','timeseries',1,'NaN',1,'Inf',1)\n\t\t\tmd = checkfield(md,'fieldname','smb.b_pos','timeseries',1,'NaN',1,'Inf',1)\n\t\t\tmd = checkfield(md,'fieldname','smb.b_neg','timeseries',1,'NaN',1,'Inf',1)\n\t\t\tmd = checkfield(md,'fieldname','smb.b_max','timeseries',1,'NaN',1,'Inf',1)\n\t\t\tmd = checkfield(md,'fieldname','smb.b_min','timeseries',1,'NaN',1,'Inf',1)\n\n\t\tmd = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1)\n\t\treturn md\n\t# }}}\n\tdef marshall(self,prefix,md,fid): # {{{\n\n\t\tyts=md.constants.yts\n\n\t\tWriteData(fid,prefix,'name','md.smb.model','data',9,'format','Integer');\n\t\tWriteData(fid,prefix,'object',self,'class','smb','fieldname','ela','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)\n\t\tWriteData(fid,prefix,'object',self,'class','smb','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)\n\t\tWriteData(fid,prefix,'object',self,'class','smb','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)\n\t\tWriteData(fid,prefix,'object',self,'class','smb','fieldname','b_max','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)\n\t\tWriteData(fid,prefix,'object',self,'class','smb','fieldname','b_min','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)\n\t\t\n\t\t#process requested outputs\n\t\toutputs = self.requested_outputs\n\t\tindices = [i for i, x in enumerate(outputs) if x == 'default']\n\t\tif len(indices) > 0:\n\t\t\toutputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]\n\t\t\toutputs =outputscopy\n\t\tWriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray')\n\n\t# }}}\n","sub_path":"issm/SMBgradientsela.py","file_name":"SMBgradientsela.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"628101795","text":"from prompt_toolkit.filters import completion_is_selected\nfrom prompt_toolkit.key_binding import KeyBindings\n\nkb = KeyBindings()\n\n\n@kb.add(\"enter\", filter=completion_is_selected)\ndef _(event):\n event.current_buffer.complete_state = None\n b = event.app.current_buffer\n b.complete_state = None\n","sub_path":"chcli/key_bindings.py","file_name":"key_bindings.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"608238560","text":"import GaudiKernel.SystemOfUnits as Units\nfrom Gaudi.Configuration import *\nfrom PhysSelPython.Wrappers import AutomaticData, DataOnDemand, Selection, SelectionSequence\nfrom Configurables import CombineParticles, FilterDesktop, OfflineVertexFitter\nfrom Configurables import DaVinci\nfrom Configurables import SubstitutePID\n\nfrom Configurables import MCDecayTreeTuple\nfrom Configurables import MCTupleToolReconstructed, MCReconstructed\nfrom Configurables import BackgroundCategory\n\ndoTest = True\nif doTest:\n simulation = False\n polarity = -1\n year = \"2012\"\n\n\ndef createDTFInput(inputSel, outputCont):\n algName = 'SubPID_'+outputCont\n Sub = SubstitutePID ( algName ) #Code = \"DECTREE('[Beauty -> Charm X- ]CC')\" )\n\n Sub.Code = \"DECTREE( '[(Beauty -> D0 pi-), (Beauty -> D0 pi+)]' )\" \n Sub.MaxChi2PerDoF = -666\n Sub.Substitutions = {' Beauty -> D0 ^pi- ' : 'p~-',\n ' Beauty -> D0 ^pi+ ' : 'p+'\n }\n Sub.Inputs = [inputSel.outputLocation()]\n return Sub\n\n\n#--Scaler----------------------------------------------------------------\nfrom Configurables import TrackScaleState\nscaler = TrackScaleState( 'StateScale' )\n#------------------------------------------------------------------------\n\nkaons = DataOnDemand(Location = \"Phys/StdAllNoPIDsKaons/Particles\")\nprotons = DataOnDemand(Location = \"Phys/StdAllNoPIDsProtons/Particles\")\nlongpions = DataOnDemand(Location = \"Phys/StdAllNoPIDsPions/Particles\")\n\n#-------------------------------------------------------------------------------------------------\nlocationB = \"/Event/BhadronCompleteEvent/Phys/B2D0PiD2HHBeauty2CharmLine/Particles\"\nlocationBk = \"/Event/BhadronCompleteEvent/Phys/B2D0KD2HHBeauty2CharmLine/Particles\"\nif simulation:\n locationB = \"/Event/AllStreams/Phys/B2D0PiD2HHBeauty2CharmLine/Particles\"\nB2D0h = AutomaticData(Location = locationB)\nB2D0pi = AutomaticData(Location = locationB)\n\nmyPreAmble = [ \"Z = VFASPF(VZ)\" ,\n \"DZ1 = CHILD(Z,1)-Z\",\n \"DZ2 = CHILD(Z,2)-Z\",\n \"VCHISQDOF = VFASPF(VCHI2/VDOF)\",\n \"MIPCHI2 = MIPCHI2DV(PRIMARY)\",\n \"MIP = MIPDV(PRIMARY)\",\n \"NKaon = NINGENERATION(ABSID=='K-', 1)\",\n \"NKaonFailPID = NINTREE( ((ABSID=='K+') & (PIDK<0) ) )\",\n \"NKaonFail = CHILD(NKaonFailPID, 2)\",\n \"NPion = NINGENERATION(ABSID=='pi-', 1)\",\n \"NPionFromD0 = NINGENERATION(ABSID=='pi-', 2)\",\n \"NPim = NINGENERATION(ID=='pi-', 1)\",\n \"NPip = NINGENERATION(ID=='pi+', 1)\",\n ]\n\n# First filter the B- --> (D0 -> K+- pi-+) pi- candidates\nselCode = \"(MINTREE('K+'==ABSID,PROBNNk)>0.05)&(MINTREE('D0'==ABSID, M)>1815*MeV)&(MAXTREE('D0'==ABSID, M)<1915*MeV) & (NPionFromD0==1)\"\nselCode2 = \"(MINTREE('K+'==ABSID,PROBNNk)>0.05)&(MINTREE('pi+'==ABSID,PROBNNpi)>0.05)&(MINTREE('D0'==ABSID, M)>1815*MeV)&(MAXTREE('D0'==ABSID, M)<1915*MeV) & (NPionFromD0==1) & (M>5000*MeV) & (M<6000*MeV) & (BPVDIRA>0.9999)\"\n#selCode = \"(MINTREE('K+'==ABSID,PROBNNk)>0.05)&(MINTREE('D0'==ABSID, M)>1815*MeV)&(MAXTREE('D0'==ABSID, M)<1915*MeV)\"\n_MyX2D0piFilt = FilterDesktop('_MyX2D0piFilt', Preambulo=myPreAmble, Code=selCode )\n_MyX2DpiFilt = FilterDesktop('_MyX2D0piFilt', Preambulo=myPreAmble, Code=selCode2 )\nMyX2D0pi = Selection(\"MyX2D0pi\", Algorithm = _MyX2D0piFilt, RequiredSelections = [B2D0h] )\nMyX2D0pion = Selection(\"MyX2D0pion\", Algorithm = _MyX2D0piFilt, RequiredSelections = [B2D0pi] )\n#-------------------------------------------------------------------------------------------------\n# Now, do the mass swap on the pion --> proton\n# --------------------------------------------\noutputCont = \"MyX2D0p\"\noutputCont2 = \"MyX2D0pi\"\nsubpid = createDTFInput(MyX2D0pi,outputCont)\nparticleSwap = Selection( \"particleSwap_\"+outputCont, Algorithm = subpid, RequiredSelections=[MyX2D0pi])\n# ------------------------------------------------------------\n# Finally, make some selections on this new decay, X --> D0 p.\n# ------------------------------------------------------------\nselCode2 = \"(MINTREE('p+'==ABSID,PROBNNp)>0.1)&(M>4000*MeV)&(M<12000*MeV)\"\n_MyX2D0pFilt = FilterDesktop('_MyX2D0pFilt', Preambulo=myPreAmble, Code=selCode2 )\nMyX2D0p = Selection(\"MyX2D0p\", Algorithm = _MyX2D0pFilt, RequiredSelections = [particleSwap] )\n# ---------------------------------\n# Now, the final selection sequence\n# ----------------------------------\nSelSeqMyX2D0p = SelectionSequence('SelSeq'+outputCont, TopSelection = MyX2D0p)\nseqMyX2D0p = SelSeqMyX2D0p.sequence()\n# Control channel (B --> D0 K)\nSelSeqMyX2D0pi = SelectionSequence('SelSeq'+outputCont2, TopSelection = MyX2D0pion)\nseqMyX2D0pi = SelSeqMyX2D0pi.sequence()\n\n\n\n###########################################################################\n# Configure DaVinci\n###########################################################################\nfrom Configurables import DaVinci\nfrom Configurables import CondDB\nfrom Configurables import DecayTreeTuple, MCDecayTreeTuple\nimportOptions(\"DecayTreeTuple_Xibc.py\")\n\nfrom PhysConf.Filters import LoKi_Filters\nfltrs = LoKi_Filters (STRIP_Code = \" HLT_PASS_RE('StrippingB2D0PiD2HHBeauty2CharmLineDecision') \")\nfltrSeq = fltrs.sequence ( 'MyFilters' ) \n\nfrom Configurables import LoKi__HDRFilter as StripFilter\nif simulation == False:\n DaVinci().EventPreFilters = [fltrSeq]\n\n\ntuple0 = DecayTreeTuple( \"Xibc2D0p\" )\ntuple0.Inputs = [ SelSeqMyX2D0p.outputLocation() ]\ntuplepi = DecayTreeTuple( \"B2D0pi\" )\ntuplepi.Inputs = [ SelSeqMyX2D0pi.outputLocation() ]\nwstuple0 = DecayTreeTuple( \"wsXibc2D0p\")\nwstuple0.Inputs = [ SelSeqMyX2D0p.outputLocation() ]\n\nif simulation:\n tuple0.ToolList += [ \"TupleToolMCTruth\", \"TupleToolMCBackgroundInfo\" ]\n wstuple0.ToolList += [ \"TupleToolMCTruth\", \"TupleToolMCBackgroundInfo\" ]\n tuplepi.ToolList += [ \"TupleToolMCTruth\", \"TupleToolMCBackgroundInfo\" ]\n\n # MC Truth information - filled for ALL events\n decay = \"[Xi_bc+ => ^(D0 => ^K- ^pi+) ^p+]CC\"\n mcTuple = MCDecayTreeTuple(\"MCTupleXb2D0p\")\n mcTuple.Decay = decay\n mcTuple.ToolList = [ \"MCTupleToolKinematic\", \"MCTupleToolReconstructed\" ] \n mcTuple.UseLabXSyntax = True\n mcTuple.RevertToPositiveID = False\n\n# ---------------\n# Gaudi sequences\n# ---------------\n#MyX2D0pGauSeq = GaudiSequencer(\"MyX2D0pGauSeq\")\n#MyX2D0pGauSeq.Members += [scaler ]\n#MyX2D0pGauSeq.Members += [seqMyX2D0p ]\n#MyX2D0pGauSeq.Members += [ tuple0 ]\n\n#MywsX2D0pGauSeq = GaudiSequencer(\"MywsX2D0pGauSeq\")\n#MywsX2D0pGauSeq.Members += [scaler ]\n#MywsX2D0pGauSeq.Members += [seqMyX2D0p ]\n#MywsX2D0pGauSeq.Members += [ tuple1 ]\n\n\n\n#---------------------------------------------------------------\n\nDaVinci().UserAlgorithms = [ scaler, seqMyX2D0p, seqMyX2D0pi, tuple0, wstuple0, tuplepi]\nif simulation:\n DaVinci().appendToMainSequence( [mcTuple] )\n\n#\nDaVinci().EvtMax = -1\nDaVinci().DataType = year\nDaVinci().TupleFile = \"tuple.root\"\nDaVinci().PrintFreq = 2000\n\nfrom Configurables import CondDB\nif simulation:\n DaVinci().DDDBtag=\"Sim08-20130503-1\"\n if polarity<0: DaVinci().CondDBtag=\"Sim08-20130503-1-vc-md100\"\n if polarity>0: DaVinci().CondDBtag=\"Sim08-20130503-1-vc-mu100\"\n DaVinci().Lumi = False\n DaVinci().Simulation = True\nelse:\n CondDB( LatestGlobalTagByDataType = year )\n DaVinci().Lumi = True\n DaVinci().InputType = 'DST'\n\nif doTest:\n from GaudiConf import IOHelper\n IOHelper().inputFiles([\n '/afs/cern.ch/work/s/sblusk/00041836_00000335_1.bhadroncompleteevent.dst'\n ], clear=True)\n\n#\n\n\n\n\n","sub_path":"sblusk/GridScripts/D0h/RunXb2D0h.py","file_name":"RunXb2D0h.py","file_ext":"py","file_size_in_byte":7561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"212846321","text":"# Day_02_01_placeholder.py\r\nimport tensorflow as tf\r\n\r\n\r\ndef not_used():\r\n a = tf.placeholder(tf.int32)\r\n b = tf.placeholder(tf.int32)\r\n c = tf.constant(6)\r\n\r\n add1 = tf.add(a, b)\r\n add2 = tf.add(a, c)\r\n\r\n sess = tf.Session()\r\n sess.run(tf.global_variables_initializer())\r\n\r\n print(sess.run(add1, feed_dict={a: 3, b: 4}))\r\n print(sess.run(add1, feed_dict={a: 2, b: 3}))\r\n print(sess.run(add2, feed_dict={a: 2}))\r\n\r\n sess.close()\r\n\r\n\r\n# 문제\r\n# 구구단의 특정 단을 출력하는 함수를 만드세요.\r\n# 텐서플로우의 placeholder 사용.\r\n# multiply.\r\ndef dan99(dan):\r\n left = tf.placeholder(tf.int32)\r\n rite = tf.placeholder(tf.int32)\r\n\r\n calc = tf.multiply(left, rite)\r\n\r\n sess = tf.Session()\r\n sess.run(tf.global_variables_initializer())\r\n\r\n for i in range(1, 10):\r\n result = sess.run(calc, feed_dict={left: dan, rite: i})\r\n print('{} x {} = {}'.format(dan, i, result))\r\n # print(dan, 'x', i, '=', result)\r\n\r\n sess.close()\r\n\r\n\r\ndef dan99_adv(dan):\r\n left = tf.constant(dan)\r\n rite = tf.placeholder(tf.int32)\r\n\r\n calc = tf.multiply(left, rite)\r\n\r\n sess = tf.Session()\r\n sess.run(tf.global_variables_initializer())\r\n\r\n for i in range(1, 10):\r\n result = sess.run(calc, feed_dict={rite: i})\r\n print('{} x {} = {:2}'.format(dan, i, result))\r\n\r\n sess.close()\r\n\r\n\r\n# dan99(7)\r\ndan99_adv(7)\r\n","sub_path":"Day_02_01_placeholder.py","file_name":"Day_02_01_placeholder.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"560803188","text":"from typing import List\n\nfrom src import db\n\n\nclass TaskUtils:\n\n @staticmethod\n def just_names_and_uris(results: List[db.Model]):\n return [{\"name\": result.name, \"uri\": result.spot_uri} for result in results]\n\n @staticmethod\n def deduplicate_list_of_dicts(results: List[dict], key: str) -> List[dict]:\n done = set()\n\n def go():\n for result in results:\n if key in result and result[key] not in done:\n done.add(result[key])\n yield result\n\n return list(go())\n","sub_path":"src/tasks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"254785221","text":"__author__ = 'aum'\nfrom functools import wraps\nfrom os import listdir\nfrom os.path import exists\nfrom pprint import pprint\nfrom functools import partial\npprint = partial(pprint,indent=2, width=40)\nimport re\npat = re.compile(r\"(\\S+)|(<[^>]*>)\",flags=re.MULTILINE)\ntext= open('html_test.html','r').read()\n#print(text)\n\ndef is_opening_tag(token):\n return token.startswith(\"<\") and not token.startswith(\"</\")\n\n\ndef ver1():\n def scanner(text):\n for m in pat.finditer(text):\n token = m.group(0)\n #print(\"Feeding: %s\" % repr(token))\n yield token\n yield None # to signal EOF\n\n def parse_items(closing_tag = None):\n elems = []\n while 1:\n token = token_stream.__next__()\n if not token:\n break # EOF\n if is_opening_tag(token):\n elems.append(parse_elem(token))\n elif token == closing_tag:\n break\n else:\n elems.append(token)\n return elems\n def parse_elem(opening_tag):\n name = opening_tag[1:-1]\n closing_tag = \"</%s>\" % name\n items = parse_items(closing_tag)\n return (name, items)\n token_stream = scanner(text)\n tree = parse_items()\n return tree\n #print(tree)\n\n\ndef ver2():\n\n def parse_elem(opening_tag):\n name = opening_tag[1:-1]\n closing_tag = \"</%s>\" % name\n items = yield from parse_items(closing_tag)\n return (name, items)\n\n def parse_items(closing_tag=None):\n elems = []\n while 1:\n token = (yield)\n if not token:\n break # EOF\n if is_opening_tag(token):\n temp = yield from parse_elem(token)\n elems.append(temp)\n elif token == closing_tag:\n break\n else: elems.append(token)\n return elems\n\n def run(text):\n parser = parse_items()\n next(parser)\n try:\n for m in pat.finditer(text):\n token = m.group(0)\n #print(\"Feeding: %s\" % repr(token))\n parser.send(token)\n parser.send(None) # to signal EOF\n except StopIteration as e:\n tree = e.args[0]\n return tree\n #print(tree)\n\n return run(text)\ndef main():\n tree = ver2()\n pprint(tree)\ndef time_test(*args):\n import timeit\n for function in args:\n print(\"FUNCTION: {0:s} RESULT: {1:f}\".format(function.__name__,\n timeit.timeit(\"%s()\" % function.__name__, setup=\"from __main__ import %s\" % function.__name__,number=1000)))\n\nif __name__ == '__main__':\n #main()\n time_test(ver1,ver2)\n #ver1()\n","sub_path":"examples/black_magic/how_cooroutins_generators/yield_from_exmpl_test.py","file_name":"yield_from_exmpl_test.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"254150232","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.db.models import Q\n\nERROR_MESSAGE_SELF_FOLDER = 'Folder does not have self parent'\nERROR_MESSAGE_RECURSIVE_FOLDER = 'Folder does not have a recursive relation'\n\n\nclass FolderManager(models.Manager):\n def folders_by_user(self, user):\n folders = self.filter(\n Q(owner=user) | \\\n Q(read_only_access__pk=user.pk) | \\\n Q(root_access__pk=user.pk)\n )\n return folders\n\n\nclass Folder(models.Model):\n name = models.CharField(verbose_name=_(\"Folder name\"), max_length=\"150\")\n date_created = models.DateTimeField(auto_now=True)\n owner = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_(\"Folder owner\"), related_name=\"folder_owner\")\n\n read_only_access = models.ManyToManyField(\n settings.AUTH_USER_MODEL, verbose_name=_(\"Read only access in folder\"),\n blank=True, null=True, related_name=\"folder_users_read_only\"\n )\n\n root_access = models.ManyToManyField(\n settings.AUTH_USER_MODEL, verbose_name=_(\"Admin only access in folder\"),\n blank=True, null=True, related_name=\"folder_root_users\"\n )\n\n parent = models.ForeignKey(\n 'self', verbose_name=_('Parent folder'), blank=True, null=True, related_name=\"folder_parent\"\n )\n\n objects = models.Manager()\n folder_manager = FolderManager()\n\n def generate_full_path(self):\n path = []\n current_folder = self\n while current_folder.parent:\n path.append(current_folder.parent.name)\n current_folder = current_folder.parent\n\n return '/%s' % ('/').join(path[::-1])\n\n class Meta:\n verbose_name = _(\"Folder\")\n verbose_name_plural = _(\"Folders\")\n\n def _validate_on_recursive_relation(self):\n current_folder = self.parent\n while current_folder.parent:\n if current_folder.parent == self:\n raise ValidationError(ERROR_MESSAGE_RECURSIVE_FOLDER)\n current_folder = current_folder.parent\n\n def is_read_only_access(self, user):\n return user in self.read_only_access.all()\n\n def is_root_access(self, user):\n return user in self.root_access.all()\n\n def is_owner(self, user):\n return user == self.owner\n\n def is_read_access(self, user):\n return self.is_root_access(user) or self.is_read_only_access(user) or self.is_owner(user)\n\n def get_access_sub_folders(self, user):\n return self.folder_parent.filter(\n Q(owner=user) | \\\n Q(read_only_access__pk=user.pk) | \\\n Q(root_access__pk=user.pk)\n )\n\n def get_access_files(self, user):\n return self.file_parent_folder.filter(\n Q(owner=user) | \\\n Q(read_only_access__pk=user.pk) | \\\n Q(root_access__pk=user.pk)\n )\n\n def clean(self):\n if self == self.parent:\n raise ValidationError(ERROR_MESSAGE_SELF_FOLDER)\n self._validate_on_recursive_relation()\n\n def __unicode__(self):\n return self.name\n\n\nclass MetaFileManager(models.Manager):\n def files_by_user(self, user):\n files = self.filter(\n Q(owner=user) | \\\n Q(read_only_access__pk=user.pk) | \\\n Q(root_access__pk=user.pk)\n )\n return files\n\n\nclass MetaFile(models.Model):\n UNKNOWN = 'unknown'\n TYPE_FILES = {\n 'pdf': 'pdf file',\n 'html': 'html_file',\n 'unknown': 'unknown file'\n }\n\n name = models.CharField(verbose_name=_(\"File name\"), max_length=\"150\")\n date_created = models.DateTimeField(auto_now=True)\n size = models.IntegerField(verbose_name=_(\"File size in bytes\"))\n type = models.CharField(verbose_name=_(\"File type\"), max_length=100, blank=True, null=True)\n owner = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_(\"File owner\"), related_name=\"file_owner\")\n\n read_only_access = models.ManyToManyField(\n settings.AUTH_USER_MODEL, verbose_name=_(\"Read only access in file\"),\n blank=True, null=True, related_name=\"file_users_read_only\"\n )\n\n root_access = models.ManyToManyField(\n settings.AUTH_USER_MODEL, verbose_name=_(\"Admin only access in file\"),\n blank=True, null=True, related_name=\"file_root_users\"\n )\n\n folder = models.ForeignKey(\n Folder, verbose_name=_('File parent folder'), related_name=\"file_parent_folder\"\n )\n\n objects = models.Manager()\n file_manager = MetaFileManager()\n\n def _get_file_type(self):\n name_data = self.name.split('.')\n type_file = self.TYPE_FILES[self.UNKNOWN]\n if len(name_data) > 1 and name_data[-1] in self.TYPE_FILES:\n type_file = self.TYPE_FILES[name_data[-1]]\n return type_file\n\n def _validate_file_type(self):\n if self.type not in self.TYPE_FILES:\n return self._get_file_type()\n\n def save(self, *args, **kwargs):\n if not self.type:\n self.type = self._get_file_type()\n else:\n self.type = self._validate_file_type()\n\n super(MetaFile, self).save(*args, **kwargs)\n\n def is_read_only_access(self, user):\n return user in self.read_only_access.all()\n\n def is_root_access(self, user):\n return user in self.root_access.all()\n\n def is_owner(self, user):\n return user == self.owner\n\n def is_read_access(self, user):\n return (self.is_root_access(user) or self.is_read_only_access(user) or self.is_owner(user)) and\\\n self.folder.is_read_access(user)\n\n def generate_full_path(self):\n current_folder = self.folder\n path = [current_folder.name]\n while current_folder.parent:\n path.append(current_folder.parent.name)\n current_folder = current_folder.parent\n\n return '/%s' % ('/').join(path[::-1])\n\n def __unicode__(self):\n return self.name","sub_path":"meta_info_disk/meta_info_disk/apps/meta_disk/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"201838789","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 4 11:41:48 2018\r\n\r\n@author: Yeshu\r\n\r\nWorking dates and time in python\r\n\r\nSource: Pluralsight\r\n\r\nspeaker : gorgey pushkov\r\n\r\n\"\"\"\r\n\r\nimport time\r\n\r\nimport datetime\r\n\r\nimport calendar\r\n\r\n\"\"\"\r\nperf_counter: \r\n\"\"\"\r\n\r\n# starting the time counter :\r\n# i.e starts a time count\r\n# to measure any events time elapsed\r\n\r\ndef fun():\r\n print(\"heloo I have started the counter\")\r\n print(\"f() took\",time.perf_counter() - start)\r\nstart = time.perf_counter()\r\nfun()\r\n\r\n# getting the performance of the perf_counter \r\ntime.get_clock_info('perf_counter').resolution\r\n\r\n\r\n\"\"\"\r\ndefining a function: fun1 takes a num and returns square of it\r\n\"\"\"\r\n\r\ndef fun1(val):\r\n return val**2\r\n\"\"\"\r\ndefining another function that takes first function as parameter\r\n\"\"\"\r\ndef fun2(f):\r\n start = time.perf_counter()\r\n s = f()\r\n return time.perf_counter()- start, s\r\n# calling sencond funtino with first function with required params for the \r\n# first function\r\nfun2( lambda: fun1(5))\r\n\r\n\r\n\"\"\"\r\nmonotonic:\r\n\"\"\"\r\nstart = time.monotonic()\r\n\r\n\r\ntime.monotonic() - start\r\n\r\n\r\n\"\"\"\r\nclock\r\n\"\"\"\r\ntime.clock()\r\n\r\n\"\"\"\r\nThe time since:\r\n 01/01/1970\r\n\"\"\"\r\n# gives the number seconds from that data\r\ntime.time()\r\n\r\n\r\n# stores the number of seconds upto excecution to current_time variable\r\ncurrent_time = time.time()\r\ncurrent_time\r\n\r\n# converts the seconds to the correct detailed time format\r\ntime.ctime(current_time+60)\r\n\r\n\r\n# adding 42 days to the current variable\r\ntime.ctime(current_time + 42*24*60*60)\r\n\r\n\r\n\r\ntime.localtime()\r\ntime.struct_time(time.localtime())\r\n\r\n\"\"\"\r\ndatetime module:\r\n\"\"\"\r\n# creating a datetime object:\r\n# \r\ntemp_datetime = datetime.datetime(2019, 1,10,10,0)\r\n\r\n# getting number of days left for that day\r\n# gives a time delta object\r\ndiff = temp_datetime - datetime.datetime.now()\r\ntype(diff)\r\n\r\n#working with timedelta objects:\r\ndiff - datetime.timedelta(days = 4)\r\n\r\n\r\n\"\"\"\r\nDealing with time zones:\r\n\"\"\"\r\n\r\ndatetime.date.today()\r\n\r\ndatetime.date(1994,3,4)\r\n\r\ndatetime.date(1994, 3,4).replace(year = 2000)\r\n\r\n#limitations of the datetime date object\r\ndatetime.date.min\r\ndatetime.date.max\r\n\r\ndatetime.time()\r\n\r\ndatetime.datetime.now().date()\r\ndatetime.datetime.now().time()\r\n\r\ndatetime.datetime.min\r\ndatetime.datetime.max\r\n\r\n\r\n\"\"\"\r\nWorking with local times:\r\nUTC: Universal Coordinated time\r\n\r\nDST: Day light saving time\r\n\r\n\"\"\"\r\nimport pytz\r\n\r\nimport tzlocal\r\n\r\n\r\namsterdam = pytz.timezone(\"Europe/Amsterdam\")\r\n\r\nnaive = datetime.datetime(2018,1,1,20,25,0)\r\nprint(naive)\r\n\r\naware = amsterdam.localize(naive)\r\nprint(aware)\r\n\r\naware.tzinfo\r\n\r\n# summer time in amsterdam:\r\n\r\nnaive_summer = datetime.datetime(2018,8,1,20,25,55)\r\naware_summer = amsterdam.localize(naive_summer)\r\nprint(aware_summer)\r\n\r\n#time zone in US\r\neastern = pytz.timezone(\"US/Eastern\")\r\neastern\r\n\r\naware_eastern = eastern.localize(naive_summer)\r\nprint(aware_eastern)\r\n\r\naware_eastern == naive_summer.astimezone(eastern)\r\n\r\nlocal = pytz.timezone(\"Asia/Calcutta\")\r\naware_local = local.localize(naive_summer)\r\naware_local\r\n\r\n\r\ntzlocal.get_localzone()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Working_with_dates_time.py","file_name":"Working_with_dates_time.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"545553966","text":"dictionary = {\n 'sml' : 'sap mat lon',\n 'dcmm' : 'dong co menh mong',\n}\n\nwhile True:\n\n for key in dictionary:\n print(key, end='\\t')\n print()\n word = input(\"Your code?\")\n if word in dictionary:\n print(\"Code:\", word)\n print(\"Translation:\", dictionary[word])\n else:\n choice = input('Not found. Do you want to contribute? (Y/N)').lower()\n if choice == \"y\":\n translation = input('Enter your translation:')\n dictionary[word] = translation\n print('Updated:', word, \":\", dictionary[word])\n elif choice == \"n\":\n print('Not updated')\n exit = input(\"Exit? (Y/N)\").lower()\n if exit == \"y\":\n break\n else:\n True\n","sub_path":"Fundamentals/Fun05/class/dictionary-look-up.py","file_name":"dictionary-look-up.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"434265575","text":"# Kullanıcıdan bir input alin ve bu inputun içindeki büyük ve küçük harf sayılarını veren bir fonksiyon yazınız.\nprint(\"\"\"\"\nBuyuk ve Kucuk Harfleri Bulma Fonksiyonu\n\ncikis icin 'q' ya basin..\n\"\"\")\nimport string\n\ndef buyukKucukHarf(str):\n kucukHarfler = []\n buyukHarfler = []\n k = 0 #kucuk harf adedi\n b = 0 #buyuk harf adedi\n\n for i in str:\n if i in string.ascii_lowercase:\n #kucuk harfleri bulup listeye aktardik\n kucukHarfler.append(i)\n k+=1 #kucuk harf adedini artirdik\n elif i in string.ascii_uppercase:\n # buyuk harfleri bulup listeye aktardik\n buyukHarfler.append(i)\n b+=1 #buyuk harf adedini artirdik\n\n print('{} adet kucuk harf vardir. Kucuk harfler {}'.format(k, kucukHarfler))\n print('{} adet buyuk harf vardir. Buyuk harfler {}'.format(b, buyukHarfler))\n\ntry:\n\n while True:\n str = input('Bir string girin: ')\n buyukKucukHarf(str)\nexcept:\n print('Hatali islem. Program sonlandirildi.. ')","sub_path":"9. BuyukKucukHarf.py","file_name":"9. BuyukKucukHarf.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"491430110","text":"\"\"\"Provides all the generic data related to the personal information.\"\"\"\n\nBLOOD_GROUPS = (\n 'O+',\n 'A+',\n 'B+',\n 'AB+',\n 'O−',\n 'A−',\n 'B−',\n 'AB−',\n)\n\nMUSIC_GENRE = [\n 'Pop',\n 'Rock',\n 'Hard Rock',\n 'Rhythm & Blues (R&B)',\n 'Country',\n 'Rock & Roll',\n 'Soul',\n 'Country Pop',\n 'Pop Rock',\n 'Heavy Metal',\n 'Progressive Rock',\n 'Alternative Rock',\n 'Jazz',\n 'New Wave',\n 'Synthpop',\n 'Hip Hop',\n 'Folk',\n 'New Age',\n 'Blues Rock',\n 'Ambient',\n 'Ambient house',\n 'Classic',\n 'Neoclassic',\n 'Drum and bass',\n]\n\nGENDER_SYMBOLS = (\n '♂',\n '♀',\n '⚲',\n)\n\nSEXUALITY_SYMBOLS = (\n '⚤',\n '⚢',\n '⚣',\n '⚥',\n '⚧',\n '⚪',\n)\n\nENGLISH_LEVEL = [\n 'Beginner',\n 'Elementary',\n 'Pre - Intermediate',\n 'Intermediate',\n 'Upper Intermediate',\n 'Advanced',\n 'Proficiency',\n]\n\nUSERNAMES = [\n 'aardvark',\n 'ababa',\n 'aback',\n 'abaft',\n 'abalone',\n 'abandoned',\n 'abashed',\n 'abatis',\n 'abdel',\n 'abdominal',\n 'abele',\n 'aberrant',\n 'abhorrent',\n 'abidal',\n 'abiding',\n 'abiezer',\n 'abilities',\n 'abiogenesis',\n 'abject',\n 'ablaze',\n 'able',\n 'ablution',\n 'abnegative',\n 'abnormal',\n 'aboard',\n 'abody',\n 'abolished',\n 'abominable',\n 'aboriginal',\n 'aborter',\n 'aborticide',\n 'abortive',\n 'abounding',\n 'abrar',\n 'abrasax',\n 'abrasive',\n 'abridged',\n 'abroad',\n 'abrupt',\n 'abrus',\n 'abscess',\n 'absconsa',\n 'absent',\n 'absit',\n 'absolute',\n 'absorbed',\n 'absorbing',\n 'abstain',\n 'abstinent',\n 'abstracted',\n 'absurd',\n 'abucco',\n 'abundant',\n 'abundantia',\n 'abusers',\n 'abusive',\n 'abyssinian',\n 'acana',\n 'acanthurus',\n 'acceptable',\n 'accessible',\n 'accidental',\n 'accidia',\n 'acclimatise',\n 'accurate',\n 'aceology',\n 'acephalous',\n 'acers',\n 'achaean',\n 'achamma',\n 'achates',\n 'achira',\n 'achmetha',\n 'achromic',\n 'acid',\n 'acidic',\n 'aciduria',\n 'acinar',\n 'ackey',\n 'acoustic',\n 'acree',\n 'acrid',\n 'acrite',\n 'acrook',\n 'acryl',\n 'actinon',\n 'actually',\n 'acuate',\n 'acubens',\n 'acute',\n 'ad',\n 'adamant',\n 'adamczyk',\n 'adansonia',\n 'adapa',\n 'adaptable',\n 'adaptive',\n 'adcox',\n 'addendum',\n 'adders',\n 'addicted',\n 'addiction',\n 'addressee',\n 'adebayo',\n 'adena',\n 'adenitis',\n 'adermia',\n 'adhesive',\n 'adiana',\n 'adine',\n 'adirondack',\n 'adjoining',\n 'adjuster',\n 'adman',\n 'administrate',\n 'admissible',\n 'admissions',\n 'admonisher',\n 'adolph',\n 'adolphe',\n 'adorable',\n 'adoree',\n 'adorer',\n 'adown',\n 'adriaan',\n 'adriena',\n 'adriene',\n 'adventure',\n 'adventurer',\n 'adventuring',\n 'adventurous',\n 'adverted',\n 'advertised',\n 'advocate',\n 'aeonian',\n 'aerobatic',\n 'aesthetic',\n 'affenpinscher',\n 'affiliate',\n 'affluent',\n 'afloat',\n 'afraid',\n 'afret',\n 'african',\n 'afterfuture',\n 'afterglow',\n 'afterimage',\n 'afterlife',\n 'afternight',\n 'against',\n 'agalloch',\n 'agamic',\n 'agathodaemon',\n 'agaty',\n 'agdistis',\n 'agent',\n 'aggies',\n 'aggregat',\n 'aggressive',\n 'agitprop',\n 'agnail',\n 'agnar',\n 'agnatha',\n 'agnomen',\n 'agnosia',\n 'agonal',\n 'agonizing',\n 'agosto',\n 'agreeable',\n 'ahead',\n 'aiding',\n 'aiglet',\n 'ailing',\n 'aindrea',\n 'airflow',\n 'airish',\n 'airlock',\n 'airplay',\n 'airtight',\n 'aisling',\n 'aissaoua',\n 'aitch',\n 'aiwan',\n 'ajar',\n 'akbash',\n 'akinesia',\n 'akita',\n 'akkadian',\n 'alair',\n 'alaite',\n 'alanine',\n 'alans',\n 'alanson',\n 'alaric',\n 'albata',\n 'albatross',\n 'albian',\n 'alcalde',\n 'alcheringa',\n 'alcindor',\n 'alcoa',\n 'alcoholic',\n 'alcove',\n 'alcyone',\n 'aldols',\n 'aldus',\n 'alegre',\n 'alene',\n 'alert',\n 'alessand',\n 'alexandrite',\n 'alexas',\n 'alexis',\n 'alfred',\n 'algal',\n 'algedi',\n 'alger',\n 'algerine',\n 'algonquin',\n 'algorithms',\n 'alidia',\n 'alien',\n 'aliens',\n 'aligner',\n 'alike',\n 'alist',\n 'alister',\n 'alive',\n 'aliyah',\n 'alkalurops',\n 'alkyds',\n 'allan',\n 'allard',\n 'allay',\n 'alleged',\n 'allegiances',\n 'allegri',\n 'alleluia',\n 'allen',\n 'allergy',\n 'alleyway',\n 'allgood',\n 'allida',\n 'alligator',\n 'alligators',\n 'alliya',\n 'allowance',\n 'allstate',\n 'allthing',\n 'alluring',\n 'alluvium',\n 'almadia',\n 'aloed',\n 'alogism',\n 'aloof',\n 'alpaca',\n 'alsaleh',\n 'alshain',\n 'alten',\n 'alterant',\n 'alterman',\n 'altin',\n 'altiplano',\n 'altitudes',\n 'altruistic',\n 'aluminosis',\n 'alumnal',\n 'aluta',\n 'alvarez',\n 'alvaro',\n 'alveolate',\n 'alvera',\n 'alvine',\n 'alway',\n 'alyda',\n 'alyre',\n 'amalgamation',\n 'amalie',\n 'amarelle',\n 'amaryllis',\n 'amazing',\n 'amazons',\n 'ambarella',\n 'amber',\n 'amberoid',\n 'amberous',\n 'ambiguous',\n 'ambition',\n 'ambitions',\n 'ambitious',\n 'ambivalent',\n 'ambivert',\n 'ambsace',\n 'ambush',\n 'ameed',\n 'amelina',\n 'ameliorators',\n 'amgad',\n 'amick',\n 'amines',\n 'ammar',\n 'ammeter',\n 'amnesia',\n 'amontillado',\n 'amorim',\n 'amorist',\n 'amorphia',\n 'amour',\n 'amperage',\n 'amphibia',\n 'amphibological',\n 'amphigory',\n 'amril',\n 'amstutz',\n 'amuck',\n 'amused',\n 'amusing',\n 'amylan',\n 'anabasis',\n 'anabel',\n 'anaconda',\n 'anaesthetic',\n 'analogue',\n 'analyst',\n 'analytic',\n 'anamorphose',\n 'ananda',\n 'anaryan',\n 'anasa',\n 'anasazi',\n 'anastasia',\n 'anastasis',\n 'anatolic',\n 'ancestry',\n 'anchors',\n 'ancient',\n 'ancon',\n 'andalusite',\n 'ander',\n 'andira',\n 'andrease',\n 'anemone',\n 'anemony',\n 'anent',\n 'anesthetize',\n 'angara',\n 'angelate',\n 'angeleyes',\n 'angelfish',\n 'angelika',\n 'angelo',\n 'anglesmith',\n 'angostura',\n 'angry',\n 'anhedonia',\n 'animated',\n 'animations',\n 'anime',\n 'anisotropic',\n 'anita',\n 'ann-marie',\n 'annale',\n 'annalisa',\n 'annamaria',\n 'annelid',\n 'annemari',\n 'annie',\n 'annihilates',\n 'annoyed',\n 'annoyer',\n 'annoying',\n 'annum',\n 'anoop',\n 'anoraks',\n 'another',\n 'anstett',\n 'answers',\n 'ant',\n 'antdom',\n 'anteal',\n 'anteater',\n 'antebellum',\n 'antelope',\n 'anterograde',\n 'anthema',\n 'anthems',\n 'anthonin',\n 'anthonis',\n 'anthrol',\n 'anthropos',\n 'anthuriums',\n 'antibiotic',\n 'antical',\n 'antically',\n 'anticyclone',\n 'antifowl',\n 'antinome',\n 'antinormal',\n 'antipart',\n 'antipodes',\n 'antiprime',\n 'antisun',\n 'antivenom',\n 'antivirus',\n 'antonin',\n 'antonym',\n 'antre',\n 'antsy',\n 'antuan',\n 'anukit',\n 'anvil',\n 'anxious',\n 'anything',\n 'apaches',\n 'apama',\n 'apartness',\n 'apathetic',\n 'apatosaurus',\n 'ape',\n 'aperies',\n 'aphelandra',\n 'aphotic',\n 'apina',\n 'aplomb',\n 'aplysia',\n 'apoda',\n 'apogon',\n 'apolline',\n 'apologies',\n 'aporia',\n 'apostrophe',\n 'apparition',\n 'appetence',\n 'appetite',\n 'appleblossom',\n 'applejack',\n 'apples',\n 'appleton',\n 'application',\n 'appointment',\n 'appraisal',\n 'approachable',\n 'april',\n 'apron',\n 'apropos',\n 'aptitude',\n 'apurba',\n 'aquatic',\n 'aqueduct',\n 'arachnida',\n 'arachnoid',\n 'araks',\n 'arana',\n 'araneid',\n 'arbacia',\n 'arbel',\n 'arcane',\n 'archeus',\n 'archfiend',\n 'archimedes',\n 'architectural',\n 'architeuthis',\n 'arcturia',\n 'arcus',\n 'ardea',\n 'ardelia',\n 'ardith',\n 'ardys',\n 'areito',\n 'areopagite',\n 'arethusa',\n 'argento',\n 'arghan',\n 'argiope',\n 'argonaut',\n 'argument',\n 'argus',\n 'arias',\n 'arienzo',\n 'arisen',\n 'arleng',\n 'arles',\n 'arley',\n 'arlin',\n 'arlyn',\n 'armadillo',\n 'armado',\n 'armando',\n 'armenoid',\n 'arming',\n 'armour',\n 'armourer',\n 'arney',\n 'arnis',\n 'arnone',\n 'arock',\n 'aromatic',\n 'arora',\n 'arpen',\n 'arpita',\n 'arracacha',\n 'arranger',\n 'arras',\n 'arrays',\n 'arrhythmia',\n 'arriba',\n 'arrogant',\n 'arrowy',\n 'arsenium',\n 'arses',\n 'artaba',\n 'artemis',\n 'arterial',\n 'arteries',\n 'artery',\n 'arthritis',\n 'article',\n 'articulate',\n 'artiller',\n 'artiste',\n 'artur',\n 'arundo',\n 'arvin',\n 'arzun',\n 'asbest',\n 'asbestosis',\n 'ascanius',\n 'ascension',\n 'ashamed',\n 'ashcake',\n 'ashlar',\n 'ashleigh',\n 'ashlie',\n 'ashlin',\n 'ashore',\n 'ashpan',\n 'ashton',\n 'asians',\n 'asleep',\n 'asmear',\n 'asoka',\n 'asouth',\n 'aspersion',\n 'aspic',\n 'aspidium',\n 'aspire',\n 'aspiring',\n 'ass',\n 'assailants',\n 'assault',\n 'assimilate',\n 'assistant',\n 'assorted',\n 'assuming',\n 'asters',\n 'astomia',\n 'astonisher',\n 'astonishing',\n 'astor',\n 'astoria',\n 'astral',\n 'astrolabe',\n 'astronautic',\n 'astrophil',\n 'aswan',\n 'atavistic',\n 'atavus',\n 'ateles',\n 'athelia',\n 'athene',\n 'athenor',\n 'athletics',\n 'atique',\n 'atlanta',\n 'atlantis',\n 'atlas',\n 'atman',\n 'atmospheric',\n 'atoning',\n 'atopy',\n 'atpco',\n 'attractive',\n 'attrition',\n 'attune',\n 'atune',\n 'atwood',\n 'auberge',\n 'aubert',\n 'aucan',\n 'audette',\n 'auditoria',\n 'audrie',\n 'augeri',\n 'augurs',\n 'aural',\n 'aurevoir',\n 'auric',\n 'auricularia',\n 'aurite',\n 'auroras',\n 'aurore',\n 'auspicious',\n 'australi',\n 'autocall',\n 'autogiro',\n 'automatic',\n 'available',\n 'avalanche',\n 'avantgarde',\n 'avenger',\n 'avenue',\n 'average',\n 'averardo',\n 'avernal',\n 'avestan',\n 'avgas',\n 'aviation',\n 'avigdor',\n 'avocet',\n 'avouch',\n 'avuncular',\n 'awake',\n 'awaken',\n 'award',\n 'aware',\n 'awatch',\n 'awave',\n 'awesome',\n 'awest',\n 'awful',\n 'awide',\n 'awoken',\n 'axenic',\n 'axiomatic',\n 'axled',\n 'axolotl',\n 'aymara',\n 'ayoup',\n 'ayukawa',\n 'aywie',\n 'azhar',\n 'azido',\n 'azine',\n 'azoic',\n 'aztecs',\n 'azuma',\n 'baalath',\n 'babak',\n 'babbage',\n 'baboon',\n 'baboonery',\n 'babuina',\n 'babyface',\n 'baccalaureate',\n 'bachelor',\n 'backcross',\n 'backdoor',\n 'backers',\n 'backgammon',\n 'backpacker',\n 'backspace',\n 'bactrian',\n 'badge',\n 'badger',\n 'badly',\n 'badminton',\n 'bagdad',\n 'bagels',\n 'bagging',\n 'baggy',\n 'baghdadi',\n 'bagpipes',\n 'bahama',\n 'bahamian',\n 'baited',\n 'bajau',\n 'bajury',\n 'bakers',\n 'baklavas',\n 'baktun',\n 'balaban',\n 'balas',\n 'balatron',\n 'balboa',\n 'balcom',\n 'balcony',\n 'baldest',\n 'baldric',\n 'balinese',\n 'ballate',\n 'ballistae',\n 'ballroom',\n 'ballsy',\n 'balmoral',\n 'balmy',\n 'balser',\n 'balthasar',\n 'balunda',\n 'bambie',\n 'banaba',\n 'banat',\n 'banda',\n 'bande',\n 'bandicoot',\n 'bandits',\n 'bandmaster',\n 'banes',\n 'banish',\n 'banky',\n 'bannet',\n 'banshie',\n 'bantay',\n 'banya',\n 'baptist',\n 'barb',\n 'barbara',\n 'barbi',\n 'barclay',\n 'bardolph',\n 'bardsley',\n 'bares',\n 'bargeman',\n 'barit',\n 'barite',\n 'barkery',\n 'barkier',\n 'barmecide',\n 'barnacle',\n 'barnstormer',\n 'barong',\n 'barracuda',\n 'barrels',\n 'barriere',\n 'barse',\n 'bartizan',\n 'basco',\n 'basenji',\n 'bashed',\n 'basile',\n 'basin',\n 'basis',\n 'basker',\n 'baskin',\n 'basset',\n 'bastille',\n 'bastion',\n 'bastioned',\n 'bat',\n 'batara',\n 'batch',\n 'bateau',\n 'bateman',\n 'bathe',\n 'bathed',\n 'batiks',\n 'batis',\n 'baton',\n 'batster',\n 'batten',\n 'battlegrounds',\n 'battlers',\n 'battles',\n 'battling',\n 'batule',\n 'batwa',\n 'bauch',\n 'bayard',\n 'bayesian',\n 'bazooka',\n 'beachman',\n 'beachwear',\n 'beagle',\n 'bealle',\n 'bear',\n 'beasts',\n 'beate',\n 'beatitude',\n 'beatitudes',\n 'beaucoup',\n 'beaulieu',\n 'beaux',\n 'beaver',\n 'beaverish',\n 'becca',\n 'beccafico',\n 'bechern',\n 'becke',\n 'beckoning',\n 'become',\n 'bedding',\n 'bedlamite',\n 'bedroom',\n 'bedrooms',\n 'bedtime',\n 'bee',\n 'beebe',\n 'beechy',\n 'beefsteak',\n 'beelol',\n 'beethovenian',\n 'beetle',\n 'befouled',\n 'begley',\n 'behalf',\n 'behaviour',\n 'behead',\n 'beland',\n 'belanda',\n 'belar',\n 'belay',\n 'belee',\n 'belich',\n 'belie',\n 'believe',\n 'believer',\n 'belight',\n 'belion',\n 'belissa',\n 'bellboy',\n 'bellhop',\n 'bellmaker',\n 'bellman',\n 'bellwood',\n 'bemar',\n 'bemis',\n 'bemole',\n 'bemoon',\n 'benares',\n 'bench',\n 'bender',\n 'benight',\n 'benjamite',\n 'benjie',\n 'benni',\n 'benthic',\n 'benthos',\n 'benton',\n 'benward',\n 'benzein',\n 'benzie',\n 'beograd',\n 'beppie',\n 'berberine',\n 'berenices',\n 'beresfor',\n 'berkelium',\n 'berkowitz',\n 'berlitz',\n 'bernadette',\n 'bernadin',\n 'bernelle',\n 'bernice',\n 'berri',\n 'berthe',\n 'beshir',\n 'beswick',\n 'betaking',\n 'bethel',\n 'bethlehem',\n 'beverlee',\n 'beverly',\n 'bevin',\n 'bevvy',\n 'bewitch',\n 'bewitching',\n 'beylic',\n 'bezzo',\n 'bhutia',\n 'biabo',\n 'bianka',\n 'bibliomane',\n 'bickford',\n 'biddie',\n 'bider',\n 'biedermeier',\n 'bifront',\n 'biggers',\n 'bigha',\n 'bigman',\n 'bigots',\n 'bigwig',\n 'bihai',\n 'bijan',\n 'bijou',\n 'biker',\n 'bilayer',\n 'bilbo',\n 'bilio',\n 'billable',\n 'billiards',\n 'billows',\n 'billowy',\n 'binda',\n 'binette',\n 'binghi',\n 'binits',\n 'binman',\n 'binturong',\n 'biochemical',\n 'biogen',\n 'biologists',\n 'biomagnetic',\n 'biomechanics',\n 'biosynthesis',\n 'biotech',\n 'biotechnological',\n 'biplab',\n 'bird',\n 'birdmen',\n 'birdseed',\n 'birendra',\n 'birken',\n 'birman',\n 'birretta',\n 'birthing',\n 'birthmark',\n 'bison',\n 'biteme',\n 'bitter',\n 'bitterness',\n 'bitton',\n 'bitumen',\n 'biune',\n 'bizen',\n 'bizonia',\n 'blabber',\n 'blackbelly',\n 'blackberry',\n 'blackbirds',\n 'blackest',\n 'blackfeet',\n 'blackings',\n 'blackleg',\n 'blackman',\n 'blackroot',\n 'blackseed',\n 'blacktongue',\n 'blacky',\n 'blais',\n 'blame',\n 'blanca',\n 'blanch',\n 'blasphemy',\n 'blasted',\n 'blaze',\n 'blazed',\n 'blazers',\n 'blazon',\n 'bleach',\n 'bleaching',\n 'bleeker',\n 'blending',\n 'blent',\n 'blindeyes',\n 'blinkered',\n 'blissfully',\n 'blisters',\n 'blizz',\n 'bloch',\n 'blockader',\n 'bloodhound',\n 'bloodless',\n 'bloodletting',\n 'bloodshedder',\n 'bloodsports',\n 'bloodstains',\n 'blotto',\n 'blowing',\n 'blows',\n 'blowy',\n 'blubber',\n 'blueberries',\n 'bluebill',\n 'bluecollar',\n 'bluefish',\n 'bluely',\n 'bluestocking',\n 'bluestones',\n 'boar',\n 'boarding',\n 'boards',\n 'boars',\n 'boaster',\n 'boats',\n 'bobadil',\n 'bobbee',\n 'bobber',\n 'bobbery',\n 'bobby',\n 'bobbye',\n 'bobcat',\n 'bobotie',\n 'bobwhite',\n 'bocoy',\n 'boden',\n 'bodhi',\n 'bodier',\n 'bogard',\n 'bogert',\n 'bohdan',\n 'boiko',\n 'boilerman',\n 'boing',\n 'boisset',\n 'bolas',\n 'boldface',\n 'bolete',\n 'bolio',\n 'bolshevik',\n 'bombay',\n 'bombsight',\n 'bombyx',\n 'bommer',\n 'bonanzas',\n 'bondon',\n 'bonehead',\n 'boneless',\n 'bongo',\n 'bongos',\n 'bonita',\n 'bonobo',\n 'boobies',\n 'booby',\n 'boodie',\n 'boohoo',\n 'booking',\n 'bookmaker',\n 'bookworm',\n 'boons',\n 'boose',\n 'boosters',\n 'boother',\n 'bopeep',\n 'borak',\n 'boran',\n 'borane',\n 'borderless',\n 'boreades',\n 'borgh',\n 'bornagain',\n 'borneo',\n 'boroughs',\n 'borrelli',\n 'borsht',\n 'boser',\n 'bosom',\n 'bosomy',\n 'bossa',\n 'bosset',\n 'bossman',\n 'bottlefeed',\n 'bottleman',\n 'bouche',\n 'boudreau',\n 'bouncy',\n 'bounder',\n 'bourcier',\n 'bourgeois',\n 'bourguig',\n 'bourlet',\n 'bouse',\n 'boutade',\n 'bouto',\n 'bouzouki',\n 'bovid',\n 'bowers',\n 'bowwow',\n 'bowyer',\n 'boyar',\n 'boyscout',\n 'brach',\n 'brachial',\n 'brack',\n 'brackets',\n 'braddock',\n 'bradley',\n 'braggers',\n 'brahms',\n 'brainwasher',\n 'brainwork',\n 'bramble',\n 'brambles',\n 'branch',\n 'brancher',\n 'brandice',\n 'brandie',\n 'brann',\n 'brassard',\n 'braunschweiger',\n 'breaded',\n 'breaker',\n 'breakless',\n 'breakthrough',\n 'breakup',\n 'breakwater',\n 'breaster',\n 'breaststroker',\n 'breathless',\n 'breeds',\n 'breena',\n 'breezing',\n 'brekel',\n 'brennand',\n 'breton',\n 'brevier',\n 'briar',\n 'bribe',\n 'bridal',\n 'bridgeman',\n 'bridges',\n 'briel',\n 'brierley',\n 'brigandine',\n 'brightly',\n 'brimborion',\n 'brimful',\n 'brims',\n 'briolette',\n 'british',\n 'britt',\n 'broadway',\n 'brocade',\n 'broccoli',\n 'broch',\n 'brockie',\n 'brockman',\n 'broddy',\n 'brody',\n 'brogan',\n 'brogues',\n 'broking',\n 'bromes',\n 'bronco',\n 'bronk',\n 'bronny',\n 'bronze',\n 'broody',\n 'brooklyn',\n 'broom',\n 'broomer',\n 'brose',\n 'brownlee',\n 'browsers',\n 'bruise',\n 'brushwood',\n 'brushy',\n 'brusque',\n 'brutter',\n 'brydges',\n 'brynn',\n 'bryophyte',\n 'bubak',\n 'bubales',\n 'buccan',\n 'buccina',\n 'bucketman',\n 'buckeye',\n 'buckhorn',\n 'buckling',\n 'buckman',\n 'buddie',\n 'budding',\n 'buder',\n 'budgerigar',\n 'buffalo',\n 'bufonidae',\n 'bugbear',\n 'buggyman',\n 'bugler',\n 'built',\n 'bulanda',\n 'bulbous',\n 'bulgaria',\n 'bulimia',\n 'bulldog',\n 'bullen',\n 'bullfrog',\n 'bullhorn',\n 'bullocks',\n 'bumfs',\n 'bumpier',\n 'bumpy',\n 'bunchberry',\n 'bunni',\n 'burek',\n 'burel',\n 'burger',\n 'burgesses',\n 'burgle',\n 'burial',\n 'burian',\n 'burin',\n 'burker',\n 'burkey',\n 'burley',\n 'burlie',\n 'burmese',\n 'burps',\n 'burrower',\n 'burrus',\n 'burry',\n 'busby',\n 'busch',\n 'business',\n 'businesswoman',\n 'busybody',\n 'butcheress',\n 'butta',\n 'buttered',\n 'butterfish',\n 'butterfly',\n 'butting',\n 'buxom',\n 'buyable',\n 'bygones',\n 'byran',\n 'byroad',\n 'byron',\n 'bystreet',\n 'caatinga',\n 'cabala',\n 'cabalist',\n 'caballer',\n 'caballero',\n 'caban',\n 'cabasset',\n 'cabinda',\n 'cablet',\n 'caboodle',\n 'cabral',\n 'cabrio',\n 'cacara',\n 'cachet',\n 'cadaveric',\n 'caddle',\n 'cadmium',\n 'caelum',\n 'caffeina',\n 'cagatay',\n 'caggy',\n 'caiman',\n 'cajaput',\n 'caking',\n 'calabrese',\n 'calamine',\n 'calamite',\n 'calcar',\n 'calcine',\n 'calculous',\n 'calcutta',\n 'calefacient',\n 'calinda',\n 'calista',\n 'callery',\n 'calumny',\n 'calvary',\n 'camacho',\n 'camber',\n 'cambeva',\n 'cambre',\n 'cambrian',\n 'cambridge',\n 'camden',\n 'camel',\n 'camelus',\n 'cameo',\n 'camion',\n 'campbell',\n 'camper',\n 'campo',\n 'camused',\n 'canadian',\n 'canamo',\n 'canberra',\n 'candida',\n 'cangle',\n 'canille',\n 'cannibal',\n 'cannibals',\n 'cannikin',\n 'canopus',\n 'canossa',\n 'cantabile',\n 'cantalas',\n 'cantaloupes',\n 'cantharis',\n 'canto',\n 'cantoral',\n 'canuck',\n 'canyon',\n 'capabler',\n 'capelet',\n 'capelin',\n 'capistrano',\n 'capitalism',\n 'capitation',\n 'caplin',\n 'capozzi',\n 'caprice',\n 'capricornus',\n 'capriole',\n 'capturer',\n 'capuche',\n 'capybara',\n 'caracal',\n 'carambole',\n 'carapo',\n 'carapus',\n 'carayan',\n 'carbonite',\n 'carburant',\n 'carcass',\n 'cardamom',\n 'cardia',\n 'cardiff',\n 'carding',\n 'career',\n 'caregiver',\n 'carella',\n 'carful',\n 'caribou',\n 'caridean',\n 'carinal',\n 'carine',\n 'carita',\n 'carlean',\n 'carlene',\n 'carless',\n 'carlet',\n 'carlett',\n 'carlock',\n 'carlyle',\n 'carmelite',\n 'carmencita',\n 'carmina',\n 'carnations',\n 'carnell',\n 'carnivore',\n 'caroli',\n 'carolus',\n 'caron',\n 'carotid',\n 'carpetbag',\n 'carpool',\n 'carrefour',\n 'carrizo',\n 'carted',\n 'cartesian',\n 'carving',\n 'casas',\n 'cascarilla',\n 'casco',\n 'caseloads',\n 'casey',\n 'cashana',\n 'cashbox',\n 'caslon',\n 'cassady',\n 'cassandra',\n 'cassat',\n 'cassolette',\n 'cassondra',\n 'cassowary',\n 'castaways',\n 'castell',\n 'castilian',\n 'castiron',\n 'castles',\n 'castling',\n 'casualist',\n 'cat',\n 'catacombs',\n 'catamenia',\n 'catbird',\n 'catchpole',\n 'caterina',\n 'caterpillar',\n 'caterpillars',\n 'catfight',\n 'catfish',\n 'catgut',\n 'cathedrals',\n 'catherina',\n 'cathole',\n 'catie',\n 'cation',\n 'cattle',\n 'cauchy',\n 'cauliflower',\n 'causes',\n 'cautions',\n 'cautivo',\n 'cavalero',\n 'cavatina',\n 'cavish',\n 'caxton',\n 'cayapa',\n 'cayuga',\n 'ceara',\n 'cebil',\n 'cebus',\n 'cecon',\n 'cedric',\n 'ceibo',\n 'celadon',\n 'celarent',\n 'celature',\n 'celebrations',\n 'celebrity',\n 'celesta',\n 'cellmate',\n 'celloid',\n 'cellule',\n 'celsius',\n 'celtish',\n 'cembalo',\n 'cementation',\n 'cenozoic',\n 'cense',\n 'censored',\n 'centenary',\n 'centered',\n 'centipede',\n 'centrefolds',\n 'centric',\n 'centrist',\n 'centuple',\n 'cephalotripsy',\n 'ceramics',\n 'ceratium',\n 'cercocebus',\n 'ceremonies',\n 'ceriel',\n 'cerite',\n 'cerulean',\n 'ceruleum',\n 'ceruse',\n 'cessna',\n 'chafe',\n 'chaja',\n 'chaka',\n 'chakras',\n 'chalon',\n 'chalot',\n 'chalton',\n 'chalumeau',\n 'chamade',\n 'chameleon',\n 'chameleons',\n 'chamois',\n 'champ',\n 'champing',\n 'chancery',\n 'chances',\n 'chandan',\n 'chander',\n 'chandra',\n 'chanson',\n 'chanteuse',\n 'chaotic',\n 'chape',\n 'chaperno',\n 'chaperone',\n 'chapfallen',\n 'chaplin',\n 'chappy',\n 'charging',\n 'charil',\n 'charlene',\n 'charline',\n 'charlotte',\n 'charmian',\n 'charmless',\n 'charta',\n 'chasing',\n 'chatelaine',\n 'chaudhry',\n 'chaudry',\n 'chauffeur',\n 'chaute',\n 'chavender',\n 'chaya',\n 'cheapest',\n 'chechen',\n 'cheeking',\n 'cheering',\n 'cheetah',\n 'cheetham',\n 'chegre',\n 'chela',\n 'chelone',\n 'chemistry',\n 'chemoreceptor',\n 'chenault',\n 'cheng',\n 'chengwei',\n 'cheques',\n 'cherimoya',\n 'cherish',\n 'cherished',\n 'cherly',\n 'cherlyn',\n 'cherokee',\n 'cherries',\n 'cheryl',\n 'chetan',\n 'chewer',\n 'chiasma',\n 'chichi',\n 'chicken',\n 'chicomecoatl',\n 'chiefs',\n 'chieftain',\n 'chien',\n 'chigger',\n 'chignon',\n 'chihuahua',\n 'childe',\n 'childhood',\n 'chilicote',\n 'chimalapa',\n 'chimbley',\n 'chimpanzee',\n 'chinamen',\n 'chinchilla',\n 'chine',\n 'chinho',\n 'chinook',\n 'chinotti',\n 'chipchap',\n 'chipmunk',\n 'chipped',\n 'chiquito',\n 'chiropractor',\n 'chiseler',\n 'chisolm',\n 'chital',\n 'chitter',\n 'chivalric',\n 'chivalrous',\n 'chocolatey',\n 'choctaw',\n 'choices',\n 'choler',\n 'choluteca',\n 'choosey',\n 'chops',\n 'chorai',\n 'chordate',\n 'chores',\n 'chotts',\n 'chough',\n 'chouser',\n 'chrisman',\n 'chrismary',\n 'christea',\n 'christel',\n 'christia',\n 'christianson',\n 'christl',\n 'christoffel',\n 'chromo',\n 'chrysant',\n 'chrysanthemum',\n 'chrysops',\n 'chrystal',\n 'chukchi',\n 'chump',\n 'chumps',\n 'chunkiest',\n 'chunmei',\n 'churchill',\n 'churinga',\n 'churn',\n 'cicatrix',\n 'cichlid',\n 'cigua',\n 'cilice',\n 'cimex',\n 'cinderel',\n 'cineraria',\n 'cingulate',\n 'cinque',\n 'cinter',\n 'circadian',\n 'circle',\n 'circulate',\n 'ciscos',\n 'cithara',\n 'citral',\n 'citrons',\n 'civies',\n 'civility',\n 'claimed',\n 'claimer',\n 'clairvoyants',\n 'clam',\n 'clamber',\n 'clamorous',\n 'clandestine',\n 'clarance',\n 'clarified',\n 'clarin',\n 'clarita',\n 'clason',\n 'classical',\n 'clatty',\n 'claudius',\n 'claustrum',\n 'claval',\n 'claws',\n 'cleancut',\n 'cleanup',\n 'clemens',\n 'clepsydra',\n 'clerks',\n 'clethra',\n 'clevie',\n 'clients',\n 'cliffs',\n 'clifton',\n 'climbed',\n 'climber',\n 'clinic',\n 'clink',\n 'clipper',\n 'clitia',\n 'clockhouse',\n 'clocks',\n 'clockwise',\n 'cloherty',\n 'clone',\n 'clonus',\n 'close',\n 'clote',\n 'cloudage',\n 'clubs',\n 'coagulate',\n 'coaly',\n 'coarse',\n 'coast',\n 'coater',\n 'coati',\n 'coatimundi',\n 'cobble',\n 'cobblers',\n 'cobbra',\n 'cobol',\n 'cobra',\n 'cobwebs',\n 'cocain',\n 'cocaine',\n 'cochin',\n 'cocker',\n 'cockeyed',\n 'cocking',\n 'cockroach',\n 'cocoa',\n 'cocooned',\n 'cod',\n 'codebreaker',\n 'codfish',\n 'codicil',\n 'coerced',\n 'coeval',\n 'coffeehouse',\n 'coffin',\n 'coffinmaker',\n 'coghlan',\n 'cogitate',\n 'cohabitants',\n 'cohesion',\n 'coils',\n 'cointer',\n 'colder',\n 'coldish',\n 'colene',\n 'coleridge',\n 'coleslaw',\n 'colias',\n 'colicky',\n 'collard',\n 'colleague',\n 'collegium',\n 'collie',\n 'collisions',\n 'colloid',\n 'cologs',\n 'colon',\n 'colorant',\n 'colorate',\n 'colorize',\n 'colourblind',\n 'colston',\n 'colts',\n 'columbic',\n 'comart',\n 'comate',\n 'combaz',\n 'combinator',\n 'combo',\n 'comfit',\n 'comfort',\n 'comfortable',\n 'comix',\n 'comma',\n 'commanded',\n 'commander',\n 'commanding',\n 'compatriot',\n 'complement',\n 'completer',\n 'completing',\n 'complex',\n 'compliant',\n 'complier',\n 'compose',\n 'compress',\n 'compulsed',\n 'computer',\n 'computerise',\n 'concentrate',\n 'concentric',\n 'concrete',\n 'concussion',\n 'condom',\n 'conestoga',\n 'confab',\n 'confection',\n 'confederacy',\n 'confers',\n 'confessions',\n 'conform',\n 'confucius',\n 'confused',\n 'conger',\n 'congregate',\n 'conjure',\n 'connelly',\n 'connexions',\n 'conniption',\n 'conquered',\n 'conscience',\n 'consciences',\n 'consciousness',\n 'conservative',\n 'consolable',\n 'console',\n 'consolidated',\n 'consonance',\n 'constanta',\n 'constitutions',\n 'constructor',\n 'consultant',\n 'contemplative',\n 'contemptible',\n 'contemptuous',\n 'content',\n 'continuum',\n 'contradiction',\n 'contrary',\n 'contribution',\n 'controllers',\n 'convair',\n 'convected',\n 'converse',\n 'converses',\n 'convict',\n 'convolvulus',\n 'coogan',\n 'cookeys',\n 'coolest',\n 'cooling',\n 'cooper',\n 'copious',\n 'copperfield',\n 'copyist',\n 'coquelicot',\n 'coquet',\n 'coquitlam',\n 'corabelle',\n 'coral',\n 'coranto',\n 'corban',\n 'corbett',\n 'cordilleran',\n 'cordy',\n 'coregonus',\n 'corena',\n 'corie',\n 'corina',\n 'corker',\n 'corkey',\n 'cormac',\n 'cormorant',\n 'cornea',\n 'corners',\n 'cornflake',\n 'cornice',\n 'cornishman',\n 'cornual',\n 'coronet',\n 'corporates',\n 'corporeal',\n 'correal',\n 'correct',\n 'correy',\n 'corrigan',\n 'corruption',\n 'corsair',\n 'cortina',\n 'corvettes',\n 'corvo',\n 'corydon',\n 'cosimo',\n 'cosine',\n 'cosmetic',\n 'cosmorama',\n 'costard',\n 'costarred',\n 'costed',\n 'costello',\n 'costs',\n 'costumes',\n 'costuming',\n 'cotte',\n 'cottonmouth',\n 'cottontail',\n 'cotys',\n 'couchy',\n 'cougar',\n 'couma',\n 'coumara',\n 'countersink',\n 'countess',\n 'countor',\n 'counts',\n 'couplet',\n 'cousins',\n 'coved',\n 'cow',\n 'coward',\n 'cowhand',\n 'cowkeeper',\n 'coxswain',\n 'coyan',\n 'coyish',\n 'coyle',\n 'coyote',\n 'cozen',\n 'crab',\n 'crabber',\n 'crabby',\n 'cradler',\n 'craft',\n 'cramped',\n 'crane',\n 'craney',\n 'cranic',\n 'crankless',\n 'cranky',\n 'crassula',\n 'crataegus',\n 'craving',\n 'crawthumper',\n 'craze',\n 'creak',\n 'creaks',\n 'creatine',\n 'creating',\n 'creative',\n 'creche',\n 'credendum',\n 'credenza',\n 'creecy',\n 'creen',\n 'creeps',\n 'cremone',\n 'crepeau',\n 'crescentia',\n 'cricker',\n 'crile',\n 'criminologist',\n 'crimp',\n 'crinoid',\n 'crinoline',\n 'crista',\n 'cristie',\n 'cristina',\n 'criterium',\n 'criticaster',\n 'criticism',\n 'critter',\n 'croci',\n 'crocky',\n 'crocodile',\n 'cronet',\n 'crony',\n 'croppy',\n 'croquette',\n 'crosse',\n 'crossways',\n 'croteau',\n 'crow',\n 'crowds',\n 'crozer',\n 'crozier',\n 'cruce',\n 'cruche',\n 'crucify',\n 'crude',\n 'cruise',\n 'cruising',\n 'crumble',\n 'crumblier',\n 'crumby',\n 'crumpler',\n 'crustacean',\n 'crusty',\n 'cruth',\n 'cryptic',\n 'cuarenta',\n 'cuculla',\n 'cudden',\n 'cuerda',\n 'cuirassier',\n 'cuisse',\n 'culebra',\n 'culet',\n 'culinary',\n 'culled',\n 'cumulate',\n 'cunard',\n 'cupholder',\n 'cupper',\n 'curate',\n 'curcuma',\n 'curcumas',\n 'curlew',\n 'curley',\n 'curupira',\n 'curver',\n 'curvilinear',\n 'cuscus',\n 'cushing',\n 'cusick',\n 'customer',\n 'customize',\n 'cusumano',\n 'cutesy',\n 'cutlass',\n 'cutlet',\n 'cutline',\n 'cutthroat',\n 'cuttlefish',\n 'cyanic',\n 'cybernetic',\n 'cyborgs',\n 'cycles',\n 'cyclic',\n 'cycloid',\n 'cynthy',\n 'cypher',\n 'cypress',\n 'cyprus',\n 'cyrenaic',\n 'cyros',\n 'cytherea',\n 'd-day',\n 'daaboul',\n 'dabber',\n 'dacca',\n 'dachshund',\n 'dacian',\n 'dadaism',\n 'dahoon',\n 'daimen',\n 'dairylea',\n 'dairyman',\n 'daisi',\n 'dalcassian',\n 'dalmatian',\n 'damaged',\n 'damaris',\n 'damil',\n 'damnation',\n 'damocles',\n 'damping',\n 'danceable',\n 'dangersome',\n 'dangle',\n 'danie',\n 'danielak',\n 'danize',\n 'danny',\n 'daphna',\n 'dapped',\n 'darkener',\n 'darkens',\n 'darker',\n 'darkies',\n 'darkness',\n 'darnel',\n 'darrack',\n 'darrel',\n 'darrin',\n 'darshi',\n 'dartboard',\n 'dartman',\n 'dashed',\n 'dastardly',\n 'databank',\n 'dates',\n 'datos',\n 'datura',\n 'daube',\n 'dauphine',\n 'davey',\n 'davidh',\n 'davidian',\n 'dawne',\n 'dawns',\n 'daylights',\n 'dayman',\n 'daymare',\n 'dayspring',\n 'dayton',\n 'dazing',\n 'deadlocked',\n 'deanery',\n 'dearaujo',\n 'deathy',\n 'deaved',\n 'debased',\n 'debater',\n 'debilitate',\n 'debride',\n 'debus',\n 'decaf',\n 'decafid',\n 'decagon',\n 'decatur',\n 'decayed',\n 'deceive',\n 'decembrist',\n 'decency',\n 'decil',\n 'decimate',\n 'decision',\n 'deckchair',\n 'deckers',\n 'deckie',\n 'decking',\n 'decolor',\n 'decoupage',\n 'decries',\n 'decubitus',\n 'dedicates',\n 'deeann',\n 'deena',\n 'deer',\n 'deere',\n 'deermeat',\n 'defeatism',\n 'defect',\n 'defensor',\n 'defiant',\n 'defined',\n 'deflatable',\n 'defloration',\n 'deforestation',\n 'deformative',\n 'deformity',\n 'defrance',\n 'degenerative',\n 'dehaan',\n 'dehydration',\n 'deidre',\n 'deifier',\n 'deipnophobia',\n 'dejan',\n 'dejected',\n 'dekko',\n 'dekle',\n 'delage',\n 'delaminate',\n 'delano',\n 'delat',\n 'delawn',\n 'delayer',\n 'delight',\n 'delila',\n 'deliquescent',\n 'delirious',\n 'deliver',\n 'delly',\n 'delmor',\n 'deloris',\n 'delphinite',\n 'delroy',\n 'deluxe',\n 'demarch',\n 'demeo',\n 'demijohn',\n 'demimark',\n 'demir',\n 'demised',\n 'demiss',\n 'demons',\n 'demur',\n 'dendral',\n 'denes',\n 'denice',\n 'dennie',\n 'denny',\n 'denominate',\n 'dentin',\n 'dentine',\n 'depark',\n 'depict',\n 'depicting',\n 'deposit',\n 'depraved',\n 'deprive',\n 'deranger',\n 'derates',\n 'derelict',\n 'dermis',\n 'dervish',\n 'descended',\n 'desdemon',\n 'desecration',\n 'deserving',\n 'designers',\n 'desirae',\n 'desires',\n 'desiri',\n 'desistance',\n 'desolates',\n 'despoiler',\n 'despot',\n 'dessa',\n 'dessain',\n 'destructive',\n 'detailer',\n 'determinant',\n 'detin',\n 'detlev',\n 'detonations',\n 'detour',\n 'detours',\n 'detur',\n 'deuce',\n 'deuteron',\n 'deutzia',\n 'devaluation',\n 'developed',\n 'devera',\n 'devest',\n 'deviated',\n 'devious',\n 'devoir',\n 'devotes',\n 'devow',\n 'dewberry',\n 'dewdrop',\n 'dewit',\n 'dewitte',\n 'dextro',\n 'dhangar',\n 'dhava',\n 'dhole',\n 'dhoul',\n 'diablo',\n 'diagnose',\n 'diaphane',\n 'diccon',\n 'dichter',\n 'dickerson',\n 'dickford',\n 'didactic',\n 'didani',\n 'didie',\n 'didine',\n 'didus',\n 'dielike',\n 'diena',\n 'diene',\n 'dieri',\n 'diets',\n 'differences',\n 'differentiator',\n 'diffraction',\n 'digestives',\n 'dight',\n 'dijian',\n 'dikkop',\n 'diktat',\n 'dilated',\n 'dilbert',\n 'dimension',\n 'dimitra',\n 'dined',\n 'dingar',\n 'dingbats',\n 'dingley',\n 'dingo',\n 'dinkey',\n 'dinner',\n 'dinners',\n 'dinny',\n 'dinosaur',\n 'dipak',\n 'dipietro',\n 'diplopod',\n 'diptera',\n 'direction',\n 'directory',\n 'dirigent',\n 'dirtbird',\n 'disadventure',\n 'disappear',\n 'disappearance',\n 'disazo',\n 'disbelief',\n 'discolor',\n 'disconsolate',\n 'discordia',\n 'discording',\n 'discount',\n 'discoverer',\n 'discovert',\n 'discriminant',\n 'discus',\n 'disembodied',\n 'disgrace',\n 'disheart',\n 'dislocator',\n 'dismember',\n 'disorderer',\n 'disorient',\n 'dispassioned',\n 'dispatched',\n 'dispirited',\n 'display',\n 'displayer',\n 'dissave',\n 'distad',\n 'distances',\n 'distinctive',\n 'disturber',\n 'ditch',\n 'ditone',\n 'ditto',\n 'divergence',\n 'dives',\n 'divest',\n 'divide',\n 'divinely',\n 'diviner',\n 'diving',\n 'divots',\n 'divus',\n 'diwata',\n 'djins',\n 'docherty',\n 'docken',\n 'documentary',\n 'dodie',\n 'dodo',\n 'dog',\n 'dogfish',\n 'dogged',\n 'dogie',\n 'doglike',\n 'dogtag',\n 'doily',\n 'doina',\n 'dollop',\n 'dolman',\n 'dolmen',\n 'dolomites',\n 'dolphin',\n 'domination',\n 'dominiqu',\n 'dominium',\n 'donal',\n 'donga',\n 'donica',\n 'donkey',\n 'donned',\n 'donnie',\n 'donning',\n 'donohue',\n 'doodad',\n 'doodlebug',\n 'doolittle',\n 'doree',\n 'dorelia',\n 'dories',\n 'dormouse',\n 'dorsal',\n 'dorser',\n 'dorter',\n 'dosanjh',\n 'dosers',\n 'dosser',\n 'dotan',\n 'dotes',\n 'dotson',\n 'dotted',\n 'dotterel',\n 'double',\n 'doubledecker',\n 'doubts',\n 'dougall',\n 'douping',\n 'doused',\n 'dove',\n 'dovelet',\n 'dower',\n 'downbeat',\n 'downcome',\n 'downless',\n 'downs',\n 'downtown',\n 'downturn',\n 'dowse',\n 'draconis',\n 'dragnet',\n 'dragoman',\n 'dragonfly',\n 'drainage',\n 'drainer',\n 'drainpipe',\n 'drakes',\n 'drane',\n 'draughtsman',\n 'dreader',\n 'dreads',\n 'dreaminess',\n 'dreamworld',\n 'dredges',\n 'dreep',\n 'drench',\n 'drenched',\n 'drescher',\n 'dresel',\n 'dress',\n 'dresser',\n 'drever',\n 'dreyfus',\n 'dreyfuss',\n 'dribbling',\n 'drier',\n 'drink',\n 'drive',\n 'drizzly',\n 'dropped',\n 'dropping',\n 'dropsy',\n 'droud',\n 'drover',\n 'drseuss',\n 'drugless',\n 'drumlin',\n 'drumline',\n 'drunks',\n 'dryas',\n 'dubose',\n 'duck',\n 'duckers',\n 'duckies',\n 'ducking',\n 'duckwalk',\n 'duello',\n 'duenas',\n 'dugong',\n 'dulcea',\n 'dullhead',\n 'dulosis',\n 'dumas',\n 'dumbs',\n 'dumper',\n 'dunder',\n 'dungs',\n 'dunker',\n 'dunlin',\n 'dunsmore',\n 'dupable',\n 'dupes',\n 'dupree',\n 'durango',\n 'duress',\n 'durmast',\n 'durovic',\n 'durrell',\n 'dusky',\n 'dustbox',\n 'dustman',\n 'dustuck',\n 'dusun',\n 'dutiful',\n 'dwale',\n 'dweller',\n 'dynamism',\n 'dynamistic',\n 'dyslogistic',\n 'dyspepsia',\n 'dziemian',\n 'eagle',\n 'eamonn',\n 'eardrum',\n 'earles',\n 'earlier',\n 'earlock',\n 'earmark',\n 'earring',\n 'earrings',\n 'earth',\n 'earthenware',\n 'earwig',\n 'eastland',\n 'ebenezer',\n 'eccentrics',\n 'echard',\n 'echidna',\n 'echinus',\n 'eckler',\n 'eclair',\n 'econometrics',\n 'ecstasy',\n 'ecthyma',\n 'edenize',\n 'edlin',\n 'edsel',\n 'eduard',\n 'educable',\n 'edwin',\n 'eeeeee',\n 'eel',\n 'efficacious',\n 'efficience',\n 'efficient',\n 'egality',\n 'eggfish',\n 'egipto',\n 'egret',\n 'eidetic',\n 'eikon',\n 'eladio',\n 'eland',\n 'elanor',\n 'elasmosaur',\n 'elastica',\n 'elberta',\n 'elbow',\n 'elding',\n 'eldreth',\n 'eleanore',\n 'eleazar',\n 'electrified',\n 'electrocute',\n 'electrodes',\n 'electrolysis',\n 'electrophone',\n 'electrostatic',\n 'electrotechnics',\n 'elegances',\n 'elephant',\n 'elephantseal',\n 'elephas',\n 'elevator',\n 'elevatory',\n 'elfreda',\n 'elgar',\n 'elianora',\n 'elided',\n 'eliminable',\n 'eliminator',\n 'elinor',\n 'elizabethan',\n 'elk',\n 'elkins',\n 'eller',\n 'ellie',\n 'elsey',\n 'elusions',\n 'elusory',\n 'elute',\n 'elvera',\n 'elvira',\n 'elysia',\n 'emacs',\n 'emball',\n 'embark',\n 'embay',\n 'embittered',\n 'emblem',\n 'embrica',\n 'embryon',\n 'emera',\n 'emilee',\n 'emilios',\n 'eminence',\n 'emirate',\n 'emissary',\n 'emmaline',\n 'emmett',\n 'emmey',\n 'emogene',\n 'emollient',\n 'emond',\n 'emory',\n 'empathetic',\n 'empathic',\n 'emperors',\n 'empress',\n 'emu',\n 'enamels',\n 'enchanter',\n 'encloud',\n 'endang',\n 'endeavours',\n 'enderle',\n 'endosteum',\n 'endrys',\n 'enforces',\n 'engineman',\n 'engle',\n 'englishmen',\n 'engrave',\n 'engravers',\n 'enhancer',\n 'eniac',\n 'enkidu',\n 'ennead',\n 'enrapt',\n 'enrica',\n 'enriquet',\n 'enshroud',\n 'ensign',\n 'entach',\n 'entails',\n 'ental',\n 'enteron',\n 'entomb',\n 'envelop',\n 'enviable',\n 'ephemeron',\n 'ephialtes',\n 'ephyra',\n 'epical',\n 'epicenter',\n 'epicentral',\n 'episcopalian',\n 'epistropheus',\n 'epomophorus',\n 'equalling',\n 'equilibrio',\n 'equivocal',\n 'erasement',\n 'erastus',\n 'erbach',\n 'erection',\n 'erena',\n 'ergal',\n 'ericsson',\n 'eriksson',\n 'erithacus',\n 'erlenmeyer',\n 'ermey',\n 'erminia',\n 'ernestine',\n 'erode',\n 'erroll',\n 'erwin',\n 'erykah',\n 'erythrocyte',\n 'escalus',\n 'esclavage',\n 'escobilla',\n 'eskar',\n 'eskimo',\n 'esmond',\n 'esparto',\n 'esposito',\n 'essed',\n 'esson',\n 'estelle',\n 'ester',\n 'estes',\n 'estevam',\n 'estherian',\n 'estrange',\n 'esurience',\n 'etalon',\n 'etheline',\n 'ethelyn',\n 'ether',\n 'etherize',\n 'ethically',\n 'eulalia',\n 'eulalie',\n 'eunice',\n 'euonymus',\n 'euphonism',\n 'euphori',\n 'eurasian',\n 'evangelian',\n 'evaporative',\n 'evened',\n 'evens',\n 'evensong',\n 'everyman',\n 'everyone',\n 'evoked',\n 'evokes',\n 'evzone',\n 'ewing',\n 'exacta',\n 'exaggerating',\n 'excalibur',\n 'excavating',\n 'except',\n 'exciton',\n 'excitor',\n 'exclude',\n 'excoriation',\n 'executant',\n 'executed',\n 'exegesis',\n 'exegete',\n 'exert',\n 'exfoliate',\n 'exhibits',\n 'existential',\n 'exophoria',\n 'exorcise',\n 'exordia',\n 'exotic',\n 'expatriate',\n 'expiry',\n 'explains',\n 'exploiters',\n 'explorations',\n 'explorers',\n 'explosion',\n 'expone',\n 'exponent',\n 'exposition',\n 'expresso',\n 'extemporaneity',\n 'externity',\n 'extraneous',\n 'extravert',\n 'extremal',\n 'eyeball',\n 'eyeballs',\n 'eyebrow',\n 'eyeglasses',\n 'eyelashes',\n 'eyeline',\n 'eyeshot',\n 'eyewink',\n 'ezekiel',\n 'fabio',\n 'fabler',\n 'fabrizio',\n 'faceman',\n 'facer',\n 'factice',\n 'facto',\n 'fagan',\n 'fagottino',\n 'fahey',\n 'failsafe',\n 'fairish',\n 'fairless',\n 'fairy',\n 'falchion',\n 'falcon',\n 'faliscan',\n 'fallacy',\n 'faller',\n 'fanes',\n 'fanner',\n 'fantasize',\n 'fatback',\n 'fatidical',\n 'feels',\n 'ferret',\n 'ferrous',\n 'ferule',\n 'fewer',\n 'fiction',\n 'fiducial',\n 'filmer',\n 'finch',\n 'findings',\n 'firearms',\n 'fish',\n 'flabs',\n 'flamer',\n 'flamingo',\n 'flamingos',\n 'flatland',\n 'flattop',\n 'fletcher',\n 'flightless',\n 'flits',\n 'flounder',\n 'fluffs',\n 'fly',\n 'flycatcher',\n 'fogger',\n 'foothill',\n 'forehead',\n 'forger',\n 'forgotten',\n 'fortepiano',\n 'fortes',\n 'fortuneteller',\n 'forzando',\n 'fossa',\n 'fox',\n 'frazzled',\n 'freemen',\n 'frigatebird',\n 'friseur',\n 'frog',\n 'fugio',\n 'funkia',\n 'gaffe',\n 'galago',\n 'gallican',\n 'gar',\n 'gargantuan',\n 'gasped',\n 'gaur',\n 'gazelle',\n 'gecko',\n 'geology',\n 'geometry',\n 'gerbil',\n 'gharial',\n 'giantpanda',\n 'gibbon',\n 'gibed',\n 'giggled',\n 'gingiva',\n 'giraffe',\n 'girlies',\n 'gizzard',\n 'glasses',\n 'glioma',\n 'globefish',\n 'gloms',\n 'glucose',\n 'glycerol',\n 'gnat',\n 'gnu',\n 'goat',\n 'going',\n 'goldfinch',\n 'goldfish',\n 'goodwill',\n 'goose',\n 'gooses',\n 'gopher',\n 'gorilla',\n 'goshawk',\n 'gouger',\n 'graciousness',\n 'granulator',\n 'grasper',\n 'grasshopper',\n 'graybeard',\n 'greener',\n 'greengage',\n 'gregariousness',\n 'greyhound',\n 'greylag',\n 'grievance',\n 'griffin',\n 'gript',\n 'groggy',\n 'grouse',\n 'guanaco',\n 'guars',\n 'guernsey',\n 'guineafowl',\n 'guineapig',\n 'gull',\n 'gulley',\n 'gummers',\n 'gunslinger',\n 'guppy',\n 'habanera',\n 'hadron',\n 'hadrons',\n 'halbert',\n 'haler',\n 'hamster',\n 'handbasket',\n 'hangfire',\n 'hardline',\n 'hare',\n 'harmonious',\n 'harpy',\n 'harrier',\n 'hautbois',\n 'havanese',\n 'havens',\n 'havocs',\n 'hawk',\n 'headwaiter',\n 'heartbreak',\n 'hedgehog',\n 'heeler',\n 'hellion',\n 'hematite',\n 'hemoglobin',\n 'henna',\n 'herbivore',\n 'heron',\n 'herring',\n 'heterosexual',\n 'highbrows',\n 'hillock',\n 'hilum',\n 'himalayan',\n 'hippopotamus',\n 'hoc',\n 'hocus',\n 'hoers',\n 'hoising',\n 'hollyhocks',\n 'holts',\n 'hometown',\n 'hoops',\n 'hopeful',\n 'hornet',\n 'horse',\n 'hubcaps',\n 'hubristic',\n 'huddled',\n 'human',\n 'humiliation',\n 'hummingbird',\n 'hydroponics',\n 'hyena',\n 'ibis',\n 'idiots',\n 'idolatrous',\n 'iguana',\n 'illegal',\n 'imagining',\n 'imbued',\n 'immerging',\n 'immolator',\n 'immune',\n 'impala',\n 'impious',\n 'improve',\n 'impulsively',\n 'inbounds',\n 'incarnate',\n 'incognitos',\n 'indecency',\n 'index',\n 'indexical',\n 'indri',\n 'indris',\n 'indulger',\n 'industry',\n 'inequality',\n 'inexplicit',\n 'infest',\n 'ingots',\n 'insect',\n 'inspector',\n 'inspired',\n 'installation',\n 'insular',\n 'integrate',\n 'intercom',\n 'intercoms',\n 'interflow',\n 'internal',\n 'interregnum',\n 'invigoration',\n 'inviscid',\n 'invite',\n 'irater',\n 'iridescent',\n 'ironwork',\n 'irradiation',\n 'irregular',\n 'irrelevantly',\n 'jacanas',\n 'jackal',\n 'jaguar',\n 'jalop',\n 'janitors',\n 'javanese',\n 'jay',\n 'jazzing',\n 'jellyfish',\n 'jenny',\n 'jeopardise',\n 'jerries',\n 'jocund',\n 'jollier',\n 'jostler',\n 'jujube',\n 'juking',\n 'kabiki',\n 'kakapo',\n 'kangaroo',\n 'kerning',\n 'keyless',\n 'kibbutz',\n 'killing',\n 'kilohertz',\n 'kilts',\n 'kindle',\n 'kingdoms',\n 'kingfisher',\n 'kinkajou',\n 'kiwi',\n 'kiwifruit',\n 'koala',\n 'kolhoz',\n 'kooks',\n 'kouprey',\n 'kudu',\n 'kwashiorkor',\n 'labradoodle',\n 'labyrinth',\n 'laceration',\n 'lacrosse',\n 'ladybird',\n 'lambs',\n 'lamebrain',\n 'landlords',\n 'landmark',\n 'lapwing',\n 'lark',\n 'latria',\n 'launce',\n 'laureate',\n 'lawless',\n 'lazying',\n 'leafy',\n 'lease',\n 'lectures',\n 'lefty',\n 'lemming',\n 'lemon',\n 'lemur',\n 'leopard',\n 'lesbians',\n 'levering',\n 'levied',\n 'libra',\n 'lieve',\n 'lifer',\n 'liger',\n 'lingering',\n 'lining',\n 'lion',\n 'lionfish',\n 'lipomas',\n 'litotes',\n 'lizard',\n 'llama',\n 'lobations',\n 'lobster',\n 'locoed',\n 'locust',\n 'lollygag',\n 'loment',\n 'longhair',\n 'longlines',\n 'longshoremen',\n 'loris',\n 'loudness',\n 'louie',\n 'loupes',\n 'louse',\n 'lovebirds',\n 'lovers',\n 'lucidity',\n 'ludicrous',\n 'lumen',\n 'lymph',\n 'lynx',\n 'lyrebird',\n 'macaw',\n 'macrophage',\n 'madonna',\n 'madras',\n 'magenta',\n 'magistral',\n 'magpie',\n 'maidenhead',\n 'maile',\n 'maimed',\n 'malices',\n 'mallard',\n 'malpractice',\n 'maltese',\n 'malvasia',\n 'manatee',\n 'manche',\n 'mandrill',\n 'manning',\n 'mariachi',\n 'marijuanas',\n 'markhor',\n 'martello',\n 'marten',\n 'massa',\n 'masseurs',\n 'masterly',\n 'masterstroke',\n 'mastiff',\n 'mastoid',\n 'mavie',\n 'mayfly',\n 'meanwhile',\n 'meatmen',\n 'mechanic',\n 'medical',\n 'mediums',\n 'meerkat',\n 'megalomaniac',\n 'merchants',\n 'merrily',\n 'metalsmith',\n 'metatarsi',\n 'meteorology',\n 'microtome',\n 'miffs',\n 'migraine',\n 'millage',\n 'milled',\n 'millipede',\n 'mindsets',\n 'minima',\n 'mink',\n 'mirth',\n 'mistermed',\n 'mitten',\n 'mixers',\n 'mocha',\n 'moggie',\n 'mogul',\n 'moguls',\n 'moirai',\n 'molar',\n 'mole',\n 'molly',\n 'monastery',\n 'mongeese',\n 'mongoose',\n 'mongrel',\n 'monikers',\n 'monkey',\n 'monkeyshines',\n 'monomania',\n 'moorhen',\n 'moors',\n 'moose',\n 'moped',\n 'moralistic',\n 'moratoria',\n 'mosks',\n 'mosquito',\n 'mosso',\n 'moth',\n 'mothball',\n 'motility',\n 'motivator',\n 'motorman',\n 'mouse',\n 'mousse',\n 'mule',\n 'mullite',\n 'multijet',\n 'musician',\n 'mutine',\n 'myalgic',\n 'named',\n 'namelessly',\n 'nappy',\n 'narwhal',\n 'naturalistic',\n 'naturalists',\n 'navies',\n 'neanderthal',\n 'nepenthe',\n 'netlike',\n 'neuter',\n 'newborns',\n 'newfoundland',\n 'newt',\n 'nibble',\n 'nightingale',\n 'ninjas',\n 'nobodies',\n 'nodder',\n 'nonbelief',\n 'normalcy',\n 'normality',\n 'norms',\n 'novelette',\n 'numbat',\n 'nympholept',\n 'obscenity',\n 'obsoletes',\n 'ocelot',\n 'octopus',\n 'oddballs',\n 'offside',\n 'offsprings',\n 'okapi',\n 'olm',\n 'omnivora',\n 'oncogene',\n 'onions',\n 'onomatopoeia',\n 'opossum',\n 'oppose',\n 'orache',\n 'organismal',\n 'orthodox',\n 'oryx',\n 'ostraca',\n 'ostrich',\n 'otter',\n 'outlandish',\n 'outlet',\n 'outside',\n 'overdogs',\n 'overshadow',\n 'overview',\n 'owl',\n 'ox',\n 'oxeyes',\n 'oxides',\n 'oyster',\n 'ozonic',\n 'pacas',\n 'padauk',\n 'pademelon',\n 'pager',\n 'painful',\n 'palindrome',\n 'palmar',\n 'palmetto',\n 'pancreatitis',\n 'panicked',\n 'panther',\n 'panthers',\n 'pantomime',\n 'papain',\n 'papal',\n 'paperweight',\n 'papillon',\n 'paradise',\n 'parlay',\n 'parrot',\n 'parsed',\n 'parser',\n 'parterres',\n 'partridge',\n 'paseos',\n 'passe',\n 'passwords',\n 'pastorale',\n 'patness',\n 'patter',\n 'pauses',\n 'peacemaker',\n 'peacock',\n 'peafowl',\n 'pecky',\n 'pediatric',\n 'pedicab',\n 'pedlers',\n 'pedophile',\n 'peery',\n 'pekingese',\n 'pelican',\n 'penguin',\n 'penning',\n 'pennyroyal',\n 'pensione',\n 'penstemon',\n 'peponidas',\n 'perfecto',\n 'peroxid',\n 'persian',\n 'perturbation',\n 'petal',\n 'pewit',\n 'pheasant',\n 'phosphate',\n 'photon',\n 'picoline',\n 'pig',\n 'pigeon',\n 'pika',\n 'pike',\n 'pinnacle',\n 'pinole',\n 'pinwheel',\n 'pioneering',\n 'piperazine',\n 'pipsqueak',\n 'piques',\n 'piranha',\n 'pirogue',\n 'pisiform',\n 'placebos',\n 'plasmoid',\n 'platypus',\n 'playland',\n 'please',\n 'pleonastic',\n 'plimsol',\n 'plotter',\n 'poesy',\n 'poetess',\n 'pointer',\n 'politics',\n 'polled',\n 'pommies',\n 'pondering',\n 'pony',\n 'poodle',\n 'pooled',\n 'porcupine',\n 'porkpie',\n 'porpoise',\n 'positive',\n 'possum',\n 'postcard',\n 'postfire',\n 'poundage',\n 'pourer',\n 'poverty',\n 'prawn',\n 'preatomic',\n 'precognition',\n 'preview',\n 'primeval',\n 'princesse',\n 'prisons',\n 'processor',\n 'proclaimed',\n 'progression',\n 'prophecy',\n 'prosecutor',\n 'prostitute',\n 'protesting',\n 'protomartyr',\n 'prune',\n 'pseudonym',\n 'puffin',\n 'puffs',\n 'pug',\n 'pullover',\n 'pulvinus',\n 'puma',\n 'purdah',\n 'pyrogenicity',\n 'pyrrhic',\n 'quail',\n 'qualm',\n 'quarts',\n 'quebrachos',\n 'quelea',\n 'quetzal',\n 'quietens',\n 'quokka',\n 'quoll',\n 'rabbit',\n 'rabboni',\n 'raccoon',\n 'racker',\n 'racon',\n 'ragdoll',\n 'rail',\n 'raincoat',\n 'ram',\n 'raphia',\n 'rat',\n 'ratiocinator',\n 'rattlesnake',\n 'raven',\n 'razers',\n 'realest',\n 'reaper',\n 'reasonable',\n 'receipt',\n 'recipe',\n 'reddeer',\n 'redips',\n 'redout',\n 'redpanda',\n 'reefer',\n 'reflection',\n 'refuted',\n 'regularity',\n 'reindeer',\n 'reinvent',\n 'relaxing',\n 'relentless',\n 'religion',\n 'removed',\n 'repair',\n 'replenished',\n 'represented',\n 'requestor',\n 'restrict',\n 'retort',\n 'retractor',\n 'reversible',\n 'revulsion',\n 'rhinoceros',\n 'rhizobium',\n 'riced',\n 'ridicule',\n 'rille',\n 'robin',\n 'rolfers',\n 'rook',\n 'rooky',\n 'roseola',\n 'rotavirus',\n 'rotted',\n 'rottweiler',\n 'rousseau',\n 'routeman',\n 'rovers',\n 'roving',\n 'rubeola',\n 'ruff',\n 'rumpus',\n 'runaround',\n 'russet',\n 'ruthlessness',\n 'rykes',\n 'sabed',\n 'saddlers',\n 'salads',\n 'salamander',\n 'sales',\n 'salmon',\n 'saltire',\n 'saltish',\n 'samaras',\n 'samba',\n 'sanatorium',\n 'sanded',\n 'sandpiper',\n 'santalol',\n 'saola',\n 'sapid',\n 'sapient',\n 'sardine',\n 'sarges',\n 'sassiest',\n 'satsumas',\n 'sawbucks',\n 'sawer',\n 'sawing',\n 'saxes',\n 'scabs',\n 'scaled',\n 'scallywags',\n 'scalp',\n 'scalper',\n 'scampers',\n 'scams',\n 'scandic',\n 'scarabaeus',\n 'scarabs',\n 'scarcity',\n 'scarlet',\n 'scarped',\n 'scatt',\n 'scattershot',\n 'scheduler',\n 'schematic',\n 'scheme',\n 'schipperke',\n 'schizophrenic',\n 'schlock',\n 'schmelze',\n 'schnaps',\n 'schnecken',\n 'schrik',\n 'schuit',\n 'schuss',\n 'science',\n 'sciences',\n 'scimitar',\n 'scintillator',\n 'scions',\n 'scirocco',\n 'scissor',\n 'sclera',\n 'scoop',\n 'scoot',\n 'scope',\n 'scorch',\n 'scorching',\n 'scorer',\n 'scorner',\n 'scorpion',\n 'scouth',\n 'scrag',\n 'scraps',\n 'scrimpy',\n 'scriptures',\n 'scrod',\n 'scroll',\n 'scrounge',\n 'scruff',\n 'sculpt',\n 'scumbag',\n 'scumble',\n 'scurry',\n 'scuzzy',\n 'scythe',\n 'scythed',\n 'seahorse',\n 'seal',\n 'seaside',\n 'seatbelts',\n 'seated',\n 'seaters',\n 'seawan',\n 'seaward',\n 'seaweeds',\n 'sebasic',\n 'seconds',\n 'secret',\n 'secretive',\n 'secretor',\n 'section',\n 'sectored',\n 'sedated',\n 'sedater',\n 'sedatives',\n 'sedimentary',\n 'seduced',\n 'seemly',\n 'seersucker',\n 'segment',\n 'segued',\n 'segueing',\n 'seiner',\n 'seining',\n 'seise',\n 'seiser',\n 'seism',\n 'selachian',\n 'seldom',\n 'sellouts',\n 'selvas',\n 'semblance',\n 'senary',\n 'senna',\n 'sensorium',\n 'separated',\n 'septs',\n 'serines',\n 'serval',\n 'setae',\n 'sexualized',\n 'shakable',\n 'shaly',\n 'shaman',\n 'shamus',\n 'shandies',\n 'shaping',\n 'shark',\n 'shawm',\n 'sheep',\n 'sheeting',\n 'shelver',\n 'sheriff',\n 'shott',\n 'shove',\n 'shrew',\n 'shrimp',\n 'siamese',\n 'siberian',\n 'sided',\n 'sidetracked',\n 'sighless',\n 'signal',\n 'signor',\n 'silanes',\n 'silhouette',\n 'silicon',\n 'silly',\n 'simars',\n 'simmer',\n 'simoniac',\n 'simoom',\n 'simpleminded',\n 'singly',\n 'sirens',\n 'sizzles',\n 'skellum',\n 'sketch',\n 'skims',\n 'skinkers',\n 'skunk',\n 'slammer',\n 'slaters',\n 'sledged',\n 'slinking',\n 'sloth',\n 'smackers',\n 'smarmy',\n 'smokers',\n 'smoldering',\n 'snail',\n 'snails',\n 'snake',\n 'snakebite',\n 'snakey',\n 'snarling',\n 'snips',\n 'snobby',\n 'snorkeling',\n 'snowdrop',\n 'snowdrops',\n 'snowshoe',\n 'soave',\n 'socked',\n 'sokols',\n 'solarise',\n 'soling',\n 'solitude',\n 'solver',\n 'somali',\n 'sophies',\n 'soundless',\n 'sourish',\n 'spacial',\n 'spancel',\n 'sparrow',\n 'spawners',\n 'species',\n 'spectators',\n 'speculate',\n 'speer',\n 'spelter',\n 'spent',\n 'spice',\n 'spider',\n 'spieler',\n 'spiritually',\n 'splay',\n 'splendent',\n 'splendiferous',\n 'sponge',\n 'sportsmen',\n 'sprit',\n 'squeal',\n 'squid',\n 'squirrel',\n 'squirting',\n 'stacker',\n 'stallions',\n 'stampeded',\n 'staple',\n 'starfish',\n 'starling',\n 'starship',\n 'starvation',\n 'stele',\n 'stelic',\n 'stengah',\n 'steric',\n 'stingray',\n 'stinkbug',\n 'stirrup',\n 'stoat',\n 'stoop',\n 'stoper',\n 'stork',\n 'streamliner',\n 'street',\n 'strenuous',\n 'stripling',\n 'stubbles',\n 'stupid',\n 'stylar',\n 'subatom',\n 'subfusc',\n 'subspace',\n 'sucks',\n 'suddens',\n 'suedes',\n 'suing',\n 'sundering',\n 'sunshiny',\n 'supershow',\n 'superstardom',\n 'supervene',\n 'surcease',\n 'surrey',\n 'suspected',\n 'suzerain',\n 'swallow',\n 'swan',\n 'sweatband',\n 'switchers',\n 'syllogist',\n 'sylvan',\n 'syphered',\n 'systemic',\n 'tabloids',\n 'tafia',\n 'tailcoat',\n 'takeout',\n 'tang',\n 'tapadera',\n 'tapir',\n 'tarantas',\n 'tariff',\n 'tarsier',\n 'tastier',\n 'tasty',\n 'taunting',\n 'tawer',\n 'taxidermist',\n 'teenage',\n 'telegrams',\n 'telephoto',\n 'tenant',\n 'tenons',\n 'termite',\n 'terrorized',\n 'tessera',\n 'testimony',\n 'tetra',\n 'tewing',\n 'thanking',\n 'theist',\n 'thieving',\n 'thorax',\n 'thousand',\n 'thrilling',\n 'throne',\n 'thrower',\n 'thrush',\n 'thunderstorm',\n 'thyroxine',\n 'tiffany',\n 'tiger',\n 'tilak',\n 'tilled',\n 'tinfoil',\n 'tingler',\n 'tinkle',\n 'tipple',\n 'toad',\n 'tobacconist',\n 'toking',\n 'tommed',\n 'toner',\n 'tonic',\n 'tonights',\n 'tonsured',\n 'tootle',\n 'topkick',\n 'torot',\n 'torpedos',\n 'torpor',\n 'tortoise',\n 'toucan',\n 'touchable',\n 'toughie',\n 'tovarish',\n 'toxicologist',\n 'trachea',\n 'tracing',\n 'tracking',\n 'tradition',\n 'transact',\n 'transform',\n 'transistors',\n 'tressed',\n 'trigs',\n 'trinity',\n 'trioxide',\n 'tritoma',\n 'tropicbird',\n 'trout',\n 'trucker',\n 'trust',\n 'tuatara',\n 'tuner',\n 'tupelo',\n 'turkey',\n 'turmeric',\n 'turtle',\n 'tutorial',\n 'tzarina',\n 'uakari',\n 'uguisu',\n 'ultrasonic',\n 'umbrellabird',\n 'umiaq',\n 'unaccountably',\n 'unacted',\n 'undercount',\n 'underlain',\n 'underling',\n 'undermined',\n 'unladylike',\n 'unmercifully',\n 'unrecorded',\n 'unreliable',\n 'unremarkable',\n 'unshackled',\n 'unspecific',\n 'uppercut',\n 'utilize',\n 'utilizer',\n 'validity',\n 'valours',\n 'vanished',\n 'vaultier',\n 'vegan',\n 'veining',\n 'vermillions',\n 'vertebras',\n 'vibrio',\n 'viceless',\n 'videotape',\n 'viking',\n 'vilification',\n 'vineal',\n 'viper',\n 'vises',\n 'vituperative',\n 'vivers',\n 'vocalist',\n 'vodkas',\n 'vomer',\n 'voyageurs',\n 'vulture',\n 'waddie',\n 'wafer',\n 'waggle',\n 'waiting',\n 'wakened',\n 'walies',\n 'wallaby',\n 'wallet',\n 'walrus',\n 'wampum',\n 'wangler',\n 'wanton',\n 'wared',\n 'warship',\n 'warthog',\n 'warthogs',\n 'washy',\n 'wasp',\n 'watercolors',\n 'waylay',\n 'weasel',\n 'weedlike',\n 'westwards',\n 'whale',\n 'whammo',\n 'whippet',\n 'whitier',\n 'whoever',\n 'wildebeest',\n 'wimple',\n 'wingy',\n 'winterberry',\n 'wipers',\n 'wivern',\n 'woesome',\n 'wolf',\n 'wolverine',\n 'wombat',\n 'wonderful',\n 'wonders',\n 'woodcock',\n 'woodlouse',\n 'woodpecker',\n 'woofs',\n 'workbench',\n 'worker',\n 'worm',\n 'wound',\n 'woundless',\n 'wrasse',\n 'wrath',\n 'wren',\n 'wries',\n 'yaird',\n 'yak',\n 'yealing',\n 'yeanling',\n 'yucca',\n 'zaffre',\n 'zapateo',\n 'zappiest',\n 'zebra',\n 'zebu',\n 'zelkova',\n 'zillionaire',\n 'zonkey',\n 'zooks',\n 'zorse',\n]\n\nSOCIAL_NETWORKS = {\n 'facebook': 'facebook.com/{}',\n 'twitter': 'twitter.com/{}',\n 'instagram': 'instagram.com/{}',\n 'vk': 'vk.com/{}',\n}\n","sub_path":"mimesis/data/int/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":59426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"81536557","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# -*- coding: utf-8 -*-\n\ntry:\n from setuptools import setup\n from setuptools.command.install import install\nexcept ImportError:\n from distutils.core import setup\n from distutils.core.command.install import install\n\nfrom IPython.html.nbextensions import install_nbextension\n\ndef make_cmdclass(setupfile, path, enable=None):\n \"\"\"Build nbextension cmdclass dict for the setuptools.setup method.\n\n Parameters\n ----------\n setupfile: str\n Path to the setup file.\n path: str\n Directory relative to the setup file that the nbextension code lives in.\n enable: [str=None]\n Extension to \"enable\". Enabling an extension causes it to be loaded\n automatically by the IPython notebook.\n\n Usage\n -----\n setup(\n name='flightwidgets',\n ...\n cmdclass=make_cmdclass(__file__, 'flightwidgets', 'flightwidgets/init'),\n )\n \"\"\"\n\n from setuptools.command.install import install\n from setuptools.command.develop import develop\n from os.path import dirname, abspath, join\n\n from IPython.html.services.config import ConfigManager\n\n def run_nbextension_install(develop):\n install_nbextension(join(dirname(abspath(setupfile)), path), symlink=develop)\n if enable is not None:\n print(\"Enabling the extension ...\")\n cm = ConfigManager()\n cm.update('notebook', {\"load_extensions\": {enable: True}})\n\n class InstallCommand(install):\n def run(self):\n print(\"Installing Python module...\")\n install.run(self)\n print(\"Installing nbextension ...\")\n run_nbextension_install(False)\n\n class DevelopCommand(develop):\n def run(self):\n print(\"Installing Python module...\")\n develop.run(self)\n print(\"Installing nbextension ...\")\n run_nbextension_install(True)\n \n return {\n 'install': InstallCommand,\n 'develop': DevelopCommand,\n }\n\n\nfrom glob import glob \nsetup(\n name='bitjet',\n version='0.2.1',\n description='Binary visualization using IPython widgets',\n author='Kyle Kelley',\n author_email='rgbkrk@gmail.com',\n license='New BSD License',\n url='https://github.com/rgbkrk/bitjet',\n keywords='data visualization interactive interaction python ipython widgets widget',\n install_requires=['ipython'],\n classifiers=['Development Status :: 4 - Beta',\n 'Programming Language :: Python',\n 'License :: OSI Approved :: MIT License'],\n packages=['bitjet'],\n include_package_data=True,\n cmdclass=make_cmdclass(__file__, 'bitjet')\n)\n","sub_path":"pypi_install_script/bitjet-0.2.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"163443868","text":"#!/usr/bin/python\n\nimport turtle\nimport math\nimport tkinter\n\nbob=turtle.Turtle()\ndef polygon(t, n, length):\n angle=360/n\n for i in range(n):\n t.fd(length)\n t.lt(angle)\n polygon(bob, 7, 70)\n","sub_path":"Python/23-09-2018/circle.py","file_name":"circle.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"79488868","text":"\"\"\"Class definitions for configuring acoustic model training\"\"\"\nfrom __future__ import annotations\n\nimport os\nfrom collections import Counter\nfrom typing import Iterator, List, Tuple\n\nimport yaml\n\nfrom ..trainers import (\n BaseTrainer,\n IvectorExtractorTrainer,\n LdaTrainer,\n MonophoneTrainer,\n SatTrainer,\n TriphoneTrainer,\n)\nfrom .align_config import AlignConfig\nfrom .base_config import (\n DEFAULT_CLITIC_MARKERS,\n DEFAULT_COMPOUND_MARKERS,\n DEFAULT_PUNCTUATION,\n PARSING_KEYS,\n BaseConfig,\n ConfigError,\n)\nfrom .feature_config import FeatureConfig\n\n__all__ = [\n \"TrainingConfig\",\n \"train_yaml_to_config\",\n \"load_basic_train\",\n \"load_basic_train_ivector\",\n \"load_test_config\",\n \"load_sat_adapt\",\n \"load_no_sat_adapt\",\n]\n\n\nclass TrainingConfig(BaseConfig):\n \"\"\"\n Configuration class for storing parameters and trainers for training acoustic models\n \"\"\"\n\n def __init__(self, training_configs):\n self.training_configs = training_configs\n counts = Counter([x.train_type for x in self.training_configs])\n self.training_identifiers = []\n curs = {x.train_type: 1 for x in self.training_configs}\n for t in training_configs:\n i = t.train_type\n if counts[t.train_type] != 1:\n i += str(curs[t.train_type])\n curs[t.train_type] += 1\n self.training_identifiers.append(i)\n\n self.punctuation = DEFAULT_PUNCTUATION\n self.clitic_markers = DEFAULT_CLITIC_MARKERS\n self.compound_markers = DEFAULT_COMPOUND_MARKERS\n\n def update_from_align(self, align_config: AlignConfig) -> None:\n \"\"\"Update parameters from an AlignConfig\"\"\"\n for tc in self.training_configs:\n tc.overwrite = align_config.overwrite\n tc.cleanup_textgrids = align_config.cleanup_textgrids\n\n def update(self, data: dict) -> None:\n \"\"\"Update parameters\"\"\"\n for k, v in data.items():\n if k in PARSING_KEYS:\n if not v:\n continue\n if \"-\" in v:\n v = \"-\" + v.replace(\"-\", \"\")\n if \"]\" in v and r\"\\]\" not in v:\n v = v.replace(\"]\", r\"\\]\")\n if not hasattr(self, k):\n raise ConfigError(\"No field found for key {}\".format(k))\n setattr(self, k, v)\n for trainer in self.values():\n trainer.update(data)\n\n def keys(self) -> List:\n \"\"\"List of training identifiers\"\"\"\n return self.training_identifiers\n\n def values(self) -> List[BaseTrainer]:\n \"\"\"List of trainers\"\"\"\n return self.training_configs\n\n def items(self) -> Iterator:\n \"\"\"Iterator over training identifiers and trainers\"\"\"\n return zip(self.training_identifiers, self.training_configs)\n\n def __getitem__(self, item: str) -> BaseTrainer:\n \"\"\"Get trainer based on identifier\"\"\"\n if item not in self.training_identifiers:\n raise KeyError(f\"{item} not a valid training identifier\")\n return self.training_configs[self.training_identifiers.index(item)]\n\n @property\n def uses_sat(self) -> bool:\n \"\"\"Flag for whether a trainer uses speaker adaptation\"\"\"\n for k in self.keys():\n if k.startswith(\"sat\"):\n return True\n return False\n\n\ndef train_yaml_to_config(\n path: str, require_mono: bool = True\n) -> Tuple[TrainingConfig, AlignConfig]:\n \"\"\"\n Helper function to load acoustic model training configurations\n\n Parameters\n ----------\n path: str\n Path to yaml file\n\n Returns\n -------\n :class:`~montreal_forced_aligner.config.train_config.TrainingConfig`\n Training configuration\n :class:`~montreal_forced_aligner.config.align_config.AlignConfig`\n Alignment configuration\n \"\"\"\n with open(path, \"r\", encoding=\"utf8\") as f:\n data = yaml.load(f, Loader=yaml.SafeLoader)\n global_params = {}\n training = []\n training_params = []\n global_feature_params = {}\n for k, v in data.items():\n if k == \"training\":\n for t in v:\n for k2, v2 in t.items():\n feature_config = FeatureConfig()\n if k2 == \"monophone\":\n training.append(MonophoneTrainer(feature_config))\n elif k2 == \"triphone\":\n training.append(TriphoneTrainer(feature_config))\n elif k2 == \"lda\":\n training.append(LdaTrainer(feature_config))\n elif k2 == \"sat\":\n training.append(SatTrainer(feature_config))\n elif k2 == \"ivector\":\n training.append(IvectorExtractorTrainer(feature_config))\n training_params.append(v2)\n elif k == \"features\":\n global_feature_params.update(v)\n else:\n global_params[k] = v\n feature_config = FeatureConfig()\n feature_config.update(global_feature_params)\n align_config = AlignConfig(feature_config)\n align_config.update(global_params)\n training_config = None\n if training:\n for i, t in enumerate(training):\n if i == 0 and require_mono and t.train_type not in [\"mono\", \"ivector\"]:\n raise ConfigError(\"The first round of training must be monophone.\")\n t.update(global_params)\n t.update(training_params[i])\n t.feature_config.update(global_feature_params)\n training_config = TrainingConfig(training)\n align_config.feature_config.fmllr = training_config.uses_sat\n if align_config.beam >= align_config.retry_beam:\n raise ConfigError(\"Retry beam must be greater than beam.\")\n return training_config, align_config\n\n\ndef load_basic_train() -> Tuple[TrainingConfig, AlignConfig]:\n \"\"\"\n Helper function to load the default parameters\n\n Returns\n -------\n :class:`~montreal_forced_aligner.config.train_config.TrainingConfig`\n Training configuration\n :class:`~montreal_forced_aligner.config.align_config.AlignConfig`\n Alignment configuration\n \"\"\"\n base_dir = os.path.dirname(os.path.abspath(__file__))\n training_config, align_config = train_yaml_to_config(\n os.path.join(base_dir, \"basic_train.yaml\")\n )\n return training_config, align_config\n\n\ndef load_sat_adapt() -> Tuple[TrainingConfig, AlignConfig]:\n \"\"\"\n Helper function to load the default speaker adaptation parameters for adapting an acoustic model to new data\n\n Returns\n -------\n :class:`~montreal_forced_aligner.config.train_config.TrainingConfig`\n Training configuration\n :class:`~montreal_forced_aligner.config.align_config.AlignConfig`\n Alignment configuration\n \"\"\"\n base_dir = os.path.dirname(os.path.abspath(__file__))\n training_config, align_config = train_yaml_to_config(\n os.path.join(base_dir, \"adapt_sat.yaml\"), require_mono=False\n )\n training_config.training_configs[0].fmllr_iterations = range(\n 0, training_config.training_configs[0].num_iterations\n )\n training_config.training_configs[0].realignment_iterations = range(\n 0, training_config.training_configs[0].num_iterations\n )\n return training_config, align_config\n\n\ndef load_no_sat_adapt() -> Tuple[TrainingConfig, AlignConfig]:\n \"\"\"\n Helper function to load the default parameters for adapting an acoustic model to new data without speaker adaptation\n\n Returns\n -------\n :class:`~montreal_forced_aligner.config.train_config.TrainingConfig`\n Training configuration\n :class:`~montreal_forced_aligner.config.align_config.AlignConfig`\n Alignment configuration\n \"\"\"\n base_dir = os.path.dirname(os.path.abspath(__file__))\n training_config, align_config = train_yaml_to_config(\n os.path.join(base_dir, \"adapt_nosat.yaml\"), require_mono=False\n )\n training_config.training_configs[0].realignment_iterations = range(\n 0, training_config.training_configs[0].num_iterations\n )\n return training_config, align_config\n\n\ndef load_basic_train_ivector() -> Tuple[TrainingConfig, AlignConfig]:\n \"\"\"\n Helper function to load the default parameters for training ivector extractors\n\n Returns\n -------\n :class:`~montreal_forced_aligner.config.train_config.TrainingConfig`\n Training configuration\n :class:`~montreal_forced_aligner.config.align_config.AlignConfig`\n Alignment configuration\n \"\"\"\n base_dir = os.path.dirname(os.path.abspath(__file__))\n training_config, align_config = train_yaml_to_config(\n os.path.join(base_dir, \"basic_train_ivector.yaml\")\n )\n return training_config, align_config\n\n\ndef load_test_config() -> Tuple[TrainingConfig, AlignConfig]:\n \"\"\"\n Helper function to load the default parameters for validating corpora\n\n Returns\n -------\n :class:`~montreal_forced_aligner.config.train_config.TrainingConfig`\n Training configuration\n :class:`~montreal_forced_aligner.config.align_config.AlignConfig`\n Alignment configuration\n \"\"\"\n base_dir = os.path.dirname(os.path.abspath(__file__))\n training_config, align_config = train_yaml_to_config(\n os.path.join(base_dir, \"test_config.yaml\")\n )\n return training_config, align_config\n","sub_path":"montreal_forced_aligner/config/train_config.py","file_name":"train_config.py","file_ext":"py","file_size_in_byte":9498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"535408094","text":"#!/usr/local/bin/python3\n\n###The script grabs mature.fa.gz and organisms.gz of current release from mirbase FTP, parses both files, map phylum as per organism code in mirname and populates mirBASE table in mir_master\n###Usage ./GetmiRBASE_1a.py\n\nfrom ftplib import FTP\nimport sys\nimport mysql.connector as sql\nimport gzip\n\n#################################Config#####################################\n\n##Server to upload data a.k.a destination server with table to hold results of PARE validation\ndestserver = 'raichu.dbi.udel.edu'#####Value should be in ''\n\nftpurl = 'mirbase.org'\n\n#############################################################################\n\ndef ConnectToDB(server, infile):\n \n ##infile values are '0' when you dont want to pulaod data from local file and '1' when you wish to upload data by local file\n ##EX:con=sql.connect(host= server, user='kakrana', passwd='livetheday', local_infile = infile)\n ##Now later in script you can\n ##cur.execute(\"LOAD DATA LOCAL INFILE './scoring_input_extend2' INTO TABLE kakrana_data.mir_page_results FIELDS TERMINATED BY ','\")\n \n print ('\\nTrying to connect to mySQL server on %s' % (server))\n # Try to connect to the database\n try:\n con=sql.connect(host= server, user='kakrana', passwd='livetheday')###local_infile = 1 not supported yet so a table has to be updated on row basis\n print ('Connection Established\\n')\n\n # If we cannot connect to the database, send an error to the user and exit the program.\n except sql.Error:\n print (\"Error %d: %s\" % (sql.Error.args[0],sql.Error.args[1]))\n sys.exit(1)\n\n return con\n\ndef FTPGet(ftpurl):\n \n ftp = FTP(ftpurl)\n ftp.login() ###Anonymous login, if required\n #ftp.retrlines('LIST') ### List root folder\n ftp.cwd(\"/pub/mirbase/CURRENT\")## Get to the current version\n #ftp.retrlines('LIST')\n \n #gzfile = open( 'mature.fa.gz','wb') ### wb is for write binary\n #ftp.retrbinary('RETR mature.fa.gz', gzfile.write)\n files = ['mature.fa.gz','organisms.txt.gz']\n \n \n for file in files:\n \n ##miR_file = 'mature.fa.gz'\n #ftp.retrbinary('RETR mature.fa.gz', open(mir_file,'wb').write)\n ftp.retrbinary('RETR %s' % file, open(file,'wb').write)\n \n ##Lets unpack the file\n ftp.quit()\n return files ###Both files in form of list\n \ndef mirBASEParse(files):\n \n ##Read and Parse the organism file\n org_in = gzip.open(files[1], 'rb')\n org_raw = org_in.read()\n org_in.close()\n org_code = org_raw.decode('utf8')\n #print (org_code)\n \n ###aqu\tAQU\tAmphimedon queenslandica\tMetazoa;Porifera;\n code_dict = {} ###dictionary to hold codes and phylum\n org_blocks = org_code.split('\\n')\n for i in org_blocks[:-1]:##exclude item after last newline \n ent = i.split()\n #print (ent)\n org_code = ent[0]\n phylum = ent[-1].split(';')[0]\n code_dict[org_code] = phylum \n #print (phylum)\n #break\n \n mir_list = []##list that will hold result\n #print (afile)\n fh_in = gzip.open(files[0],'rb')\n mir_base_raw = fh_in.read()\n fh_in.close()\n mir_base = mir_base_raw.decode('utf8')\n #print(mir_base)\n mir_blocks= mir_base.split('>')\n \n ##>cel-let-7-5p MIMAT0000001 Caenorhabditis elegans let-7-5p\n ##UGAGGUAGUAGGUUGUAUAGUU\n \n for i in mir_blocks[1:]:\n block = i.strip('\\n')##Remove newline from end of entry\n ent = block.split('\\n')##Use the newline between header and sequence to split\n info = ent[0].split()\n name = info[0]\n org = name.split('-')[0]\n phylum = code_dict[org]\n accession = info[1]\n organism = '%s %s' % (info[2],info[3])\n gen_name = info[4]\n mir_seq = ent[1]\n mir_len = len(mir_seq)\n print (name,accession,organism,gen_name,mir_seq,mir_len, phylum)\n \n mir_list.append((name,accession,organism,gen_name,mir_seq,mir_len, phylum))\n # \n #for i in mir_list:\n # print(i)\n \n return mir_list\n \ndef TableUpload(con, mir_list):###Con is connection and res_upload is file from last module which has genomic coords and need to be upload\n ##Upload scoring_input_extend to table - please make sure that columns are in file are in order of the columns in the table\n \n cur = con.cursor()##Connect to destination server with table\n #res_file = 'scoring_input_extend_upload' \n \n print ('\\nClearing the table before updating.....')\n cur.execute(\"TRUNCATE TABLE mir_master.mirBASE\")## Clear table before writing\n #con2.commit()\n print ('\\nTable cleared successfully, update in process')\n \n ##Current implementation of mysql.connector does not support instant upload by local file - see ConnectToDB() module for implementation\n ##Original query - LOAD DATA LOCAL INFILE \"./scoring_input_extend\" INTO TABLE kakrana_data.mir_page_results FIELDS TERMINATED BY ',';\n ##cur.execute(\"LOAD DATA LOCAL INFILE './scoring_input_extend2' INTO TABLE kakrana_data.mir_page_results FIELDS TERMINATED BY ','\")\n ##So fill table on row by row basis\n \n add_row = \"INSERT INTO mir_master.mirBASE (mir_name,accession,organism,generic_name,mir_seq,mir_len,phylum) VALUES (%s, %s, %s, %s, %s, %s, %s)\"\n \n #test_data =cel-let-7-5p MIMAT0000001 Caenorhabditis elegans UGAGGUAGUAGGUUGUAUAGUU 22\n \n for ent in mir_list:\n #print(ent[0], ent[1], ent[2], ent[3], ent[4], ent[5])\n res_upload = (ent[0], ent[1], ent[2], ent[3], ent[4], ent[5], ent[6])\n cur.execute(add_row,res_upload) \n con.commit()\n \n cur.close()\n \n \n \ndef main(): \n gzfile = FTPGet(ftpurl)\n mir_list = mirBASEParse(gzfile)\n con=ConnectToDB(destserver, 0)\n TableUpload(con, mir_list)\n \n \n\n\nif __name__ == '__main__':\n #url = 'ftp://mirbase.org/pub/mirbase/CURRENT/'\n afile = './mature.fa'\n main()\n sys.exit()\n \n ","sub_path":"mirBASE/GetmiRBASE_1a.py","file_name":"GetmiRBASE_1a.py","file_ext":"py","file_size_in_byte":5964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"596771041","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 8 15:56:47 2019\r\n\r\n@author: orhun\r\n\"\"\"\r\nimport time;\r\nstartTime=time.time(); # saving current time to find execution time later\r\nwith open('the_truman_show_script.txt', 'r') as script: # reading text\r\n text = script.read();\r\n script.close(); \r\nn = len(text);\r\nans_i=1; # index of output lines\r\n\r\ndef bmh(pattern,s_index):\r\n global text,n,index_found; # using global variables\r\n p_Length=len(pattern);\r\n bmt = []; # bad match table array\r\n for k in range(256): # array size of 256 for every ascii character \r\n bmt.append(p_Length); # filling length of pattern\r\n for k in range(p_Length - 1):# filling the table with corresponding skip values\r\n bmt[ord(pattern[k])] = p_Length - k - 1;#- of symbols in the patttern\r\n bmt = tuple(bmt); # turning array into tuple since indexes will cover all ascii numbers\r\n k = s_index + p_Length - 1; # s_index will be useful on the second call of the function\r\n while k < n: # horspool search starts from here\r\n j = p_Length - 1; i = k;\r\n while j >= 0 and text[i] == pattern[j]:\r\n j -= 1;\r\n i -= 1;\r\n if j == -1:\r\n index_found= i + 1;\r\n k += bmt[ord(text[k])]; # -to here \r\n return index_found;\r\n \r\nstatements = open(\"statements.txt\", \"r\");\r\nfor pattern in statements: # reading line by line with the help of for\r\n starting_index=0;\r\n index_found=-1;\r\n pattern=pattern[:-1];\r\n m=len(pattern);\r\n _index=0; \r\n while _index<m: # brute force \"_\" search\r\n if(pattern[_index]==\"_\"): break;\r\n else: _index+=1; \r\n firstP=pattern[0:_index-1]; # splitting pattern in to two to search them seperately\r\n secondP=pattern[_index+4:m]; \r\n f_Found = bmh(firstP,starting_index); # f_Found is the starting index of the pattern in the text\r\n if(index_found!=-1): # check for whether pattern is in the text or not (probably there is a better way to check this)\r\n starting_index = f_Found + len(firstP) + 4; # setting the index after \"___\" to starting_index \r\n s_Found = bmh(secondP,starting_index); # s_Found is the starting index of the part where starts after \"___\" \r\n print(str(ans_i)+\")\"+pattern); # printing original statements from the source\r\n ans_i+=1; # incrementing answer index\r\n if(index_found!=-1): # checking again :%\r\n print(firstP+text[(f_Found+(len(firstP))):s_Found]+secondP); # printing the firstP + the missing part + secondP\r\n else:\r\n print(\"Statement NOT found\"); # if the pattern is not found index_found wouldn't be changed so..\r\nprint ('The script took {0} second !'.format(time.time() - startTime)); # total execution time\r\n","sub_path":"Horspool's Algorithm.py","file_name":"Horspool's Algorithm.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"127112739","text":"from mesh.standard import bind\nfrom spire.mesh import Definition, MeshDependency\nfrom spire.schema import *\nfrom sqlalchemy.orm.collections import attribute_mapped_collection\n\nfrom flux.bindings import platoon\nfrom flux.constants import *\n\nschema = Schema('flux')\n\nProcess = bind(platoon, 'platoon/1.0/process')\n\nclass Operation(Model):\n \"\"\"A workflow operation.\"\"\"\n\n class meta:\n schema = schema\n tablename = 'operation'\n\n id = Token(segments=2, nullable=False, primary_key=True)\n name = Text(nullable=False)\n phase = Enumeration(OPERATION_PHASES, nullable=False)\n description = Text()\n schema = Definition()\n parameters = Json()\n\n outcomes = relationship('Outcome', backref='operation',\n collection_class=attribute_mapped_collection('name'),\n cascade='all,delete-orphan', passive_deletes=True)\n\n @property\n def queue_id(self):\n return 'flux-operation:%s' % self.id\n\n @classmethod\n def create(cls, session, outcomes, **attrs):\n operation = cls(**attrs)\n\n for name, outcome in outcomes.iteritems():\n outcome = Outcome(name=name, **outcome)\n operation.outcomes[name] = outcome\n\n session.add(operation)\n return operation\n\n def initiate(self, tag, input=None, id=None, timeout=None):\n params = {'queue_id': self.queue_id, 'tag': tag}\n if id is not None:\n params['id'] = id\n if input is not None:\n params['input'] = input\n if timeout is not None:\n params['timeout'] = timeout\n return Process.create(**params)\n\n def update(self, session, outcomes=None, **attrs):\n self.update_with_mapping(**attrs)\n if outcomes is not None:\n collection = self.outcomes\n for name, outcome in outcomes.iteritems():\n if name in collection:\n collection[name].update_with_mapping(outcome)\n else:\n collection[name] = Outcome(name=name, **outcome)\n for name in collection.keys():\n if name not in outcomes:\n del collection[name]\n\nclass Outcome(Model):\n \"\"\"An operation outcome.\"\"\"\n\n class meta:\n constraints = [UniqueConstraint('operation_id', 'name')]\n schema = schema\n tablename = 'outcome'\n\n id = Identifier()\n operation_id = ForeignKey('operation.id', nullable=False, ondelete='CASCADE')\n name = Token(nullable=False)\n description = Text()\n outcome = Enumeration('success failure', nullable=False)\n schema = Definition()\n","sub_path":"flux/models/operation.py","file_name":"operation.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"594394033","text":"import jsonlines\n\n\"\"\"\nProcess the MRP dataset from mrp format to csv format for annotation\n\"\"\"\nmrp_path = '//'\n#the latest mrp processed sentence file .mrp\ninput_file = '../data_annotation/mrp_ucca_no_wsj_2.mrp'\nout_file = open('../data_annotation/data_mrp_ucca_no_wsj_2.csv', 'w')\nout_file.write(f'sent_id\\tsentence\\td-unit\\n')\n\n#process jsonline file format\ntotal = 0\nwith jsonlines.open(mrp_path+input_file) as reader:\n\n for obj in reader:\n\n print(obj['id'] , ' ')\n\n sentence = obj['input']\n # print(obj['nodes'])\n # print(obj['edges'])\n for edge in obj['edges']:\n if edge['label'] == 'D':\n # print(edge)\n source_node =obj['nodes'][edge['source']]\n target_node = obj['nodes'][edge['target']]\n d_unit = \"\"\n if 'anchors' not in target_node:\n while 'anchors' not in target_node:\n #search for the edge whose source is the current target node\n targets = []\n for e in obj['edges']:\n if e['source'] == target_node['id']:\n targets.append(obj['nodes'][e['target']])\n #have list of targets\n # print(targets)\n for t in targets:\n if 'anchors' in t:\n # print(sentence[t['anchors'][0]['from'] :t['anchors'][0]['to']])\n d_unit += sentence[t['anchors'][0]['from'] :t['anchors'][0]['to']]\n d_unit += ' '\n target_node = t\n else:\n target_node = t\n break\n else:\n for anchor in target_node['anchors']:\n # print(sentence[anchor['from'] : anchor['to']])\n d_unit += sentence[anchor['from'] : anchor['to']]\n print(d_unit)\n out_file.write(obj['id'])\n out_file.write(\"\\t\")\n out_file.write(sentence)\n out_file.write(\"\\t\")\n out_file.write(d_unit)\n out_file.write('\\n')\n\n\n\n total+=1\n\n\nprint(\"total:\", total)\n\n","sub_path":"scripts/mrp_process.py","file_name":"mrp_process.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"623409487","text":"\n\"\"\"\nThis module is composed by a group of functions that computes some measures\nin the time-series individually.\n\nTODO\n----\nentropy rate (paper transfer entropy)\n\"\"\"\n\nimport numpy as np\nimport scipy\n\nimport utils\n\n\ndef measure_ts(X, method, **kwargs):\n \"\"\"Function which acts as a switcher and wraps all the possible functions\n related with the measure of a property in a time-series.\n\n Parameters\n ----------\n X: array_like, shape(N, M)\n signals of the elements of the system. They are recorded in N times M\n elements of the system.\n method: str, optional\n possible methods to be used in order to measure some paramter of the\n time series given.\n kwargs: dict\n extra variables to be used in the selected method. It is required that\n the keys match with the correct parameters of the method selected. If\n this is not the case will raise an error.\n\n Returns\n -------\n measure: array_like, shape(M, p)\n is the resultant measure of each time series of the system. The\n selected measure can be a multidimensional measure and returns p values\n for each time series.\n\n \"\"\"\n\n # Switcher\n if method == 'entropy':\n measure = entropy(X, **kwargs)\n elif method == 'hurst':\n measure = hurst(X, **kwargs)\n elif method == 'pfd':\n measure = pfd(X, **kwargs)\n elif method not in ['entropy', 'hurst', 'pfd']:\n pass\n\n return measure\n\n\n###############################################################################\n#################### ENTROPY ##################################################\ndef entropy(X1, base=None):\n \"\"\"Entropy measure of a given time-serie.\n\n References\n ----------\n ..[1] http://orange.biolab.si/blog/2012/06/15/joint-entropy-in-python/\n\n \"\"\"\n\n # Format matrix in order to have a column-format dynamics\n if len(X1.shape) < 2:\n X1 = np.matrix(X1).T\n\n # Initialize variables\n [rows, cols] = X1.shape\n entropies = np.zeros(shape=(cols, 1))\n\n # Calculation of the entropy for each one of the columns\n for i in range(cols):\n X = X1[:, i]\n probs = [np.mean(X == c) for c in set(X)]\n entropies[i] = scipy.stats.entropy(probs, base=base)\n\n return entropies[:, 0]\n\n\n#def shan_entropy(c):\n# c_normalized = c/float(np.sum(c))\n# c_normalized = c_normalized[np.nonzero(c_normalized)]\n# H = -sum(c_normalized* np.log(c_normalized))\n# return H\n#\n## TODEPRECATE\n#def entropy(X1):\n###http://orange.biolab.si/blog/2012/06/15/joint-entropy-in-python/\n# if len(X1.shape)<2:\n# X1 = np.matrix(X1).T\n# [rows, cols] = X1.shape\n# entropies = np.zeros(shape=(cols,1))\n# for i in range(cols):\n# X = X1[:,i]\n# probs = [np.mean(X == c) for c in set(X)]\n# entropies[i] = np.sum(-p * np.log2(p) for p in probs)\n# #print entropies\n# return entropies\n#\n## FASTER Possible alternative\n#def entropy2(X1, base = None):\n###http://orange.biolab.si/blog/2012/06/15/joint-entropy-in-python/\n# if len(X1.shape)<2:\n# X1 = np.matrix(X1).T\n# [rows, cols] = X1.shape\n# entropies = np.zeros(shape=(cols,1))\n# for i in range(cols):\n# X = X1[:,i]\n# probs = np.histogram(X, bins = len(set(X)) ,density=True)[0]\n# entropies[i] = scipy.stats.entropy(probs, base=base)\n# return entropies\n\n\n###############################################################################\n#################### HURST ####################################################\ndef hurst(X):\n \"\"\"Compute the Hurst exponent of X. If the output H = 0.5, the behavior of\n the time-series is similar to random walk. If H<0.5, the time-series cover\n less \"distance\" than a random walk, viceversa.\n\n Parameters\n ----------\n X : array_like, shape(N,)\n a 1-D real time series.\n\n Returns\n -------\n H : float\n Hurst exponent\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.random.randn(4096)\n >>> hurst(a)\n 0.5057444\n\n References\n ----------\n .. [1] Hurst, H.E. (1951). Trans. Am. Soc. Civ. Eng. 116: 770.\n .. [2] Hurst, H.E.; Black, R.P.; Simaika, Y.M. (1965). Long-term storage:\n an experimental study. London: Constable.\n .. [3] Mandelbrot, Benoit B., The (Mis)Behavior of Markets, A Fractal View\n of Risk, Ruin and Reward (Basic Books, 2004), pp. 186-195\n\n Code\n ----\n [.] Code in Matlab\n http://www.mathworks.com/matlabcentral/fileexchange/\n 19148-hurst-parameter-estimate\n [.] Code in Python\n http://www.drtomstarke.com/index.php/calculation-of-the-hurst-exponent-\n to-test-for-trend-and-mean-reversion\n [.] Code in R\n https://r-forge.r-project.org/scm/viewvc.php/pkg/PerformanceAnalytics/R\n /HurstIndex.R?view=markup&root=returnanalytics\n\n Applications\n ------------\n Finance, neuro, ...\n\n Improvements\n ------------\n - Fit the powerlaw in a likehood way.\n ..[-] Clauset, Cosma Rohilla Shalizi, M. E. J. Newman (2009).\n \"Power-law distributions in empirical data\". SIAM Review 51: 661-703\n - ...\n\n \"\"\"\n # Initialization\n N = X.shape[0]\n T = np.linspace(1, N, N)\n CS_X = np.cumsum(X)\n Ave_T = CS_X/T\n\n # Initialazing vectors\n S_T = np.zeros((N))\n R_T = np.zeros((N))\n\n # Compute for each point in the serie the accumulate value of\n # std and range in order to get this values with different sample size\n for i in xrange(N):\n # Std vector calculation\n S_T[i] = np.std(X[:i+1])\n # Vector of range between trend in i and in the rest of the TS\n X_T = CS_X - T * Ave_T[i]\n R_T[i] = np.max(X_T[:i + 1]) - np.min(X_T[:i + 1])\n # Logaritmic ratio of max difference with and std\n R_S = R_T / S_T\n R_S = np.log(R_S)\n\n # Compute the log TS\n n = np.log(T).reshape(N, 1)\n\n # Fitting the linear regression by least squares\n H = np.linalg.lstsq(n[1:], R_S[1:])[0]\n return H[0]\n\n###############################################################################\n\n\n###############################################################################\n#################### pfd ####################################################\ndef pfd(X):\n \"\"\"Compute Petrosian Fractal Dimension of a time series.\n\n Parameters\n ----------\n X : array_like, shape(N,)\n a 1-D real time series.\n\n Returns\n -------\n Pfd : float\n Petrosian Fractal dimension of the time series.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.random.randn(4096)\n >>> pfd(a)\n\n References\n ----------\n .. [1] A. Petrosian, \"Kolmogorov complexity of finite sequences and\n recognition of different preictal EEG patterns,\" in Proceedings of 8th\n IEEE Symposium on Computer-Based Medical Systems, 1995.\n\n \"\"\"\n\n # Compute First order difference\n D = np.diff(X)\n # number of sign changes in derivative of the signal\n N_delta = 0\n for i in xrange(1, D.shape[0]):\n if D[i]*D[i-1] < 0:\n N_delta += 1\n n = X.shape[0]\n Pfd = np.log10(n)/(np.log10(n)+np.log10(n/n+0.4*N_delta))\n return Pfd\n\n###############################################################################\n\n\n###############################################################################\n###################### hfd ####################################################\ndef hfd(X, kMax=0):\n \"\"\"Compute Higuchi's Fractal Dimension of a time series X.\n\n Parameters\n ----------\n X : array_like, shape(N,)\n a 1-D real time series.\n\n Returns\n -------\n Pfd : float\n Petrosian Fractal dimension of the time series.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.random.randn(4096)\n >>> hfd(a)\n\n References\n ----------\n .. [1] Higuchi, T.: Approach to an irregular time series on the basics of\n the fractal theory. Physica D: Nonlinear Phenomena 31(2), 277-283 (1988)\n .. [2] Wang, Q., Sourina, O., Nguyen, M.K.: Fractal dimension based\n algorithm for neurofeedback games. In: Proc. CGI 2010, Singapore,\n p. SP25 (2010) p. 5\n\n \"\"\"\n\n # Set to default value kMax based on ref [2]\n if kMax == 0:\n kMax = 2 ** (np.log2(X.shape[0]) - 4)\n\n L = np.zeros((kMax, 1))\n x = np.zeros((kMax, 2))\n N = X.shape[0]\n # Loop for all the sizes of kMax\n for k in xrange(1, kMax):\n Lk = np.zeros(k)\n for m in xrange(0, k):\n Lmk = 0\n for i in xrange(1, int(np.floor((N-m)/k))):\n Lmk += abs(X[m+i*k] - X[m+i*k-k])\n Lmk = Lmk*(N - 1)/np.floor((N - m)/float(k))/k\n Lk[m] = Lmk\n L[k] = np.log(np.mean(Lk))\n x[k, :] = np.array([np.log(float(1) / k), 1])\n\n (p, r1, r2, s) = np.linalg.lstsq(x, L)\n return p[0][0]\n\n\n###############################################################################\n###################### Hjorth mobility ########################################\ndef hjorth(X):\n \"\"\" Compute Hjorth mobility and complexity of a time series.\n\n Notes\n -----\n To speed up, it is recommended to compute D before calling this function\n because D may also be used by other functions whereas computing it here\n again will slow down.\n\n Parameters\n ----------\n X : array_like, shape(N,)\n a 1-D real time series.\n\n Returns\n -------\n HM : float\n Hjorth mobility\n Comp : float\n Hjorth complexity\n\n References\n ----------\n .. [1] B. Hjorth, \"EEG analysis based on time domain properties,\"\n Electroencephalography and Clinical Neurophysiology , vol. 29,\n pp. 306-310, 1970.\n \"\"\"\n\n # Compute the first order difference\n D = np.diff(X)\n # pad the first difference\n D = np.hstack([X[0], D])\n\n #\n n = X.shape[0]\n M2 = np.float(np.sum(D ** 2))/n\n TP = np.sum(X ** 2)\n M4 = np.sum((D[1:] - D[:D.shape[0]-1])**2)/n\n\n # Hjorth Mobility and Complexity\n HM = np.sqrt(M2 / TP)\n Comp = np.sqrt(np.float(M4) * TP / M2 / M2)\n\n return HM, Comp\n\n\n###############################################################################\n########################## Svd Entropy ########################################\ndef svd_entropy(X, tau=1, D=1):\n \"\"\"Compute SVD Entropy from time series.\n\n Notes\n -------------\n \"\"\"\n\n # Substitute to a function.\n Y = utils.sliding_embeded_transf(X, tau, D)\n\n # Singular value descomposition\n W = np.linalg.svd(Y, compute_uv=0)\n\n # Normalize singular values\n W /= np.sum(W)\n\n # Compute entropy of svd\n H_svd = - np.sum(W * np.log(W))\n\n return H_svd\n\n\n###############################################################################\n########################## Spectral Entropy ###################################\ndef spectral_entropy(X, bins=50):\n \"\"\"Compute spectral entropy of a time series. Spectral entropy is the\n entropy associated to the entropy in the distribution of the power of a\n time series between its frequency spectrum space.\n\n Parameters\n ----------\n X : array_like, shape(N,)\n a 1-D real time series.\n bins : int\n number of bins in which we want to discretize the frequency spectrum\n space in order to compute the entropy.\n\n Returns\n -------\n H_sp : float\n Spectral entropy\n\n TODO:\n ----\n Fs and its influence in the entropy. And part of the entropy dividing.\n Dependent on the number of bins!!!!!!!!!!!!!!!!\n \"\"\"\n # Power spectral\n ps = np.abs(np.fft.fft(X))**2\n # binning:\n psd, freq = np.histogram(ps, bins, normed=True)\n # Compute entropy (?)\n H_sp = - np.sum(psd * np.log2(psd+1e-16))/np.log2(psd.shape[0])\n return H_sp\n\n\n###############################################################################\n########################## Fisher information #################################\ndef fisher_info(X, tau, D):\n \"\"\" Compute Fisher information of a time series.\n\n Parameters\n ----------\n X : array_like, shape(N,)\n a 1-D real time series.\n tau : integer\n the lag or delay when building a embedding sequence. tau will be used\n to build embedding matrix and compute singular values.\n D : integer\n the embedding dimension to build an embedding matrix from a given\n series. DE will be used to build embedding matrix and compute\n singular values if W or M is not provided.\n\n Returns\n -------\n FI : integer\n Fisher information\n\n \"\"\"\n\n # Substitute to a function.\n Y = utils.sliding_embeded_transf(X, tau, D)\n # Singular value descomposition\n W = np.linalg.svd(Y, compute_uv=0)\n # Compute Fisher information\n FI = np.sum((W[1:] - W[:W.shape[0]-1])**2)/W[:W.shape[0]-1]\n FI = FI[0]\n return FI\n\n\n###############################################################################\n########################## Fisher information #################################\ndef dfa(X):\n \"\"\"Compute Detrended Fluctuation Analysis from a time series X. There is\n an adaptation function of the one provided in pyEGG.\n\n The first step to compute DFA is to integrate the signal. Let original\n series be X= [x(1), x(2), ..., x(N)].\n The integrated signal Y = [y(1), y(2), ..., y(N)] is obtained as follows\n y(k) = \\sum_{i=1}^{k}{x(i)-Ave} where Ave is the mean of X.\n\n The second step is to partition/slice/segment the integrated sequence Y\n into boxes. At least two boxes are needed for computing DFA. Box sizes are\n specified by the L argument of this function. By default, it is from 1/5 of\n signal length to one (x-5)-th of the signal length, where x is the nearest\n power of 2 from the length of the signal, i.e., 1/16, 1/32, 1/64, 1/128,...\n In each box, a linear least square fitting is employed on data in the box.\n Denote the series on fitted line as Yn. Its k-th elements, yn(k),\n corresponds to y(k).\n\n For fitting in each box, there is a residue, the sum of squares of all\n offsets, difference between actual points and points on fitted line.\n F(n) denotes the square root of average total residue in all boxes when box\n length is n, thus\n Total_Residue = \\sum_{k=1}^{N}{(y(k)-yn(k))}\n F(n) = \\sqrt(Total_Residue/N)\n The computing to F(n) is carried out for every box length n. Therefore, a\n relationship between n and F(n) can be obtained. In general, F(n) increases\n when n increases.\n\n Finally, the relationship between F(n) and n is analyzed. A least square\n fitting is performed between log(F(n)) and log(n). The slope of the fitting\n line is the DFA value, denoted as Alpha. To white noise, Alpha should be\n 0.5. Higher level of signal complexity is related to higher Alpha.\n\n Parameters\n ----------\n X: array_like, shape(N,)\n a time series\n Ave: integer, optional\n The average value of the time series\n L: 1-D Python list of integers\n A list of box size, integers in ascending order\n\n Returns\n -------\n Alpha : integer\n the result of DFA analysis, thus the slope of fitting line of log(F(n))\n vs. log(n).\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.random.randn(4096)\n >>> dfa(a)\n 0.490035110345\n\n Reference\n ---------\n .. [1] Peng C-K, Havlin S, Stanley HE, Goldberger AL. Quantification of\n scaling exponents and crossover phenomena in nonstationary heartbeat\n time series. _Chaos_ 1995;5:82-87\n .. [2] http://www.physionet.org/tutorials/fmnc/node5.html\n\n Notes\n -----\n This value depends on the box sizes very much. When the input is a white\n noise, this value should be 0.5. But, some choices on box sizes can lead to\n the value lower or higher than 0.5, e.g. 0.38 or 0.58.\n\n Based on many test, I set the box sizes from 1/5 of signal length to one\n (x-5)-th of the signal length, where x is the nearest power of 2 from the\n length of the signal, i.e., 1/16, 1/32, 1/64, 1/128, ...\n \"\"\"\n\n ## 1. Compute values\n # Size X\n N_X = X.shape[0]\n # Compute mean\n Ave = np.mean(X)\n # Integrate of the signal\n Y = np.cumsum(X)\n Y -= Ave\n # Compute an array of box size (integers) in ascending order reducing box\n # size dependant as it is explained in the Notes\n L = np.floor(X.shape[0]*1/(2**np.array(range(4, int(np.log2(N_X))-4))))\n if np.all(L != 0):\n raise Exception(\"Too big box for the given time series.\")\n\n # F(n) of different given box length n\n F = np.zeros(L.shape[0])\n for i in xrange(L.shape[0]):\n # for each box length L[i]\n n = int(L[i])\n # for each box\n for j in xrange(0, N_X, n):\n if j+n < N_X:\n c = range(j, j+n)\n # coordinates of time in the box\n c = np.vstack([c, np.ones(n)]).T\n # the value of data in the box\n y = Y[j:j+n]\n # add residue in this box\n F[i] += np.linalg.lstsq(c, y)[1]\n F[i] /= ((N_X/n)*n)\n F = np.sqrt(F)\n\n # Computation of alpha\n Alpha = np.linalg.lstsq(np.vstack([np.log(L),\n np.ones(L.shape[0])]).T,\n np.log(F))[0][0]\n return Alpha\n","sub_path":"TimeSeriesTools/Measures/measures.py","file_name":"measures.py","file_ext":"py","file_size_in_byte":17236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"455718837","text":"\n'''\nAuthor : acidlab.help@gmail.com\nTitle : DCGall.py\n'''\nfrom bs4 import BeautifulSoup\nimport requests\nimport datetime\nimport os\n\nclass PostWork:\n def __init__(self):\n self.gallList = {\n # 다른 갤러리에 적용시 추가\n 'Gitadora' : 'https://gall.dcinside.com/mgallery/board/view/?id=gitadora&no=',\n }\n self.postList = {\n # 다른 게시물을 활용할 경우 추가\n 'Shinmungo' : '104842',\n 'test' : '10761',\n }\n self.postInfo = {\n # 필요한 정보 추가\n 1 : '댓글 ',\n 2 : '추천 ',\n 3 : '조회 ',\n }\n\n def getUrlByParam(self, gall, param):\n if type(param) is str:\n return self.gallList[gall] + self.postList[param]\n else:\n return False\n\n def getUrl(self, _url):\n return _url\n\n def getGallData(self, url):\n try:\n user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'\n headers = {'User-Agent': user_agent}\n response = requests.get(url,headers=headers)\n html = response.content\n return BeautifulSoup(html, 'html.parser')\n except Exception as e:\n return False\n\n def checkCount(self, data, case):\n # _case = {1 : '댓글 ', 2: '추천 ', 3: '조회 '}\n if data is False:\n return False\n else:\n if case is 1:\n parsedReply = str(data.find('span', {'class' : 'gall_comment'}))\n elif case is 2:\n parsedReply = str(data.find('span', {'class' : 'gall_reply_num'}))\n elif case is 3:\n parsedReply = str(data.find('span', {'class' : 'gall_count'}))\n \n pos = [parsedReply.find(self.postInfo[case]) + len(self.postInfo[case]),\n parsedReply.find('</span>')]\n return int(parsedReply[pos[0]:pos[1]])\n \n def saveDocument(self, data, misc):\n if data is False:\n return False\n else:\n # WIndows 환경에서 ':' 문자 파일명 허용 안 됨.\n timeStamp = str(datetime.datetime.now()).replace(' ','_').replace(':','-').replace('.','-')\n dirName = 'DCGall_' + timeStamp\n docInfo = [ (data.find('span', {'class' : 'title_subject'})),\n (data.find('span', {'class' : 'nickname in'})),\n (data.find('div', {'style' : 'overflow:hidden;'})),\n ]\n try:\n if not(os.path.isdir(dirName)):\n os.makedirs(os.path.join(dirName))\n except OSError as e:\n print(\"Failed to create directory\")\n raise\n os.chdir('./'+dirName)\n targetFile = open(timeStamp+'.html', 'w')\n try:\n for info in docInfo:\n targetFile.write(str(info)+'<br>')\n except Exception as e:\n targetFile.write(e+'<br>')\n finally:\n targetFile.close()\n\n if misc is True: # 현재 작동안함\n images = [x['src'] for x in data.find('div', {'class' : 'writing_view_box'}).find_all('img')]\n try:\n for image in images:\n fileName = str(datetime.datetime.now()).replace(' ','_').replace(':','-').replace('.','-')+'.jpg'\n with open(fileName, \"wb\") as file:\n print(image)\n getFile = requests.get(image)\n file.write(getFile.content)\n except Exception as e:\n print('saveDocument :: failed to get Images')\n return False\n print('saveDocument :: Success')\n os.chdir('../')","sub_path":"DCGall.py","file_name":"DCGall.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"283789076","text":"import pandas as pd \nfrom datetime import date\nimport numpy as np\n\ndates = pd.date_range(start='2019-08-01', end = '2020-05-01', freq='D').values\ndates = [str(x)[0:10] for x in dates]\n\n############## Adelaide ################\na1 = pd.read_csv('Datasets/Adelaide/adelaide-cbd, australia-air-quality.csv')\na1['date'] = pd.to_datetime(a1['date'])\na1.set_index('date', inplace = True)\na1 = a1[a1[' co']!=' ']\n\na2 = pd.read_csv('Datasets/Adelaide/north-western adelaide le fevre 1, australia-air-quality.csv')\na2['date'] = pd.to_datetime(a2['date'])\na2.set_index('date', inplace = True)\na2 = a2[a2[' co']!=' ']\n\na3 = pd.read_csv('Datasets/Adelaide/southern-adelaide christies, australia-air-quality.csv')\na3['date'] = pd.to_datetime(a3['date'])\na3.set_index('date', inplace = True)\na3 = a3[a3[' co']!=' ']\n\na4 = pd.read_csv('Datasets/Adelaide/western-adelaide netley, australia-air-quality.csv')\na4['date'] = pd.to_datetime(a4['date'])\na4.set_index('date', inplace = True)\na4 = a4[a4[' co']!=' ']\n\na_dict = {}\nfor date in dates:\n\tc, t1, t2, t3, t4 = 0, 0, 0, 0, 0\n\tif date in a1.index:\n\t\tt1 = int(a1.loc[date,' co'])\n\t\tc +=1\n\tif date in a2.index:\n\t\tt2 = int(a2.loc[date,' co'])\n\t\tc+=1\n\tif date in a3.index:\n\t\tt3 = int(a3.loc[date,' co'])\n\t\tc+=1\n\tif date in a4.index:\n\t\tt4 = int(a4.loc[date,' co'])\n\t\tc+=1\n\tif c ==0:\n\t\ta_dict[date]= None \n\tif c !=0:\n\t\ta_dict[date]= (t1+t2+t3+t4)/c\n\n############## Brisbane ################\nb1 = pd.read_csv('Datasets/Brisbane/brisbane-cbd, australia-air-quality.csv')\nb1['date'] = pd.to_datetime(b1['date'])\nb1.set_index('date', inplace = True)\nb1 = b1[b1[' co']!=' ']\n\nb2 = pd.read_csv('Datasets/Brisbane/cannon-hill, australia-air-quality.csv')\nb2['date'] = pd.to_datetime(b2['date'])\nb2.set_index('date', inplace = True)\nb2 = b2[b2[' co']!=' ']\n\nb3 = pd.read_csv('Datasets/Brisbane/lytton,-australia-air-quality.csv')\nb3['date'] = pd.to_datetime(b3['date'])\nb3.set_index('date', inplace = True)\nb3 = b3[b3[' co']!=' ']\n\nb4 = pd.read_csv('Datasets/Brisbane/rocklea,-australia-air-quality.csv')\nb4['date'] = pd.to_datetime(b4['date'])\nb4.set_index('date', inplace = True)\nb4 = b4[b4[' co']!=' ']\n\nb5 = pd.read_csv('Datasets/Brisbane/south-brisbane, australia-air-quality.csv')\nb5['date'] = pd.to_datetime(b5['date'])\nb5.set_index('date', inplace = True)\nb5 = b5[b5[' co']!=' ']\n\nb6 = pd.read_csv('Datasets/Brisbane/springwood,-australia-air-quality.csv')\nb6['date'] = pd.to_datetime(b6['date'])\nb6.set_index('date', inplace = True)\nb6 = b6[b6[' co']!=' ']\n\nb7 = pd.read_csv('Datasets/Brisbane/woolloongabba,-australia-air-quality.csv')\nb7['date'] = pd.to_datetime(b7['date'])\nb7.set_index('date', inplace = True)\nb7 = b7[b7[' co']!=' ']\n\nb8 = pd.read_csv('Datasets/Brisbane/wynnum-west, australia-air-quality.csv')\nb8['date'] = pd.to_datetime(b8['date'])\nb8.set_index('date', inplace = True)\nb8 = b8[b8[' co']!=' ']\n\nb9 = pd.read_csv('Datasets/Brisbane/wynnum,-australia-air-quality.csv')\nb9['date'] = pd.to_datetime(b9['date'])\nb9.set_index('date', inplace = True)\nb9 = b9[b9[' co']!=' ']\n\nb_dict = {}\nfor date in dates:\n\tc, t1, t2, t3, t4, t5, t6, t7, t8, t9 = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\tif date in b1.index:\n\t\tt1 = int(b1.loc[date,' co'])\n\t\tc +=1\n\tif date in b2.index:\n\t\tt2 = int(b2.loc[date,' co'])\n\t\tc+=1\n\tif date in b3.index:\n\t\tt3 = int(b3.loc[date,' co'])\n\t\tc+=1\n\tif date in b4.index:\n\t\tt4 = int(b4.loc[date,' co'])\n\t\tc+=1\n\tif date in b5.index:\n\t\tt5 = int(b5.loc[date,' co'])\n\t\tc+=1\n\tif date in b6.index:\n\t\tt6 = int(b6.loc[date,' co'])\n\t\tc+=1\n\tif date in b7.index:\n\t\tt7 = int(b7.loc[date,' co'])\n\t\tc+=1\n\tif date in b8.index:\n\t\tt8 = int(b8.loc[date,' co'])\n\t\tc+=1\n\tif date in b9.index:\n\t\tt9 = int(b9.loc[date,' co'])\n\t\tc+=1\n\tif c ==0:\n\t\tb_dict[date]= None \n\tif c !=0:\n\t\tb_dict[date]= (t1+t2+t3+t4+t5+t6+t7+t8+t9)/c\n\n############## Melbourne ################\nm1 = pd.read_csv('Datasets/Melbourne/alphington,-australia-air-quality.csv')\nm1['date'] = pd.to_datetime(m1['date'])\nm1.set_index('date', inplace = True)\nm1 = m1[m1[' co']!=' ']\n\nm2 = pd.read_csv('Datasets/Melbourne/box-hill, australia-air-quality.csv')\nm2['date'] = pd.to_datetime(m2['date'])\nm2.set_index('date', inplace = True)\nm2 = m2[m2[' co']!=' ']\n\nm3 = pd.read_csv('Datasets/Melbourne/brighton,-australia-air-quality.csv')\nm3['date'] = pd.to_datetime(m3['date'])\nm3.set_index('date', inplace = True)\nm3 = m3[m3[' co']!=' ']\n\nm4 = pd.read_csv('Datasets/Melbourne/brooklyn,-australia-air-quality.csv')\nm4['date'] = pd.to_datetime(m4['date'])\nm4.set_index('date', inplace = True)\nm4 = m4[m4[' co']!=' ']\n\nm5 = pd.read_csv('Datasets/Melbourne/campbellfield-air-quality.csv')\nm5['date'] = pd.to_datetime(m5['date'])\nm5.set_index('date', inplace = True)\nm5 = m5[m5[' co']!=' ']\n\nm6 = pd.read_csv('Datasets/Melbourne/dallas,-australia-air-quality.csv')\nm6['date'] = pd.to_datetime(m6['date'])\nm6.set_index('date', inplace = True)\nm6 = m6[m6[' co']!=' ']\n\nm7 = pd.read_csv('Datasets/Melbourne/dandenong,-australia-air-quality.csv')\nm7['date'] = pd.to_datetime(m7['date'])\nm7.set_index('date', inplace = True)\nm7 = m7[m7[' co']!=' ']\n\nm8 = pd.read_csv('Datasets/Melbourne/footscray,-australia-air-quality.csv')\nm8['date'] = pd.to_datetime(m8['date'])\nm8.set_index('date', inplace = True)\nm8 = m8[m8[' co']!=' ']\n\nm9 = pd.read_csv('Datasets/Melbourne/macleod,-australia-air-quality.csv')\nm9['date'] = pd.to_datetime(m9['date'])\nm9.set_index('date', inplace = True)\nm9 = m9[m9[' co']!=' ']\n\nm10 = pd.read_csv('Datasets/Melbourne/melbourne-cbd, australia-air-quality.csv')\nm10['date'] = pd.to_datetime(m10['date'])\nm10.set_index('date', inplace = True)\nm10 = m10[m10[' co']!=' ']\n\nm11 = pd.read_csv('Datasets/Melbourne/pt.-cook, australia-air-quality.csv')\nm11['date'] = pd.to_datetime(m11['date'])\nm11.set_index('date', inplace = True)\nm11 = m11[m11[' co']!=' ']\n\nm_dict = {}\nfor date in dates:\n\tc, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11 = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\tif date in m1.index:\n\t\tt1 = int(m1.loc[date,' co'])\n\t\tc +=1\n\tif date in m2.index:\n\t\tt2 = int(m2.loc[date,' co'])\n\t\tc+=1\n\tif date in m3.index:\n\t\tt3 = int(m3.loc[date,' co'])\n\t\tc+=1\n\tif date in m4.index:\n\t\tt4 = int(m4.loc[date,' co'])\n\t\tc+=1\n\tif date in m5.index:\n\t\tt5 = int(m5.loc[date,' co'])\n\t\tc+=1\n\tif date in m6.index:\n\t\tt6 = int(m6.loc[date,' co'])\n\t\tc+=1\n\tif date in m7.index:\n\t\tt7 = int(m7.loc[date,' co'])\n\t\tc+=1\n\tif date in m8.index:\n\t\tt8 = int(m8.loc[date,' co'])\n\t\tc+=1\n\tif date in m9.index:\n\t\tt9 = int(m9.loc[date,' co'])\n\t\tc+=1\n\tif date in m10.index:\n\t\tt10 = int(m10.loc[date,' co'])\n\t\tc+=1\n\tif date in m11.index:\n\t\tt11 = int(m11.loc[date,' co'])\n\t\tc+=1\n\tif c ==0:\n\t\tm_dict[date]= None \n\tif c !=0:\n\t\tm_dict[date]= (t1+t2+t3+t4+t5+t6+t7+t8+t9+t10+t11)/c\n\n\n############## Perth ################\np1 = pd.read_csv('Datasets/Perth/caversham,-australia-air-quality.csv')\np1['date'] = pd.to_datetime(p1['date'])\np1.set_index('date', inplace = True)\np1 = p1[p1[' co']!=' ']\n\np2 = pd.read_csv('Datasets/Perth/duncraig,-australia-air-quality.csv')\np2['date'] = pd.to_datetime(p2['date'])\np2.set_index('date', inplace = True)\np2 = p2[p2[' co']!=' ']\n\np3 = pd.read_csv('Datasets/Perth/quinns-rocks, australia-air-quality.csv')\np3['date'] = pd.to_datetime(p3['date'])\np3.set_index('date', inplace = True)\np3 = p3[p3[' co']!=' ']\n\np4 = pd.read_csv('Datasets/Perth/south-lake, australia-air-quality.csv')\np4['date'] = pd.to_datetime(p4['date'])\np4.set_index('date', inplace = True)\np4 = p4[p4[' co']!=' ']\n\np_dict = {}\nfor date in dates:\n\tc, t1, t2, t3, t4 = 0, 0, 0, 0, 0\n\tif date in p1.index:\n\t\tt1 = int(p1.loc[date,' co'])\n\t\tc +=1\n\tif date in p2.index:\n\t\tt2 = int(p2.loc[date,' co'])\n\t\tc+=1\n\tif date in p3.index:\n\t\tt3 = int(p3.loc[date,' co'])\n\t\tc+=1\n\tif date in p4.index:\n\t\tt4 = int(p4.loc[date,' co'])\n\t\tc+=1\n\tif c ==0:\n\t\tp_dict[date]= None \n\tif c !=0:\n\t\tp_dict[date]= (t1+t2+t3+t4)/c\n\n############## Sydney ################\ns1 = pd.read_csv('Datasets/Sydney/bargo-sydney south-west, australia-air-quality.csv')\ns1['date'] = pd.to_datetime(s1['date'])\ns1.set_index('date', inplace = True)\ns1 = s1[s1[' co']!=' ']\n\ns2 = pd.read_csv('Datasets/Sydney/bringelly-sydney south-west, australia-air-quality.csv')\ns2['date'] = pd.to_datetime(s2['date'])\ns2.set_index('date', inplace = True)\ns2 = s2[s2[' co']!=' ']\n\ns3 = pd.read_csv('Datasets/Sydney/camden-sydney south-west, australia-air-quality.csv')\ns3['date'] = pd.to_datetime(s3['date'])\ns3.set_index('date', inplace = True)\ns3 = s3[s3[' co']!=' ']\n\ns4 = pd.read_csv('Datasets/Sydney/chullora-sydney east, australia-air-quality.csv')\ns4['date'] = pd.to_datetime(s4['date'])\ns4.set_index('date', inplace = True)\ns4 = s4[s4[' co']!=' ']\n\ns5 = pd.read_csv('Datasets/Sydney/cook-and phillip sydney east, australia-air-quality.csv')\ns5['date'] = pd.to_datetime(s5['date'])\ns5.set_index('date', inplace = True)\ns5 = s5[s5[' co']!=' ']\n\ns6 = pd.read_csv('Datasets/Sydney/earlwood-sydney east, australia-air-quality.csv')\ns6['date'] = pd.to_datetime(s6['date'])\ns6.set_index('date', inplace = True)\ns6 = s6[s6[' co']!=' ']\n\ns7 = pd.read_csv('Datasets/Sydney/liverpool-sydney south-west, australia-air-quality.csv')\ns7['date'] = pd.to_datetime(s7['date'])\ns7.set_index('date', inplace = True)\ns7 = s7[s7[' co']!=' ']\n\ns8 = pd.read_csv('Datasets/Sydney/macquarie-park sydney east, australia-air-quality.csv')\ns8['date'] = pd.to_datetime(s8['date'])\ns8.set_index('date', inplace = True)\ns8 = s8[s8[' co']!=' ']\n\ns9 = pd.read_csv('Datasets/Sydney/north-parramatta sydney north-west, australia-air-quality.csv')\ns9['date'] = pd.to_datetime(s9['date'])\ns9.set_index('date', inplace = True)\ns9 = s9[s9[' co']!=' ']\n\ns10 = pd.read_csv('Datasets/Sydney/prospect-sydney north-west, australia-air-quality.csv')\ns10['date'] = pd.to_datetime(s10['date'])\ns10.set_index('date', inplace = True)\ns10 = s10[s10[' co']!=' ']\n\ns11 = pd.read_csv('Datasets/Sydney/randwick-sydney east, australia-air-quality.csv')\ns11['date'] = pd.to_datetime(s11['date'])\ns11.set_index('date', inplace = True)\ns11 = s11[s11[' co']!=' ']\n\ns12 = pd.read_csv('Datasets/Sydney/richmond-sydney north-west, australia-air-quality.csv')\ns12['date'] = pd.to_datetime(s12['date'])\ns12.set_index('date', inplace = True)\ns12 = s12[s12[' co']!=' ']\n\ns13 = pd.read_csv('Datasets/Sydney/rouse-hill sydney north-west, australia-air-quality.csv')\ns13['date'] = pd.to_datetime(s13['date'])\ns13.set_index('date', inplace = True)\ns13 = s13[s13[' co']!=' ']\n\ns14 = pd.read_csv('Datasets/Sydney/rozelle-sydney east, australia-air-quality.csv')\ns14['date'] = pd.to_datetime(s14['date'])\ns14.set_index('date', inplace = True)\ns14 = s14[s14[' co']!=' ']\n\ns15 = pd.read_csv('Datasets/Sydney/st-marys sydney north-west, australia-air-quality.csv')\ns15['date'] = pd.to_datetime(s15['date'])\ns15.set_index('date', inplace = True)\ns15 = s15[s15[' co']!=' ']\n\ns_dict = {}\nfor date in dates:\n\tc, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15 = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\tif date in s1.index:\n\t\tt1 = int(s1.loc[date,' co'])\n\t\tc +=1\n\tif date in s2.index:\n\t\tt2 = int(s2.loc[date,' co'])\n\t\tc+=1\n\tif date in s3.index:\n\t\tt3 = int(s3.loc[date,' co'])\n\t\tc+=1\n\tif date in s4.index:\n\t\tt4 = int(s4.loc[date,' co'])\n\t\tc+=1\n\tif date in s5.index:\n\t\tt5 = int(s5.loc[date,' co'])\n\t\tc+=1\n\tif date in s6.index:\n\t\tt6 = int(s6.loc[date,' co'])\n\t\tc+=1\n\tif date in s7.index:\n\t\tt7 = int(s7.loc[date,' co'])\n\t\tc+=1\n\tif date in s8.index:\n\t\tt8 = int(s8.loc[date,' co'])\n\t\tc+=1\n\tif date in s9.index:\n\t\tt9 = int(s9.loc[date,' co'])\n\t\tc+=1\n\tif date in s10.index:\n\t\tt10 = int(s10.loc[date,' co'])\n\t\tc+=1\n\tif date in s11.index:\n\t\tt11 = int(s11.loc[date,' co'])\n\t\tc+=1\n\tif date in s12.index:\n\t\tt12 = int(s12.loc[date,' co'])\n\t\tc+=1\n\tif date in s13.index:\n\t\tt13 = int(s13.loc[date,' co'])\n\t\tc+=1\n\tif date in s14.index:\n\t\tt14 = int(s14.loc[date,' co'])\n\t\tc+=1\n\tif date in s15.index:\n\t\tt15 = int(s15.loc[date,' co'])\n\t\tc+=1\n\tif c ==0:\n\t\ts_dict[date]= None \n\tif c !=0:\n\t\ts_dict[date]= (t1+t2+t3+t4+t5+t6+t7+t8+t9+t10+t11+t12+t13+t14+t15)/c\n\n########### Dataframe Creation ############\noutput_df = pd.DataFrame(index = dates)\noutput_df['Adelaide'] = a_dict.values()\noutput_df['Brisbane'] = b_dict.values()\noutput_df['Melbourne'] = m_dict.values()\noutput_df['Perth'] = p_dict.values()\noutput_df['Sydney'] = s_dict.values()\n\noutput_df.to_csv('Datasets/Average_co.csv')\n\n\n\n\n","sub_path":"Code/Australian Code (Early)/Merger_co.py","file_name":"Merger_co.py","file_ext":"py","file_size_in_byte":12221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"154519541","text":"# Imports\nimport os\nimport glob\nimport numpy as np\nfrom tensorflow import keras\nimport tensorflow.keras.layers as layers\nimport tensorflow as tf\n\n\nimport urllib.request\nimport matplotlib.pyplot as plt\nfrom random import randint\n\n\n# change calues only here\n__max_item_per_class__ = 30000\n__epoch__ = 15\n\n\n# Download the dataset\ndef download():\n base = 'https://storage.googleapis.com/quickdraw_dataset/full/numpy_bitmap/'\n for c in classes:\n cls_url = c.replace('_', '%20')\n path = base+cls_url+'.npy'\n print(path)\n urllib.request.urlretrieve(path, './data/'+c+'.npy')\n\n\n# Load the data\n# root = directory of npy files\n# vfold_ratio = percentage of validation data\n# max_items_per_class = number of training data + validation data\ndef load_data(root, vfold_ratio=0.2, max_items_per_class=__max_item_per_class__):\n all_files = glob.glob(os.path.join(root, '*.npy'))\n\n # Initialize variables\n x = np.empty([0, 784])\n y = np.empty([0])\n class_names = []\n\n # Load each data file\n for idx, file in enumerate(all_files):\n # print(\"reading file: \", idx, \" \", file)\n data = np.load(file)\n data = data[0: max_items_per_class, :]\n labels = np.full(data.shape[0], idx)\n\n x = np.concatenate((x, data), axis=0)\n y = np.append(y, labels)\n\n class_name, ext = os.path.splitext(os.path.basename(file))\n class_names.append(class_name)\n\n # Randomize the dataset\n permutation = np.random.permutation(y.shape[0])\n x = x[permutation, :]\n y = y[permutation]\n\n # Separate into training and testing\n vfold_size = int(x.shape[0] / 100 * (vfold_ratio * 100))\n\n # x_test = image data for validation set\n # y_test = label of image for validation set\n x_test = x[0:vfold_size, :]\n y_test = y[0:vfold_size]\n\n # x_train = image data for training set\n # y_train = label of image for training set\n x_train = x[vfold_size:x.shape[0], :]\n y_train = y[vfold_size:y.shape[0]]\n return x_train, y_train, x_test, y_test, class_names\n\n\n# Read class names\n# f = open(\"skribbl_classes.txt\", \"r\")\nf = open(\"mini_classes.txt\", \"r\")\nclasses = f.readlines()\nf.close()\n\nclasses = [c.replace('\\n', '').replace(' ', '_') for c in classes]\n\n\n# Download the class files\n# download()\n\n\n# Read in the data\nx_train, y_train, x_test, y_test, class_names = load_data('data')\nnum_classes = len(class_names)\nimage_size = 28\n\n# print(len(x_train))\n\nidx = randint(0, len(x_train))\n# plt.imshow(x_train[idx].reshape(28, 28))\n# print(class_names[int(y_train[idx].item())])\n\n\n# Preprocess the data to prepare it for training\n# Reshape and normalize\nx_train = x_train.reshape(x_train.shape[0], image_size, image_size, 1).astype('float32')\nx_test = x_test.reshape(x_test.shape[0], image_size, image_size, 1).astype('float32')\n\nx_train /= 255.0\nx_test /= 255.0\n\n\n# Convert class vectors to class matrices\n# to_categorical has to be used if we are going to apply categorical cross-entropy\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\n\n# Create the model\n# Create CNN\n# This model has 3 2D-convolution layers and 2 dense layers\n# The sequential model is a linear stack of layers.\n# Define model\nmodel = keras.Sequential()\n# This layer applies 16 convolution filters of size 3x3 each.\n# The activation function relu takes the negative values in the tensor and replaces them with zeros.\nmodel.add(layers.Convolution2D(16, (3, 3),\n padding='same',\n input_shape=x_train.shape[1:], activation='relu'))\n# Max pooling layer with pooling size 2x2\n# pool_size: tuple of 2 integers, factors by which to downscale (vertical, horizontal)\n# Pool size of (2, 2) will halve the input in both spatial dimension.\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n# This layer applies 32 convolution filters of size 3x3 each.\nmodel.add(layers.Convolution2D(32, (3, 3), padding='same', activation='relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n# This layer applies 64 convolution filters of size 3x3 each.\nmodel.add(layers.Convolution2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n# This layer flattens the input. This does not affect batch size.\n# Flatten the layers to use it for the dense layers\n# This converts the input from the shape [batch_size,a,b,c] to [batch_size,axbxc]\n# This is important because in the dense layers we cannot apply 2D arrays.\nmodel.add(layers.Flatten())\n# Fully connected layer/Layer of feed forward neural network/Dense layer with 128 hidden units/neurons/nodes\n# Activation function = relu (rectified linear unit)\nmodel.add(layers.Dense(128, activation='relu'))\n# Last layer of the network with 100 output neurons because we have 100 classes\n# Dense layer with output units 100 which represents the number of classes we need in our recognition system.\n# Final activation function = softmax\n# The final result should be a class probability in order to achieve a qualitative output.\n# Softmax gives an output between 0 and 1 which can be interpreted as a class probability.\nmodel.add(layers.Dense(100, activation='softmax'))\n\n\n# Train model\n# This creates an Adam optimizer using the default learning rate.\n# Default arguments of optimizer:\n# Learning rate = 0.001, beta_1 = 0.9, beta_2 = 0.999, epsilon = None,\n# Learning rate decay over each update (decay) = 0.0, amsgrad = False\n#adam = tf.train.AdamOptimizer()\nadam = tf.keras.optimizers.Adam() # use a keras optimizer to prevent the warning during saving the model\n\n# Before training the model, the learning process has to be configured, which is done via the compile().\n# This receives three arguments: optimizer, loss, and metrics\n# Optimizers specifies the training procedure\n# optimizer = We used the Adam algorithm to optimize the loss function\n# Loss = has to be minimized during optimization\n# loss = We calculated this using categorical cross-entropy. This configures the model for categorical classification.\n# This evaluates the cross-entropy of the predicted output and the true label.\n# Metric is used to judge the performance of the model or to monitor training\nmodel.compile(loss='categorical_crossentropy',\n optimizer=adam,\n metrics=['top_k_categorical_accuracy'])\n# model.compile(loss='categorical_crossentropy',\n# optimizer=adam,\n# metrics=['accuracy'])\n\n# This prints a summary representation of the model.\nprint(model.summary())\n\n\n# Training\n# Train the model on a dataset for 5 epochs and 256 batches with 10% validation split\n# x = image data\n# y = labels\n# validation_split = fraction of images reserved for validation (between 0 and 1)\n# validation_split = the validation data used will be the last 10% of the data and is never shuffled\n# batch_size = number of dataset elements we apply at the model at a time.\n# The model slices the data into smaller batches and iterates over these batches during training.\n# epochs = how many times we iterate over the current batch NOT the whole dataset\n# epoch = one iteration over the entire input data, which is done in smaller batches\n# Fit the model\nhistory = model.fit(x=x_train, y=y_train, validation_split=0.1, batch_size=256, verbose=2, epochs=__epoch__)\n\n\n# https://machinelearningmastery.com/display-deep-learning-model-training-history-in-keras/\n# list all data in history\nprint(history.history.keys())\n# for compile with 'accuracy'\n# summarize history for accuracy\n# plt.plot(history.history['acc'])\n# plt.plot(history.history['val_acc'])\n# plt.title('model accuracy')\n# plt.ylabel('accuracy')\n# plt.xlabel('epoch')\n# plt.legend(['train', 'test'], loc='upper left')\n# # plt.show()\n# plt.savefig('acc.png')\n# plt.close()\n# # summarize history for loss\n# plt.plot(history.history['loss'])\n# plt.plot(history.history['val_loss'])\n# plt.title('model loss')\n# plt.ylabel('loss')\n# plt.xlabel('epoch')\n# plt.legend(['train', 'test'], loc='upper left')\n# plt.savefig('loss.png')\n# # plt.show()\n\n# for compile with 'top_k_categorical_accuracy'\n# summarize history for accuracy\nplt.plot(history.history['top_k_categorical_accuracy'])\nplt.plot(history.history['val_top_k_categorical_accuracy'])\nplt.title('model top_k_categorical_accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\n# plt.show()\nplt.savefig('top_k_cat_acc.png')\nplt.close()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.savefig('loss.png')\n# plt.show()\n\n\n# Testing\n# Evaluate on unseen data\nscore = model.evaluate(x_test, y_test, verbose=2)\nprint('Test accuracy: {:0.2f}%'.format(score[1] * 100))\n\n\n# Inference\nidx = randint(0, len(x_test))\nimg = x_test[idx]\nplt.imshow(img.squeeze())\npred = model.predict(np.expand_dims(img, axis=0))[0]\nind = (-pred).argsort()[:5]\nlatex = [class_names[x] for x in ind]\nprint(latex)\n\n\n\n# Store the classes\n# with open('class_names.txt', 'w') as file_handler:\n# for item in class_names:\n# file_handler.write(\"{}\\n\".format(item))\n\n\n# Prepare the model for web format\n# Save the model so we can convert it\n# The Keras model is saved into a HDF5 file which contains:\n# architecture of the model, allowing to recreate the model (.json file)\n# weights of the model (shard files)\n# training configuration (loss, optimizer)\n# state of the optimizer, allowing to resume training exactly where you left off\nmodel.save('keras.h5')\n\n\n# Import tensorflowjs for conversion\nimport tensorflowjs as tfjs\ntfjs_target_dir = './'\n\n# Convert the model\ntfjs.converters.save_keras_model(model, tfjs_target_dir)","sub_path":"Python_Scripts/skribbl_30k_15e.py","file_name":"skribbl_30k_15e.py","file_ext":"py","file_size_in_byte":9770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"653119961","text":"import logging\n\nfrom selenium import webdriver\nfrom time import sleep\n\nfrom selenium.common.exceptions import StaleElementReferenceException, NoSuchElementException, TimeoutException\n\n_logger = logging.getLogger('mfw_click')\n\nif __name__ == '__main__':\n logging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s %(name)-10s %(levelname)-5s %(message)s',\n datefmt='%y-%m-%d %H:%M:%S',\n # handlers=[RotatingFileHandler('mfw_click.log', maxBytes=1024 * 1024 * 50, backupCount=30)]\n )\n _logger.info(\"program is running\")\n chrome_driver_path = r'C:\\pythonWorkSpace\\simba-python-utils\\resources\\chromedriver.exe'\n browser = webdriver.Chrome(executable_path=chrome_driver_path)\n login_url = 'xxx'\n browser.get(login_url)\n while browser.title == 'login':\n sleep(5)\n other_url = 'xxx'\n order_url = 'xxx'\n browser.implicitly_wait(10)\n max_times = 10\n begin = 0\n while True:\n try:\n if begin < max_times:\n begin = begin + 1\n browser.get(other_url)\n else:\n begin = 0\n browser.refresh()\n sleep(3)\n browser.get(order_url)\n sleep(1.5)\n main_element = browser.find_element_by_xpath(\"//div[@id='main_container']\")\n table_element = main_element.find_element_by_tag_name('table')\n body = table_element.find_element_by_tag_name('tbody')\n _logger.info(\"current order info is {0}\".format(body.text))\n rows = body.find_elements_by_tag_name('tr')\n cols = rows[0].find_elements_by_tag_name('td')\n if len(cols) > 1:\n _logger.info(\"there is {0} order to click\".format(len(rows)))\n for i in range(len(rows)):\n cell = rows[i].find_elements_by_tag_name('td')[len(cols) - 1]\n if cell.text == 'ban':\n cell.click()\n _logger.info(\"click order of {0}\".format(rows[i].text))\n sleep(1)\n else:\n _logger.warning(\"couldn't click order of {0}\".format(rows[i].text))\n except NoSuchElementException as nse:\n _logger.error(\"document is not ready\")\n sleep(2)\n except StaleElementReferenceException as sere:\n _logger.error(\"document is outdated\")\n sleep(2)\n except TimeoutException as te:\n _logger.error(\"timeout error\")\n except Exception as e:\n _logger.error(\"deal order occur unknown an exception\")\n _logger.exception(e)\n sleep(2)\n sleep(1.5)\n","sub_path":"simba/spider/mfw_click.py","file_name":"mfw_click.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"325655503","text":"# parameter variable\n#\n# author: Harshvardhan Pandit\n# email: me@harshp.com\n#\n# A parameter variable represents a description of an input parameter\n# of a workflow step. Parameter variables can only be used by workflow steps.\n#\n# IRI: http://www.opmw.org/ontology/ParameterVariable\n#\n# Example:\n#\n# @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n# @prefix opmw: <http://www.opmw.org/ontology/> .\n#\n# <http://www.opmw.org/export/resource/\n# ParameterVariable/AQUAFLOW_NTM_LATITUDE>\n#\n# a opmw:WorkflowTemplateArtifact , opmw:ParameterVariable ;\n# rdfs:label \"Parameter variable Latitude\" ;\n# opmw:correspondsToTemplate\n# <http://www.opmw.org/export/resource/\n# WorkflowTemplate/AQUAFLOW_NTM> .\n#\n# has super-classes: opmw:WorkflowTemplateArtifact\n# is in domain of: hasDimensionality, isGeneratedBy\n# is in range of: opmw:isParameterOfTemplate, uses\n\nimport collections\n\nfrom rdflib import Graph\nfrom rdflib import URIRef, Literal\n\nfrom .namespaces import namespace_manager\nfrom .namespaces import RDF, RDFS, XSD\nfrom .namespaces import OPMW, PROV, PPLAN, DC, DCTERMS\n\nfrom .resource import RDFResource\n\n\nclass ParameterVariable(RDFResource):\n \"\"\"ParameterVariable\"\"\"\n\n def __init__(self):\n\n # parameter URI\n # self._uri = None\n\n # attributes\n self._label = None\n self._dimensionality = None\n\n # links\n self._template = None\n self._used_by = []\n self._execution_artifacts = []\n\n # parameter URI\n # @property\n # def uri(self):\n # return self._uri\n\n # @uri.setter\n # def uri(self, value):\n # if isinstance(value, str):\n # self._uri = URIRef(value)\n # elif isinstance(value, URIRef):\n # self._uri = value\n # elif value is None:\n # self._uri = None\n # else:\n # raise ValueError('parameter URI must be empty or URI')\n\n # rdfs:label\n # label is a string for the parameter's title\n # label types can be str, xsd:string\n @property\n def label(self):\n return self._label\n\n @label.setter\n def label(self, value):\n if isinstance(value, str):\n self._label = Literal(value, datatype=XSD.string)\n elif isinstance(value, Literal) and value.datatype == XSD.string:\n self._label = value\n else:\n raise ValueError('label must be a string')\n\n # opmw:hasDimensionality\n # dimensionality of the artifact: 0 for single file, 1 for collection, etc.\n # int, xsd:integer\n @property\n def dimensionality(self):\n return self._dimensionality\n\n @dimensionality.setter\n def dimensionality(self, value):\n if isinstance(value, int):\n self._dimensionality = Literal(value, datatype=XSD.integer)\n elif isinstance(value, Literal) and value.datatype == XSD.integer:\n self._dimensionality = value\n else:\n try:\n self.dimensionality = int(value)\n except ValueError:\n raise ValueError('dimensionality must be a valid integer')\n\n # opmw:isParameterOfTemplate\n # links the parameter to the template it was used in\n # str, URI\n @property\n def template(self):\n return self._template\n\n @template.setter\n def template(self, value):\n if isinstance(value, str):\n try:\n self._template = URIRef(value)\n except ValueError:\n pass\n else:\n return\n self._template = Literal(value, datatype=XSD.string)\n elif isinstance(value, Literal) and value.datatype == XSD.string:\n self._template = value\n elif isinstance(value, URIRef):\n self._template = value\n elif value is None:\n self._template = None\n else:\n raise ValueError('template must be empty, string or URI')\n\n # opmw:uses\n # linked to steps that use this parameter\n # list of URI\n @property\n def used_by(self):\n return self._used_by\n\n @used_by.setter\n def used_by(self, values):\n if not isinstance(values, collections.Iterable):\n raise ValueError('used by should be a list')\n processes = []\n for value in values:\n if isinstance(value, URIRef):\n processes.append(value)\n else:\n try:\n processes.append(URIRef(value))\n except ValueError:\n raise ValueError('failed to convert to URI')\n self._used_by = processes\n\n # opmw:correspondsToTemplateArtifact\n # linked to execution artifact\n # list of URI\n @property\n def execution_artifacts(self):\n return self._execution_artifacts\n\n @execution_artifacts.setter\n def execution_artifacts(self, values):\n if not isinstance(values, collections.Iterable):\n raise ValueError('used by should be a list')\n artifacts = []\n for value in values:\n if isinstance(value, URIRef):\n artifacts.append(value)\n else:\n try:\n artifacts.append(URIRef(value))\n except ValueError:\n raise ValueError('failed to convert to URI')\n self._execution_artifacts = artifacts\n\n def validate(self):\n \"\"\"validate this parameter\n returns boolean result along with error message\"\"\"\n if not self._label:\n return False, 'label is empty'\n return True, None\n\n @property\n def graph(self):\n \"\"\"expose parameter as RDF graph\n returns rdflib.Graph\"\"\"\n\n graph = Graph()\n graph.namespace_manager = namespace_manager\n if not self._uri:\n raise AttributeError('paremeter URI cannot be empty')\n parameter = self._uri\n # rdf:type\n graph.add((parameter, RDF.type, OPMW.ParameterVariable))\n graph.add((parameter, RDF.type, OPMW.WorkflowTemplateArtifact))\n # rdfs:label\n graph.add((parameter, RDFS.label, self._label))\n # opmw:hasDimensionality\n if self._dimensionality:\n graph.add((\n parameter, OPMW.hasDimensionality, self._dimensionality))\n # opmw:correspondsToTemplate\n if self._template:\n graph.add((\n parameter, OPMW.isParameterOfTemplate, self._template))\n return graph\n\n def printobject(self):\n for key in self.__dict__.keys():\n value = getattr(self, key[1:], None)\n print(key, type(value), value)\n\n @staticmethod\n def parse_from_graph(graph, parameter_uri):\n\n def _handler_for_list_of_uris(property_name):\n def _handler(parameter, value, property_name=property_name):\n values = getattr(parameter, property_name)\n values.append(value)\n setattr(parameter, property_name, values)\n return _handler\n\n _namespaces = [\n str(n) for n in\n (DCTERMS, RDFS, RDF, OPMW, PPLAN, PROV, DC)]\n\n _attribs = {\n 'label': lambda p, x: setattr(p, 'label', x),\n 'hasDimensionality':\n lambda p, x: setattr(p, 'dimensionality', x),\n 'isParameterOfTemplate':\n lambda p, x: setattr(p, 'template', x),\n 'uses': _handler_for_list_of_uris('used_by')\n }\n\n parameter = ParameterVariable()\n parameter.uri = parameter_uri\n\n if not parameter_uri.startswith('<'):\n parameter_uri = '<' + parameter_uri\n if not parameter_uri.endswith('>'):\n parameter_uri += '>'\n\n query = '''\n SELECT ?p ?o\n WHERE {\n { %s ?p ?o }\n UNION\n { ?o ?p %s }\n }''' % (parameter_uri, parameter_uri)\n try:\n query_results = graph.query(query)\n for attrib_type, uri in query_results:\n # DEBUG\n print(attrib_type, uri)\n for namespace in _namespaces:\n if namespace in attrib_type:\n attrib_type = attrib_type.split(namespace)[1]\n if attrib_type in _attribs:\n handler = _attribs[attrib_type]\n handler(parameter, uri)\n # DEBUG\n parameter.printobject()\n except Exception:\n raise\n\n return parameter\n\nif __name__ == '__main__':\n import os\n from rdflib import plugin\n from rdflib import store\n ident = URIRef(\"rdflib_test\")\n uri = Literal(\n \"sqlite:///%(here)s/development.sqlite\" % {\"here\": os.getcwd()})\n # store = plugin.get(\"SQLAlchemy\", Store)(identifier=ident)\n plugin.register(\n 'SQLAlchemy', store.Store,\n 'rdflib_sqlalchemy.SQLAlchemy', 'SQLAlchemy')\n graph = Graph('SQLAlchemy', identifier=ident)\n graph.open(uri)\n template_uri = URIRef('http://lvh.me/directed-study/harsh/param_var_A')\n ParameterVariable.parse_from_graph(graph, template_uri)\n graph.close()\n","sub_path":"libOPMW/classes/parameter_variable.py","file_name":"parameter_variable.py","file_ext":"py","file_size_in_byte":9143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"620481895","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 11 19:03:07 2018\n\n@author: xsxsz\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data/', one_hot=True)\nx=tf.placeholder(tf.float32,[None,784])\ny_=tf.placeholder(tf.float32,[None,10])\nprint(type(mnist))\nprint('----------------')\ntemp=mnist.train.next_batch(4)\nprint(type(temp))\nprint('----------------')\ntemp1=temp[0]\ntemp1=temp1.reshape(4,28,28)\nplt.figure(figsize=(12,10))\nprint(temp1.shape)\nprint('----------------')\nfig,ax=plt.subplots(nrows=2,ncols=2,sharex=True,sharey=True)\nax=ax.flatten()\nfor i in range(4):\n ax[i].imshow(temp1[i,:,:])\n ","sub_path":"tensorflow/tensorflow_mnist_load.py","file_name":"tensorflow_mnist_load.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"215396132","text":"#regression model in keras\n\nimport numpy as np\nfrom keras.layers import Dense\nfrom keras.models import Sequential\n\npred = np.loadtxt('predictors_data.csv',delimiter = ',')\ncols = pred.shape[1]\n\n#building\nmodel = Sequential()\nmodel.add(Dense(100, activation = 'relu', input_shape = (cols,)))\t#input layer\nmodel.add(Dense(100, activation = 'relu'))\nmodel.add(Dense(1))\t#output layer\n\n#compiling\nmodel.compile(optimizer = 'adam', loss = 'mean_squared_error')\n#fitting\nmodel.fit(pred, target)","sub_path":"buildModel.py","file_name":"buildModel.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"426258115","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of REANA.\n# Copyright (C) 2018, 2019, 2020, 2021, 2022 CERN.\n#\n# REANA is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Pytest configuration for REANA-Workflow-Controller.\"\"\"\n\nfrom __future__ import absolute_import, print_function\n\nfrom datetime import datetime, timedelta\nimport os\n\n\nimport flask_login\nimport pytest\nfrom mock import Mock, patch\n\nfrom reana_db.models import (\n WorkspaceRetentionAuditLog,\n WorkspaceRetentionRule,\n WorkspaceRetentionRuleStatus,\n)\n\nfrom reana_server.factory import create_app\n\n\n@pytest.fixture(scope=\"module\")\ndef base_app(tmp_shared_volume_path):\n \"\"\"Flask application fixture.\"\"\"\n config_mapping = {\n \"AVAILABLE_WORKFLOW_ENGINES\": \"serial\",\n \"SERVER_NAME\": \"localhost:5000\",\n \"SECRET_KEY\": \"SECRET_KEY\",\n \"TESTING\": True,\n \"FLASK_ENV\": \"development\",\n \"SHARED_VOLUME_PATH\": tmp_shared_volume_path,\n \"SQLALCHEMY_DATABASE_URI\": os.getenv(\"REANA_SQLALCHEMY_DATABASE_URI\"),\n \"SQLALCHEMY_TRACK_MODIFICATIONS\": False,\n \"APP_THEME\": None,\n \"THEME_ICONS\": None,\n }\n app_ = create_app(config_mapping=config_mapping)\n return app_\n\n\n@pytest.fixture()\ndef _get_user_mock():\n mocked_user = Mock(is_authenticated=False, roles=[])\n mocked_get_user = Mock(return_value=mocked_user)\n with patch(\"flask_login.utils._get_user\", mocked_get_user):\n yield flask_login.utils._get_user\n\n\n@pytest.fixture()\ndef workflow_with_retention_rules(sample_serial_workflow_in_db, session):\n workflow = sample_serial_workflow_in_db\n workflow.reana_specification = dict(workflow.reana_specification)\n workflow.reana_specification[\"inputs\"] = {\n \"files\": [\"input.txt\", \"to_be_deleted/input.txt\"],\n \"directories\": [\"inputs\", \"to_be_deleted/inputs\"],\n }\n workflow.reana_specification[\"outputs\"] = {\n \"files\": [\"output.txt\", \"to_be_deleted/output.txt\"],\n \"directories\": [\"outputs\", \"to_be_deleted/outputs\"],\n }\n current_time = datetime.now()\n\n def create_retention_rule(\n pattern, days, status=WorkspaceRetentionRuleStatus.active\n ):\n return WorkspaceRetentionRule(\n workflow_id=workflow.id_,\n workspace_files=pattern,\n retention_days=2 + days,\n status=status,\n apply_on=current_time + timedelta(days=days),\n )\n\n workflow.retention_rules = [\n create_retention_rule(\n \"this_matches_nothing\",\n days=-2,\n status=WorkspaceRetentionRuleStatus.pending,\n ),\n create_retention_rule(\"inputs\", days=-1),\n create_retention_rule(\"**/*.txt\", days=-1),\n create_retention_rule(\"to_be_deleted\", days=-1),\n create_retention_rule(\"**/*\", days=+1),\n ]\n session.add_all(workflow.retention_rules)\n session.add(workflow)\n session.commit()\n\n yield workflow\n\n session.query(WorkspaceRetentionAuditLog).delete()\n session.query(WorkspaceRetentionRule).delete()\n session.commit()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"76817220","text":"from datetime import datetime\n\nfrom hamper.interfaces import (ChatCommandPlugin, Command, PopulationPlugin,\n PresencePlugin)\n\n\nclass Seen(ChatCommandPlugin, PopulationPlugin, PresencePlugin):\n \"\"\"Keep track of when a user does something, and say when a user was last\n seen when asked\"\"\"\n\n name = 'seen'\n priority = 10\n users = {}\n\n @classmethod\n def update_users(cls, bot, nickname, seen=True):\n \"\"\"Add or update an existing user in the users dict\"\"\"\n\n # dont add the bot to the user dict\n if nickname == bot.nickname:\n return\n\n # get user if it exists\n user = cls.users.get(nickname, None)\n # only update seen if user exists, and seen is true\n if seen and user:\n cls.users[nickname].update_seen()\n else:\n # user doesn't exist.\n # if seen is true (default case for all but nameReply)\n # add them with current time as last seen\n if seen:\n user = User(nickname)\n else:\n # namesReply case, this is not a user action; so no seen time\n user = User(nickname, seen=None)\n\n # store the user object with the nickname for easy dict lookups\n user = {nickname.lower(): user}\n cls.users.update(user)\n\n @classmethod\n def names(cls, bot, channel):\n \"\"\"Sends the NAMES command to the IRC server.\"\"\"\n channel = channel.lower()\n bot.sendLine(\"NAMES %s\" % channel)\n\n def joined(self, bot, channel):\n \"\"\"called after the bot joins a channel\"\"\"\n # Send a names command\n Seen.names(bot, channel)\n\n def userJoined(self, bot, user, channel):\n \"\"\"When user joins a channel, add them to the user dict\"\"\"\n Seen.update_users(bot, user)\n\n def userLeft(self, bot, user, channel):\n Seen.update_users(bot, user)\n\n def userQuit(self, bot, user, quitMessage):\n Seen.update_users(bot, user)\n\n def namesReply(self, bot, prefix, params):\n \"\"\"called when the server replies to the NAMES request\"\"\"\n channel = params[2]\n nicks = params[3].split(' ')\n for nick in nicks:\n # Strip op status in name.\n if nick[0] in ['#', '@']:\n nick = nick[1:]\n Seen.update_users(bot, nick, seen=False)\n\n def namesEnd(self, bot, prefix, params):\n pass\n\n def message(self, bot, comm):\n nick = comm['user']\n Seen.update_users(bot, nick)\n # dispatch out to commands.\n return super(Seen, self).message(bot, comm)\n\n class SeenCommand(Command):\n \"\"\"Say when you last saw a nickname\"\"\"\n regex = r'^seen (.*)$'\n onlyDirected = False\n\n name = 'seen'\n short_desc = 'seen username - When was user \"username\" last seen?'\n long_desc = None\n\n def command(self, bot, comm, groups):\n \"\"\"Determine last time a nickname was seen\"\"\"\n if groups[0].isspace():\n return\n\n name = groups[0].strip()\n\n # Grab the user from the database\n user = self.plugin.users.get(name.lower(), None)\n if name.lower() == bot.nickname.lower():\n bot.reply(comm, 'I am always here!')\n # the user has never been seen\n elif user is None:\n bot.reply(comm, 'I have not seen {0}'.format(name))\n # user exists database and has been seen\n elif user.seen:\n time_format = 'at %I:%M %p on %b-%d'\n seen = user.seen.strftime(time_format)\n bot.reply(comm, 'Seen {0.nickname} {1}'.format(user, seen))\n # if the user exists in the database, but has not been seen active\n # since the bot joined\n else:\n bot.reply(comm, 'I have not seen {0}'.format(name))\n\n class NamesCommand(Command):\n \"\"\"List all users in the channel.\"\"\"\n regex = r'^(names?|users?|nicks?)\\s?(?:list)?$'\n onlyDirected = False\n\n name = 'names'\n short_desc = 'Get the list of users in channel.'\n long_desc = None\n\n def command(self, bot, comm, groups):\n \"\"\"Print out a list of users in the channel\"\"\"\n # Could be better, anytime we're checking users we should send a\n # new names request, and set the command to be deffered until\n # namesEnd\n userlist = self.plugin.users\n nicknames = [nick for nick in userlist.keys()]\n if nicknames:\n message = \", \".join(nicknames)\n bot.reply(comm, '{0} list: {1}.'.format(groups[0], message))\n else:\n # Trigger a names request as a fall back.\n Seen.names()\n bot.reply(comm, 'No users in list. Needs work.')\n\n\nclass User(object):\n\n def __init__(self, nickname, seen=datetime.now()):\n self.nickname = nickname\n # Default seen time is on creation.\n self.seen = seen\n\n def update_seen(self):\n self.seen = datetime.now()\n\n def __repr__(self):\n return self.nickname\n\n\nseen = Seen()\n","sub_path":"hamper/plugins/seen.py","file_name":"seen.py","file_ext":"py","file_size_in_byte":5190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"110345850","text":"from acdc.image import Image\n\nif __name__ == '__main__':\n\n ingester = Image('/etc/fedora/amherst.cfg', 'asc')\n ingester.add_collection('collection:asc')\n ingester.add_metadata('metadata')\n ingester.add_imagedir('/Data/ASC/ma00027Hitchcock/Box05/')\n if ingester.test():\n ingester.run()\n","sub_path":"image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"12596508","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\nclass ResPartner(models.Model):\n _inherit = 'res.partner'\n \n @api.depends('vehiculos_ids')\n def _compute_vehiculos(self):\n for partner in self:\n partner.vehiculos_count = len(partner.vehiculos_ids)\n \n mecanico = fields.Boolean(\"Mecanico\")\n \n vehiculos_count = fields.Integer(string='# of vehiculos', compute='_compute_vehiculos', readonly=True)\n vehiculos_ids = fields.One2many(\"taller.vehiculos\", 'partner_id',string='Vehiculos', readonly=True, copy=False)\n \n @api.multi\n def action_view_vehiculos(self):\n self.ensure_one()\n action = self.env.ref(\"taller.action_taller_vehiculos\").read()[0]\n vehiculos = self.vehiculos_ids\n if len(vehiculos) > 1:\n action['domain'] = [('id', 'in', vehiculos.ids)]\n elif len(vehiculos) == 1:\n action['views'] = [(self.env.ref('taller.view_taller_vehiculos_form').id, 'form')]\n action['res_id'] = vehiculos.ids[0]\n else:\n action = {'type': 'ir.actions.act_window_close'}\n return action","sub_path":"taller/models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"428862989","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 22 13:07:55 2017\n\n@author: hsadeghi\n\"\"\"\n\n#import tensorflow as tf\n#\n#from data_loader import read_and_decode\n#from __future__ import print_function\n\n\n\n\nf=open('noisy_list.txt', \"r\")\n\nfor i in f:\n print(i)\n\n \nf.close()\n \n \n#with open('noisy_list.txt', \"r\") as f:\n# file_name_noisy = f.read(5) \n\n\n\n\n\n\n#%%\n\n#\n#filename = \"/vol/grid-solar/sgeusers/hsadeghi/segan_data/segan.tfrecords\"\n#\n#filename_queue = tf.train.string_input_producer([filename])\n#\n#wave, noisy = read_and_decode(filename_queue, 2**8, preemph=0.95)\n#\n#\n#\n#sess=tf.Session()\n#\n#\n#print(sess.run(tf.shape(wave)[0]))\n#\n\n\n#%%\n\n\n\n","sub_path":"May/codec_segan/test_data_loader.py","file_name":"test_data_loader.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"458547571","text":"# Lint as: python2, python3\n# Copyright 2019 Google LLC. All Rights Reserved.\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\nimport absl\nimport os\n\nimport kfp\n\nfrom tfx.orchestration import metadata\nfrom tfx.orchestration import pipeline\nfrom tfx.orchestration.beam.beam_dag_runner import BeamDagRunner\nfrom tfx.orchestration.kubeflow import kubeflow_dag_runner\n\nfrom pipeline import create_pipeline\n\n\n_project_id = os.getenv(\"PROJECT_ID\")\n_region = os.getenv(\"GCP_REGION\")\n_artifact_store_uri = os.getenv(\"ARTIFACT_STORE_URI\")\n_tfx_image = os.getenv(\"KUBEFLOW_TFX_IMAGE\")\n_pipeline_name = os.getenv(\"PIPELINE_NAME\")\n_data_root = os.getenv(\"DATA_ROOT_URI\")\n\n\n_pipeline_root = '{}/{}/{}'.format(\n _artifact_store_uri, \n _pipeline_name,\n kfp.dsl.RUN_ID_PLACEHOLDER)\n\n_beam_tmp_folder = '{}/beam/tmp'.format(_artifact_store_uri)\n\n_beam_pipeline_args = [\n '--runner=DataflowRunner',\n '--project=' + _project_id,\n '--temp_location=' + _beam_tmp_folder,\n '--region=' + _region,\n ]\n\n\n# To run this pipeline from the python CLI:\n# $python taxi_pipeline_hello.py\nif __name__ == '__main__':\n absl.logging.set_verbosity(absl.logging.INFO)\n\n metadata_config = kubeflow_dag_runner.get_default_kubeflow_metadata_config()\n pipeline_operator_funcs = kubeflow_dag_runner.get_default_pipeline_operator_funcs()\n \n runner_config = kubeflow_dag_runner.KubeflowDagRunnerConfig(\n kubeflow_metadata_config = metadata_config,\n pipeline_operator_funcs = pipeline_operator_funcs,\n tfx_image=_tfx_image)\n\n kubeflow_dag_runner.KubeflowDagRunner(config=runner_config).run(\n create_pipeline(\n pipeline_name=_pipeline_name,\n pipeline_root=_pipeline_root,\n data_root=_data_root,\n beam_pipeline_args=_beam_pipeline_args))\n","sub_path":"hello_world/dataflow_runner.py","file_name":"dataflow_runner.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"73963679","text":"import logging\nimport numpy as np\n\nclass Experience(object):\n def __init__(self, agentNum, memorysize=50000):\n self.exp = []\n self.temp = []\n self.memCount = []\n self.agentNum = agentNum\n self.memorysize = memorysize\n for i in range(agentNum):\n nextExp = []\n nextTemp = None\n self.exp.append(nextExp)\n self.temp.append(nextTemp)\n self.memCount.append(0)\n logging.basicConfig(filename='exp_logger.log', level=logging.INFO)\n\n logger = logging.getLogger(\"wind_logger\")\n headerstr = \"turbinId,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,action,reward,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,s_,split,power,totalreward,award,penalty\"\n logger.critical(headerstr)\n\n def add(self, turbineId, in_s, in_a, in_r, infoPackage=None):\n # print in_s\n # print len(in_s), in_a, in_r\n if self.temp[turbineId] is not None:\n # do sup\n item = self.temp[turbineId]\n (s, a, r) = item\n s_ = in_s\n item_ = np.hstack((s, [a, r], s_))\n # log_item_ = (s, [a, r], s_)\n\n # print \"logging\"\n logger = logging.getLogger(\"wind_logger\")\n logstr = str(turbineId)\n for num in item_:\n logstr += \",\" + str(num)\n if infoPackage is not None:\n logstr += \",--,\" + \",\".join(infoPackage)\n logger.critical(logstr)\n\n # store\n # print(item_[26])\n ith = self.memCount[turbineId]\n if ith < self.memorysize:\n self.exp[turbineId].append(item_)\n else:\n self.exp[turbineId][ith%self.memorysize]\n self.memCount[turbineId] += 1\n\n item = (in_s, in_a, in_r)\n self.temp[turbineId] = item\n\n def get(self, turbineId):\n return self.exp[turbineId]\n\n def expLen(self, turbinId):\n return len(self.exp[turbinId])\n\n def sampleBatch(self, turbineId, batch_size):\n aExp = self.get(turbineId)\n memory = np.array(aExp)\n memory_counter = len(aExp)\n sample_index = np.random.choice(memory_counter, size=batch_size)\n batch_memory = memory[sample_index, :]\n return batch_memory\n\n def allSampleBatch(self, batch_size):\n each_size = batch_size/self.agentNum\n allBatchMemory = self.sampleBatch(0, each_size + batch_size%self.agentNum)\n for i in range(1, self.agentNum):\n allBatchMemory = np.concatenate((allBatchMemory, self.sampleBatch(i, each_size)), axis=0)\n return allBatchMemory\n","sub_path":"support/Experience.py","file_name":"Experience.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"49478661","text":"fdays=28\nDIM = [0,31,fdays,31,30,31,30,31,31,30,31,30,31]\nclass Date:\n \"\"\" a user-defined data structure that\n stores and manipulates dates\n \"\"\"\n\n # the constructor is always named __init__ !\n def __init__(self, month, day, year):\n \"\"\" the constructor for objects of type Date \"\"\"\n self.month = month\n self.day = day\n self.year = year\n\n # the \"printing\" function is always named __repr__ !\n def __repr__(self):\n \"\"\" This method returns a string representation for the\n object of type Date that calls it (named self).\n\n ** Note that this _can_ be called explicitly, but\n it more often is used implicitly via the print\n statement or simply by expressing self's value.\n \"\"\"\n s = \"%02d/%02d/%04d\" % (self.month, self.day, self.year)\n return s\n\n\n # here is an example of a \"method\" of the Date class:\n def isLeapYear(self):\n \"\"\" Returns True if the calling object is\n in a leap year; False otherwise. \"\"\"\n if self.year % 400 == 0: return True\n elif self.year % 100 == 0: return False\n elif self.year % 4 == 0: return True\n return False\n\n def tomorrow(self):\n if self.isLeapYear == True:\n fdays=29\n if (self.day +1) > (DIM[self.month])==0:\n self.day=1; self.month+=1;\n if self.month > 12 ==0:\n self.month=1;self.year+=1;\n else:\n self.day+=1\n s = \"%02d/%02d/%04d\" % (self.month, self.day, self.year)\n def yesterday(self):\n if self.isLeapYear == True:\n fdays=29\n if self.day-1<1:\n self.month-=1; self.day=DIM[self.month];\n if self.month==0:\n self.month=12; self.day=31; self.year-=1;\n else:\n self.day-=1;\n s = \"%02d/%02d/%04d\" % (self.month, self.day, self.year)\n def addNDays(self,n):\n while n>0 :\n self.tomorrow()\n print(self)\n n-=1;\n def subNdays(self,n):\n while n>0:\n self.yesterday()\n print(self)\n n-=1\n def isBefore(self,d2):\n if self.year < d2.year:\n return True\n elif self.year > d2.year:\n return False\n elif self.year == d2.year:\n if self.month<d2.month:\n return True\n elif self.month > d2.month:\n return False\n elif self.month == d2.month:\n if self.day < d2.day:\n return True\n elif self.day > d2.day:\n return False\n elif self.day == d2.day:\n return False\ndef copy(self):\n \"\"\" Returns a new object with the same month, day, year\n as the calling object (self).\n \"\"\"\n dnew = Date(self.month, self.day, self.year)\n return dnew\n\na='OMGLOLDATES NEW TEST'","sub_path":"Trinket/Week 1/1_1_Dates.py","file_name":"1_1_Dates.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"615935517","text":"import collections\nimport os\nimport itertools\nimport random\nimport json\nfrom collections.abc import Iterable\nfrom types import GeneratorType\n\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom networkx.readwrite.json_graph import node_link_graph, node_link_data\nfrom numpy.random import gamma\n\nCENTROID_DIM_LENGTH = 2 # TODO do we need a settings.py file?\ntry:\n from .biconnected import calculate_com_inner\n cython_biconnected = True\nexcept ImportError:\n cython_biconnected = False\n\ndef np_to_native(o):\n if isinstance(o, np.integer):\n return int(o)\n elif isinstance(o, np.floating):\n return float(o)\n elif isinstance(o, np.ndarray):\n return o.tolist()\n elif isinstance(o, dict):\n return {np_to_native_keys(k):np_to_native(v) for k, v in o.items()}\n elif isinstance(o, str):\n return o # this is fine, but don't recurse through iterables\n elif isinstance(o, (Iterable, GeneratorType)):\n return tuple([np_to_native(v) for v in o]) #\n else:\n return o\n\n\ndef np_to_native_keys(o):\n if isinstance(o, (int, np.integer)):\n return int(o)\n elif isinstance(o, (float, np.floating)):\n return float(o)\n else:\n return str(o) # seems like best option\n\n\ndef xy_to_xtx(X, Y):\n # assuming that X is repeated for each partition\n # X is p times m\n # y is n times p\n\n logger = np.zeros(shape=(X.shape[1], X.shape[1]))\n num_reps = Y.shape[0]\n for i in range(X.shape[1]):\n for j in range(X.shape[1]):\n logger[i, j] = X[:, i].T @ X[:, j]\n\n x_mega_list = []\n for i in range(logger.shape[0]):\n x_list = []\n for j in range(logger.shape[0]):\n x_list.append(logger[i, j] * np.identity(num_reps))\n\n x_mega_list.append(np.concatenate(x_list, axis=1))\n\n xtx = np.concatenate(x_mega_list, axis=0)\n xty = np.ndarray(shape=(Y.shape[0] * X.shape[1]))\n\n for i in range(Y.shape[0]):\n for j in range(X.shape[1]):\n xty[i + j * Y.shape[0]] = X[:, j].T @ Y[i, :].T\n return xtx, xty\n\nclass State(object):\n\n\n\n def __init__(self, graph, coloring, log_contested_edges = True, include_external_border = True,\n coerce_int = True, apd=0.1, ideal_pop = None, involution = 1, graph_type='lattice', **kwargs):\n\n\n if coerce_int:\n # this is important to ensure it's compatible with our Cython speedups\n relabeling = {i: int(i) for i in graph.nodes()}\n coloring = {int(k):v for k,v in coloring.items()}\n graph = nx.relabel_nodes(graph, relabeling, copy=True)\n\n self.coerce_int = coerce_int\n self.graph = graph\n self.graph_type = graph_type\n\n self.node_to_color = coloring\n d = collections.defaultdict(set)\n for node_id, district_id in coloring.items():\n d[district_id].add(node_id)\n self.color_to_node = dict(d)\n\n num_districts = len(self.color_to_node)\n\n population_total = sum(graph.nodes()[node]['population'] for node in graph.nodes)\n minimum_population = population_total/num_districts - population_total*apd/2\n maximum_population = population_total/num_districts + population_total*apd/2\n\n self.minimum_population = minimum_population\n self.maximum_population = maximum_population\n self.iteration = 0\n self.state_log = []\n self.move_log = [] # move log is state_log plus 'None' each time we make an involution\n self.ideal_pop = ideal_pop\n self.involution = involution\n self.include_external_border = include_external_border\n\n self.log_contested_edges = log_contested_edges # rip these out into a mixin?\n self.contested_edge_counter = collections.defaultdict(int)\n self.contested_node_counter = collections.defaultdict(int)\n\n\n self.connected_true_counter = [] # TODO remove after finished debugging\n self.connected_false_counter = []\n\n for name, kwarg in kwargs.items():\n setattr(self, name, kwarg) # set attribute as required\n\n @property\n def _json_dict(self):\n\n # these just won't get serialized as they are difficult to initialize or store properly, mostly the updated attrs\n ignore = {\"district_boundary\", \"district_boundary_updated\", \"com_centroid\", \"com_updated\", \"contested_edges\",\n \"contested_nodes\", \"contested_edges_updated\", \"boundary_node_counter\", \"boundary_node_updated\",\n \"articulation_points\", \"articulation_points_updated\", \"adj_mapping\", \"adj_mapping_full\", \"perimeter_computer\"\n }\n\n custom_dict = {'graph': node_link_data(self.graph),\n 'color_to_node': {k: list(v) for k, v in self.color_to_node.items()}, # can't have sets\n }\n other_dict = {key: value for key, value in self.__dict__.items() if key not in custom_dict and key not in ignore}\n other_dict.update(custom_dict)\n return np_to_native(other_dict)\n # return json.dumps(other_dict)\n\n @classmethod\n def from_object(cls, Y, X, graph, node_to_color=None, rho=0.5, lambda_scalar = 1., **kwargs):\n\n\n if node_to_color is None:\n\n color_to_node = greedy_graph_coloring(graph, num_districts=kwargs['num_districts'])\n node_to_color = {}\n for color, nodes in color_to_node.items():\n for node in nodes:\n node_to_color[node] = color\n\n state = State(graph, node_to_color, **kwargs)\n\n\n state.lambda_scalar = lambda_scalar\n\n # note that these don't correspond to the actual shapes of xtx and xty used below - we're assuming a kroenecker\n # product here\n state.simple_Y = Y\n state.simple_X = X\n state.N = state.simple_Y.shape[0]*state.simple_Y.shape[1] # total number of observations\n\n xtx, xty = xy_to_xtx(X,Y)\n state.xty = xty\n state.xtx = xtx\n # state.yty = np.mean(Y.T @ Y)/state.N\n state.yty = np.sum(Y.T @ Y)/state.N\n state.p = state.xtx.shape[0]\n state.P1 = 1./state.p*np.ones(shape=(state.p, state.p)) # P_1 projection matrix\n\n state.phi = gamma(1, 1) # bit of a random draw here - is this bad?\n\n # initialize state parameters\n # state.W = state.graph_laplacian_naive()\n # state.W = state.graph_lap_alternate() # adjacency representation\n # U = np.zeros(shape=(state.p, len(state.color_to_node)))\n # for node, color in node_to_color.items():\n # U[node, color] = 1\n # state.U = U # assignment matrix\n state.rho = rho\n # inv, Lambda, inner = state.matrix_computation(state.W, state.U)\n # state.inv = state.get_inv(state.W, state.phi)\n # state.inv = inv\n # state.inv_det_log = np.linalg.slogdet(state.inv)[1] - np.linalg.slogdet(Lambda)[1] - np.linalg.slogdet(inner)[1]\n # state.likelihood = state.xty.T @ state.inv @ state.xty\n\n return state\n\n\n def matrix_computation(self, W, U):\n\n Lambda = self.get_lambda(W)\n lu = Lambda @ U\n inner = np.linalg.inv(U.T @ lu + np.identity(U.shape[1]))\n Phi = Lambda - lu @ inner @ lu.T\n inv_updated = np.linalg.inv(self.xtx + Phi)\n\n return inv_updated, Lambda, inner\n\n def get_inv(self, W, phi):\n\n return np.linalg.inv(self.xtx + self.get_lambda(W))\n\n def get_lambda(self, W):\n return (self.rho * W + (1 - self.rho) * np.identity(W.shape[0]))*self.lambda_scalar\n # return (np.identity(W.shape[0]) - self.rho*W)* self.lambda_scalar + self.P1\n\n\n\n\n def graph_lap_alternate(self):\n\n lap = np.zeros(shape=(len(self.node_to_color), len(self.node_to_color)), dtype='int')\n for node_id, color in self.node_to_color.items():\n neighbors = list(self.graph.neighbors(node_id))\n\n lap[node_id, node_id] = 0\n\n for neighbor in neighbors:\n if self.node_to_color[neighbor] == color:\n lap[node_id, neighbor] = 1\n\n return lap\n\n @classmethod\n def from_json(cls, js):\n # js is the nested, already parsed dictionary object\n graph = node_link_graph(js['graph'])\n return cls(graph, js['node_to_color'], **{k:v for k,v in js.items() if k != 'graph'})\n\n\n @classmethod\n def from_folder(cls, folder_path, num_districts=3, apd=0.1, **kwargs):\n\n\n files = os.listdir(folder_path)\n\n # TODO make these into a function, this is horrible\n border_file = [i for i in files if 'BORDERLENGTHS' in i][0]\n borders = pd.read_csv(os.path.join(folder_path, border_file), sep='\\\\t', header=None, names=['node_id', 'other_node','border_length'])\n centroids_file = [i for i in files if 'CENTROIDS' in i][0]\n centroids = pd.read_csv(os.path.join(folder_path, centroids_file), sep='\\\\t', header=None, names=['node_id', 'x','y'])\n centroids_dict = {node_id: {'x': x, 'y': y} for node_id, x, y in centroids.itertuples(index=False)}\n population_file = [i for i in files if 'POPULATION' in i][0]\n population = pd.read_csv(os.path.join(folder_path, population_file), sep='\\\\t', header=None, names=['node_id', 'population'])\n pop_dict = {node_id: {'population': population} for node_id, population in population.itertuples(index=False)}\n area_file = [i for i in files if 'AREAS' in i][0]\n area = pd.read_csv(os.path.join(folder_path, area_file), sep='\\\\t', header=None, names=['node_id', 'area'])\n area_dict = {node_id: {'area': area} for node_id, area in area.itertuples(index=False)}\n\n graph = nx.Graph()\n\n for node_id, other_node, border_length in borders.itertuples(index=False):\n if node_id != -1:\n graph.add_edge(node_id, other_node, border_length=border_length)\n else:\n graph.add_node(other_node, boundary=True, external_border=border_length)\n # need to make sure we get boundary correct here\n\n\n # guarantee we have a boundary entry for each\n for node_id in graph.nodes():\n\n graph.nodes()[node_id]['Centroid'] = np.array([centroids_dict[node_id]['x'],\n centroids_dict[node_id]['y']] , dtype='d')\n\n graph.nodes()[node_id]['population'] = pop_dict[node_id]['population']\n graph.nodes()[node_id]['area'] = area_dict[node_id]['area']\n\n\n if 'boundary' not in graph.nodes()[node_id]:\n graph.nodes()[node_id]['boundary'] = False\n graph.nodes()[node_id]['external_border'] = 0 # TODO we can eliminate one of these to simplify\n\n # print(len(graph.nodes))\n\n population_total = sum(graph.nodes()[node]['population'] for node in graph.nodes)\n\n minimum_population = population_total/num_districts - population_total*apd/2\n maximum_population = population_total/num_districts + population_total*apd/2\n\n counter = 0\n loop_max = 100\n # loop until we achieve a valid coloring\n while True:\n counter += 1\n valid_coloring = True\n coloring = greedy_graph_coloring(graph, num_districts=num_districts)\n # print(coloring)\n # check minimum population is valid\n for color, nodes in coloring.items():\n if sum(graph.nodes()[node_id]['population'] for node_id in nodes) < minimum_population or (\n sum(graph.nodes()[node_id]['population'] for node_id in nodes) > maximum_population):\n valid_coloring = False\n break\n\n if counter > loop_max:\n raise ValueError(\"Exceeded maximum number of allowable attempts\")\n\n if valid_coloring:\n break\n\n # produce reverse lookup\n node_to_color = {}\n for district_id, nodes in coloring.items():\n node_to_color.update({node_id: district_id for node_id in nodes})\n\n return State(graph, coloring=node_to_color, apd=apd, **kwargs)\n\n\n\n def check_connected_lookup(self, proposal):\n # TODO finish this off so we can use it\n\n node_id, old_color, new_color = proposal\n\n # check that smaller one is still connected\n district_nodes = self.color_to_node[old_color].difference(\n {node_id}) # all of the old_color nodes without the one we're removing\n to_connect = district_nodes.intersection(\n set(self.graph.neighbors(node_id))) # need to show each of these are still connected\n\n if not to_connect: # TODO should this check get run here or should it be guaranteed?\n return False # we deleted the last node of a district, this is illegal\n\n init = min(to_connect)\n to_connect = {i for i in to_connect if i!=init or (init, i) in self.start_stop_to_chain}\n\n to_search = [init] # ordered list of nodes available to search\n visited_set = {init}\n\n connected_counter = 0\n\n while True: # there are still nodes we haven't found\n connected_counter += 1\n\n # evaluate halting criteria\n if not to_connect - visited_set: # we visited all of the nodes we needed to search\n self.connected_true_counter.append(connected_counter)\n return True\n if not to_search: # no more nodes available to search\n # raise ValueError(\"\")\n self.connected_false_counter.append(connected_counter)\n return False\n\n next_node = to_search.pop()\n\n # new nodes that we haven't seen yet\n new_neighbors = set(self.graph.neighbors(to_search.pop())).intersection(district_nodes).difference(\n visited_set)\n\n priority_neighbors = to_connect.intersection(new_neighbors)\n nonpriority_neighbors = new_neighbors - priority_neighbors\n visited_set.update(new_neighbors) # seen new neighbors\n to_search.extend(nonpriority_neighbors)\n to_search.extend(priority_neighbors) # ensure that priority neighbors are at the top of the queue\n\n def __setattr__(self, key, value):\n self.__dict__[key] = value\n\n def handle_move(self, move):\n self.move_log.append(move)\n self.iteration += 1 # always change this\n if move is not None:\n # self.state_log.append(move)\n self.flip(move[0], move[2]) # TODO check this indexing\n\n\n def flip(self, node_id, district_id):\n # TODO this should be an internal method, since if you start executing it it won't update _proposal_state as well\n # update lookups\n old_color = self.node_to_color[node_id]\n self.color_to_node[old_color].remove(node_id)\n self.color_to_node[district_id].add(node_id)\n self.node_to_color[node_id] = district_id\n\n # record the move\n\n\n # for stat in self.tallied_stats:\n # # the stat tally giveth\n # self.stat_tally[stat][district_id] += self.graph.nodes()[node_id][stat] # node_data[node_id][stat]\n # # ...and it taketh away\n # self.stat_tally[stat][old_color] -= self.graph.nodes()[node_id][stat] # self.node_data[node_id][stat]\n\n # shim to add in data\n\n @classmethod\n def from_file_hardcode(cls):\n # TODO update this for new graph stuff\n # just for testing purposes on Duplin Onslow\n filepath = 'nonreversiblecodebase/data/DuplinOnslow/Duplin_C_Onslow_P__BORDERLENGTHS.txt'\n # todo sort out\n\n edges = []\n node_data = dict()\n delim = '\\t'\n border_key = '-1'\n with open(filepath) as f:\n for line in f:\n L = line.strip().split(delim)\n if L[0] != border_key and L[1] != border_key: # ignore border for now\n edges.append((int(L[0]), int(L[1])))\n\n population_filepath = 'nonreversiblecodebase/data/DuplinOnslow/Duplin_C_Onslow_P__POPULATION.txt'\n with open(population_filepath) as f:\n for line in f:\n L = line.strip().split(delim)\n node_id = int(L[0])\n population = float(L[1])\n node_data[node_id] = {'population': population, 'node_count': 1} # instantiate with population\n\n centroids_filepath = 'nonreversiblecodebase/data/DuplinOnslow/Duplin_C_Onslow_P__CENTROIDS.txt'\n with open(centroids_filepath) as f:\n for line in f:\n L = line.strip().split(delim)\n node_id = int(L[0])\n node_data[node_id]['x'] = float(L[1])\n node_data[node_id]['y'] = float(L[2])\n\n # node to color - hardcoded to\n coloring = {0: 1001, 1: 1001, 10: 1001, 19: 1001, 20: 1001,\n 2: 1002, 12: 1002, 21: 1002, 22: 1002, 23: 1002,\n 3: 1003, 9: 1003, 7: 1003, 5: 1003, 6: 1003,\n 4: 1004, 14: 1004, 15: 1004, 16: 1004, 17: 1004, 24: 1004,\n 8: 1005, # just leave this one as a single to see if that causes issues\n 11: 1006, 13: 1006, 18: 1006}\n\n node_list = list(coloring.keys())\n\n return State.from_edge_node_list(node_list, edges, coloring=coloring, node_data=node_data)\n\n\n @classmethod\n def from_edge_node_list(cls, node_list, edge_list, coloring, node_data=None, edge_data=None, tallied_stats=('population', 'node_count')):\n ''' allows user to initialize state as (V,E), as well as node_data, edge_data instead of passing a nx.graph object with info attached\n user must still provide coloring as before'''\n\n graph = nx.Graph()\n graph.add_nodes_from(node_list)\n graph.add_edges_from(edge_list)\n\n if node_data is not None:\n nx.set_node_attributes(graph, node_data)\n if edge_data is not None:\n nx.set_edge_attributes(graph, edge_data)\n\n return State(graph, coloring, tallied_stats=tallied_stats)\n\n @classmethod\n def from_state(cls, state, **kwargs):\n '''Shim that accepts 'legacy' state object and initializes new class '''\n coloring = state['nodeToDistrict']\n graph = state['graph'] # includes all necessary data? do we need to recode anything?\n\n return State(graph, coloring, tallied_stats=[], **kwargs) # should tallied stats be different?\n\n\n\ndef greedy_graph_coloring(graph, num_districts=3):\n\n nodes_to_draft = set(graph.nodes())\n\n # initialize with random set\n seed_nodes = random.sample(nodes_to_draft, k=num_districts)\n for node_id in seed_nodes:\n nodes_to_draft.remove(node_id)\n color_to_node = {district_id: {seed_nodes.pop()} for district_id in range(num_districts)} # TODO these need to be actually random\n draftable_nodes = {district_id: set([i for i in itertools.chain(*[graph.neighbors(j) for j in color_to_node[district_id]])]) for district_id in color_to_node}\n drafted_nodes = set(itertools.chain(*color_to_node.values()))\n\n while nodes_to_draft:\n\n for district_id in color_to_node:\n while draftable_nodes[district_id]:\n node = draftable_nodes[district_id].pop()\n if node not in drafted_nodes:\n drafted_nodes.add(node)\n color_to_node[district_id].add(node)\n draftable_nodes[district_id].update(graph.neighbors(node))\n nodes_to_draft.remove(node)\n break\n\n return color_to_node\n\n\ndef log_contested_edges(state):\n # maybe manage an array so we don't need to use these horrible loops\n for edge in state.contested_edges:\n # contested_nodes = set(itertools.chain(*state.contested_edges)) # this is horrible, maybe start tracking contested nodes?\n state.contested_edge_counter[edge] += 1\n\n for node in state.contested_nodes:\n state.contested_node_counter[node] += 1\n\n\ndef connected_breadth_first(state, node_id, old_color):\n\n district_nodes = state.color_to_node[old_color].difference({node_id}) # all of the old_color nodes without the one we're removing\n to_connect = district_nodes.intersection(set(state.graph.neighbors(node_id))) # need to show each of these are still connected\n\n if not to_connect: # TODO should this check get run here or should it be guaranteed?\n return False # we deleted the last node of a district, this is illegal\n\n init = to_connect.pop()\n to_search = [init] # ordered list of nodes available to search\n visited_set = {init}\n\n connected_counter = 0\n\n while True: # there are still nodes we haven't found\n connected_counter += 1\n\n # evaluate halting criteria\n if not to_connect - visited_set: # we visited all of the nodes we needed to search\n state.connected_true_counter.append(connected_counter)\n return True\n if not to_search: # no more nodes available to search\n # raise ValueError(\"\")\n state.connected_false_counter.append(connected_counter)\n return False\n\n # new nodes that we haven't seen yet\n new_neighbors = set(state.graph.neighbors(to_search.pop())).intersection(district_nodes).difference(visited_set)\n\n priority_neighbors = to_connect.intersection(new_neighbors)\n nonpriority_neighbors = new_neighbors - priority_neighbors\n visited_set.update(new_neighbors) # seen new neighbors\n to_search.extend(nonpriority_neighbors)\n to_search.extend(priority_neighbors) # ensure that priority neighbors are at the top of the queue\n\n\nclass RingPointer(object):\n\n def __init__(self, node_id, downstream):\n self.node_id = node_id\n self.downstream = downstream # next ringpointer in chain\n\n\n def __hash__(self):\n return self.node_id # this is a compact hash\n\n\ndef ring_connectivity_naive(state):\n # create the ring connectivity objects for a thing\n # requires that edges be counted in a clockwise fashion - how to do this best?\n pass\n\n\n\n\n\n\ndef update_ring_connectivity(state):\n\n if not hasattr('ring_lookup', state):\n state.ring_lookup = ring_connectivity_naive(state)\n\n\n else:\n for move in state.move_log[state.ring_lookup_updated:]:\n if move is not None:\n node_id, old_color, new_color = move\n\n\n\n # todo stuff here\n\n\n\n state.ring_lookup_updated = state.iteration\n\ndef test_ring_connectivity(node_id, old_color, new_color, state):\n # test if number of neighbors is\n\n return len(state.ring_lookup[old_color][node_id].out_connections) == 1 # if there are multiple, we have a problem and can't remove this\n\n","sub_path":"build/lib/nrmc/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":22642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"19610569","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\n\n\"\"\"\npages = []\nread = ' '\nwhile read != '':\n read = input(\"Enter URLs: \")\n pages.append(read)\n\"\"\"\noutput_file_path = input(\"Path to output file: \")\n\noutput_file = open(output_file_path, 'w', encoding=\"utf-8\")\n\nprint(\"Loading started\")\n\nstart = time.time()\n\nfor page in range(1, 601):\n URL = 'https://poetory.ru/pir/rating/'\n URL += str(page)\n response = requests.get(URL)\n soup = BeautifulSoup(response.text, 'lxml')\n quotes = soup.find_all('div', class_=\"item-text\")\n\n print(\"Page\", str(page) + \"...\")\n\n for item in quotes:\n stikh = str(item)\n stikh = stikh.lstrip('<div class=\"item-text\">').rstrip('</div>')\n output_file.write(stikh + '\\n\\n')\n print(stikh)\n print(\"Done\")\n\nprint(time.time() - start)","sub_path":"parser_v1.py","file_name":"parser_v1.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"4735517","text":"####################################################\n# LSrouter.py\n# Names:Wudi Wang\n# NetIds:wudiw\n#####################################################\n\nimport sys\nfrom collections import defaultdict\nfrom router import Router\nfrom packet import Packet\nfrom json import dumps, loads\n\nfrom collections import namedtuple\n\n\n\nclass LSrouter(Router):\n \"\"\"Link state routing protocol implementation.\"\"\"\n LSP = namedtuple(\"LSP\", \"addr sequenceNum lsp\")\n def __init__(self, addr, heartbeatTime):\n \"\"\"TODO: add your own class fields and initialization code here\"\"\"\n Router.__init__(self, addr) # initialize superclass - don't remove\n\n self.sequenceNum = 0\n self.directHopTable = {} # indexed by port, contain addr\n self.directHopCost = {} # indexed by port, contain direct cost\n self.hopToPortTable = {} # indexed by addr, contain which port to send\n\n self.lsp = {} # addr : cost\n\n self.lsptoSend = LSrouter.LSP(self.addr, self.sequenceNum, self.lsp)\n \n self.hopLSP = {self.addr:self.lsptoSend} # indexed by addr\n\n self.routingTable = {}\n\n self.lastUpdateTime = 0;\n self.heartbeatTime = heartbeatTime\n\n \n\n def handlePacket(self, port, packet):\n \"\"\"TODO: process incoming packet\"\"\"\n if packet.isTraceroute():\n # print 'src:' + packet.srcAddr + '; to: ' + packet.dstAddr \n if packet.dstAddr in self.routingTable:\n hopToSend = packet.dstAddr\n while self.routingTable[hopToSend][1] != self.addr:\n hopToSend = self.routingTable[hopToSend][1]\n # print 'hopToSend' + hopToSend\n if hopToSend in self.hopToPortTable:\n self.send(self.hopToPortTable[hopToSend], packet)\n return\n elif packet.isRouting():\n recvLSPList = loads(packet.getContent())\n recvLSP = LSrouter.LSP(recvLSPList[0], recvLSPList[1],recvLSPList[2])\n networkChanged = self.updateLSPTable(recvLSP)\n if networkChanged:\n self.sendLSP()\n self.calShortestPath()\n self.forwardLSP(packet)\n\n\n\n\n def handleNewLink(self, port, endpoint, cost):\n \"\"\"TODO: handle new link\"\"\"\n self.directHopTable[port] = endpoint\n self.directHopCost[port] = cost\n self.hopToPortTable[endpoint] = port\n self.lsp[endpoint] = cost\n\n # update network:\n self.hopLSP[self.addr] = self.lsptoSend\n self.sendLSP()\n self.calShortestPath()\n\n\n def handleRemoveLink(self, port):\n \"\"\"TODO: handle removed link\"\"\"\n if port not in self.directHopTable:\n return\n addrToRemove = self.directHopTable[port]\n self.directHopTable = {p:table for p,table in self.directHopTable.iteritems() if p != port}\n self.directHopCost = {p:table for p,table in self.directHopCost.iteritems() if p != port}\n self.hopToPortTable = {p:table for p,table in self.hopToPortTable.iteritems() if p != addrToRemove}\n self.lsp = {addr:table for addr,table in self.lsp.iteritems() if addr != addrToRemove}\n\n self.hopLSP[self.addr] = self.lsptoSend\n self.sendLSP()\n self.calShortestPath()\n\n\n def handleTime(self, timeMillisecs):\n \"\"\"TODO: handle current time\"\"\"\n if timeMillisecs - self.lastUpdateTime > self.heartbeatTime:\n self.lastUpdateTime = timeMillisecs\n self.sendLSP()\n self.calShortestPath()\n\n\n def debugString(self):\n \"\"\"TODO: generate a string for debugging in network visualizer\"\"\"\n return dumps(self.routingTable) + '\\n' + dumps(self.hopLSP)\n\n def sendLSP(self):\n self.sequenceNum = self.sequenceNum + 1\n self.lsptoSend = LSrouter.LSP(self.addr, self.sequenceNum, self.lsp)\n for port in self.directHopTable:# send routingTable to directly connected hops\n self.send(port, Packet(Packet.ROUTING, self.addr, self.directHopTable[port], content=dumps(self.lsptoSend)))\n\n def calShortestPath(self):\n confirmed = {self.addr:(0, self.addr)}\n lastAddHop = self.addr\n \n tentative = {}\n \n while True:\n if lastAddHop in self.hopLSP:\n lastAddHopLSP = self.hopLSP[lastAddHop]\n # print self.addr, lastAddHop\n for addr in lastAddHopLSP.lsp:\n costToThisNeighbor = confirmed[lastAddHop][0] + lastAddHopLSP.lsp[addr]\n if addr not in confirmed and addr not in tentative:\n tentative[addr] = (costToThisNeighbor, lastAddHop)\n elif addr in tentative:\n if costToThisNeighbor < tentative[addr][0]:\n tentative[addr] = (costToThisNeighbor, lastAddHop)\n\n if len(tentative) == 0:\n break\n else:\n lowestCostAddr = tentative.keys()[0]\n lowestCost = tentative[lowestCostAddr][0]\n for addr in tentative:\n if tentative[addr][0] < lowestCost:\n lowestCostAddr = addr\n lowestCost = tentative[addr][0]\n confirmed[lowestCostAddr] = (lowestCost, tentative[lowestCostAddr][1])\n tentative = {p:table for p, table in tentative.iteritems() if p != lowestCostAddr}\n lastAddHop = lowestCostAddr\n\n self.routingTable = confirmed.copy()\n\n\n\n\n def removeLinkNetwork(self, addr1, addr2):\n # not used\n linkToRemove = frozenset(addr1, addr2)\n if linkToRemove not in self.network:\n return False\n self.network = {link:cost for link, cost in self.network.iteritems() if link != linkToRemove}\n return True\n\n def addLinkNetwork(self, addr1, addr2, cost):\n # not used\n linkToAdd = frozenset(addr1, addr2)\n if linkToAdd in self.network:\n if cost == self.network[linkToAdd]:\n return False\n self.network[linkToAdd] = cost\n return True\n\n def updateLSPTable(self, recvLSP):\n \n # print recvLSP\n if (recvLSP.addr in self.hopLSP and recvLSP.sequenceNum > self.hopLSP[recvLSP.addr].sequenceNum):\n if not LSrouter.isLSPSame(recvLSP.lsp, self.hopLSP[recvLSP.addr].lsp):\n self.hopLSP[recvLSP.addr] = recvLSP\n return True\n else:\n return False\n elif recvLSP.addr not in self.hopLSP:\n self.hopLSP[recvLSP.addr] = recvLSP\n return True\n\n else:\n return False\n def forwardLSP(self, packet):\n for port in self.directHopTable:# send routingTable to directly connected hops\n self.send(port, packet)\n\n\n @staticmethod\n def isLSPSame(lsp1, lsp2):\n if len(lsp1) != len(lsp2):\n return False\n else:\n for key in lsp1:\n if key not in lsp2:\n return False\n elif lsp1[key] != lsp2[key]:\n return False\n\n return True","sub_path":"assignments/assignment2/LSrouter.py","file_name":"LSrouter.py","file_ext":"py","file_size_in_byte":7126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"88117479","text":"#\tProject Euler - Problem One.\n#\tAuthor: Ronald Zielaznicki\n#\tProblem: If we list all the natural numbers below 10 that are multiples \n#\t\tof 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\n#\t\tFind the sum of all the multiples of 3 or 5 below 1000\n\n#finds the sum of the multiples of 3 or 5 up to number x\ndef sumOfMultiples(x):\n\tsumReturn = 0\n\t\n\ti = 3\n\twhile (i < x):\n\t\tsumReturn += i\n\t\ti += 3\n\t\n\ti = 5\n\twhile (i < x):\n\t\tif(i % 3 != 0):\n\t\t\tsumReturn += i\n\t\ti += 5;\n\t\n\treturn sumReturn\n\nprint (\"Answer: \", sumOfMultiples(1000))","sub_path":"ProblemOne/ProblemOne.py","file_name":"ProblemOne.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"410019090","text":"################################################################################\n# Copyright (C) 2019 drinfernoo #\n# #\n# This Program is free software; you can redistribute it and/or modify #\n# it under the terms of the GNU General Public License as published by #\n# the Free Software Foundation; either version 2, or (at your option) #\n# 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 XBMC; see the file COPYING. If not, write to #\n# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. #\n# http://www.gnu.org/copyleft/gpl.html #\n################################################################################\n\nimport xbmc\nimport xbmcgui\n\nimport os\n\nfrom resources.libs.common.config import CONFIG\nfrom resources.libs.common import directory\nfrom resources.libs.common import logging\nfrom resources.libs.common import tools\nfrom resources.libs.gui import window\n\n\ndef view_current():\n window.show_text_box(CONFIG.ADDONTITLE, tools.read_from_file(CONFIG.ADVANCED).replace('\\t', ' '))\n\n\ndef remove_current():\n dialog = xbmcgui.Dialog()\n ok = dialog.yesno(CONFIG.ADDONTITLE, \"[COLOR {0}]Está seguro de que desea eliminar el advancedsettings.xml actual?[/COLOR]\".format(CONFIG.COLOR2),\n yeslabel=\"[B][COLOR springgreen]Si[/COLOR][/B]\",\n nolabel=\"[B][COLOR red]No[/COLOR][/B]\")\n\n if ok:\n if os.path.exists(CONFIG.ADVANCED):\n tools.remove_file(CONFIG.ADVANCED)\n logging.log_notify(\"[COLOR {0}]{1}[/COLOR]\".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]advancedsettings.xml eliminado[/COLOR]\".format(CONFIG.COLOR2))\n xbmc.executebuiltin('Container.Refresh()')\n else:\n logging.log_notify(\"[COLOR {0}]{1}[/COLOR]\".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]advancedsettings.xml no encontrado[/COLOR]\".format(CONFIG.COLOR2))\n else:\n logging.log_notify(\"[COLOR {0}]{1}[/COLOR]\".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]advancedsettings.xml no eliminado[/COLOR]\".format(CONFIG.COLOR2))\n\n\ndef _write_setting(category, tag, value):\n from xml.etree import ElementTree\n\n exists = os.path.exists(CONFIG.ADVANCED)\n\n if exists:\n root = ElementTree.parse(CONFIG.ADVANCED).getroot()\n else:\n root = ElementTree.Element('advancedsettings')\n\n tree_category = root.find('./{0}'.format(category))\n if tree_category is None:\n tree_category = ElementTree.SubElement(root, category)\n\n category_tag = tree_category.find(tag)\n if category_tag is None:\n category_tag = ElementTree.SubElement(tree_category, tag)\n\n category_tag.text = '{0}'.format(value)\n\n tree = ElementTree.ElementTree(root)\n\n logging.log('Writing {0} - {1}: {2} to advancedsettings.xml'.format(category, tag, value), level=xbmc.LOGDEBUG)\n tree.write(CONFIG.ADVANCED)\n\n xbmc.executebuiltin('Container.Refresh()')\n\n\nclass AdvancedMenu:\n def __init__(self):\n self.dialog = xbmcgui.Dialog()\n\n self.tags = {}\n\n def show_menu(self, url=None):\n directory.add_dir('[COLOR azure]Configuración Rápida advancedsettings.xml[/COLOR]',\n {'mode': 'advanced_settings', 'action': 'quick_configure'}, icon=CONFIG.ICONMAINT,\n themeit=CONFIG.THEME3)\n\n if os.path.exists(CONFIG.ADVANCED):\n directory.add_file('Ver Actual advancedsettings.xml',\n {'mode': 'advanced_settings', 'action': 'view_current'}, icon=CONFIG.ICONMAINT,\n themeit=CONFIG.THEME3)\n directory.add_file('Eliminar Actual advancedsettings.xml',\n {'mode': 'advanced_settings', 'action': 'remove_current'}, icon=CONFIG.ICONMAINT,\n themeit=CONFIG.THEME3)\n \n response = tools.open_url(CONFIG.ADVANCEDFILE)\n url_response = tools.open_url(url)\n local_file = os.path.join(CONFIG.ADDON_PATH, 'resources', 'text', 'advanced.json')\n\n if url_response:\n TEMPADVANCEDFILE = url_response.text\n elif response:\n TEMPADVANCEDFILE = response.text\n elif os.path.exists(local_file):\n TEMPADVANCEDFILE = tools.read_from_file(local_file)\n else:\n TEMPADVANCEDFILE = None\n logging.log(\"[Advanced Settings] No hay Ajustes Preestablecidos Disponibles\")\n \n if TEMPADVANCEDFILE:\n import json\n\n directory.add_separator(icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n \n try:\n advanced_json = json.loads(TEMPADVANCEDFILE)\n except:\n advanced_json = None\n logging.log(\"[Advanced Settings] ERROR: Formato no válido para {0}.\".format(TEMPADVANCEDFILE))\n \n if advanced_json:\n presets = advanced_json['presets']\n if presets and len(presets) > 0:\n for preset in presets:\n name = preset.get('name', '')\n section = preset.get('section', False)\n preseturl = preset.get('url', '')\n icon = preset.get('icon', CONFIG.ADDON_ICON)\n fanart = preset.get('fanart', CONFIG.ADDON_FANART)\n description = preset.get('description', '')\n\n if not name:\n logging.log('[Advanced Settings] Missing tag \\'name\\'', level=xbmc.LOGDEBUG)\n continue\n if not preseturl:\n logging.log('[Advanced Settings] Missing tag \\'url\\'', level=xbmc.LOGDEBUG)\n continue\n \n if section:\n directory.add_dir(name, {'mode': 'advanced_settings', 'url': preseturl},\n description=description, icon=icon, fanart=fanart, themeit=CONFIG.THEME3)\n else:\n directory.add_file(name,\n {'mode': 'advanced_settings', 'action': 'write_advanced', 'name': name,\n 'url': preseturl},\n description=description, icon=icon, fanart=fanart, themeit=CONFIG.THEME2)\n else:\n logging.log(\"[Advanced Settings] URL no funciona: {0}\".format(CONFIG.ADVANCEDFILE))\n\n def quick_configure(self):\n directory.add_file('[COLOR azure]Los cambios no se reflejarán hasta que se reinicie Kodi.[/COLOR]', icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n directory.add_file('[COLOR azure]Haga Clic aquí para reiniciar Kodi.[/COLOR]', {'mode': 'forceclose'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n # directory.add_file('Más categorías próximamente :)', icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n directory.add_separator(middle='[B]CATEGORIAS[/B]')\n # directory.add_dir('Troubleshooting', {'mode': 'advanced_settings', 'action': 'show_section', 'tags': 'loglevel|jsonrpc'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n # directory.add_dir('Playback', {'mode': 'advanced_settings', 'action': 'show_section', 'tags': 'skiploopfilter|video|audio|edl|pvr|epg|forcedswaptime'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n # directory.add_dir('Video Library', {'mode': 'advanced_settings', 'action': 'show_section', 'tags': 'videoextensions|discstubextensions|languagecodes|moviestacking|folderstacking|cleandatetime|cleanstrings|tvshowmatching|tvmultipartmatching'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n directory.add_dir('[COLOR azure]RED y CACHE[/COLOR]', {'mode': 'advanced_settings', 'action': 'show_section', 'tags': 'cache|network'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n\n def show_section(self, tags):\n from xml.etree import ElementTree\n\n split_tags = tags.split('|')\n logging.log(split_tags)\n\n exists = os.path.exists(CONFIG.ADVANCED)\n\n if exists:\n root = ElementTree.parse(CONFIG.ADVANCED).getroot()\n\n for category in root.findall('*'):\n name = category.tag\n if name not in split_tags:\n continue\n\n values = {}\n\n for element in category.findall('*'):\n values[element.tag] = element.text\n\n self.tags[name] = values\n\n if len(self.tags) == 0:\n directory.add_file('No existe ninguna configuración para esta categoría en su advancedsettings.xml file.', icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n directory.add_separator()\n \n for category in self.tags:\n directory.add_separator(category.upper())\n\n for tag in self.tags[category]:\n value = self.tags[category][tag]\n\n if value is None:\n value = ''\n\n directory.add_file('{0}: {1}'.format(tag, value), {'mode': 'advanced_settings', 'action': 'set_setting',\n 'category': category, 'tag': tag, 'value': value},\n icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n\n def set_setting(self, category, tag, current):\n value = None\n \n if category == 'cache':\n value = self._cache(tag, current)\n elif category == 'network':\n value = self._network(tag, current)\n \n if value:\n _write_setting(category, tag, value)\n \n def _cache(self, tag, current):\n value = None\n \n if tag == 'buffermode':\n values = ['Buffer all internet filesystems',\n 'Buffer all filesystems',\n 'Only buffer true internet filesystems',\n 'No buffer',\n 'All network filesystems']\n \n items = []\n for i in range(len(values)):\n items.append(xbmcgui.ListItem(label=str(i), label2=values[i]))\n \n value = self.dialog.select('Choose a Value', items, preselect=int(current), useDetails=True)\n elif tag == 'memorysize':\n free_memory = tools.get_info_label('System.Memory(free)')\n free_converted = tools.convert_size(int(float(free_memory[:-2])) * 1024 * 1024)\n \n recommended = int(float(free_memory[:-2]) / 3) * 1024 * 1024\n recommended_converted = tools.convert_size(int(float(free_memory[:-2]) / 3) * 1024 * 1024)\n \n value = tools.get_keyboard(default='{0}'.format(recommended), heading='Memory Size in Bytes\\n(Recommended: {0} = {1})'.format(recommended_converted, recommended))\n elif tag == 'readfactor':\n value = tools.get_keyboard(default='{0}'.format(current), heading='Fill Rate of Cache\\n(High numbers will cause heavy bandwidth use!)')\n \n return value\n \n def _network(self, tag, current):\n msgs = {'curlclienttimeout': 'Timeout in seconds for libcurl (http/ftp) connections',\n 'curllowspeedtime': 'Time in seconds for libcurl to consider a connection lowspeed',\n 'curlretries': 'Amount of retries for certain failed libcurl operations (e.g. timeout)',\n 'httpproxyusername': 'Username for Basic Proxy Authentication',\n 'httpproxypassword': 'Password for Basic Proxy Authentication'}\n \n value = tools.get_keyboard(default='{0}'.format(current), heading=msgs[tag])\n \n return value\n \n def write_advanced(self, name, url):\n response = tools.open_url(url)\n\n if response:\n if os.path.exists(CONFIG.ADVANCED):\n choice = self.dialog.yesno(CONFIG.ADDONTITLE,\n \"[COLOR {0}]Le gustaría sobrescribir su Advanced Settings actual [COLOR {1}]{2}[/COLOR]?[/COLOR]\".format(\n CONFIG.COLOR2, CONFIG.COLOR1, name),\n yeslabel=\"[B][COLOR springgreen]Sobrescribir[/COLOR][/B]\",\n nolabel=\"[B][COLOR red]Cancelar[/COLOR][/B]\")\n else:\n choice = self.dialog.yesno(CONFIG.ADDONTITLE,\n \"[COLOR {0}]Le gustaría descargar e instalar [COLOR {1}]{2}[/COLOR]?[/COLOR]\".format(\n CONFIG.COLOR2, CONFIG.COLOR1, name),\n yeslabel=\"[B][COLOR springgreen]Instalar[/COLOR][/B]\",\n nolabel=\"[B][COLOR red]Cancelar[/COLOR][/B]\")\n\n if choice == 1:\n tools.write_to_file(CONFIG.ADVANCED, response.text)\n tools.kill_kodi(msg='[COLOR {0}]El nuevo ajuste preestablecido advancedsettings.xml se ha escrito correctamente, pero los cambios no surtirán efecto hasta que cierre Kodi.[/COLOR]'.format(\n CONFIG.COLOR2))\n else:\n logging.log(\"[Advanced Settings] instalación canceleda\")\n logging.log_notify('[COLOR {0}]{1}[/COLOR]'.format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]Escritura Canceleda![/COLOR]\".format(CONFIG.COLOR2))\n return\n else:\n logging.log(\"[Advanced Settings] URL no funciona: {0}\".format(url))\n logging.log_notify('[COLOR {0}]{1}[/COLOR]'.format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]URL No Funciona[/COLOR]\".format(CONFIG.COLOR2))\n","sub_path":"matrix/plugin.program.TVBAN-Matrix-27junioFull/resources/libs/advanced.py","file_name":"advanced.py","file_ext":"py","file_size_in_byte":14816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"132876678","text":"from django.urls import path\n\nfrom tapir.coop import views\n\napp_name = \"coop\"\nurlpatterns = [\n path(\n \"share/<int:pk>/edit\",\n views.ShareOwnershipUpdateView.as_view(),\n name=\"share_update\",\n ),\n path(\n \"share/<int:pk>/delete\",\n views.share_ownership_delete,\n name=\"shareownership_delete\",\n ),\n path(\"user/draft/\", views.DraftUserListView.as_view(), name=\"draftuser_list\"),\n path(\n \"user/draft/create\",\n views.DraftUserCreateView.as_view(),\n name=\"draftuser_create\",\n ),\n path(\n \"user/draft/register\",\n views.DraftUserRegisterView.as_view(),\n name=\"draftuser_register\",\n ),\n path(\n \"user/draft/register/confirm\",\n views.DraftUserConfirmRegistrationView.as_view(),\n name=\"draftuser_confirm_registration\",\n ),\n path(\n \"user/draft/<int:pk>/edit\",\n views.DraftUserUpdateView.as_view(),\n name=\"draftuser_update\",\n ),\n path(\n \"user/draft/<int:pk>\",\n views.DraftUserDetailView.as_view(),\n name=\"draftuser_detail\",\n ),\n path(\n \"user/draft/<int:pk>/delete\",\n views.DraftUserDeleteView.as_view(),\n name=\"draftuser_delete\",\n ),\n path(\n \"user/draft/<int:pk>/signed_membership_agreement\",\n views.mark_signed_membership_agreement,\n name=\"mark_draftuser_signed_membership_agreement\",\n ),\n path(\n \"user/draft/<int:pk>/attended_welcome_session\",\n views.mark_attended_welcome_session,\n name=\"mark_draftuser_attended_welcome_session\",\n ),\n path(\n \"member/<int:pk>/attended_welcome_session\",\n views.mark_shareowner_attended_welcome_session,\n name=\"mark_shareowner_attended_welcome_session\",\n ),\n path(\n \"user/draft/<int:pk>/membership_agreement\",\n views.draftuser_membership_agreement,\n name=\"draftuser_membership_agreement\",\n ),\n path(\n \"membership_agreement\",\n views.empty_membership_agreement,\n name=\"empty_membership_agreement\",\n ),\n path(\n \"user/draft/<int:pk>/create_user\",\n views.create_user_from_draftuser,\n name=\"draftuser_create_user\",\n ),\n path(\n \"member/<int:shareowner_pk>/create_shareownership\",\n views.ShareOwnershipCreateView.as_view(),\n name=\"share_create\",\n ),\n path(\n \"member/<int:shareowner_pk>/create_user\",\n views.CreateUserFromShareOwnerView.as_view(),\n name=\"create_user_from_shareowner\",\n ),\n path(\n \"user/draft/<int:pk>/draftuser_create_share_owner\",\n views.create_share_owner_from_draftuser,\n name=\"draftuser_create_share_owner\",\n ),\n path(\n \"member/\",\n views.CurrentShareOwnerListView.as_view(),\n name=\"active_shareowner_list\",\n ),\n path(\n \"member/export/mailchimp\",\n views.ShareOwnerExportMailchimpView.as_view(),\n name=\"shareowner_export_mailchimp\",\n ),\n path(\n \"member/<int:pk>/membership_confirmation\",\n views.shareowner_membership_confirmation,\n name=\"shareowner_membership_confirmation\",\n ),\n path(\n \"member/<int:pk>/membership_agreement\",\n views.shareowner_membership_agreement,\n name=\"shareowner_membership_agreement\",\n ),\n path(\n \"member/<int:pk>/membership_confirmation/send\",\n views.send_shareowner_membership_confirmation_welcome_email,\n name=\"send_shareowner_membership_confirmation_welcome_email\",\n ),\n path(\n \"user/draft/<int:pk>/register_payment\",\n views.register_draftuser_payment,\n name=\"register_draftuser_payment\",\n ),\n path(\n \"member/<int:pk>/\",\n views.ShareOwnerDetailView.as_view(),\n name=\"shareowner_detail\",\n ),\n path(\n \"member/<int:pk>/edit\",\n views.ShareOwnerUpdateView.as_view(),\n name=\"shareowner_update\",\n ),\n]\n","sub_path":"tapir/coop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"240107454","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Discipline',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='EventType',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='Race',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ('location', models.CharField(max_length=200)),\n ('date', models.DateTimeField()),\n ('descriptions', models.TextField(blank=True)),\n ('website', models.CharField(max_length=200, blank=True)),\n ('participants', models.IntegerField(default=0)),\n ('discipline', models.ForeignKey(to='races.Discipline')),\n ('type', models.ForeignKey(to='races.EventType')),\n ],\n ),\n ]\n","sub_path":"racemanager/races/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"70338774","text":"\"\"\"\nClient classes for the GA4GH reference implementation.\n\"\"\"\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport json\nimport requests\nimport posixpath\nimport logging\n\nimport ga4gh.protocol as protocol\nimport ga4gh.exceptions as exceptions\n\n\nclass HttpClient(object):\n \"\"\"\n GA4GH Http Client\n \"\"\"\n\n def __init__(self, urlPrefix, debugLevel=0, key=None):\n self._urlPrefix = urlPrefix\n self._debugLevel = debugLevel\n self._bytesRead = 0\n self._key = key\n self._pageSize = None\n\n # logging config\n # TODO we need to revisit this logging setup so that we can\n # disentangle our logs from urllib3's.\n logging.basicConfig()\n self._logger = logging.getLogger(__name__)\n if self._debugLevel == 0:\n logLevel = logging.WARN\n elif self._debugLevel == 1:\n logLevel = logging.INFO\n else:\n logLevel = logging.DEBUG\n self._logger.setLevel(logLevel)\n\n requestsLog = logging.getLogger(\"requests.packages.urllib3\")\n requestsLog.setLevel(logLevel)\n if self._debugLevel == 0:\n # suppress warning about using https without cert verification\n requests.packages.urllib3.disable_warnings()\n requestsLog.propagate = True\n\n def getPageSize(self):\n \"\"\"\n Returns the suggested maximum size of pages of results returned by\n the server.\n \"\"\"\n return self._pageSize\n\n def getBytesRead(self):\n \"\"\"\n Returns the total number of (non HTTP) bytes read from the server\n by this client.\n \"\"\"\n return self._bytesRead\n\n def setPageSize(self, pageSize):\n \"\"\"\n Sets the requested maximum size of pages of results returned by the\n server to the specified value.\n \"\"\"\n self._pageSize = pageSize\n\n def _getAuth(self):\n return {'key': self._key}\n\n # Ordinarily logger's implementation will take care of if log messages\n # should be emitted based on the log level. The _shouldLog* methods\n # are only used if there are additional performance hits involved in\n # creating the log message that we want to avoid otherwise.\n def _shouldLogDebug(self):\n return self._debugLevel > 1\n\n def _shouldLogInfo(self):\n return self._debugLevel > 0\n\n def _debugResponse(self, jsonString):\n if self._shouldLogDebug():\n self._logger.debug(\"json response:\")\n prettyString = self._prettyJsonString(jsonString)\n self._logger.debug(prettyString)\n\n def _debugRequest(self, jsonString):\n if self._shouldLogDebug():\n self._logger.debug(\"json request:\")\n prettyString = self._prettyJsonString(jsonString)\n self._logger.debug(prettyString)\n\n def _prettyJsonString(self, jsonString):\n # note: expensive method\n return json.dumps(json.loads(jsonString), sort_keys=True, indent=4)\n\n def _checkStatus(self, response):\n if response.status_code != requests.codes.ok:\n self._logger.error(\"%s %s\", response.status_code, response.text)\n raise exceptions.RequestNonSuccessException(\n \"Url {0} had status_code {1}\".format(\n response.url, response.status_code))\n\n def _updateBytesRead(self, jsonString):\n self._bytesRead += len(jsonString)\n\n def _deserializeResponse(self, response, protocolResponseClass):\n jsonResponseString = response.text\n self._updateBytesRead(jsonResponseString)\n self._debugResponse(jsonResponseString)\n if jsonResponseString == '':\n raise exceptions.EmptyResponseException()\n responseObject = protocolResponseClass.fromJsonString(\n jsonResponseString)\n return responseObject\n\n def _doRequest(self, httpMethod, url, protocolResponseClass,\n httpParams={}, httpData=None):\n \"\"\"\n Performs a request to the server and returns the response\n \"\"\"\n headers = {}\n params = self._getAuth()\n params.update(httpParams)\n self._logger.info(\"{0} {1}\".format(httpMethod, url))\n if httpData is not None:\n headers.update({\"Content-type\": \"application/json\"})\n self._debugRequest(httpData)\n response = requests.request(\n httpMethod, url, params=params, data=httpData, headers=headers,\n verify=False)\n self._checkStatus(response)\n return self._deserializeResponse(response, protocolResponseClass)\n\n def runSearchRequest(self, protocolRequest, objectName,\n protocolResponseClass):\n \"\"\"\n Runs the specified request at the specified objectName and instantiates\n an object of the specified class. We yield each object in listAttr.\n If pages of results are present, repeat this process until the\n pageToken is null.\n \"\"\"\n fullUrl = posixpath.join(self._urlPrefix, objectName + '/search')\n notDone = True\n while notDone:\n data = protocolRequest.toJsonString()\n responseObject = self._doRequest(\n 'POST', fullUrl, protocolResponseClass, httpData=data)\n valueList = getattr(\n responseObject, protocolResponseClass.getValueListName())\n self._logger.info(\"Response pageSize={}\".format(len(valueList)))\n for extract in valueList:\n yield extract\n notDone = responseObject.nextPageToken is not None\n protocolRequest.pageToken = responseObject.nextPageToken\n\n def listReferenceBases(self, id_, start=None, end=None):\n \"\"\"\n Returns an iterator over the bases from the server in the form\n of consecutive strings. This command does not conform to the\n patterns of the other search and get requests, and is implemented\n differently.\n \"\"\"\n url = \"references/{id}/bases\"\n fullUrl = posixpath.join(self._urlPrefix, url).format(id=id_)\n request = protocol.ListReferenceBasesRequest()\n request.start = start\n request.end = end\n notDone = True\n while notDone:\n response = self._doRequest(\n 'GET', fullUrl, protocol.ListReferenceBasesResponse,\n request.toJsonDict())\n self._logger.info(\"Response pageSize={}\".format(\n len(response.sequence)))\n yield response.sequence\n notDone = response.nextPageToken is not None\n request.pageToken = response.nextPageToken\n\n def runGetRequest(self, objectName, protocolResponseClass, id_):\n \"\"\"\n Requests an object from the server and returns the object of\n type protocolResponseClass that has id id_.\n Used for requests where a single object is the expected response.\n \"\"\"\n url = \"{objectName}/{id}\"\n fullUrl = posixpath.join(\n self._urlPrefix, url).format(id=id_, objectName=objectName)\n return self._doRequest('GET', fullUrl, protocolResponseClass)\n\n def getDataset(self, id_):\n \"\"\"\n Returns a dataset from the server\n \"\"\"\n return self.runGetRequest(\"datasets\", protocol.Dataset, id_)\n\n def getReferenceSet(self, id_):\n \"\"\"\n Returns a referenceSet from the server\n \"\"\"\n return self.runGetRequest(\"referencesets\", protocol.ReferenceSet, id_)\n\n def getReference(self, id_):\n \"\"\"\n Returns a reference from the server\n \"\"\"\n return self.runGetRequest(\"references\", protocol.Reference, id_)\n\n def getReadGroupSet(self, id_):\n \"\"\"\n Returns a read group set from the server\n \"\"\"\n return self.runGetRequest(\n \"readgroupsets\", protocol.ReadGroupSet, id_)\n\n def getReadGroup(self, id_):\n \"\"\"\n Returns a read group from the server\n \"\"\"\n return self.runGetRequest(\"readgroups\", protocol.ReadGroup, id_)\n\n def getCallset(self, id_):\n \"\"\"\n Returns a callset from the server\n \"\"\"\n return self.runGetRequest(\"callsets\", protocol.CallSet, id_)\n\n def getVariant(self, id_):\n \"\"\"\n Returns a variant from the server\n \"\"\"\n return self.runGetRequest(\"variants\", protocol.Variant, id_)\n\n def searchVariants(\n self, variantSetId, start=None, end=None, referenceName=None,\n callSetIds=None):\n \"\"\"\n Returns an iterator over the Variants from the server\n \"\"\"\n request = protocol.SearchVariantsRequest()\n request.referenceName = referenceName\n request.start = start\n request.end = end\n request.variantSetId = variantSetId\n request.callSetIds = callSetIds\n request.pageSize = self._pageSize\n return self.runSearchRequest(\n request, \"variants\", protocol.SearchVariantsResponse)\n\n def getVariantSet(self, id_):\n \"\"\"\n Returns a variantSet from the server\n \"\"\"\n return self.runGetRequest(\"variantsets\", protocol.VariantSet, id_)\n\n def searchVariantSets(self, datasetId):\n \"\"\"\n Returns an iterator over the VariantSets on the server. If datasetId\n is specified, return only the VariantSets in this dataset.\n \"\"\"\n request = protocol.SearchVariantSetsRequest()\n request.datasetId = datasetId\n request.pageSize = self._pageSize\n return self.runSearchRequest(\n request, \"variantsets\", protocol.SearchVariantSetsResponse)\n\n def searchReferenceSets(\n self, accession=None, md5checksum=None, assemblyId=None):\n \"\"\"\n Returns an iterator over the ReferenceSets from the server.\n \"\"\"\n request = protocol.SearchReferenceSetsRequest()\n request.accession = accession\n request.md5checksum = md5checksum\n request.assemblyId = assemblyId\n request.pageSize = self._pageSize\n return self.runSearchRequest(\n request, \"referencesets\", protocol.SearchReferenceSetsResponse)\n\n def searchReferences(\n self, referenceSetId, accession=None, md5checksum=None):\n \"\"\"\n Returns an iterator over the References from the server\n \"\"\"\n request = protocol.SearchReferencesRequest()\n request.referenceSetId = referenceSetId\n request.accession = accession\n request.md5checksum = md5checksum\n request.pageSize = self._pageSize\n return self.runSearchRequest(\n request, \"references\", protocol.SearchReferencesResponse)\n\n def searchCallSets(self, variantSetId, name=None):\n \"\"\"\n Returns an iterator over the CallSets from the server\n \"\"\"\n request = protocol.SearchCallSetsRequest()\n request.variantSetId = variantSetId\n request.name = name\n request.pageSize = self._pageSize\n return self.runSearchRequest(\n request, \"callsets\", protocol.SearchCallSetsResponse)\n\n def searchReadGroupSets(self, datasetId, name=None):\n \"\"\"\n Returns an iterator over the ReadGroupSets from the server\n \"\"\"\n request = protocol.SearchReadGroupSetsRequest()\n request.datasetId = datasetId\n request.name = name\n request.pageSize = self._pageSize\n return self.runSearchRequest(\n request, \"readgroupsets\", protocol.SearchReadGroupSetsResponse)\n\n def searchReads(\n self, readGroupIds, referenceId=None, start=None, end=None):\n \"\"\"\n Returns an iterator over the Reads from the server\n \"\"\"\n request = protocol.SearchReadsRequest()\n request.readGroupIds = readGroupIds\n request.referenceId = referenceId\n request.start = start\n request.end = end\n request.pageSize = self._pageSize\n return self.runSearchRequest(\n request, \"reads\", protocol.SearchReadsResponse)\n\n def searchDatasets(self):\n \"\"\"\n Returns an iterator over the Datasets from the server\n \"\"\"\n request = protocol.SearchDatasetsRequest()\n request.pageSize = self._pageSize\n return self.runSearchRequest(\n request, \"datasets\", protocol.SearchDatasetsResponse)\n","sub_path":"ga4gh/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":12337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"645154325","text":"from getgauge.python import step,data_store\nfrom api.mms.activity.activity_list import ActivityList\nfrom api.mms.activity.activity_detail import ActivityDetail\nfrom api.mms.activity.activity_punish import ActivityPunish\nfrom models.mt.pt_merchant import MallPunishmentLimit as MallModel\n\n\n@step(\"获取商家端活动列表,更改更改act_type=<act_type>,act_cate=<act_cate>\")\ndef activity_list(act_type,act_cate):\n activity_list = ActivityList()\n activity_list.data['act_type'] = int(act_type)\n activity_list.data['act_cate'] = int(act_cate)\n resp = activity_list.request()\n\n assert resp['code'] == 0 \n if resp['payload']['list']:\n data_store.suite['schedule_id'] = resp['payload']['list'][0]['schedule_id']\n\n\n@step(\"商家端活动详情,schedule_id=<schedule_id>\")\ndef activity_detail(schedule_id):\n schedule_id = data_store.suite['schedule_id'] if not schedule_id else schedule_id\n activity_detail = ActivityDetail()\n activity_detail.data['schedule_id'] = int(schedule_id)\n resp = activity_detail.request()\n\n assert resp['code'] == 0\n\n\n@step(\"校验并更新商家资质参加活动\")\ndef activity_punish():\n activity_punish = ActivityPunish()\n resp = activity_punish.request()\n\n assert resp['code'] == 0\n if resp['payload'].get('id', False):\n update_mall_status(data_store.suite['mall_id'])\n\n\n@step('db更新店铺资质,用于添加商品参加活动,mall_id=<mall_id>')\ndef update_mall_status(mall_id):\n mall_id = data_store.suite['mall_id'] if not mall_id else int(mall_id)\n data = MallModel.filter(mall_id=mall_id)\n\n if len(data):\n for i in data:\n print(i.mall_id)\n i.mall_id = 0\n i.save()\n assert True\n","sub_path":"banshee-master/step_impl/mms/activity_info.py","file_name":"activity_info.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"207189517","text":"import os\n\nimport pytest\nfrom adcm_pytest_plugin.utils import get_data_dir\n\n# pylint: disable=W0611, W0621\nfrom tests.ui_tests.app.app import ADCMTest\nfrom tests.ui_tests.app.pages import Configuration, LoginPage\n\nDATADIR = get_data_dir(__file__)\nBUNDLES = os.path.join(os.path.dirname(__file__), \"../stack/\")\n\nNO_TOOLTIP_FIELDS = ['string_required_by_default_without_type',\n 'string_read_only_any_without_type']\n\n\n@pytest.fixture(scope='function')\ndef service(sdk_client_fs):\n bundle = sdk_client_fs.upload_from_fs(DATADIR)\n cluster = bundle.cluster_create(name='tooltips')\n cluster.service_add(name='tooltips_test')\n return cluster.service(name=\"tooltips_test\")\n\n\n@pytest.fixture()\ndef app(adcm_fs):\n return ADCMTest(adcm_fs)\n\n\n@pytest.fixture()\ndef login(app):\n app.driver.get(app.adcm.url)\n login = LoginPage(app.driver)\n login.login(\"admin\", \"admin\")\n\n\n@pytest.fixture()\ndef ui_config(app, login, service):\n app.driver.get(\"{}/cluster/{}/service/{}/config\".format\n (app.adcm.url, service.cluster_id, service.service_id))\n return Configuration(app.driver)\n\n\n@pytest.fixture()\ndef tooltips(ui_config, service):\n config = service.prototype().config\n descriptions = [field['description'] for field in config[1:] if field['description'] != \"\"]\n textboxes = ui_config.get_textboxes()\n tooltips = []\n for textbox in textboxes:\n ttip = textbox.text.split(\":\")[0]\n if ttip in descriptions and ttip != \"\":\n tooltips.append(ui_config.get_tooltip_text_for_element(textbox))\n return tooltips, descriptions\n\n\ndef test_tooltip_presented(tooltips):\n \"\"\"Check that field have description tooltip presented\n\n :return:\n \"\"\"\n assert len(tooltips[0]) == 8\n\n\n@pytest.mark.xfail\ndef test_tooltip_text(tooltips):\n \"\"\"Check description in tooltip\n \"\"\"\n assert set(tooltips[0]).issubset(set(tooltips[1]))\n\n\n@pytest.mark.parametrize(\"field\", NO_TOOLTIP_FIELDS)\ndef test_tooltip_not_presented(field, ui_config):\n \"\"\"Check that we haven't tooltip for fields without description\n :return:\n \"\"\"\n textboxes = ui_config.get_textboxes()\n for textbox in textboxes:\n if field == textbox.text.split(\":\")[0]:\n assert not ui_config.check_tooltip_for_field(textbox)\n","sub_path":"tests/ui_tests/test_tooltips.py","file_name":"test_tooltips.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"308452839","text":"\nimport csv\nimport pygal\n\ngdpinfo = {\n \"gdpfile\": \"isp_gdp.csv\",\n \"separator\": \",\",\n \"quote\": '\"',\n \"min_year\": 1960,\n \"max_year\": 2015,\n \"country_name\": \"Country Name\",\n \"country_code\": \"Country Code\"\n }\n\ndef read_csv_as_nested_dict(filename, keyfield, separator, quote):\n \"\"\"\n Inputs:\n filename - Name of CSV file\n keyfield - Field to use as key for rows\n separator - Character that separates fields\n quote - Character used to optionally quote fields\n\n Output:\n Returns a dictionary of dictionaries where the outer dictionary\n maps the value in the key_field to the corresponding row in the\n CSV file. The inner dictionaries map the field names to the\n field values for that row.\n \"\"\"\n\n table = {}\n\n with open(filename, 'rt', newline='') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=separator,\n quotechar=quote)\n for row in csv_reader:\n # print(row)\n rowid = row[keyfield]\n table[rowid] = row\n return table\n\n\n#print(read_csv_as_nested_dict('table1.csv', 'Field1', ',', '\"'))\n\ndef build_plot_values(gdpinfo, gdpdata):\n \"\"\"\n Inputs:\n gdpinfo - GDP data information dictionary\n gdpdata - A single country's GDP stored in a dictionary whose\n keys are strings indicating a year and whose values\n are strings indicating the country's corresponding GDP\n for that year.\n\n Output:\n Returns a list of tuples of the form (year, GDP) for the years\n between \"min_year\" and \"max_year\", inclusive, from gdpinfo that\n exist in gdpdata. The year will be an integer and the GDP will\n be a float.\n \"\"\"\n table = []\n gdpdat_v2 = {}\n for k, v in gdpdata.items():\n try:\n gdpdat_v2[int(k)] = float(v)\n except ValueError:\n pass\n\n min_max = [year for year in range(gdpinfo['min_year'], gdpinfo['max_year'] + 1)]\n\n for key in min_max:\n if key in gdpdat_v2:\n table.append((key, gdpdat_v2[key]))\n return table\n\n\n\ndef build_plot_dict(gdpinfo, country_list):\n gdp_dat = read_csv_as_nested_dict(gdpinfo[\"gdpfile\"], gdpinfo[\"country_name\"], gdpinfo[\"separator\"],gdpinfo[\"quote\"])\n\n country_fetch = [k for k in gdp_dat]\n table = {}\n\n\n for country in country_list:\n #if country in country_list:\n try:\n table[country] = build_plot_values(gdpinfo, gdp_dat[country])\n except KeyError:\n table[country] = []\n\n return table\n\n\n#print(build_plot_dict({'min_year': 2000, 'country_name': 'Country Name', 'separator': ',', 'country_code': 'Code', 'gdpfile': 'gdptable1.csv', 'quote': '\"', 'max_year': 2005}, ['Country1']))\n\n\n#print(build_plot_dict(gdpinfo, ['Bangladesh']))\n\n\n\n","sub_path":"Python-Data-Visualization/w02_assignment.py","file_name":"w02_assignment.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"98043005","text":"# -*- coding: utf-8 -*-\n\nfrom abc import ABCMeta, abstractmethod\nfrom collections import Sequence, deque\n\nimport numpy as np\n\n\nclass MatrixBase(object, metaclass=ABCMeta):\n _base_tags = set()\n\n def __init__(self, backend, dtype, ioshape, initval, extent, aliases,\n tags):\n self.backend = backend\n self.tags = self._base_tags | tags\n\n self.dtype = dtype\n self.itemsize = np.dtype(dtype).itemsize\n\n # Alignment requirement for the leading dimension\n ldmod = backend.alignb // self.itemsize if 'align' in tags else 1\n\n # Our shape and dimensionality\n shape, ndim = list(ioshape), len(ioshape)\n\n if ndim == 2:\n nrow, ncol = shape\n aosoashape = shape\n else:\n nvar, narr, k = shape[-2], shape[-1], backend.soasz\n nparr = narr - narr % -k\n\n nrow = shape[0] if ndim == 3 else shape[0]*shape[1]\n ncol = nvar*nparr\n aosoashape = shape[:-2] + [nparr // k, nvar, k]\n\n # Assign\n self.nrow, self.ncol = int(nrow), int(ncol)\n\n self.datashape = aosoashape\n self.ioshape = ioshape\n\n self.leaddim = self.ncol - (self.ncol % -ldmod)\n\n self.pitch = self.leaddim*self.itemsize\n self.nbytes = self.nrow*self.pitch\n self.traits = (self.nrow, self.ncol, self.leaddim, self.dtype)\n\n # Process the initial value\n if initval is not None:\n if initval.shape != self.ioshape:\n raise ValueError('Invalid initial value')\n\n self._initval = np.asanyarray(initval, dtype=self.dtype)\n else:\n self._initval = None\n\n # Alias or allocate ourself\n if aliases:\n if extent is not None:\n raise ValueError('Aliased matrices can not have an extent')\n\n backend.alias(self, aliases)\n else:\n backend.malloc(self, extent)\n\n def get(self):\n # If we are yet to be allocated use our initial value\n if hasattr(self, '_initval'):\n if self._initval is not None:\n return self._initval\n else:\n return np.zeros(self.ioshape, dtype=self.dtype)\n # Otherwise defer to the backend\n else:\n return self._get()\n\n @abstractmethod\n def _get(self):\n pass\n\n def _pack(self, ary):\n # If necessary convert from SoA to AoSoA packing\n if ary.ndim > 2:\n n, k = ary.shape[-1], self.backend.soasz\n\n ary = np.pad(ary, [(0, 0)]*(ary.ndim - 1) + [(0, -n % k)],\n mode='constant')\n ary = ary.reshape(ary.shape[:-1] + (-1, k)).swapaxes(-2, -3)\n ary = ary.reshape(self.nrow, self.ncol)\n\n return np.ascontiguousarray(ary, dtype=self.dtype)\n\n def _unpack(self, ary):\n # If necessary unpack from AoSoA to SoA\n if len(self.ioshape) > 2:\n ary = ary.reshape(self.datashape)\n ary = ary.swapaxes(-2, -3)\n ary = ary.reshape(self.ioshape[:-1] + (-1,))\n ary = ary[..., :self.ioshape[-1]]\n\n return ary\n\n\nclass Matrix(MatrixBase):\n _base_tags = {'dense'}\n\n def __init__(self, backend, ioshape, initval, extent, aliases, tags):\n super().__init__(backend, backend.fpdtype, ioshape, initval, extent,\n aliases, tags)\n\n def set(self, ary):\n if ary.shape != self.ioshape:\n raise ValueError('Invalid matrix shape')\n\n # If we are yet to be allocated then update our initial value\n if hasattr(self, '_initval'):\n self._initval = np.asanyarray(ary, dtype=self.dtype)\n # Otherwise defer to the backend\n else:\n self._set(ary)\n\n @abstractmethod\n def _set(self, ary):\n pass\n\n def rslice(self, p, q):\n return self.backend.matrix_rslice(self, p, q)\n\n\nclass MatrixRSlice(object):\n def __init__(self, backend, mat, p, q):\n self.backend = backend\n self.parent = mat\n\n if p < 0 or q > mat.nrow or q < p:\n raise ValueError('Invalid row slice')\n\n self.p, self.q = int(p), int(q)\n self.nrow, self.ncol = self.q - self.p, mat.ncol\n self.dtype, self.itemsize = mat.dtype, mat.itemsize\n self.leaddim, self.pitch = mat.leaddim, mat.pitch\n\n self.nbytes = self.nrow*self.pitch\n self.traits = (self.nrow, self.ncol, self.leaddim, self.dtype)\n\n self.tags = mat.tags | {'slice'}\n\n @property\n def basedata(self):\n return self.parent.basedata\n\n @property\n def offset(self):\n return self.parent.offset + self.p*self.pitch\n\n\nclass ConstMatrix(MatrixBase):\n _base_tags = {'const', 'dense'}\n\n def __init__(self, backend, initval, extent, tags):\n super().__init__(backend, backend.fpdtype, initval.shape, initval,\n extent, None, tags)\n\n\nclass XchgMatrix(Matrix):\n pass\n\n\nclass MatrixBank(Sequence):\n def __init__(self, backend, mats, initbank, tags):\n mats = list(mats)\n\n # Ensure all matrices have the same traits\n if any(m.traits != mats[0].traits for m in mats[1:]):\n raise ValueError('Matrices in a bank must be homogeneous')\n\n # Check that all matrices share tags\n if any(m.tags != mats[0].tags for m in mats[1:]):\n raise ValueError('Matrices in a bank must share tags')\n\n self.backend = backend\n self.tags = tags | mats[0].tags\n\n self._mats = mats\n self._curr_idx = initbank\n self._curr_mat = mats[initbank]\n\n def __len__(self):\n return len(self._mats)\n\n def __getitem__(self, idx):\n return self._mats[idx]\n\n def __getattr__(self, attr):\n return getattr(self._curr_mat, attr)\n\n def rslice(self, p, q):\n raise RuntimeError('Matrix banks can not be sliced')\n\n @property\n def active(self):\n return self._curr_idx\n\n @active.setter\n def active(self, idx):\n self._curr_idx = idx\n self._curr_mat = self._mats[idx]\n\n\nclass View(object):\n def __init__(self, backend, matmap, rmap, cmap, rstridemap, vshape, tags):\n self.n = len(matmap)\n self.nvrow = vshape[-2] if len(vshape) == 2 else 1\n self.nvcol = vshape[-1] if len(vshape) >= 1 else 1\n self.rstrides = None\n\n # Get the different matrices which we map onto\n self._mats = [backend.mats[i] for i in np.unique(matmap)]\n\n # Extract the base allocation and data type\n self.basedata = self._mats[0].basedata\n self.refdtype = self._mats[0].dtype\n\n # Valid matrix types\n mattypes = (backend.matrix_cls, backend.matrix_rslice_cls)\n\n # Validate the matrices\n if any(not isinstance(m, mattypes) for m in self._mats):\n raise TypeError('Incompatible matrix type for view')\n\n if any(m.basedata != self.basedata for m in self._mats):\n raise TypeError('All viewed matrices must belong to the same '\n 'allocation extent')\n\n if any(m.dtype != self.refdtype for m in self._mats):\n raise TypeError('Mixed data types are not supported')\n\n # SoA size\n k = backend.soasz\n\n # Base offsets and leading dimensions for each point\n offset = np.empty(self.n, dtype=np.int32)\n leaddim = np.empty(self.n, dtype=np.int32)\n\n for m in self._mats:\n ix = np.where(matmap == m.mid)\n offset[ix], leaddim[ix] = m.offset // m.itemsize, m.leaddim\n\n # Row/column displacements\n rowdisp = rmap*leaddim\n coldisp = (cmap // k)*(self.nvcol*k) + cmap % k\n\n mapping = (offset + rowdisp + coldisp)[None,:]\n self.mapping = backend.base_matrix_cls(\n backend, np.int32, (1, self.n), mapping, None, None, tags\n )\n\n # Row strides\n if self.nvrow > 1:\n rstrides = (rstridemap*leaddim)[None,:]\n self.rstrides = backend.base_matrix_cls(\n backend, np.int32, (1, self.n), rstrides, None, None, tags\n )\n\n\nclass XchgView(object):\n def __init__(self, backend, matmap, rmap, cmap, rstridemap, vshape, tags):\n # Create a normal view\n self.view = backend.view(matmap, rmap, cmap, rstridemap, vshape, tags)\n\n # Dimensions\n self.n = n = self.view.n\n self.nvrow = nvrow = self.view.nvrow\n self.nvcol = nvcol = self.view.nvcol\n\n # Now create an exchange matrix to pack the view into\n self.xchgmat = backend.xchg_matrix((nvrow, nvcol*n), tags=tags)\n\n\nclass Queue(object, metaclass=ABCMeta):\n def __init__(self, backend):\n self.backend = backend\n\n # Last kernel we executed\n self._last = None\n\n # Items waiting to be executed\n self._items = deque()\n\n # Active MPI requests\n self.mpi_reqs = []\n\n def __lshift__(self, items):\n self._items.extend(items)\n\n def __mod__(self, items):\n self.run()\n self << items\n self.run()\n\n def __bool__(self):\n return bool(self._items)\n\n def run(self):\n while self._items:\n self._exec_next()\n self._wait()\n\n def _exec_item(self, item, args, kwargs):\n item.run(self, *args, **kwargs)\n self._last = item\n\n def _exec_next(self):\n item, args, kwargs = self._items.popleft()\n\n # If we are at a sequence point then wait for current items\n if self._at_sequence_point(item):\n self._wait()\n\n # Execute the item\n self._exec_item(item, args, kwargs)\n\n def _exec_nowait(self):\n while self._items and not self._at_sequence_point(self._items[0][0]):\n self._exec_item(*self._items.popleft())\n\n @abstractmethod\n def _at_sequence_point(self, item):\n pass\n\n @abstractmethod\n def _wait(self):\n pass\n","sub_path":"pyfr/backends/base/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":9876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"516298404","text":"import sys, math\nimport numpy as np\nfrom gym.utils import colorize, seeding\n\nimport Box2D\nfrom Box2D.b2 import (world, polygonShape, circleShape, staticBody, dynamicBody,\nedgeShape, fixtureDef, vec2)\n\nclass Terrain:\n \"\"\"Class for bipedal testing environment\"\"\"\n def __init__(self):\n self.window_size = [600, 400]\n self.world = Box2D.b2World()\n self.terrain_length = self.window_size[0]\n self.terrain_height = self.window_size[1]/4\n self.start = 20\n self.friction = 2.5\n self._seed()\n self.create()\n\n def _seed(self, seed=None):\n \"\"\"Plant seed for random generation\"\"\"\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def create(self):\n \"\"\"Randomly create a non-uniform slope for the bipedal\"\"\"\n y = self.terrain_height\n self.terrain = []\n self.terrain_x = []\n self.terrain_y = []\n slope = 0.0\n\n for x in range(self.terrain_length):\n self.terrain_x.append(x)\n # TODO: Test what this actually does\n slope = 0.4*slope + 0.01*np.sign(self.terrain_height - y)\n if x > self.start:\n slope += self.np_random.uniform(-1, 1) #1\n y += slope\n\n self.terrain_y.append(y)\n\n self.terrain_poly = []\n for i in range(self.terrain_length-1):\n poly = [\n (self.terrain_x[i], self.terrain_y[i]),\n (self.terrain_x[i+1], self.terrain_y[i+1])\n ]\n t = self.world.CreateStaticBody(\n fixtures = fixtureDef(\n shape=edgeShape(vertices=poly),\n friction = self.friction,\n categoryBits=0x0001,\n ))\n color = (0.3, 1.0 if i%2==0 else 0.8, 0.3)\n t.color1 = color\n t.color2 = color\n self.terrain.append(t)\n color = (0.4, 0.6, 0.3)\n poly += [ (poly[1][0], 0), (poly[0][0], 0) ]\n self.terrain_poly.append( (poly, color) )\n self.terrain.reverse()\n self.bodies = self.terrain\n\n def get_spawn_pos(self):\n return (15,30)\n\n\"\"\"\n def draw(self, mode='human', close=False):\n if close:\n if self.viewer is not None:\n self.viewer.close()\n self.viewer = None\n return\n\n from gym.envs.classic_control import rendering\n if self.viewer is None:\n self.viewer = rendering.Viewer(self.window_size[0], self.window_size[1])\n\n self.viewer.draw_polygon([(0,0),(self.window_size[0], 0),\n (self.window_size[0],self.window_size[1]),\n (0,self.window_size[1]),],color=(0.9, 0.9, 1.0))\n\n for poly, color in self.terrain_poly:\n self.viewer.draw_polygon(poly, color=color)\n\n for obj in self.terrain:\n for f in obj.fixtures:\n trans = f.body.transform\n if type(f.shape) is circleShape:\n t = rendering.Transform(translation=trans*f.shape.pos)\n self.viewer.draw_circle(f.shape.radius, 30, color=obj.color1).add_attr(t)\n self.viewer.draw_circle(f.shape.radius, 30, color=obj.color2, filled=False, linewidth=2).add_attr(t)\n else:\n path = [trans*v for v in f.shape.vertices]\n self.viewer.draw_polygon(path, color=obj.color1)\n path.append(path[0])\n self.viewer.draw_polyline(path, color=obj.color2, linewidth=2)\n\n return self.viewer.render(return_rgb_array = mode=='rgb_array')\n\"\"\"\n","sub_path":"Unused/terrain.py","file_name":"terrain.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"498904192","text":"from __numutil import *\nfrom __regutil import *\nfrom __asmutil import *\nfrom __gencom import *\nimport random,math,itertools\n\nr = gen('clo')\n\n######################\n# A: asm writer function\n# reg: \n# reg_val : which value store in reg\n# immed:\n\ndef gen_assert_one(A,au,reg1,reg1_val):\n # although immed is sign extend ,but we still use unsign compare\n #sval = numutil.sign32(reg_val)\n if reg1 == reg_zero:\n reg1_val = 0 \n\n au.li(reg1, reg1_val)\n try:\n result = f\"{reg1_val:0>32b}\".index('0');\n except ValueError as e:\n result = 32\n\n rd = regutil.get_one()\n au.li(reg1,reg1_val)\n A(\"clo {},{}\".format(rd, reg1))\n au.assert_equal(rd, result & 0xFFFFFFFF)\n \ndef gen_partial(A,au,reg_val_gen1, time = 2):\n #zero \n for x in range(time):\n for i in reg_list:\n reg_val1 = reg_val_gen1()\n gen_assert_one(A,au,i,reg_val1);\n\n\ndef my_gen1(A,au):\n fill_one = 2**32 - 1\n for x in range(20):\n for i in range(33):\n v = (fill_one << i) & 0xFFFFFFFF \n if i > 1:\n v += random.choice(range(2**(i - 1)))\n\n send_reg = regutil.get_one()\n gen_assert_one(A, au, send_reg,v);\n\n reg_sample = numutil.bound(32)\n for s1 in reg_sample:\n send_reg = regutil.get_one()\n gen_assert_one(A, au, send_reg, s1);\n\n gen_sample = [lambda : random.choice(range(0,10)),\\\n lambda : random.choice(range(0x7FFFFFF0,0x8000000F)),\\\n lambda : random.choice(range(0x8FFFFFF0,0xFFFFFFFF)) ]\n for i in gen_sample:\n gen_partial(A, au, i,time = 2)\n\n gen_partial(A, au, lambda : numutil.u32(),time = 20)\n au.check_and_exit()\nr.gen(my_gen1)","sub_path":"asm/generate/clo.py","file_name":"clo.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"479429770","text":"import logging\n\nimport numpy as np\nfrom pgdrive.constants import DEFAULT_AGENT, TerminationState\nfrom pgdrive.envs.pgdrive_env import PGDriveEnv as PGDriveEnvV1\nfrom pgdrive.scene_manager.traffic_manager import TrafficMode\nfrom pgdrive.utils import PGConfig, clip\n\n\nclass PGDriveEnvV2(PGDriveEnvV1):\n DEFAULT_AGENT = DEFAULT_AGENT\n\n @staticmethod\n def default_config() -> PGConfig:\n config = PGDriveEnvV1.default_config()\n config.update(\n dict(\n # ===== Traffic =====\n traffic_density=0.1,\n traffic_mode=TrafficMode.Hybrid, # \"Respawn\", \"Trigger\", \"Hybrid\"\n random_traffic=True, # Traffic is randomized at default.\n\n # ===== Cost Scheme =====\n crash_vehicle_cost=1.,\n crash_object_cost=1.,\n out_of_road_cost=1.,\n\n # ===== Reward Scheme =====\n # See: https://github.com/decisionforce/pgdrive/issues/283\n success_reward=10.0,\n out_of_road_penalty=5.0,\n crash_vehicle_penalty=5.0,\n crash_object_penalty=5.0,\n acceleration_penalty=0.0,\n driving_reward=1.0,\n general_penalty=0.0,\n speed_reward=0.5,\n use_lateral=False,\n gaussian_noise=0.0,\n dropout_prob=0.0,\n vehicle_config=dict(\n wheel_friction=0.8,\n\n # See: https://github.com/decisionforce/pgdrive/issues/297\n lidar=dict(num_lasers=240, distance=50, num_others=4, gaussian_noise=0.0, dropout_prob=0.0),\n side_detector=dict(num_lasers=0, distance=50, gaussian_noise=0.0, dropout_prob=0.0),\n lane_line_detector=dict(num_lasers=0, distance=50, gaussian_noise=0.0, dropout_prob=0.0),\n\n # Following the examples: https://docs.panda3d.org/1.10/python/programming/physics/bullet/vehicles\n max_engine_force=1000,\n max_brake_force=100,\n max_steering=40,\n max_speed=80,\n ),\n map_config=dict(block_type_version=\"v2\"),\n\n # Disable map loading!\n auto_termination=False,\n load_map_from_json=False,\n _load_map_from_json=\"\",\n )\n )\n config.remove_keys([])\n return config\n\n def __init__(self, config: dict = None):\n super(PGDriveEnvV2, self).__init__(config=config)\n\n def _post_process_config(self, config):\n config = super(PGDriveEnvV2, self)._post_process_config(config)\n if config.get(\"gaussian_noise\", 0) > 0:\n assert config[\"vehicle_config\"][\"lidar\"][\"gaussian_noise\"] == 0, \"You already provide config!\"\n assert config[\"vehicle_config\"][\"side_detector\"][\"gaussian_noise\"] == 0, \"You already provide config!\"\n assert config[\"vehicle_config\"][\"lane_line_detector\"][\"gaussian_noise\"] == 0, \"You already provide config!\"\n config[\"vehicle_config\"][\"lidar\"][\"gaussian_noise\"] = config[\"gaussian_noise\"]\n config[\"vehicle_config\"][\"side_detector\"][\"gaussian_noise\"] = config[\"gaussian_noise\"]\n config[\"vehicle_config\"][\"lane_line_detector\"][\"gaussian_noise\"] = config[\"gaussian_noise\"]\n if config.get(\"dropout_prob\", 0) > 0:\n assert config[\"vehicle_config\"][\"lidar\"][\"dropout_prob\"] == 0, \"You already provide config!\"\n assert config[\"vehicle_config\"][\"side_detector\"][\"dropout_prob\"] == 0, \"You already provide config!\"\n assert config[\"vehicle_config\"][\"lane_line_detector\"][\"dropout_prob\"] == 0, \"You already provide config!\"\n config[\"vehicle_config\"][\"lidar\"][\"dropout_prob\"] = config[\"dropout_prob\"]\n config[\"vehicle_config\"][\"side_detector\"][\"dropout_prob\"] = config[\"dropout_prob\"]\n config[\"vehicle_config\"][\"lane_line_detector\"][\"dropout_prob\"] = config[\"dropout_prob\"]\n return config\n\n def _is_out_of_road(self, vehicle):\n # A specified function to determine whether this vehicle should be done.\n # return vehicle.on_yellow_continuous_line or (not vehicle.on_lane) or vehicle.crash_sidewalk\n ret = vehicle.on_yellow_continuous_line or vehicle.on_white_continuous_line or \\\n (not vehicle.on_lane) or vehicle.crash_sidewalk\n return ret\n\n def done_function(self, vehicle_id: str):\n vehicle = self.vehicles[vehicle_id]\n done = False\n done_info = dict(\n crash_vehicle=False, crash_object=False, crash_building=False, out_of_road=False, arrive_dest=False\n )\n if vehicle.arrive_destination:\n done = True\n logging.info(\"Episode ended! Reason: arrive_dest.\")\n done_info[TerminationState.SUCCESS] = True\n elif self._is_out_of_road(vehicle):\n done = True\n logging.info(\"Episode ended! Reason: out_of_road.\")\n done_info[TerminationState.OUT_OF_ROAD] = True\n elif vehicle.crash_vehicle:\n done = True\n logging.info(\"Episode ended! Reason: crash vehicle \")\n done_info[TerminationState.CRASH_VEHICLE] = True\n # elif vehicle.out_of_route or not vehicle.on_lane or vehicle.crash_sidewalk:\n elif vehicle.crash_object:\n done = True\n done_info[TerminationState.CRASH_OBJECT] = True\n logging.info(\"Episode ended! Reason: crash object \")\n elif vehicle.crash_building:\n done = True\n done_info[TerminationState.CRASH_BUILDING] = True\n logging.info(\"Episode ended! Reason: crash building \")\n\n # for compatibility\n # crash almost equals to crashing with vehicles\n done_info[TerminationState.CRASH\n ] = done_info[TerminationState.CRASH_VEHICLE] or done_info[TerminationState.CRASH_OBJECT] or \\\n done_info[TerminationState.CRASH_BUILDING]\n return done, done_info\n\n def cost_function(self, vehicle_id: str):\n vehicle = self.vehicles[vehicle_id]\n step_info = dict()\n step_info[\"cost\"] = 0\n if self._is_out_of_road(vehicle):\n step_info[\"cost\"] = self.config[\"out_of_road_cost\"]\n elif vehicle.crash_vehicle:\n step_info[\"cost\"] = self.config[\"crash_vehicle_cost\"]\n elif vehicle.crash_object:\n step_info[\"cost\"] = self.config[\"crash_object_cost\"]\n return step_info['cost'], step_info\n\n def reward_function(self, vehicle_id: str):\n \"\"\"\n Override this func to get a new reward function\n :param vehicle_id: id of BaseVehicle\n :return: reward\n \"\"\"\n vehicle = self.vehicles[vehicle_id]\n step_info = dict()\n\n # Reward for moving forward in current lane\n if vehicle.lane in vehicle.routing_localization.current_ref_lanes:\n current_lane = vehicle.lane\n positive_road = 1\n else:\n current_lane = vehicle.routing_localization.current_ref_lanes[0]\n current_road = vehicle.current_road\n positive_road = 1 if not current_road.is_negative_road() else -1\n long_last, _ = current_lane.local_coordinates(vehicle.last_position)\n long_now, lateral_now = current_lane.local_coordinates(vehicle.position)\n\n # reward for lane keeping, without it vehicle can learn to overtake but fail to keep in lane\n if self.config[\"use_lateral\"]:\n lateral_factor = clip(\n 1 - 2 * abs(lateral_now) / vehicle.routing_localization.get_current_lane_width(), 0.0, 1.0\n )\n else:\n lateral_factor = 1.0\n\n reward = 0.0\n reward += self.config[\"driving_reward\"] * (long_now - long_last) * lateral_factor * positive_road\n reward += self.config[\"speed_reward\"] * (vehicle.speed / vehicle.max_speed) * positive_road\n\n step_info[\"step_reward\"] = reward\n\n if vehicle.arrive_destination:\n reward = +self.config[\"success_reward\"]\n elif self._is_out_of_road(vehicle):\n reward = -self.config[\"out_of_road_penalty\"]\n elif vehicle.crash_vehicle:\n reward = -self.config[\"crash_vehicle_penalty\"]\n elif vehicle.crash_object:\n reward = -self.config[\"crash_object_penalty\"]\n return reward, step_info\n\n def _get_reset_return(self):\n ret = {}\n self.scene_manager.update_state_for_all_target_vehicles()\n for v_id, v in self.vehicles.items():\n self.observations[v_id].reset(self, v)\n ret[v_id] = self.observations[v_id].observe(v)\n return ret if self.is_multi_agent else self._wrap_as_single_agent(ret)\n\n\nif __name__ == '__main__':\n\n def _act(env, action):\n assert env.action_space.contains(action)\n obs, reward, done, info = env.step(action)\n assert env.observation_space.contains(obs)\n assert np.isscalar(reward)\n assert isinstance(info, dict)\n\n # env = PGDriveEnvV2({'use_render': True, \"fast\": True, \"manual_control\": True})\n env = PGDriveEnvV2()\n try:\n obs = env.reset()\n assert env.observation_space.contains(obs)\n for _ in range(100000000):\n _act(env, env.action_space.sample())\n # for x in [-1, 0, 1]:\n # env.reset()\n # for y in [-1, 0, 1]:\n # _act(env, [x, y])\n finally:\n env.close()\n","sub_path":"pgdrive/envs/pgdrive_env_v2.py","file_name":"pgdrive_env_v2.py","file_ext":"py","file_size_in_byte":9506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"59680492","text":"################ HOME ASSIGNMENT_04\n#Задача 1 -делали\n\n'''\nЗадача 2. Дана строка, состоящая из слов, разделенных пробелами. Определите, сколько в ней слов. Используйте для решения\nзадачи метод `count`\n'''\ns = 'Дана строка состоящая из слов разделенных пробелами Определите сколько в ней слов Используйте для решения задачи метод count'\ns = s.split()\ncount = 0\nfor i in range(len(s)):\n if s.count(s[i]) > 1:\n count += 1\n else:\n count += s.count(s[i])\nprint(count)\n'''\nЗадача 3. Дана строка. Разрежьте ее на две равные части (если длина строки — четная, а если длина строки нечетная, то длина \nпервой части должна быть на один символ больше). Переставьте эти две части местами, результат запишите в новую строку \nи выведите на экран. При решении этой задачи посторайтесь не пользоваться инструкцией if.\n'''\ns = 'Дана>>>строка.'\nprint(\"Строка s:\", s)\nl = len(s)\nprint(\"Длина строки s= \", l)\ns = s[(l//2+l%2):]+s[0:(l//2+l%2)]\nprint(\"Новая строка s:\", s)\n\n#Задача 4. делали\n\"\"\"\nЗадача 5. Дана строка. Если в этой строке буква `f` встречается только один раз, выведите её индекс. \nЕсли она встречается два и более раз, выведите индекс её первого и последнего появления. Если буква `f` в данной строке \nне встречается, ничего \nне выводите.\nПри решении этой задачи использовать циклы - ЗАПРЕЩЕНО!\n\"\"\"\ns = 'ashbf fsfwebnjsdkaw'\nif s.count('f') == 1:\n print(s.find('f'))\nelif s.count('f') > 1:\n print(s.find('f'), \" \", s.rfind('f'))\n'''\nЗадача 6. Дана строка. Найдите в этой строке второе вхождение буквы f, и выведите индекс этого вхождения.\n Если буква f в данной строке встречается только один раз, выведите число -1, а если не встречается ни разу, \n выведите число -2. При решении этой задачи использовать циклы - ЗАПРЕЩЕНО!\n'''\ns = 'ashbfyftyufghjfsfwebnjsdkaw'\nx = s.find('f')\nif s.count('f') == 1:\n print(\"result -1\")\nelif s.count('f') > 1:\n x = s.find('f', x+1, -1)\n print(\"index f = \", x)\nelif s.count('f') == 0:\n print('result -2')\n#Задача 7.-делали\n\"\"\"\nЗадача 8. Дана строка, в которой буква `h` встречается как минимум два раза. Разверните последовательность символов, \nзаключенную между первым и последним появлением буквы `h`, в противоположном порядке.\n\"\"\"\ns = \"abrah codabrah neh ponyatnoh choh delath mne\"\ns2 = s[s.find('h'):s.rfind('h')+1]\nprint(s.replace(s2, s2[::-1]))\n#Задача 9. Дана строка. Замените в этой строке все цифры `1` на слово `one`.\ns = \"1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5\"\ns = s.replace(\"1\", \"one\")\nprint(s)\n#Задача 10. Дана строка. Удалите из этой строки все символы `@`\ns = \"em@il company is company@gmail.com, dont forget about '@' in adress\"\ns = s.replace(\"@\", \"\")\nprint(s)\n\n# 11. Дана строка. Замените в этой строке все появления буквы `h` на букву `H`, кроме первого и последнего вхождения.\ns = \"abrah codabrah neh ponyatnoh choh delath mne\"\ns2 = s[s.find('h')+1:s.rfind('h')]\ns2 = s2.replace('h', 'H')\nx = s.find('h')+1\ny = s.rfind('h')\ns = s[0:x]+s2+s[y::]\nprint(s)\n# 12. Дана строка. Удалите из нее все символы, чьи индексы делятся на `3`.\ns = 'abcdefghijklm'\nprint(\"Наша строка: \", s)\nprint(\"Символы чьи индексы делятся на 3: \", s[3::3])\nfor j in range(1, len(s)):\n if j % 3 == 0:\n s = s.replace(s[j], '#')\ns = s.replace('#', '')\nprint(\"Наша строка с удаленными символами: \", s)\n","sub_path":"HA_04.py","file_name":"HA_04.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"404387751","text":"import sys\nimport os\nimport time\nimport psutil\nimport shutil\nfrom pprint import pprint\nimport win32gui\nimport win32com.client\n\nsys.path.append(os.getcwd())\nfrom Controller.Common import *\nfrom Controller.DBLib import MongoDriver\n\n\nclass NoxConDocker(object):\n def __init__(self, task_info):\n self._DEBUG = True\n self.start_retry_cnt = 3\n self.error_msg = [] # 启动诊断信息\n self._taskId = task_info['taskId']\n self._task_info = task_info\n self._local_ip = LOCAL_IP\n self._org_path = os.getcwd()\n self._work_path = WORK_PATH\n self._app_name = task_info['app_name']\n self._docker_id = None\n self._docker_name = 'nox-{}'.format(task_info['taskId'])\n self._docker_img_name = task_info['docker_img_name']\n self._mdb = MongoDriver()\n\n # def __del__(self):\n # print('call NoxConDocker.__del__')\n # os.chdir(self._org_path)\n\n def docker_precheck(self):\n self.error_msg.clear()\n if not self._local_ip:\n self.add_deadly_msg('docker_precheck', '必须设定环境变量 APPSIMULATOR_IP')\n return False\n\n if not self._app_name:\n self.add_deadly_msg('docker_precheck', '必须设定App名字')\n return False\n\n mem = psutil.virtual_memory()\n if mem.free < 1 * GB: # < 1GB\n self.add_deadly_msg('docker_precheck', '剩余内存需大于 1GB.')\n return False\n else:\n self._log('docker_precheck', 'Memory: {:.1f} GB'.format(mem.free / GB))\n\n if not os.access('{}\\\\{}'.format(NOX_BACKUP_PATH, self._docker_img_name), os.R_OK):\n self.add_deadly_msg('docker_precheck', '未找到镜像文件: {}'.format(self._docker_img_name))\n return False\n\n # if len(self.docker_ps(docker_name='nox-org')) == 0:\n # self.add_deadly_msg('docker_precheck', '未找到 nox-org.')\n # return False\n\n running_dockers = self.docker_ps(docker_status=STATUS_DOCKER_RUN_OK)\n if len(running_dockers) >= len(TIMER):\n self.add_deadly_msg('docker_precheck', '启动数量不能大于 TIMER 设定数量:{}'.format(len(TIMER)))\n return False\n else:\n self._log('docker_precheck', '正在运行的模拟器数: {}'.format(len(running_dockers)))\n\n return True\n\n def docker_make_cmd(self, cmd):\n os.chdir(NOX_BIN_PATH)\n return 'NoxConsole ' + cmd\n\n def docker_exec_nox_cmd(self, cmdline):\n _stdout = ''\n _stderr = ''\n try:\n self._log('[nox_cmd] cmdline:\\n\\t', cmdline)\n time.sleep(1)\n os.chdir(NOX_BIN_PATH) # 防止 BignoxVMS 写入.py本地\n process = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n # process.wait()\n (stdout, stderr) = process.communicate()\n _stdout = stdout.decode('gbk')\n _stderr = stderr.decode('gbk')\n except Exception as e:\n self._log('<<error>> _exec_nox_cmd Exception:\\n', e)\n finally:\n os.chdir(self._org_path) # 恢复路径\n\n self._log('<<info>>[nox_cmd] stdout:\\n', _stdout)\n if _stderr:\n self._log('<<info>>[nox_cmd] stderr:\\n', _stderr)\n return 'error: {}'.format(_stderr)\n else:\n time.sleep(1)\n return _stdout\n\n def docker_cmd_kill_task(self, docker_name):\n dockers = self.docker_ps(docker_name=docker_name, docker_status=STATUS_DOCKER_RUN_OK)\n for d in dockers:\n cmd = 'TASKKILL /F /T /PID {}'.format(d['pid']) # 不能强杀,会造成 ERR:1037\n common_exec_cmd(True, cmd)\n # os.system(cmd)\n\n def docker_kill_task(self):\n # <<cmd>> taskkill /f /t /fi \"WINDOWTITLE eq task-99\"\n cmd = 'TASKKILL /F /T /FI \"WINDOWTITLE eq task-{}\"'.format(self._taskId)\n common_exec_cmd(True, cmd)\n # os.system(cmd)\n\n def docker_shake(self, cnt):\n # shell = win32com.client.Dispatch(\"WScript.Shell\")\n # shell.SendKeys('%')\n # hwnd = win32gui.FindWindow(None, self._docker_name)\n # if hwnd:\n # win32gui.SetForegroundWindow(hwnd)\n\n self._log('<<info>> docker_shake', str(cnt) + ' times')\n for _ in range(cnt):\n self.docker_exec_nox_cmd(self.docker_make_cmd(\n \"action -name:{} -key:call.shake -value:null\".format(self._docker_name)\n ))\n return True\n\n def docker_rmi(self, kill_script=False, wait_time=2): # remove docker image\n self._log('<<info>> docker_rmi', '退出并删除模拟器')\n # if kill_script: # kill �� cmd 启动的 python script_xxx.py\n # self.kill_task()\n\n time.sleep(wait_time)\n self.docker_exec_nox_cmd(self.docker_make_cmd(\"quit -name:{}\".format(self._docker_name)))\n time.sleep(wait_time)\n\n # 确保窗体关闭\n # stdout = common_exec_cmd(self._DEBUG, 'TASKLIST /FI \"WINDOWTITLE eq {}\"'.format(self._docker_name))\n # if stdout.replace('\\r\\n', '') == '信息: 没有运行的任务匹配指定标准。': # win10 win7 cmd 提示信息\n # return self.remove()\n # else:\n # return False\n self.docker_remove()\n return True\n\n def docker_rmi_all(self):\n self._log('<<info>> docker_rmi_all', 'wait: 10s')\n time.sleep(2)\n self.docker_exec_nox_cmd(self.docker_make_cmd('quitall'))\n time.sleep(10)\n return True\n\n def docker_ps(self, docker_name=None, docker_status=None):\n devices = []\n ret = self.docker_exec_nox_cmd(self.docker_make_cmd('list'))\n if ret:\n # 虚拟机名称,标题,顶层窗口句柄,工具栏窗口句柄,绑定窗口句柄,进程PID\n for s in ret.split('\\r\\n'):\n if s.startswith('nox') or s.startswith('Nox'):\n status = STATUS_WAIT if s.split(',')[-1] == '-1' else STATUS_DOCKER_RUN_OK\n name = s.split(',')[1]\n id = s.split(',')[0]\n pid = s.split(',')[-1]\n\n if (docker_status is None or status == docker_status) and (\n docker_name is None or name == docker_name):\n devices.append({'id': id, 'name': name, 'status': status, 'pid': pid})\n\n return devices\n\n def docker_pull(self): # restore\n self._log('docker_pull', self._docker_img_name)\n time.sleep(1)\n ret = self.docker_exec_nox_cmd(self.docker_make_cmd(\n 'restore -name:{} -file:\"{}\\\\{}\"'.format(self._docker_name, NOX_BACKUP_PATH, self._docker_img_name)\n ))\n if ret.find('failed') > 0:\n return False\n else:\n time.sleep(5)\n return True\n\n def docker_copy(self, org, wait_time=10):\n self._log('docker_copy', self._docker_name)\n time.sleep(wait_time)\n self.docker_exec_nox_cmd(self.docker_make_cmd(\"copy -name:{} -from:{}\".format(self._docker_name, org)))\n return True\n\n def docker_add(self):\n self._log('docker_add', self._docker_name)\n time.sleep(2)\n # ret = self.docker_exec_nox_cmd(self.docker_make_cmd(\"add -name:\" + self._docker_name))\n ret = self.docker_exec_nox_cmd(self.docker_make_cmd(\n \"add -name:\" + self._docker_name + ' -systemtype:4')) # nox 6.2.1\n time.sleep(2)\n return False if ret.find('failed') != -1 or \\\n ret.find('not') != -1 or \\\n ret.find('system type err!') != -1 else True # nox 6.2.1\n\n def docker_remove(self):\n self._log('docker_remove', self._docker_name)\n time.sleep(2)\n self.docker_exec_nox_cmd(self.docker_make_cmd(\"remove -name:{}\".format(self._docker_name)))\n time.sleep(2)\n self._mdb.docker_destroy(docker_obj=self)\n self._mdb.task_unbind_docker(self._task_info) # unbind task\n return True\n\n def docker_create(self):\n poweron = self._work_path + '\\\\static\\\\AppSimulator\\\\images\\\\temp\\\\emulators\\\\poweron.png'\n static_capture_path = '{}\\\\static\\\\AppSimulator\\\\images\\\\temp\\\\emulators\\\\capture_{}.png'.format(\n self._work_path, self._docker_name)\n if os.access(static_capture_path, os.R_OK):\n shutil.copy(poweron, static_capture_path)\n\n self._docker_id = self._mdb.docker_create(docker_obj=self)\n self._mdb.task_bind_docker(self._task_info, self._docker_id) # bind docker to task\n\n ret = self.docker_precheck()\n if not ret:\n self._log('<<error>> docker_precheck', '\\n'.join(self.error_msg))\n self.start_retry_cnt = -1 # 不满足启动条件\n return False\n\n dockers = self.docker_ps(docker_name=self._docker_name)\n if len(dockers) > 1:\n pprint(dockers)\n self.add_deadly_msg('docker_ps', '找到不止 1 个模拟器')\n self._log('<<error>> docker_ps', self.error_msg)\n return False\n\n if len(dockers) == 1:\n # if dockers[0]['status'] == STATUS_DOCKER_RUN:\n ret = self.docker_rmi(kill_script=True, wait_time=5)\n if not ret:\n self.add_deadly_msg('docker_rmi', 'rmi failed!')\n self._log('<<error>> docker_rmi', self.error_msg)\n return False\n\n # self.copy('nox-org') # copy命令不稳定\n ret = self.docker_add()\n if not ret:\n self.add_deadly_msg('docker_add', 'add failed!')\n self._log('<<error>> docker_add', self.error_msg)\n return False\n\n ret = self.docker_pull()\n if not ret:\n self.add_deadly_msg('docker_pull', 'pull failed!')\n self._log('<<error>> docker_pull', self.error_msg)\n return False\n\n return True\n\n def docker_start(self, timeout=2):\n time.sleep(timeout)\n stdout = self.docker_exec_nox_cmd(self.docker_make_cmd(\"launch -name:\" + self._docker_name))\n time.sleep(timeout)\n if stdout.find('player is not exist!') == -1:\n return True\n else:\n self.add_deadly_msg('docker_start', 'launch failed!')\n return False\n\n def docker_run(self): # run = create + start\n ret = self.docker_create()\n if ret:\n ret = self.docker_start()\n\n return ret\n\n def get_name(self):\n return self._docker_name\n\n def get_docker_id(self):\n return self._docker_id\n\n def get_taskId(self):\n return self._taskId\n\n def get_app_name(self):\n return self._app_name\n\n def add_deadly_msg(self, prefix, msg): # 模拟器致命错误\n self._log(prefix, msg)\n self.error_msg.append(msg)\n self._mdb.docker_add_deadly_msg(docker_obj=self, error_msg=msg)\n\n def _log(self, prefix, msg):\n common_log(self._DEBUG, self._taskId, 'Docker ' + self._docker_name, prefix, msg)\n\n\n# -------------------------------------------------------------------------------\ndef main(task_info):\n docker = NoxConDocker(task_info=task_info)\n docker._DEBUG = True\n return docker.docker_run()\n\n\nif __name__ == \"__main__\":\n # docker_name = sys.argv[1]\n docker_name = 'nox-2'\n task_info = {\n 'taskId': 2,\n 'app_name': 'miaopai',\n 'docker_name': docker_name,\n 'timer_no': 2\n }\n main(task_info)\n print(\"Close after 60 seconds.\")\n time.sleep(60)\n","sub_path":"Controller/NoxConDocker.py","file_name":"NoxConDocker.py","file_ext":"py","file_size_in_byte":11513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"644014414","text":"\nfrom Sire.Mol import *\nfrom Sire.IO import *\nfrom Sire.Vol import *\nfrom Sire.FF import *\nfrom Sire.MM import *\nfrom Sire.CAS import *\nfrom Sire.Maths import *\nfrom Sire.Qt import *\nfrom Sire.Units import *\nfrom Sire.System import *\nfrom Sire.Move import *\nfrom Sire.Stream import *\n\nimport sys\n\nmols = PDB().read(\"test/io/water.pdb\")\n \nprint(\"Read in %d molecules!\" % mols.nMolecules())\n\nmol = mols.moleculeAt(0).molecule()\n\nmol = mol.edit().atom( AtomName(\"O00\") ) \\\n .setProperty(\"LJ\", LJParameter(3.15363*angstrom, \\\n 0.15500*kcal_per_mol)).molecule() \\\n .atom( AtomName(\"H01\") ) \\\n .setProperty(\"charge\", 0.520 * mod_electron).molecule() \\\n .atom( AtomName(\"H02\") ) \\\n .setProperty(\"charge\", 0.520 * mod_electron).molecule() \\\n .atom( AtomName(\"M03\") ) \\\n .setProperty(\"charge\", -1.04 * mod_electron).molecule() \\\n .commit()\n\ncharges = mol.property(\"charge\")\nljs = mol.property(\"LJ\")\n\ncljff = InterCLJFF(\"water-water\")\n\ncljff.add(mol)\n\nsolvent = MoleculeGroup(\"solvent\")\nsolvent.add(mol)\n\nfor i in range(1,7):\n mol = mols.moleculeAt(i).molecule()\n\n mol = mol.edit().rename(\"T4P\") \\\n .setProperty(\"charge\", charges) \\\n .setProperty(\"LJ\", ljs) \\\n .commit()\n\n solvent.add(mol)\n cljff.add(mol)\n\nsystem = System()\nsystem.add(solvent)\nsystem.add(cljff)\n\nprint(system.energy())\n\nrbmove = MolecularDynamics( solvent, DLMRigidBody(), 1*femtosecond )\n\n#rbmove.setEnergyComponent( cljff.components().coulomb() )\n\nPDB().write(system.molecules(), \"test0000.pdb\")\n\nfor i in range(1,1000):\n rbmove.move(system, 10)\n print(i, system.energy())\n print(rbmove.kineticEnergy(), (system.energy() + rbmove.kineticEnergy()))\n\n PDB().write(system.molecules(), \"test%0004d.pdb\" % i)\n\n","sub_path":"corelib/test/SireMove/rigidbodymd.py","file_name":"rigidbodymd.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"584391725","text":"from django import forms\n\nclass detailForm(forms.Form):\n detailPart = forms.CharField(\n label='タイトル',\n max_length=15,\n widget=forms.TextInput(attrs={'class' : 'part'}),\n required=True,\n )\n detailName = forms.CharField(\n label='名称(人名)',\n max_length=15,\n widget=forms.TextInput(attrs={'class' : 'name'}),\n required=True,\n )\n detailContents = forms.CharField(\n label='内容',\n max_length=8000,\n widget=forms.Textarea(attrs={'rows': 10,'cols': 110,'class' : 'contents'}),\n required=True,\n )\n detailBiko = forms.CharField(\n label='備考',\n max_length=8000,\n widget=forms.Textarea(attrs={'rows': 10,'cols': 110,'class' : 'contents'}),\n required=True,\n )","sub_path":"memo/memoDetail/detailForms.py","file_name":"detailForms.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"14260852","text":"from libAlexa.Core.ResponseBase import ResponseBase\nfrom libAlexa.Core.Interfaces import Interfaces\n\n\nclass Channel(ResponseBase):\n def __init__(self):\n super().__init__()\n\n def set_channel(self, number, callsign):\n value = {\n \"number\": number,\n \"callSign\": callsign,\n \"affiliateCallSign\": callsign\n }\n super().add_property(Interfaces.ChannelController.value, \"channel\", value)\n","sub_path":"libAlexa/Response/Channel.py","file_name":"Channel.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"243161120","text":"import config as cfg\n\nfrom common.model import MyModel\nfrom common.dataset import MyDataset\nfrom common.utils import calc_weights_generator\n\nfor setup in cfg.setups:\n # Grab dataset\n my_dataset = MyDataset(\n collection_name = cfg.dataset['collection_name'],\n batch_size = setup['batch_size'],\n limit = cfg.dataset['limit'],\n input_shape = cfg.dataset['input_shape']\n )\n\n # Create generators\n train_generator, valid_generator, test_generator = my_dataset.get_generators()\n\n # Only for weighted loss functions\n if setup['loss_fn'] == 'wce':\n loss_weights = calc_weights_generator(train_generator)\n else:\n loss_weights = None\n\n # Create model\n my_model = MyModel(\n train_generator = train_generator,\n valid_generator = valid_generator,\n test_generator = test_generator,\n struct = cfg.model['struct'],\n arch = setup['arch'],\n loss_fn = setup['loss_fn'],\n optimizer_fn = setup['optimizer_fn'],\n batch_size = setup['batch_size'],\n batch_norm = setup['batch_norm'],\n filters = setup['filters'],\n input_shape = cfg.dataset['input_shape'],\n threshold = setup['threshold']\n )\n\n my_model.create(load_weights=False, loss_weights=loss_weights)\n my_model.print_summary()\n\n # Train model\n my_model.train(epochs = cfg.model['epochs'])\n\n # Evaluate model\n my_model.evaluate()\n\n # Plot sample output result\n # my_model.plot_result(\n # coords = (cfg.logs['axis_0'], cfg.logs['axis_1'], cfg.logs['axis_2']),\n # show = False, save = True\n # )\n\n # Save results\n my_model.save_results(f'output/models/{cfg.dataset[\"collection_name\"]}_results')\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"37978089","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import login\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth.decorators import login_required\nfrom overmortal.util.social.twitter import Twitter\nfrom overmortal.util.oauth import oauth\nimport simplejson\nfrom models import Twitter as TwitterUser\n\nTWITTER = Twitter(settings.TWITTER_API_KEY, settings.TWITTER_API_SECRET)\n\n@login_required\ndef connect(request):\n return render_to_response('twitter_connect.html', locals())\n\n@login_required\ndef oauth_request(request):\n token = TWITTER.get_unauthorised_request_token()\n auth_url = TWITTER.get_authorisation_url(token)\n response = HttpResponseRedirect(auth_url)\n request.session['unauthed_token'] = token.to_string() \n return response\n\n@login_required\ndef oauth_return(request):\n unauthed_token = request.session.get('unauthed_token', None)\n if not unauthed_token:\n return HttpResponse(\"No un-authed token cookie\")\n token = oauth.OAuthToken.from_string(unauthed_token) \n if token.key != request.GET.get('oauth_token', 'no-token'):\n return HttpResponse(\"Something went wrong! Tokens do not match\")\n access_token = TWITTER.exchange_request_token_for_access_token(token)\n auth_user = TWITTER.get_user(access_token)\n if auth_user:\n try:\n twitter_user = TwitterUser.objects.get(user = request.user)\n except ObjectDoesNotExist:\n twitter_user = TwitterUser(user = request.user, username = auth_user['screen_name'], access_token = access_token)\n twitter_user.save();\n response = HttpResponseRedirect(reverse(settings.TWITTER_OAUTH_RETURN_STRING))\n request.session['access_token'] = access_token.to_string()\n return response\n\n#@login_required\n#def get_friends(request):\n# users = []\n# access_token = request.session.get('access_token', None)\n# if not access_token:\n# return HttpResponse(\"You need an access token!\")\n# token = oauth.OAuthToken.from_string(access_token)\n# # Check if the token works on Twitter\n# auth = TWITTER.is_authenticated(token)\n# if auth:\n# # Load the credidentials from Twitter into JSON\n# creds = simplejson.loads(auth)\n# name = creds.get('name', creds['screen_name']) # Get the name\n# # Get number of friends. The API only returns 100 results per page,\n# # so we might need to divide the queries up.\n# friends_count = str(creds.get('friends_count', '100'))\n# pages = int( (int(friends_count)/100) ) + 1\n# pages = min(pages, 10) # We only want to make ten queries\n# for page in range(pages):\n# friends = TWITTER.get_friends(token, page+1)\n# # if the result is '[]', we've reached the end of the users friends\n# if friends == '[]': break\n# # Load into JSON\n# json = simplejson.loads(friends)\n# users.append(json)\n# return render_to_response('list.html', {'users': users})\n","sub_path":"lib/twitter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"525492341","text":"import re\n\n'''\nCel mai mare divizor comun a mai multor numere (definiti o functie cu numar variabil de parametri care sa rezolve acest lucru)\n'''\n\n\ndef gcd(x, y):\n if x == y:\n return x\n else:\n return gcd(max(x, y) - min(x, y), min(x, y))\n\n\nprint(\"1. \" + str(gcd(8, 4)))\n\n'''\nScrieti o functie care calculeaza cate vocale sunt intr-un sir de caractere\n'''\n\n\ndef vowel_count(word):\n return len(list(filter(lambda x: x in \"aeiouAEIOU\", word)))\n\n\nprint(\"2. \" + str(vowel_count(\"This is a sentence with 9 vowels.\")))\n\n'''\nScrieti o functie care returneaza numarul de cuvinte care exista intr-un string. Cuvintele sunt separate de spatii, semne de punctuatie (, ;, ? ! . )\n'''\n\n\ndef wordcount(sentence):\n return len(re.findall(\"[a-zA-Z]+\", sentence))\n\n\nprint(\"3. \" + str(wordcount(\"This, . is ... a ,,,sentence .,\")))\n\n'''\nScrieti o functie care primeste ca parametri doua siruri de caractere \nsi care returneaza numarul de aparitii ale primului sir de caractere in al doilea.\n'''\n\n\ndef apparitions(s1, s2):\n count = 0\n for i in range(0, len(s2)):\n if s2[i:(i + len(s1))] == s1:\n count += 1\n return count\n\n\nprint(\"4. \" + str(apparitions(\"a\", \"aaab\")))\n\n'''\nScrieti o functie care converteste in sir de caractere scris UpperCamelCase in lowercase_with_underscores.\n'''\n\n\ndef is_upper(c):\n if c.isupper():\n return \"_\" + c.lower()\n else:\n return c\n\n\ndef convert(string):\n return \"\".join(map(lambda x: is_upper(x), string))\n\n\nprint(convert(\"UpperCamelCase\"))\n\n'''\nSe da un sir de caractere care reprezinta un polinom (Ex: \"3x^3 + 5x^2 - 2x - 5\") \nsi un numar (intreg sau float). Sa se evalueze polinomul respectiv pentru valoarea data.\n'''\n\n\ndef compute(polynomial, value):\n # replacing x with value\n fixed = polynomial.replace(\"x\", \"*\" + str(value))\n\n print(fixed)\n # list of operands and numbers\n agents = re.findall(\"[0-9]+|-|\\*|\\^|\\+\", fixed)\n\n nums = agents[0::2]\n ops = agents[1::2]\n\n for i in range(0, len(agents[1::2])):\n print(nums[i] + \" \" + ops[i] + \" \" + nums[i + 1])\n\n\ncompute(\"21x^2 + 13x^2 + 3x - 3\", 4)\n\n'''\nScrieti o functie care sa returneze cel mai mare numar prim dintr-un sir de caractere dat ca parametru \n sau -1 daca sirul de caractere nu contine nici un numar prim. \nEx: input: 'ahsfaisd35biaishai23isisvdshcbsi271cidsbfsd97sidsda'; output: 271\n'''\n\n\ndef replace_alpha(c, y):\n # if current letter is followed by a digit, return a space to distinguish between numbers\n if c.isalpha() and y.isdigit():\n return \" \"\n # if its digit, return it as it is\n elif c.isdigit():\n return c\n # if its only a letter follow by some other letter, erase it\n elif c.isalpha():\n return \"\"\n\n\ndef is_prime(input):\n return all(map(lambda x: input % x != 0, list(range(2, input / 2))))\n\n\ndef biggest_prime(input):\n # parsing the list 2 consecutive letters at a time; added \" \" so it fully parses it\n removed_letters = map(lambda z, y: replace_alpha(z, y), list(input), list(input[1:] + \" \"))\n\n # filtering out the \"\" elements, and created a string that would look like: \" 27 75 271 1\"\n removed_empty_indexes = \"\".join(filter(lambda y: not y == \"\", removed_letters))\n\n # using regexes to filter out the numbers, then removing the empty \"\" and transforming them into actual ints\n list_of_numbers = map(lambda x: int(x), filter(lambda x: x != \"\", re.findall(\"[0-9]*\", removed_empty_indexes)))\n\n # filtering only the primes\n result = filter(lambda x: is_prime(x), list_of_numbers)\n\n # returning the appropiate result\n if len(result) == 0:\n return -1\n else:\n return max(result)\n\n\na = biggest_prime(\"ahsfaisd35biaishai23isisvdshcbsicidsbfsd97sidsda271\")\nprint(a)\n","sub_path":"Lab1/lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"460762172","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n commands = {\n \"HLT\": 0b01,\n \"LDI\": 0b10000010,\n \"PRN\": 0b01000111,\n \"ADD\": 0b10100000,\n \"MUL\": 0b10100010,\n \"PUSH\": 0b01000101,\n \"POP\": 0b01000110,\n \"CALL\": 0b01010000,\n \"RET\": 0b00010001,\n }\n\n commands_inverted = {\n 0b01: \"HLT\",\n 0b10000010: \"LDI\",\n 0b01000111: \"PRN\",\n 0b10100000: \"ADD\",\n 0b10100010: \"MUL\",\n 0b01000101: \"PUSH\",\n 0b01000110: \"POP\",\n 0b01010000: \"CALL\",\n 0b00010001: \"RET\"\n }\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.ram = [0] * 256 \n self.reg = [0] * 8\n # Initialize the stack pointer. R7 is the dedicated stack pointer.\n self.reg[7] = 0xf4\n self.pc = 0\n self.branch_table = {\n \"HLT\": self.HLT,\n \"LDI\": self.LDI,\n \"PRN\": self.PRN,\n \"ADD\": self.ADD,\n \"MUL\": self.MUL,\n \"PUSH\": self.PUSH,\n \"POP\": self.POP,\n \"CALL\": self.CALL,\n \"RET\": self.RET\n }\n\n def load(self, program):\n \"\"\"Load a program into memory.\"\"\"\n address = 0\n try: \n with open(program) as p:\n for instruction in p:\n instruction = instruction.strip().split(\"#\")[0]\n if instruction != \"\":\n self.ram_write(address, int(instruction, 2))\n address += 1\n except Exception:\n raise ValueError(\"Invalid file path.\")\n\n def ram_read(self, address): \n try: \n return self.ram[address]\n except IndexError:\n raise ValueError(\"The address of value \" + str(address) + \" isn't a valid location in memory\")\n \n def ram_write(self, address, value):\n self.ram[address] = value\n return value\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n\n elif op == \"MUL\":\n self.reg[reg_a] *= self.reg[reg_b]\n\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n #self.fl,\n #self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def HLT(self):\n self.pc += 1\n sys.exit(0) \n\n def LDI(self):\n self.reg[self.ram[self.pc + 1]] = self.ram[self.pc + 2]\n self.pc += 3\n \n def PRN(self):\n print(self.reg[self.ram[self.pc + 1]])\n self.pc += 2\n\n def ADD(self):\n self.alu(\"ADD\", self.ram[self.pc + 1], self.ram[self.pc + 2])\n self.pc += 3\n \n def MUL(self):\n self.alu(\"MUL\", self.ram[self.pc + 1], self.ram[self.pc + 2])\n self.pc += 3\n\n def PUSH(self):\n # The seventh register is dedicated to keeping track of the stack pointer\n SP = 7\n self.reg[SP] -= 1\n self.ram[self.reg[SP]] = self.reg[self.ram[self.pc + 1]]\n\n self.pc += 2\n \n def POP(self):\n # The seventh register is dedicated to keeping track of the stack pointer\n SP = 7 \n self.reg[self.ram[self.pc + 1]] = self.ram[self.reg[SP]]\n self.reg[SP] += 1\n\n self.pc += 2\n \n def CALL(self):\n SP = 7\n self.reg[SP] -= 1\n # Push the return address onto the stack\n self.ram[self.reg[SP]] = self.pc + 2\n # Jump to the pc held in the given register\n self.pc = self.reg[self.ram[self.pc + 1]]\n \n def RET(self):\n SP = 7 \n address_to_jump_to = self.ram[self.reg[SP]]\n self.reg[SP] += 1\n self.pc = address_to_jump_to\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n IR = None\n while IR != self.commands[\"HLT\"]:\n IR = self.ram_read(self.pc)\n\n if IR in self.commands_inverted:\n self.branch_table[self.commands_inverted[IR]]()\n else:\n raise Exception(f\"Invalid Command: {IR}\")\n \n # Reset the program counter\n self.pc = 0\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"277211599","text":"import numpy as np\nimport pickle\nimport cv2\nimport sys\nimport os\n\ndef compile(input):\n \"\"\"\n Script que convierte una imagen con transparencia en una máscara (*.dat)\n Tengo pensado implementar un algoritmo de compresión (si renpy permite el uso de threads)\n input = *.png|jpeg|webp\n \"\"\"\n\n # Obtenemos la máscara de una imagen con transparencia\n img = cv2.imread(input, cv2.IMREAD_UNCHANGED)\n alpha = img[:, :, 3]\n alpha = cv2.threshold(alpha, 0, 1, cv2.THRESH_BINARY)[1]\n\n # Array al que pasaremos a limpio\n clean = []\n for i in range(0, len(alpha)):\n list = []\n for a in alpha[i]:\n # Convertimos a integer para ahorrar aun más espacio\n list.append(int(a)) \n # Convertimos a tupla (ahorrar espacio y recursos)\n list = tuple(list) \n clean.append(list)\n\n # Convertimos la lista principal en tupla\n clean = tuple(clean)\n\n # Almacenamos en un fichero\n output = os.path.splitext(input)[0] + '.dat'\n with open(output, 'wb') as fp:\n pickle.dump(clean, fp, protocol=2)\n\n# ......\n# ......\nif len(sys.argv) == 2:\n compile( sys.argv[1] )\nelse:\n print('Necesita la entrada del fichero')","sub_path":"examples/ObjectFX/game/images/masktool.py","file_name":"masktool.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"34675146","text":"#!usr/bin/env python\n# -*- coding:utf-8 -*-\n# auther:Mr.chen\n# 描述:\n\nimport os,sys\nsys.path.append('..')\nfrom lib.Teachers_model import teacher_Model\nfrom lib.Lessons_model import lesson_Model\nfrom lib import common\n\nDIR = os.path.dirname(__file__)\nDIR = DIR.replace('src','db/')\n\nTAG = True\n\ndef create_Teachers_model():\n \"\"\"\n 创建老师模型\n :return: None\n \"\"\"\n while TAG:\n name = raw_input(\"请输入老师的姓名:\")\n age = raw_input(\"请输入老师的年龄:\")\n sex = raw_input(\"请输入老师的性别:\")\n while TAG:\n text = \"\"\"\n 老师信息如下:\n 姓名:{0}\n 年龄:{1}\n 性别:{2}\n \"\"\".format(name,age,sex)\n print (text)\n decide = raw_input(\"是否确认(y/n):\")\n if decide == 'y':\n P = teacher_Model(name,age,sex)\n dict = common.log_info_read(DIR+'config_conf')\n if dict != False:\n dict['teachers'].append(P)\n common.log_info_write(DIR + 'config_conf', dict)\n print (\"老师信息保存成功!\")\n return\n else:\n dict = {\n 'teachers':[P],\n 'lessons':[],\n 'students':[]\n }\n common.log_info_write(DIR+'config_conf',dict)\n print (\"老师信息保存成功!\")\n return\n elif decide == 'n':\n break\n else:\n print (\"您的输入有误!\")\n\n\n\ndef create_Lesson_model():\n \"\"\"\n 创建课程模型\n :return: None\n \"\"\"\n num = 0\n list = []\n dict = common.log_info_read(DIR + 'config_conf')\n if dict == False:\n print (\"请先创建老师模型后再来!\")\n return\n name = raw_input(\"请输入课程名称:\")\n cost = raw_input(\"请输入课时费:\")\n while TAG:\n print (\"目前有{0}个老师可供选择,如下:\".format(str(len(dict['teachers']))))\n for P in dict['teachers']:\n print (\"{0}:姓名:{1},年龄:{2},性别:{3}\".format(str(num+1),P.Name,P.Age,P.Sex))\n num += 1\n list.append(str(num))\n choose = raw_input(\"请输入索引选择授课老师:\")\n if choose in list:\n tobj = dict['teachers'][int(choose)-1]\n L = lesson_Model(name,cost,tobj)\n while TAG:\n text = \"\"\"\n 课程的信息如下:\n 课程名:{0}\n 课时费:{1}\n 授课老师:{2}\n \"\"\".format(name, cost, L.Tobj.Name)\n print (text)\n decide = raw_input(\"是否确认(y/n):\")\n if decide == 'y':\n dict['lessons'].append(L)\n common.log_info_write(DIR + 'config_conf', dict)\n return\n elif decide == 'n':\n return\n else:\n print (\"您的输入有误!\")\n else:\n print (\"您的输入有误!\")\n num = 0\n\n\ndef model_Config():\n \"\"\"\n 查看已经创建的模型\n :return: None\n \"\"\"\n num = 0\n Num = 0\n dict = common.log_info_read(DIR + 'config_conf')\n if dict == False:\n print (\"请先创建老师模型后再来!\")\n return\n print (\"已经创建的老师模型,如下:\".format(str(len(dict['teachers']))))\n for P in dict['teachers']:\n print (\"{0}:姓名:{1},年龄:{2},性别:{3}\".format(str(num + 1), P.Name, P.Age, P.Sex))\n num += 1\n print (\"已经创建的课程模型,如下:\".format(str(len(dict['teachers']))))\n for P in dict['lessons']:\n print (\"{0}:课程名:{1},课时费:{2},授课老师:{3}\".format(str(Num + 1), P.Lname, P.Lcost, P.Tobj.Name))\n Num += 1\n\n\n\n\ndef admin_Main(log = None):\n \"\"\"\n 管理员管理界面\n :param log: 用户登录标志\n :return: None\n \"\"\"\n while TAG:\n text = \"\"\"\n 欢迎来到管理员界面 {0}登陆中\n 1,创建老师模组\n 2,创建课程模组\n 3,查看模组配置\n 4,系统退出\n \"\"\".format(log)\n print (text)\n while TAG:\n choose = raw_input('请输入你的选择:')\n if choose == '1':\n create_Teachers_model()\n break\n elif choose == '2':\n create_Lesson_model()\n break\n elif choose == '3':\n model_Config()\n break\n elif choose == '4':\n common.Exit()\n else:\n print ('您的输入有误!')\n\nif __name__ == \"__main__\":\n admin_Main('admin')","sub_path":"LessonThree/Python06/src/admin_business.py","file_name":"admin_business.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"581553599","text":"\"\"\"\nModified from : https://github.com/Xevel/NXV11\nUnder Apache 2.0 License\n\"\"\"\n\nimport time\nimport math\nimport serial\n\nlidar_points = [None]*360 # type: list[LidarPoint]\npacket_per_cyle = int(359/4) # In order to flush the input on each rotation\n\nclass LidarPoint:\n def __init__(self, azimut=0, distance=0, quality=0, valid=False, warning=True, updTour=0, point = None):\n if point is not None:\n self.azimut = point.azimut # type: int\n self.distance = point.distance # type: int\n self.quality = point.quality # type: int\n self.valid = point.valid # type: bool\n self.warning = point.warning # type: bool\n self.updTour = point.updTour # type: int\n else:\n self.azimut = azimut # type: int\n self.distance = distance # type: int\n self.quality = quality # type: int\n self.valid = valid # type: bool\n self.warning = warning # type: bool\n self.updTour = updTour # type: int\n\n def get_cartesian_coord(self):\n return (self.distance * math.cos(math.radians(self.azimut)),\n self.distance * math.sin(math.radians(self.azimut)))\n\n\ndef read_v_2_4(lidar_serial):\n global lidar_points\n init_level = 0\n index = 0\n cycle = 0\n while True:\n try:\n time.sleep(0.00001) # do not hog the processor power\n if init_level == 0:\n b = lidar_serial.read(1)\n # start byte\n if b == bytes([0xFA]):\n init_level = 1\n else:\n init_level = 0\n elif init_level == 1:\n # position index\n b = lidar_serial.read(1)\n if bytes([0xA0]) <= b <= bytes([0xF9]):\n index = int.from_bytes(b, byteorder='big') - 0xA0\n init_level = 2\n elif b != bytes([0xFA]):\n init_level = 0\n elif init_level == 2:\n # speed\n b_speed = [b for b in lidar_serial.read(2)]\n\n # data\n b_data0 = [b for b in lidar_serial.read(4)]\n b_data1 = [b for b in lidar_serial.read(4)]\n b_data2 = [b for b in lidar_serial.read(4)]\n b_data3 = [b for b in lidar_serial.read(4)]\n\n # for the checksum, we need all the data of the packet...\n # this could be collected in a more elegent fashion...\n all_data = [0xFA, index + 0xA0] + b_speed + b_data0 + b_data1 + b_data2 + b_data3\n\n # checksum\n b_checksum = [b for b in lidar_serial.read(2)]\n incoming_checksum = int(b_checksum[0]) + (int(b_checksum[1]) << 8)\n\n # verify that the received checksum is equal to the one computed from the data\n if checksum(all_data) == incoming_checksum:\n # speed_rpm = compute_speed(b_speed)\n # gui_update_speed(speed_rpm)\n\n # motor_control(speed_rpm)\n\n lidar_points[index * 4 + 0] = new_lidar_point(index * 4 + 0, b_data0)\n lidar_points[index * 4 + 1] = new_lidar_point(index * 4 + 1, b_data1)\n lidar_points[index * 4 + 2] = new_lidar_point(index * 4 + 2, b_data2)\n lidar_points[index * 4 + 3] = new_lidar_point(index * 4 + 3, b_data3)\n\n if index == packet_per_cyle:\n cycle = (cycle + 1) % 2\n if cycle == 0:\n lidar_serial.flushInput()\n\n else:\n pass\n # the checksum does not match, something went wrong...\n # nb_errors += 1\n # label_errors.text = \"errors: \" + str(nb_errors)\n #\n # # display the samples in an error state\n # update_view(index * 4 + 0, [0, 0x80, 0, 0])\n # update_view(index * 4 + 1, [0, 0x80, 0, 0])\n # update_view(index * 4 + 2, [0, 0x80, 0, 0])\n # update_view(index * 4 + 3, [0, 0x80, 0, 0])\n\n init_level = 0 # reset and wait for the next packet\n\n else: # default, should never happen...\n init_level = 0\n except Exception as err:\n print(err)\n\n\ndef new_lidar_point(angle, data):\n x = data[0]\n x1 = data[1]\n x2 = data[2]\n x3 = data[3]\n dist_mm = x | ((x1 & 0x3f) << 8) # distance is coded on 13 bits ? 14 bits ?\n quality = x2 | (x3 << 8) # quality is on 16 bits\n return LidarPoint(angle, dist_mm, quality, not (x1 & 0x80), bool(x1 & 0x40), 0)\n\n\ndef checksum(data):\n \"\"\"Compute and return the checksum as an int.\n\n data -- list of 20 bytes (as ints), in the order they arrived in.\n \"\"\"\n # group the data by word, little-endian\n data_list = []\n for t in range(10):\n data_list.append(data[2 * t] + (data[2 * t + 1] << 8))\n\n # compute the checksum on 32 bits\n chk32 = 0\n for d in data_list:\n chk32 = (chk32 << 1) + d\n\n # return a value wrapped around on 15bits, and truncated to still fit into 15 bits\n checksum = (chk32 & 0x7FFF) + (chk32 >> 15) # wrap around to fit into 15 bits\n checksum = checksum & 0x7FFF # truncate to 15 bits\n return int(checksum)\n\n","sub_path":"daneel/ai/drivers/neato_xv11_lidar.py","file_name":"neato_xv11_lidar.py","file_ext":"py","file_size_in_byte":5418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"37557851","text":"from django.shortcuts import render\r\nfrom django.http import HttpResponse\r\n\r\nimport requests\r\nimport os\r\n\r\nfrom pythainlp.tokenize import dict_word_tokenize\r\nimport calendar\r\nfrom datetime import *\r\nfrom dateutil.relativedelta import *\r\nimport json\r\n\r\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\n\r\nnow = datetime.now()\r\n\r\nshortTimelist=['วันนี้','พรุ่งนี้','มะรืน','เมื่อวาน']\r\nprefixTimelist=['ช่วง','วันที่']\r\nrangeTimelist=['ถึง','จนถึง','-']\r\nunitTimelist=['วัน','สัปดาห์','เดือน','ปี']\r\nsufTimelist=['ก่อน','ที่แล้ว','หน้า','ข้างหน้า']\r\n\r\nnumber_dict={'หนึ่ง':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,'ยี่สิบหก':26,'ยี่สิบเจ็ด':27,'ยี่สิบแปด':28,'ยี่สิบเก้า':29,'สามสิบ':30,'สามสิบเอ็ด':31}\r\nmonth_dict={'ม.ค.':1,'ก.พ.':2,'มี.ค.':3,'เม.ย.':4,'พ.ค.':5,'มิ.ย.':6,'ก.ค.':7,'ส.ค.':8,'ก.ย.':9,'ต.ค.':10,'พ.ย.':11,'ธ.ค.':12}\r\n\r\ndef tokenize(token,json_token,time_list):\r\n\tprefix,num,unit,suffix=None,None,None,None\r\n\ttime_token=[None,1,None,1]\r\n\tfor i in range(len(token)):\r\n\t\tfor j in shortTimelist:\r\n\t\t\tif token[i]==j:\r\n\t\t\t\ttime_token[2]=token[i]\r\n\t\t\t\tjson_token.append(token[i])\r\n\t\t\t\ttime_list.append(time_token)\r\n\t\t\t\tprefix,num,unit,suffix=None,None,None,None\r\n\t\t\t\ttime_token=[None,1,None,1]\r\n\t\tfor k in prefixTimelist:\r\n\t\t\tif token[i]==k:\r\n\t\t\t\tprefix=i\r\n\t\tif type(token[i]) is int:\r\n\t\t\tnum=i\r\n\t\t\tif (token[i-1]=='วันที่'):\r\n\t\t\t\ttemp=token[i-1]+str(token[i])\r\n\t\t\t\ttime_token[0]=token[i-1]\r\n\t\t\t\ttime_token[1]=token[i]\r\n\t\t\t\ttry:\r\n\t\t\t\t\ttime_token[2]=month_dict[token[i+1]]\r\n\t\t\t\t\ttemp=temp+token[i+1]\r\n\t\t\t\texcept:\r\n\t\t\t\t\tpass\r\n\t\t\t\tjson_token.append(temp)\r\n\t\t\t\ttime_list.append(time_token)\r\n\t\t\t\tprefix,num,unit,suffix=None,None,None,None\r\n\t\t\t\ttime_token=[None,1,None,1]\r\n\t\tfor l in unitTimelist:\r\n\t\t\tif token[i]==l:\r\n\t\t\t\tunit=i\r\n\t\t\t\tif token[i+1]=='นี้':\r\n\t\t\t\t\tjson_token.append(token[i]+token[i+1])\r\n\t\t\t\t\tif token[i]!='วัน':\r\n\t\t\t\t\t\ttime_token[0]='ช่วง'\r\n\t\t\t\t\ttime_token[1]=0\r\n\t\t\t\t\ttime_token[2]=token[i]\r\n\t\t\t\t\ttime_list.append(time_token)\r\n\t\t\t\t\tprefix,num,unit,suffix=None,None,None,None\r\n\t\t\t\t\ttime_token=[None,1,None,1]\r\n\t\tfor m in sufTimelist:\r\n\t\t\tif token[i]==m:\r\n\t\t\t\tsuffix=i\r\n\t\tfor n in rangeTimelist:\r\n\t\t\tif token[i]==n:\r\n\t\t\t\tif time_list[-1][0]=='วันที่' and type(token[i+1]) is int:\r\n\t\t\t\t\ttemp='-'+str(token[i+1])\r\n\t\t\t\t\ttime_list[-1][0]='ช่วง'\r\n\t\t\t\t\ttime_list[-1][3]=token[i+1]\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\ttemp=temp+token[i+2]\r\n\t\t\t\t\t\ttime_list[-1].append(month_dict[token[i+2]])\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tpass\r\n\t\t\t\t\tjson_token[-1]=json_token[-1]+temp\r\n\t\tif unit!=None and suffix!=None and suffix-unit==1:\r\n\t\t\ttemp=''\r\n\t\t\tif prefix!=None and num!=None:\r\n\t\t\t\tif num-prefix==1 and unit-num==1:\r\n\t\t\t\t\ttemp=token[prefix]+str(token[num])\r\n\t\t\t\t\ttime_token[0]=token[prefix]\r\n\t\t\t\t\ttime_token[1]=token[num]\r\n\t\t\t\telif unit-num==1:\r\n\t\t\t\t\ttemp=str(token[num])\r\n\t\t\t\t\ttime_token[1]=token[num]\r\n\t\t\telif prefix!=None and num==None:\r\n\t\t\t\tif unit-prefix==1:\r\n\t\t\t\t\ttemp=token[prefix]\r\n\t\t\t\t\ttime_token[0]=token[prefix]\r\n\t\t\telif prefix==None and num!=None:\r\n\t\t\t\tif unit-num==1:\r\n\t\t\t\t\ttemp=str(token[num])\r\n\t\t\t\t\ttime_token[1]=token[num]\r\n\t\t\ttemp=temp+token[unit]+token[suffix]\r\n\t\t\ttime_token[2]=token[unit]\r\n\t\t\tif token[suffix]=='ข้างหน้า' or token[suffix]=='หน้า':\r\n\t\t\t\ttime_token[3]=-1\r\n\t\t\tjson_token.append(temp)\r\n\t\t\ttime_list.append(time_token)\r\n\t\t\tprefix,num,unit,suffix=None,None,None,None\r\n\t\t\ttime_token=[None,1,None,1]\r\n\r\ndef shortTime(time_token):\r\n\tif time_token[2] == 'วันนี้':\r\n\t\treturn now\r\n\telif time_token[2] == 'พรุ่งนี้':\r\n\t\treturn now+relativedelta(days=1)\r\n\telif time_token[2] == 'มะรืน':\r\n\t\treturn now+relativedelta(days=2)\r\n\telif time_token[2] == 'เมื่อวาน':\r\n\t\treturn now+relativedelta(days=-1)\r\n\telif time_token[2] == 'วัน':\r\n\t\treturn now+relativedelta(days=-time_token[1]*time_token[3])\r\n\telif time_token[2] == 'สัปดาห์':\r\n\t\treturn now+relativedelta(weeks=-time_token[1]*time_token[3])\r\n\telif time_token[2] == 'เดือน':\r\n\t\treturn now+relativedelta(months=-time_token[1]*time_token[3])\r\n\telif time_token[2] == 'ปี':\r\n\t\treturn now+relativedelta(years=-time_token[1]*time_token[3])\r\n\telif time_token[0] == 'วันที่':\r\n\t\ttry:\r\n\t\t\treturn datetime(now.year,time_token[2],time_token[1])\r\n\t\texcept:\r\n\t\t\treturn datetime(now.year,now.month,time_token[1])\r\n\r\ndef daterange(time_token,date):\r\n\tflage=0\r\n\tdt_rage=[]\r\n\tcal=calendar.Calendar()\r\n\tif date is None:\r\n\t\tyeardate=now\r\n\t\ttry:\r\n\t\t\tstart_date=datetime(now.year,time_token[2],time_token[1])\r\n\t\texcept:\r\n\t\t\ttry:\r\n\t\t\t\tstart_date=datetime(now.year,time_token[4],time_token[1])\r\n\t\t\texcept:\r\n\t\t\t\tstart_date=datetime(now.year,now.month,time_token[1])\r\n\t\ttry:\r\n\t\t\tend_date=datetime(now.year,time_token[4],time_token[3])\r\n\t\texcept:\r\n\t\t\tend_date=datetime(now.year,now.month,time_token[3])\r\n\telse:\r\n\t\tyeardate=date\r\n\t\tif int((now-date).days)>0:\r\n\t\t\tstart_date=date\r\n\t\t\tend_date=now+relativedelta(days=-1)\r\n\t\telse:\r\n\t\t\tstart_date=now+relativedelta(days=1)\r\n\t\t\tend_date=date\r\n\tfor year in cal.yeardatescalendar(yeardate.year, 1):\r\n\t\tfor month in year:\r\n\t\t\tfor week in month:\r\n\t\t\t\tfor day in week:\r\n\t\t\t\t\tfor dt in dt_rage:\r\n\t\t\t\t\t\tif day==dt:\r\n\t\t\t\t\t\t\tflage=1\r\n\t\t\t\t\tif flage==0:\r\n\t\t\t\t\t\tif time_token[2] == 'วัน' or date is None:\r\n\t\t\t\t\t\t\tif int((day-start_date.date()).days)>=0 and int((end_date.date()-day).days)>=0:\r\n\t\t\t\t\t\t\t\tdt_rage.append(day)\r\n\t\t\t\t\t\telif time_token[2] == 'สัปดาห์':\r\n\t\t\t\t\t\t\tif day == date.date():\r\n\t\t\t\t\t\t\t\treturn week\r\n\t\t\t\t\t\telif time_token[2] == 'เดือน':\r\n\t\t\t\t\t\t\tif day.month == date.date().month:\r\n\t\t\t\t\t\t\t\tdt_rage.append(day)\r\n\t\t\t\t\t\telif time_token[2] == 'ปี':\r\n\t\t\t\t\t\t\tif day.year == date.date().year:\r\n\t\t\t\t\t\t\t\tdt_rage.append(day)\r\n\t\t\t\t\tflage=0\r\n\treturn dt_rage\r\n\r\n# Create your views here.\r\ndef index(request):\r\n\ttoken=[]\r\n\ttime_token_list=[]\r\n\tdata=[]\r\n\tuserInput=request.GET.get('text')\r\n\tlm_token=dict_word_tokenize(userInput,file=os.path.join(BASE_DIR,\"hello/wordlist.txt\"),engine=\"longest-matching\")\r\n\tfor i in range(len(lm_token)):\r\n\t\ttry:\r\n\t\t\tlm_token[i]=number_dict[lm_token[i]]\r\n\t\texcept:\r\n\t\t\tpass\r\n\t\ttry:\r\n\t\t\tlm_token[i]=int(lm_token[i])\r\n\t\texcept:\r\n\t\t\tpass\r\n\ttokenize(lm_token,token,time_token_list)\r\n\tfor n in range(len(token)):\r\n\t\tdate=shortTime(time_token_list[n])\r\n\t\tif time_token_list[n][0]!='ช่วง':\r\n\t\t\tdata.append({'token':token[n],'type':'single','date':date.strftime(\"%Y-%m-%d\")})\r\n\t\telse:\r\n\t\t\tdaterang=daterange(time_token_list[n],date)\r\n\t\t\tif daterang!=[]:\r\n\t\t\t\tdata.append({'token':token[n],'type':'range','date':[dt.strftime(\"%Y-%m-%d\") for dt in daterang]})\r\n\tjson.dumps(data,ensure_ascii=False)\r\n\treturn HttpResponse(data)","sub_path":"hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"503106912","text":"import enum\nfrom binaryninja.log import log_error\n\nclass Dependency:\n @classmethod\n def can_parse(cls, file):\n raise NotImplemented\n\n def is_valid(self):\n raise NotImplemented\n\n def get_exports(self):\n raise NotImplemented\n\n def get_symbol_type(self, sym):\n return None\n\n def get_user_types(self, sym):\n return {}\n\nclass MatchingMethod(enum.Enum):\n Auto = 'auto'\n Ordinal = 'ordinal'\n Name = 'name'\n Address = 'address'\n\n\nTYPES = []\n\ndef register_dependency_type(cls):\n TYPES.append(cls)\n \ndef parse_dependency(file):\n ds = []\n for dt in TYPES:\n try:\n if not dt.can_parse(file):\n continue\n d = dt(file)\n if not d.is_valid():\n continue\n ds.append(d)\n except Exception as e:\n log_error('{} could not parse \"{}\": {}'.format(dt.__name__, file, e))\n continue\n return ds\n","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"400199397","text":"import tensorflow as tf\nimport numpy as np\n\n# define a function to add a layer into network\ndef add_layer(inputs, in_size, n_layer, out_size, activation_function=None):\n with tf.name_scope('layer'):\n layer_name = n_layer\n with tf.name_scope('Weights'):\n Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')\n tf.summary.histogram(layer_name + '/weights', Weights)\n with tf.name_scope('biases'): \n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')\n tf.summary.histogram(layer_name + '/biases', biases) \n # biases = tf.Variable(tf.zeros(1, out_size) + 0.1) \n # TypeError: unsupported operand type(s) for +: 'Tensor' and 'float'\n with tf.name_scope('Wx_plus_b'):\n Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)\n tf.summary.histogram(layer_name + '/Wx_plus_b', Wx_plus_b) \n # activation_function\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n tf.summary.histogram(layer_name + '/outputs', outputs) \n return outputs\n\n\nwith tf.name_scope('inputs'):\n xs = tf.placeholder(tf.float32, [None, 1], name='x_input')\n ys = tf.placeholder(tf.float32, [None, 1], name='y_input')\n\n# create data\nx_data = np.linspace(-1, 1, 1000)[:, np.newaxis]\nnoise = np.random.normal(0, 0.05, x_data.shape)\ny_data = np.square(x_data) - 0.5 + noise\nxs = tf.placeholder(tf.float32, [None, 1])\nys = tf.placeholder(tf.float32, [None, 1])\n\n# add hidden layers\nlay1 = add_layer(xs, 1, 'layer1',10, activation_function=tf.nn.relu)\nprediction = add_layer(lay1, 10, 'layer_pre', 1, activation_function=None)\n\n# error between prediction and real data\nwith tf.name_scope('loss'):\n loss = tf.reduce_mean(tf.reduce_sum(tf.square(prediction - ys), reduction_indices=[1]))\n # use different summary method record result\n tf.summary.scalar('loss', loss)\nwith tf.name_scope('train_step'):\n train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\n\n# train\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nmergerd = tf.summary.merge_all()\nwriter = tf.summary.FileWriter(\"./logs/\", sess.graph)\n\n# important step\nsess.run(init)\n\nfor i in range(10000):\n sess.run(train_step, feed_dict={xs: x_data, ys: y_data})\n if i % 50 == 0:\n result = sess.run(mergerd, feed_dict={xs: x_data, ys: y_data})\n writer.add_summary(result, i)","sub_path":"07_tensorboard_events.py","file_name":"07_tensorboard_events.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"554109530","text":"import tkinter as tk\nfrom tkinter import ttk\n\ndef change(t) :\n\t\tglobal what\n\t\twhat = t\n\t\t\n\n\ndef Dialog() :\n\t\n\t\n\t\t\n\t\t\n\t\n\tdialogo = tk.Toplevel()\n\t#dialogo.overrideredirect(True)\n\tdialogo.geometry(\"400x300+150+350\")\n\t#dialogo.title(\"Jugador\")\n\t\n\tdialogo.configure(bg = \"skyblue\")\n\tdialogo.resizable(0, 0)\n\t\n\tvar = tk.StringVar()\n\t\n\ttk.Label(dialogo, text = \"Nombre Del Jugador \".upper() , font = \"Verdana 8 normal\", fg = \"blue\", bg = \"skyblue\").pack( pady = 30)\n\t\n\tentry = tk.Entry(dialogo, width = 30, textvariable = var, bg = \"limegreen\", fg = \"red\", bd = 8, relief = \"raised\", justify = tk.CENTER )\n\tentry.pack()\n\t\n\tttk.Separator(dialogo, orient = tk.HORIZONTAL, style = None).place( x = 5, y = 170, width = 390, height = 5 , bordermode = tk.INSIDE)\n\t\n\t\n\t\n\t\n\tbtn = tk.Button(dialogo, text = \"Ok\", bg = \"blue\", fg = \"white\", bd = 10, relief = \"raised\", highlightbackground = \"red\", activeforeground = \"white\", activebackground = \"blue\" ,command = lambda : ( change(entry.get()), dialogo.destroy() ))\n\tbtn.pack( side = tk.BOTTOM)\n\t\n\t\n\tentry.bind(\"<Return>\", lambda event :( change(entry.get()), dialogo.destroy()))\n\t\n\tentry.focus_set()\n\t\n\tdialogo.transient(master = root)\n\t\n\tdialogo.grab_set()\n\t\n\t\n\troot.wait_window(dialogo)\n\t\n\n\ndef askstring() :\n\t\t\t\n\ta = Dialog()\n\t\n\treturn what\n\t\t\t\n\t\n\n\t\t\ndef Testear() :\n\t\n\tname1 = askstring()\n\tname2 = askstring()\n\t\n\ttk.Label(root, text = name1+name2).pack()\n\t\n\t\n\n\t\t\nwhat = \" \"\nnames = [ ]\n\n\nroot = tk.Tk()\n\n\nbtn = tk.Button(root, text = \"Test\", command = Testear)\n\nbtn.pack()\n\n\n\n\nroot.mainloop()\n\n\n#https://r.honeygain.me/SAMIR0D5F1","sub_path":"Tkinter/probando.py","file_name":"probando.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"645657753","text":"'''\nUnit testing module\n'''\nimport sys\nsys.path.append(\"../hp_norton_inventory\")\nimport os\nimport logging\nimport threading\nfrom queue import Queue\nfrom unittest import TestCase\nfrom unittest.mock import patch\nfrom pymongo import MongoClient\nfrom parallel import *\nfrom mongo_connect import *\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nclass DatabaseTests(TestCase):\n ''' Database test class '''\n def setUp(self):\n '''\n setup database and handle connections and closure\n '''\n self.test_queue = Queue()\n logger.info(f'setting up test cases')\n try:\n os.path.exists('customer.csv')\n os.path.exists('product.csv')\n os.path.exists('rental.csv')\n\n output = import_data('data', 'customer.csv', 'product.csv', 'rental.csv', self.test_queue)\n logger.info(f'{output}')\n except FileNotFoundError as e:\n logger.info(f'{e}')\n\n def tearDown(self):\n mongo = MongoDBConnection()\n with mongo:\n db = mongo.connection.hpnorton_db\n db['customer'].drop()\n db['rental'].drop()\n db['product'].drop()\n\n def test_database_created(self):\n '''\n Tests to ensure all the elements of the\n database are present\n '''\n mongo = MongoDBConnection()\n with mongo:\n db = mongo.connection.hpnorton_db\n\n ''' confirm customer document is correct '''\n customer_db = [x for x in db.customer.find()]\n self.assertEqual(customer_db[0]['customer_id'], 'user001')\n \n\n ''' confirm product document is correct '''\n product_db = [x for x in db.product.find()]\n self.assertEqual(product_db[0]['product_id'], 'prd001')\n\n\n ''' confirm rentals document is corrrect '''\n rentals_db = [x for x in db.rental.find()]\n self.assertEqual(rentals_db[0]['product_id'], 'prd001')\n\n def test_database_return_value(self):\n ''' ensures that a list of 2 tuples is returned '''\n output = import_data('data', 'customer.csv', 'product.csv', 'rental.csv', self.test_queue)\n logger.info(f'{output}')\n self.assertTupleEqual(output[0], (2002, 2002, 1000))\n self.assertTupleEqual(output[1], (0, 0, 0))\n\n def test_database_error_return(self):\n ''' ensure error count matches '''\n output = import_data('data', 'customer', 'product', 'rental', self.test_queue)\n logger.info(f'{output}')\n self.assertTupleEqual(output[0], (0, 0, 0))\n self.assertTupleEqual(output[1], (1, 1, 1))\n\n def test_available_products(self):\n ''' ensure only available products are returned '''\n output = show_available_products()\n logger.info(f'Products available for rent')\n self.assertEqual(output[0]['product_id'], 'prd001')\n self.assertEqual(output[0]['description'], '60-inch TV stand')\n self.assertEqual(output[0]['product_type'], 'livingroom')\n self.assertEqual(output[0]['quantity_available'], '3')\n\n def test_show_rentals(self):\n ''' ensure rentals are displaybed '''\n output = show_rentals('prd006')\n print(output)\n self.assertEqual(output[0]['product_id'], 'prd006')\n\n def test_main(self):\n ''' just for coverage '''\n main()","sub_path":"students/billy_galloway/lesson_7/assignment/tests/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"18796149","text":"Node_Label_list=[];\nf=open('../DHFR_node_labels.txt');\nfor line in f:\n Node_Label_list.append(int(line));\nf.close();\n\nNode_Attribute_list=[];\nf=open('../DHFR_node_attributes.txt');\nfor line in f:\n temp=line.split(',');\n for i in range(0,len(temp)):\n temp[i]=float(temp[i]);\n Node_Attribute_list.append(temp);\nf.close();\n\nBond_list=[];\nf=open('../DHFR_A.txt');\nfor line in f:\n temp=line.split(',');\n for i in range(0,len(temp)):\n temp[i]=int(temp[i]);\n Bond_list.append(temp);\nf.close();\n\nGraph_Label_list=[];\nf=open('../DHFR_graph_labels.txt');\nfor line in f:\n Graph_Label_list.append(int(line));\nf.close();\n\nGraph_Indicator_list=[];\nf=open('../DHFR_graph_indicator.txt');\nfor line in f:\n Graph_Indicator_list.append(int(line));\nf.close();\n\nmax_element=max(Node_Label_list);\nall_atom_list=[0 for i in range(0,max_element+1)];\natom_map=[0 for i in range(0,max_element+1)];\nfor j in range(0,len(Node_Label_list)):\n all_atom_list[Node_Label_list[j]]=1;\nmax_element=0;\n\nf=open('DHFR.txt','w');\nfor j in range(1,len(all_atom_list)):\n if all_atom_list[j]>0:\n max_element=max_element+1;\n atom_map[j]=max_element;\n f.write(str(j)+' ');\n\nf.write('\\n');\n\n#map_list=[0 for i in range(0,len(Graph_Indicator_list))];\nmiss=0;\n\nfor i in range(1,max(Graph_Indicator_list)+1):\n atom_list=[0 for i in range(0,max_element+1)];\n count=0;\n for j in range(0,len(Node_Label_list)):\n if Graph_Indicator_list[j] == i:\n count=count+1;\n if count>miss:\n atom_list[atom_map[Node_Label_list[j]]]=atom_list[atom_map[Node_Label_list[j]]]+1;\n for k in range(1,len(atom_list)):\n f.write(str(atom_list[k])+' ');\n f.write('\\n');\n\nf.close();","sub_path":"Notebook/data&code/DHFR/PCA/Generate_Data.py","file_name":"Generate_Data.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"175339844","text":"from functools import partial\nfrom django.db import models\nfrom django.http import HttpResponseForbidden, \\\n HttpResponseBadRequest, HttpResponseNotFound\nfrom django.utils.translation import ugettext as _\n\nfrom tojson import render_to_json\nfrom pybab.commons import dict_join\n\nfrom .commons import login_required_json_default\nfrom ..api_settings import MAX_STYLE_UPLOADS\nfrom ..models import UserStyle\n\nfrom ..forms import UserStyleForm\n\nadd_to_dicts = lambda l, d:list(map(partial(dict_join, d), l))\n\n@login_required_json_default\n@render_to_json()\ndef styles(request, index=0):\n user = request.user\n\n if request.method == 'GET':\n return _list_styles(user)\n elif request.method == 'POST':\n return _upload_style(request, user)\n elif request.method == 'DELETE':\n return _delete_style(index)\n else:\n error_msg = u\"request type \\\"{req_type}\\\"is not supported\".format(\n req_type=request.method)\n return {'success' : False,\n 'message' : _(error_msg)}, {'cls':HttpResponseForbidden}\n\ndef _list_styles(user):\n \"\"\"Returns a json where styles is the list of the user styles\"\"\"\n user_styles = add_to_dicts(\n [style.to_dict() for style in user.userstyle_set.all()],\n {'public':False})\n\n public_styles = add_to_dicts(\n [style.to_dict() for style in UserStyle.objects.filter(user__isnull=True)],\n {'public': True})\n\n return {'success':True,\n 'data':user_styles + public_styles}\n\ndef _upload_style(request, user):\n \"\"\"Returns a json with the result of the request,\n if it failed the error is reported\"\"\"\n if user.userstyle_set.count() > MAX_STYLE_UPLOADS:\n return {'success': False,\n 'errors': _(u\"You have too many styles uploaded, \\\n delete some of them.\")\n }, {'cls': HttpResponseForbidden}\n form = UserStyleForm(request.POST, user=user)\n if form.is_valid():\n form.save()\n return {'success': True}\n else:\n return {'success': False,\n 'errors': form.errors}, {'cls': HttpResponseBadRequest}\n\ndef _delete_style(pk):\n try:\n style = UserStyle.objects.get(pk=pk)\n except UserStyle.DoesNotExist:\n return ({'success': False,\n 'message': 'Style {0} does not exist'.format(pk)},\n {'cls': HttpResponseNotFound})\n try:\n style.delete()\n except models.ProtectedError as e:\n msg = (\"Cannot delete the style '{0}' because \"\n \"it is associate to the following layer: \").format(style.label)\n msg += \" \".join([\"'\"+s.layer.name+\"'\" for s in style.userlayerlink_set.all()])\n return ({'success': False,\n 'message': msg},\n {'cls': HttpResponseBadRequest})\n return {'success': True}\n\n\n\n\n","sub_path":"pybab/api/views/styles.py","file_name":"styles.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"450621067","text":"import torch\nimport torch.nn as nn\n\n\natt_OPS = {\n 'none' : lambda C, affine: Zero(stride=1),\n 'skip_connect' : lambda C, affine: Identity(),\n 'relu_conv_bn_1x1' : lambda C, affine: ReLUConvBN(C, C, 1, 1, 0, affine=affine),\n 'sep_conv_3x3' : lambda C, affine: SepConv(C, C, 3, 1, 1, affine=affine),\n 'dil_conv_3x3' : lambda C, affine: DilConv(C, C, 3, 1, 2, 2, affine=affine),\n 'avg_pool_3x3' : lambda C, affine: nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),\n 'max_pool_3x3' : lambda C, affine: nn.MaxPool2d(3, stride=1, padding=1),\n 'spatial_score' : lambda C, affine: ChannelPool(1, 1),\n 'channel_score' : lambda C, affine: SpatialPool(C)\n}\n\n\nclass ReLUConvBN(nn.Module):\n def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):\n super(ReLUConvBN, self).__init__()\n self.op = nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C_in, C_out, kernel_size, stride=stride, padding=padding, bias=False),\n nn.BatchNorm2d(C_out, affine=affine)\n )\n\n def forward(self, x):\n return self.op(x)\n\n\nclass DilConv(nn.Module):\n def __init__(self, C_in, C_out, kernel_size, stride, padding, dilation, affine=True):\n super(DilConv, self).__init__()\n self.op = nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=C_in, bias=False),\n nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_out, affine=affine),\n )\n\n def forward(self, x):\n return self.op(x)\n\n\nclass SepConv(nn.Module):\n def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):\n super(SepConv, self).__init__()\n self.op = nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, groups=C_in, bias=False),\n nn.Conv2d(C_in, C_in, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_in, affine=affine),\n nn.ReLU(inplace=False),\n nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=1, padding=padding, groups=C_in, bias=False),\n nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_out, affine=affine),\n )\n\n def forward(self, x):\n return self.op(x)\n\n\nclass Identity(nn.Module):\n def __init__(self):\n super(Identity, self).__init__()\n\n def forward(self, x):\n return x\n\n\nclass Zero(nn.Module):\n def __init__(self, stride):\n super(Zero, self).__init__()\n self.stride = stride\n\n def forward(self, x):\n n, c, h, w = x.size()\n h //= self.stride\n w //= self.stride\n if x.is_cuda:\n with torch.cuda.device(x.get_device()):\n padding = torch.cuda.FloatTensor(n, c, h, w).fill_(0)\n else:\n padding = torch.FloatTensor(n, c, h, w).fill_(0)\n return padding\n\n\nclass SpatialPool(nn.Module):\n def __init__(self, C):\n super(SpatialPool, self).__init__()\n self.aa_pool = nn.AdaptiveAvgPool2d(1)\n self.am_pool = nn.AdaptiveMaxPool2d(1)\n self.fc = nn.Linear(C * 2, C)\n\n def forward(self, x):\n b, c, _, _ = x.size()\n out = (torch.cat((self.aa_pool(x), self.am_pool(x)), dim=1)).view(b, c * 2)\n out = (self.fc(out)).view(b, c, 1, 1)\n return out.expand_as(x)\n\n\nclass ChannelPool(nn.Module):\n def __init__(self, kernel_size, stride):\n super(ChannelPool, self).__init__()\n self.channel_pool = lambda x : torch.cat((torch.max(x, dim=1)[0].unsqueeze(1), torch.mean(x, dim=1).unsqueeze(1)), dim=1)\n self.conv = nn.Conv2d(2, 1, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1) // 2, bias=False)\n\n def forward(self, x):\n out = self.channel_pool(x)\n out = self.conv(out)\n return out.expand_as(x)\n","sub_path":"anas/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"103742439","text":"#primer taller de diccionarios\n\"\"\"\nCrea un diccionario donde la clave sea el nombre del usuario y el valor sea \nel teléfono (no es necesario validar). Tendrás que ir pidiendo contactos \nhasta el usuario diga que no quiere insertar mas. No se podrán meter \nnombres repetidos.\n\"\"\"\n\ndiccionario = {}\n# bandera indicadora\nencuesta_activa = True\n\nwhile encuesta_activa:\n nombre = input(\"\\n ingreser el nombre del usuario:\").capitalize()\n if nombre in diccionario:\n print(\"el usuario\",nombre,\"ya se encuentra en el diccionario, para diferenciar pon el apellido\")\n telefono = input(\"\\n ingrese en telefono del usuario:\")\n#almacenar la respuesta en el diccionario\n diccionario[nombre] = telefono\n preguntar = input(\"¿quiertes ingresar a alguien mas? (Si/No)\").capitalize() \n if preguntar == \"No\":\n encuesta_activa = False\n print(\"\\n este es el diccionario creado:\",diccionario)\n\n \n\n\n\n","sub_path":"trabajos de la clase/#primer taller de diccionarios.py","file_name":"#primer taller de diccionarios.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"281198830","text":"# -*- coding: utf-8 -*-\n# @Author: wolther47\n# @Date: 2017-07-06 18:13:50\n# @Last Modified by: wolther47\n# @Last Modified time: 2017-08-02 13:17:01\n\nimport re\n\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import NavigableString as BSNavigableString\nfrom urllib import parse\n\n\nclass AuthError(Exception):\n \"\"\"Exceptions in authentication.\"\"\"\n\n def __init__(self, reason):\n self.reason = reason\n super().__init__(reason)\n\n def __str__(self):\n return \"Auth information error, {0}\".format(self.reason)\n\n\ndef urlJoin(base, url):\n \"\"\"Join the url.\"\"\"\n\n return parse.urljoin(\"http://\" + base, url)\n\n\ndef semester(admission_time, grade, term):\n \"\"\"Return matching academic year for request body.\"\"\"\n\n return {\n \"year\": \"{0}-{1}\".format(\n admission_time + (grade - 1),\n admission_time + grade),\n \"term\": str(term)\n }\n\n\nclass HTMLParser(object):\n \"\"\"Parsing utility\"\"\"\n\n def __init__(self, parser=\"html.parser\"):\n \"\"\"Initialize a bs instance\"\"\"\n\n self.parser = parser\n\n def formClassDict(self, seg, day, time):\n \"\"\"Form a information dict of the certain class.\"\"\"\n\n pattern = re.compile(r'{(\\d\\d?)-(\\d\\d?)(??(双|单)??)??周}')\n\n match_obj = re.search(pattern, seg[2])\n start, end, freq = match_obj.groups()\n return {\n \"course_name\": seg[0],\n \"prof\": seg[1],\n \"day\": int(day),\n \"class_time\": int(time),\n \"start_week\": int(start),\n \"end_week\": int(end),\n \"freq\": freq or \"全\",\n \"classroom\": seg[3]\n }\n\n def classSchedule(self, html):\n \"\"\"Return a list containing all classes information.\"\"\"\n\n soup = BeautifulSoup(html, self.parser)\n\n rows = soup.select(\"#tablebody\")[0].contents\n\n row_generator = (row for row in rows if not # Remove blank lines.\n isinstance(row, BSNavigableString))\n\n generator = (column.contents[1::2] # Skip all EOLs blank strings\n for column in row_generator)\n\n table, time = [], 1 # Prepare a table, class order.\n for row in generator:\n\n day = 1 # Day in a week.\n for column in row[2:]: # Skip day & a.m or p.m\n\n text = re.sub(\"</?td>\", \"\", str(column)) # Strip html tag.\n seg = text.split(\"<br/>\") # Split whole line by <br/> tag.\n del seg[-1] # Delete the last empty string.\n\n # By default, it should only contains a class in a single line.\n if len(seg) == 4:\n table.append(self.formClassDict(seg, day, time))\n\n # But sometime, it also contains two classes in a single line.\n elif len(seg) == 8:\n\n seg_1, seg_2 = seg[:4], seg[4:]\n table.append(self.formClassDict(seg_1, day, time))\n table.append(self.formClassDict(seg_2, day, time))\n\n # There DO exist lists with length 0.\n else:\n pass\n\n day += 1 # Add a day.\n\n time += 1 # Increase class order.\n\n return None if table == [] else table\n\n def borrowingBooks(self, html):\n \"\"\"Return a list containing all currently borrowed books.\"\"\"\n\n soup = BeautifulSoup(html, self.parser)\n\n info_list = [\n \"bar_code\", \"title\", \"author_info\", \"number\", \"position\",\n \"type\", \"lend_time\", \"should_return_time\"\n ]\n\n try:\n borrowed_books_table = [\n i for i in soup.select(\"#contentTable\")[0].contents\n if i != \"\\n\" # There should contains several \"\\n\"s.\n ][1:] # The first one should the heading line.\n except IndexError:\n return None\n\n borrowed_books_group = [\n i.contents[::2] # Should contain lots of \"\\n\"s.\n for i in borrowed_books_table\n ]\n\n result = []\n for book in borrowed_books_group:\n single_book_list = []\n for line in book:\n single_book_list.append(line.text.strip())\n result.append(dict(zip(info_list, single_book_list)))\n\n return result\n\n def borrowHistory(self, html):\n \"\"\"Return a list containing the borrowing history.\"\"\"\n\n soup = BeautifulSoup(html, \"html.parser\")\n\n info_list = [\n \"action\", \"bar_code\", \"title\", \"author_info\", \"number\", \"position\",\n \"type\", \"handle_time\"\n ]\n\n try:\n borrowed_books_table = [\n i for i in soup.select(\"#contentTable\")[0].contents\n if i != \"\\n\" # There should contains several \"\\n\"s.\n ][1:] # The first one should the heading line.\n except IndexError:\n return None\n\n borrowed_books_group = [\n i.contents[::2] # Should contain lots of \"\\n\"s.\n for i in borrowed_books_table\n ]\n\n result = []\n for book in borrowed_books_group:\n single_book_list = []\n for line in book:\n single_book_list.append(line.text.strip())\n result.append(dict(zip(info_list, single_book_list)))\n\n return result\n","sub_path":"sdju/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"171722767","text":"from RPIO import PWM\nimport time\n\n#Constantes\nPULSE_WIDTH_INCREMENT_GRANULARITY_US_KK = 1\nAUX_ON = 2018\nAUX_OFF = 1015\nPIN_AILERON = 24 #Verde\nPIN_ELEVATOR = 17 #Amarillo\nPIN_THROTTLE = 25 #Rojo\nPIN_RUDDER = 22 #Azul\nPIN_AUXILIARY = 18 #Morado\nAILERON_US_KK_DEFAULT = 1500 #Valor max es 1900 y valor min es 1100\nELEVATOR_US_KK_DEFAULT = 1500 #Valor max es 1900 y valor min es 1100\nTHROTTLE_US_KK_DEFAULT = 1100 #Valor max es 2400 y valor min es 1100\nRUDDER_US_KK_DEFAULT = 1500 #Valor max es 1900 y valor min es 1100\n#Outputs\naileron = PWM.Servo(0, PWM.SUBCYCLE_TIME_US_DEFAULT, PULSE_WIDTH_INCREMENT_GRANULARITY_US_KK)\nelevator = PWM.Servo(0, PWM.SUBCYCLE_TIME_US_DEFAULT, PULSE_WIDTH_INCREMENT_GRANULARITY_US_KK)\nthrottle = PWM.Servo(0, PWM.SUBCYCLE_TIME_US_DEFAULT, PULSE_WIDTH_INCREMENT_GRANULARITY_US_KK)\nrudder = PWM.Servo(0, PWM.SUBCYCLE_TIME_US_DEFAULT, PULSE_WIDTH_INCREMENT_GRANULARITY_US_KK)\nauxiliary = PWM.Servo(0, PWM.SUBCYCLE_TIME_US_DEFAULT, PULSE_WIDTH_INCREMENT_GRANULARITY_US_KK)\n\nclass NavegacionPi():\n def __init__(self):\n aileron.set_servo(PIN_AILERON, AILERON_US_KK_DEFAULT)\n time.sleep(0.5)#(0.00001)\n elevator.set_servo(PIN_ELEVATOR, ELEVATOR_US_KK_DEFAULT)\n time.sleep(0.5)\n throttle.set_servo(PIN_THROTTLE, THROTTLE_US_KK_DEFAULT)\n time.sleep(0.5)\n rudder.set_servo(PIN_RUDDER, RUDDER_US_KK_DEFAULT)\n time.sleep(0.5)\n self.auxiliary_bool(True)\n time.sleep(0.5)\n print(\"Pulso inicializado\")\n print(\"Cargando ..\")\n time.sleep(1)\n print(\"Cargando ...\")\n time.sleep(1) \n print(\"Navegacion Pi listo\")\n \n def auxiliary_bool(self, condicion):\n if condicion:\n auxiliary.set_servo(PIN_AUXILIARY, AUX_ON)\n else:\n auxiliary.set_servo(PIN_AUXILIARY, AUX_OFF)\n \n def arm_model(self):\n rudder.set_servo(PIN_RUDDER, 1100)\n time.sleep(2)\n rudder.set_servo(PIN_RUDDER, RUDDER_US_KK_DEFAULT)\n print(\"Modelo armado y listo para volar\")\n time.sleep(1)\n\n def disarm_model(self):\n rudder.set_servo(PIN_AUXILIARY, 1900)\n time.sleep(2)\n rudder.set_servo(PIN_AUXILIARY, RUDDER_US_KK_DEFAULT)\n print(\"Modelo desarmado\")\n time.sleep(1)\n \n def full_throttle(self):\n throttle.set_servo(PIN_THROTTLE, 2390)\n \n def idle_throttle(self):\n throttle.set_servo(PIN_THROTTLE, RUDDER_US_KK_DEFAULT)\n \n def get_value(self, data = \"\", separator = \"\", index = 0):\n found = 0\n str_index = [0, -1] \n max_index = len(data)-1\n for i in range(0, max_index+1):\n if found <= index:\n if data[i] == separator or i == max_index:\n found = found + 1\n str_index[0] = str_index[1] + 1\n if i == max_index:\n str_index[1] = i + 1\n else:\n str_index[1] = i\n if found > index:\n return data[str_index[0]:str_index[1]]\n else:\n return \"\"\n \n def stop(self):\n throttle.stop_servo(PIN_THROTTLE)\n rudder.stop_servo(PIN_RUDDER)\n aileron.stop_servo(PIN_AILERON)\n elevator.stop_servo(PIN_ELEVATOR)\n auxiliary.stop_servo(PIN_AUXILIARY)\n\n def send_data(self, data):\n time.sleep(0.001)\n word1 = self.get_value(data, \"_\", 0)\n word2 = self.get_value(data, \"_\", 1)\n \n #if word1 == \"+\":\n # self.full_throttle()\n #elif word == \"-\":\n # self.idle_throttle() \t\n if word1 == \"TH\":\n throttle.set_servo(PIN_THROTTLE, int(word2))\n time.sleep(0.4)\n print(\"Throttle speed :\" + str(word2)) \n elif word1 == \"RD\":\n rudder.set_servo(PIN_RUDDER, int(word2))\n time.sleep(0.4)\n print(\"Rudder:\" + str(word2))\n elif word1 == \"AI\":\n aileron.set_servo(PIN_AILERON, int(word2))\n time.sleep(0.4)\n print(\"Aileron :\" + str(word2))\n elif word1 == \"EL\":\n elevator.set_servo(PIN_ELEVATOR, int(word2))\n time.sleep(0.4)\n print(\"Elevator :\" + str(word2))\n elif word1 == \"AUX\":\n if word2 == \"ON\":\n self.auxiliary_bool(True)\n time.sleep(0.4)\n print(\"Self-Level is ON\")\n elif word2 == \"OFF\":\n self.auxiliary_bool(False)\n time.sleep(0.4)\n print(\"Self-Level is OFF\")\n elif word1 == \"ARM\":\n self.arm_model()\n time.sleep(0.4)\n elif word1 == \"DARM\":\n self.disarm_model()\n time.sleep(0.4)\n time.sleep(0.001)\n","sub_path":"NavegacionPi.py","file_name":"NavegacionPi.py","file_ext":"py","file_size_in_byte":5167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"411194675","text":"import numpy as np\n\n\ndef write_monte(spec, rslt):\n \"\"\" Write out results to table.\n \"\"\"\n num_evals = rslt['num_evals']\n num_steps = rslt['num_steps']\n points = rslt['points']\n stat = rslt['rmse']\n\n # Write out information.\n fname = 'table_4.' + str(spec + 1) + '.txt'\n with open(fname, 'w') as f:\n # Write out the heading of the table.\n args = list()\n args += ['Identifier', 'True Value', 'Mean', 'Bias', 't-Stat.', 'Std.']\n\n fmt_ = ' {:>15}' + ' {:>15}' * 5 + '\\n\\n'\n line = fmt_.format(*args)\n f.write(line)\n\n fmt_ = ' {:>15}' + ' {:15.4f}' * 5 + '\\n'\n\n for i in range(26):\n args = list()\n args += [str(i)]\n args += [points['true'][i]]\n args += [points['mean'][i]]\n args += [points['bias'][i]]\n args += [points['stat'][i]]\n args += [points['stan'][i]]\n\n line = fmt_.format(*args)\n f.write(line)\n\n string = '\\n\\n\\n {0[0]:>15} {0[1]:>15} {0[2]:>15}\\n\\n'\n f.write(string.format(['RMSE', 'Evaluations', 'Steps']))\n string = ' {:15.4f} {:>15} {:>15}'\n f.write(string.format(*[stat, int(num_evals), int(num_steps)]))\n\n\ndef process_monte(x_iter, x_true):\n \"\"\" Process results from to bootstrap iterations to fill the table with\n the required information.\n \"\"\"\n # Initialize dictionary as the results container.\n rslt = dict()\n for key_ in ['mean', 'true', 'bias', 'stan', 'stat', 'msta']:\n rslt[key_] = [None] * 26\n\n # Attach the results from each individual bootstrap run to the dictionary.\n rslt['x_iter'] = np.array(x_iter, ndmin=2)\n\n # Construct auxiliary objects\n rslt['mean'] = np.mean(rslt['x_iter'], axis=0)\n num_boots = len(rslt['x_iter'])\n\n # Construct the requested information.\n for i in range(26):\n # true parameter and bias\n rslt['true'][i] = x_true[i]\n rslt['bias'][i] = rslt['mean'][i] - rslt['true'][i]\n\n # standard deviation\n rslt['stan'][i] = 0.0\n for j in range(num_boots):\n rslt['stan'][i] += (rslt['x_iter'][j, i] - rslt['mean'][i]) ** 2\n try:\n rslt['stan'][i] = np.sqrt((1.0 / (num_boots - 1)) * rslt['stan'][i])\n except ZeroDivisionError:\n rslt['stan'][i] = 0.0\n\n # t-statistic\n if rslt['stan'][i] == 0.0:\n rslt['stat'][i] = 0.0\n else:\n rslt['stat'][i] = ((rslt['mean'][i] - x_true[i]) / rslt['stan'][i])\n rslt['stat'][i] = rslt['stat'][i] * np.sqrt(num_boots)\n\n return rslt\n","sub_path":"_modules/auxiliary_monte.py","file_name":"auxiliary_monte.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"323095475","text":"\"\"\"\nCopyright (c) 2016-2018 billyoyo\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport aiohttp\nimport asyncio\nimport time\nimport json\nimport base64\nfrom urllib import parse\n\n\nclass InvalidRequest(Exception):\n def __init__(self, *args, code=0, **kwargs):\n super().__init__(*args, **kwargs)\n self.code = code\n\n\nclass FailedToConnect(Exception): pass\n\n\nclass RankedRegions:\n \"\"\"Ranked regions supported\n\n Attributes\n ----------\n EU : str\n name of the european data centre\n NA : str\n name of the north american data centre\n ASIA : str\n name of the asian data centre\"\"\"\n EU = \"emea\"\n NA = \"ncsa\"\n ASIA = \"apac\"\n\n\nvalid_regions = [x.lower() for x in dir(RankedRegions) if \"_\" not in x]\n\n\nclass Platforms:\n \"\"\"Platforms supported\n\n Attributes\n ----------\n UPLAY : str\n name of the uplay platform\n XBOX : str\n name of the xbox platform\n PLAYSTATION : str\n name of the playstation platform\"\"\"\n\n UPLAY = \"uplay\"\n XBOX = \"xbl\"\n PLAYSTATION = \"psn\"\n\n\nvalid_platforms = [x.lower() for x in dir(Platforms) if \"_\" not in x]\n\n\nPlatformURLNames = {\n \"uplay\": \"OSBOR_PC_LNCH_A\",\n \"psn\": \"OSBOR_PS4_LNCH_A\",\n \"xbl\": \"OSBOR_XBOXONE_LNCH_A\",\n \"uplay_test\": \"RS7_PC_LNCH_A\"\n}\n\n\n# DEPRECATED - this dict is no longer updated with new OPs (sorry)\nOperatorProfiles = {\n \"DOC\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-doc.0b0321eb.png\",\n \"TWITCH\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-twitch.70219f02.png\",\n \"ASH\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-ash.9d28aebe.png\",\n \"THERMITE\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-thermite.e973bb04.png\",\n \"BLITZ\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-blitz.734e347c.png\",\n \"BUCK\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-buck.78712d24.png\",\n \"HIBANA\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-hibana.2010ec35.png\",\n \"KAPKAN\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-kapkan.db3ab661.png\",\n \"PULSE\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-pulse.30ab3682.png\",\n \"CASTLE\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-castle.b95704d7.png\",\n \"ROOK\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-rook.b3d0bfa3.png\",\n \"BANDIT\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-bandit.6d7d15bc.png\",\n \"SMOKE\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-smoke.1bf90066.png\",\n \"FROST\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-frost.f4325d10.png\",\n \"VALKYRIE\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-valkyrie.c1f143fb.png\",\n \"TACHANKA\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-tachanka.41caebce.png\",\n \"GLAZ\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-glaz.8cd96a16.png\",\n \"FUZE\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-fuze.dc9f2a14.png\",\n \"SLEDGE\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-sledge.832f6c6b.png\",\n \"MONTAGNE\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-montagne.1d04d00a.png\",\n \"MUTE\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-mute.ae51429f.png\",\n \"ECHO\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-echo.662156dc.png\",\n \"THATCHER\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-thatcher.73132fcd.png\",\n \"CAPITAO\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-capitao.1d0ea713.png\",\n \"IQ\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-iq.d97d8ee2.png\",\n \"BLACKBEARD\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-blackbeard.2292a791.png\",\n \"JAGER\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-jaeger.d8a6c470.png\",\n \"CAVEIRA\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/large-caveira.e4d82365.png\",\n \"DEFAULT\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/styles/images/mask-large-bandit.fc038cf1.png\"\n}\n\n\n# DEPRECATED - use Auth.get_operator_badge() instead\nOperatorIcons = {\n \"DEFAULT\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Glaz_Badge_229122.png\",\n \"HIBANA\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-operators-badge-hibana_275569.png\",\n \"SMOKE\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Smoke_Badge_196198.png\",\n \"KAPKAN\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Kapkan_Badge_229123.png\",\n \"TACHANKA\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Tachanka_Badge_229124.png\",\n \"THERMITE\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Thermite_Badge_196408.png\",\n \"THATCHER\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Thatcher_Badge_196196.png\",\n \"GLAZ\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Glaz_Badge_229122.png\",\n \"BANDIT\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Bandit_Badge_222163.png\",\n \"ROOK\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Rook_Badge_211296.png\",\n \"IQ\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/IQ_Badge_222165.png\",\n \"PULSE\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Pulse_Badge_202497.png\",\n \"MUTE\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Mute_Badge_196195.png\",\n \"VALKYRIE\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-operators-badge-valkyrie_250313.png\",\n \"FROST\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-operators-badge-frost_237595.png\",\n \"DOC\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Doc_Badge_211294.png\",\n \"SLEDGE\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Sledge_Badge_196197.png\",\n \"JAGER\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Jager_Badge_222166.png\",\n \"BLACKBEARD\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-operators-badge-blackbeard_250312.png\",\n \"FUZE\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Fuze_Badge_229121.png\",\n \"ECHO\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-operators-badge-echo_275572.png\",\n \"CAVEIRA\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-operators-badge-caveira_263102.png\",\n \"BLITZ\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Blitz_Badge_222164.png\",\n \"MONTAGNE\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Montagne_Badge_211295.png\",\n \"ASH\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Ash_Badge_196406.png\",\n \"TWITCH\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Twitch_Badge_211297.png\",\n \"CASTLE\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/Castle_Badge_196407.png\",\n \"BUCK\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-operators-badge-buck_237592.png\",\n \"CAPITAO\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-operators-badge-capitao_263100.png\",\n \"JACKAL\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-velvet-shell-badge-jackal_282825.png\",\n \"MIRA\": \"https://ubistatic19-a.akamaihd.net/resource/en-GB/game/rainbow6/siege/R6-velvet-shell-badge-mira_282826.png\",\n \"ELA\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/badge-ela.63ec2d26.png\",\n \"LESION\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/badge-lesion.07c3d352.png\",\n \"YING\": \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/badge-ying.b88be612.png\",\n \"DOKKAEBI\": \"https://ubistatic19-a.akamaihd.net/resource/en-us/game/rainbow6/siege/r6-white-noise-badge-dokkaebi_306314.png\",\n \"VIGIL\": \"https://ubistatic19-a.akamaihd.net/resource/en-us/game/rainbow6/siege/r6-white-noise-badge-vigil_306315.png\",\n \"ZOFIA\": \"https://ubistatic19-a.akamaihd.net/resource/en-gb/game/rainbow6/siege/zofia_badge_306416.png\"\n}\n\n\n# DEPRECATED - use Auth.get_operator_statistic() instead\nOperatorStatistics = {\n \"DOC\": \"teammaterevive\",\n \"TWITCH\": \"gadgetdestroybyshockdrone\",\n \"ASH\": \"bonfirewallbreached\",\n \"THERMITE\": \"reinforcementbreached\",\n \"BLITZ\": \"flashedenemy\",\n \"BUCK\": \"kill\",\n \"HIBANA\": \"detonate_projectile\",\n \"KAPKAN\": \"boobytrapkill\",\n \"PULSE\": \"heartbeatspot\",\n \"CASTLE\": \"kevlarbarricadedeployed\",\n \"ROOK\": \"armortakenteammate\",\n \"BANDIT\": \"batterykill\",\n \"SMOKE\": \"poisongaskill\",\n \"FROST\": \"dbno\",\n \"VALKYRIE\": \"camdeployed\",\n \"TACHANKA\": \"turretkill\",\n \"GLAZ\": \"sniperkill\",\n \"FUZE\": \"clusterchargekill\",\n \"SLEDGE\": \"hammerhole\",\n \"MONTAGNE\": \"shieldblockdamage\",\n \"MUTE\": \"gadgetjammed\",\n \"ECHO\": \"enemy_sonicburst_affected\",\n \"THATCHER\": \"gadgetdestroywithemp\",\n \"CAPITAO\": \"lethaldartkills\",\n \"IQ\": \"gadgetspotbyef\",\n \"BLACKBEARD\": \"gunshieldblockdamage\",\n \"JAGER\": \"gadgetdestroybycatcher\",\n \"CAVEIRA\": \"interrogations\",\n \"JACKAL\": \"cazador_assist_kill\",\n \"MIRA\": \"black_mirror_gadget_deployed\",\n \"LESION\": \"caltrop_enemy_affected\",\n \"ELA\": \"concussionmine_detonate\",\n \"YING\": \"dazzler_gadget_detonate\",\n \"DOKKAEBI\": \"phoneshacked\",\n \"VIGIL\": \"diminishedrealitymode\",\n \"ZOFIA\": \"concussiongrenade_detonate\"\n}\n\n\nOperatorStatisticNames = {\n \"DOC\": \"Teammates Revived\",\n \"TWITCH\": \"Gadgets Destroyed With Shock Drone\",\n \"ASH\": \"Walls Breached\",\n \"THERMITE\": \"Reinforcements Breached\",\n \"BLITZ\": \"Enemies Flashed\",\n \"BUCK\": \"Shotgun Kills\",\n \"HIBANA\": \"Projectiles Detonated\",\n \"KAPKAN\": \"Boobytrap Kills\",\n \"PULSE\": \"Heartbeat Spots\",\n \"CASTLE\": \"Barricades Deployed\",\n \"ROOK\": \"Armor Taken\",\n \"BANDIT\": \"Battery Kills\",\n \"SMOKE\": \"Poison Gas Kills\",\n \"FROST\": \"DBNOs From Traps\",\n \"VALKYRIE\": \"Cameras Deployed\",\n \"TACHANKA\": \"Turret Kills\",\n \"GLAZ\": \"Sniper Kills\",\n \"FUZE\": \"Cluster Charge Kills\",\n \"SLEDGE\": \"Hammer Holes\",\n \"MONTAGNE\": \"Damage Blocked\",\n \"MUTE\": \"Gadgets Jammed\",\n \"ECHO\": \"Enemies Sonic Bursted\",\n \"THATCHER\": \"Gadgets Destroyed\",\n \"CAPITAO\": \"Lethal Dart Kills\",\n \"IQ\": \"Gadgets Spotted\",\n \"BLACKBEARD\": \"Damage Blocked\",\n \"JAGER\": \"Projectiles Destroyed\",\n \"CAVEIRA\": \"Interrogations\",\n \"JACKAL\": \"Footprint Scan Assists\",\n \"MIRA\": \"Black Mirrors Deployed\",\n \"LESION\": \"Enemies poisoned by Gu mines\",\n \"YING\": \"Candela devices detonated\",\n \"ELA\": \"Grzmot Mines Detonated\",\n \"DOKKAEBI\": \"Phones Hacked\",\n \"VIGIL\": \"Drones Deceived\",\n \"ZOFIA\": \"Concussion Grenades Detonated\",\n \"FINKA\": \"Nano-boosts used\",\n \"LION\": \"Enemies revealed\",\n \"ALIBI\": \"Enemies pinged by decoys\",\n \"MAESTRO\": \"Enemies spotted with turret camera\",\n \"MAVERICK\": \"D.I.Y. Blowtorch\",\n \"CLASH\": \"CCE Shield\",\n \"KAID\": \"Rtila Electroclaw\",\n \"NOMAD\": \"Airjab repulsion grenades\",\n \"MOZZIE\": \"Tiny 4-legged bots\",\n \"GRIDLOCK\": \"Hexagonal cluster of spikes\"\n}\n\n\nclass WeaponTypes:\n \"\"\"Weapon Types\n\n Attributes\n ----------\n ASSAULT_RIFLE : int\n the assault rifle weapon id\n SUBMACHINE_GUN : int\n the submachine gun weapon id\n MARKSMAN_RIFLE : int\n the marksman rifle weapon id\n SHOTGUN : int\n the shotgun weapon id\n HANDGUN : int\n the handgun weapon id\n LIGHT_MACHINE_GUN : int\n the light machine gun weapon id\n MACHINE_PISTOL : int\n the machine pistol weapon id\"\"\"\n ASSAULT_RIFLE = 0\n SUBMACHINE_GUN = 1\n MARKSMAN_RIFLE = 2\n SHOTGUN = 3\n HANDGUN = 4\n LIGHT_MACHINE_GUN = 5\n MACHINE_PISTOL = 6\n\n\nWeaponNames = [\n \"Assault Rifle\",\n \"Submachine Gun\",\n \"Marksman Rifle\",\n \"Shotgun\",\n \"Handgun\",\n \"Light Machine Gun\",\n \"Machine Pistol\"\n]\n\n\nGamemodeNames = {\n \"securearea\": \"Secure Area\",\n \"rescuehostage\": \"Hostage Rescue\",\n \"plantbomb\": \"Bomb\"\n}\n\n\nclass Auth:\n \"\"\"Holds your authentication information. Used to retrieve Player objects\n\n Parameters\n ----------\n email : Optional[str]\n Your Ubisoft email\n password : Optional[str]\n Your Ubisoft password\n token : Optional[str]\n Your Ubisoft auth token, either supply this OR email/password\n appid : Optional[str]\n Your Ubisoft appid, not required\n cachetime : Optional[float]\n How long players are cached for (in seconds)\n max_connect_retries : Optional[int]\n How many times the auth client will automatically try to reconnect, high numbers can get you temporarily banned\n\n Attributes\n ----------\n session\n aiohttp client session\n token : str\n your token\n appid : str\n your appid\n sessionid : str\n the current connections session id (will change upon attaining new key)\n key : str\n your current auth key (will change every time you connect)\n spaceids : dict\n contains the spaceid for each platform\n profileid : str\n your profileid (corresponds to your appid)\n userid : str\n your userid (corresponds to your appid)\n cachetime : float\n the time players are cached for\n cache : dict\n the current player cache\n\n \"\"\"\n\n @staticmethod\n def get_basic_token(email, password):\n return base64.b64encode((email + \":\" + password).encode(\"utf-8\")).decode(\"utf-8\")\n\n def __init__(self, email=None, password=None, token=None, appid=None,\n cachetime=120, max_connect_retries=1, session=None):\n if session is not None:\n self.session = session\n else:\n self.session = aiohttp.ClientSession()\n\n self.max_connect_retries = max_connect_retries\n\n if email is not None and password is not None:\n self.token = Auth.get_basic_token(email, password)\n elif token is not None:\n self.token = token\n else:\n raise TypeError(\"Argument error, requires either email/password or token to be set, neither given\")\n\n if appid is not None:\n self.appid = appid\n else:\n self.appid = \"39baebad-39e5-4552-8c25-2c9b919064e2\"\n\n self.sessionid = \"\"\n self.key = \"\"\n self.uncertain_spaceid = \"\"\n self.spaceids = {\n \"uplay\": \"5172a557-50b5-4665-b7db-e3f2e8c5041d\",\n \"psn\": \"05bfb3f7-6c21-4c42-be1f-97a33fb5cf66\",\n \"xbl\": \"98a601e5-ca91-4440-b1c5-753f601a2c90\",\n \"uplay_test\": \"41aebcf5-56eb-4f1e-b154-9eb46718f465\"\n }\n self.profileid = \"\"\n self.userid = \"\"\n self.genome = \"\"\n\n self.cachetime = cachetime\n self.cache={}\n\n self._definitions = None\n self._op_definitions = None\n self._login_cooldown = 0\n\n @asyncio.coroutine\n def connect(self):\n \"\"\"|coro|\n\n Connect to ubisoft, automatically called when needed\"\"\"\n if time.time() < self._login_cooldown:\n raise FailedToConnect(\"login on cooldown\")\n\n resp = yield from self.session.post(\"https://connect.ubi.com/ubiservices/v2/profiles/sessions\", headers = {\n \"Content-Type\": \"application/json\",\n \"Ubi-AppId\": self.appid,\n \"Authorization\": \"Basic \" + self.token\n }, data=json.dumps({\"rememberMe\": True}))\n\n data = yield from resp.json()\n\n if \"ticket\" in data:\n self.key = data.get(\"ticket\")\n self.sessionid = data.get(\"sessionId\")\n self.uncertain_spaceid = data.get(\"spaceId\")\n else:\n raise FailedToConnect\n\n @asyncio.coroutine\n def get(self, *args, retries=0, referer=None, json=True, platform=\"uplay\", **kwargs):\n if not self.key:\n for i in range(self.max_connect_retries):\n try:\n yield from self.connect()\n break\n except FailedToConnect:\n pass\n else:\n raise FailedToConnect\n\n if \"headers\" not in kwargs: kwargs[\"headers\"] = {}\n kwargs[\"headers\"][\"Authorization\"] = \"Ubi_v1 t=\" + self.key\n if platform == \"uplay_test\":\n kwargs[\"headers\"][\"Ubi-AppId\"] = \"a427a342-56bb-437b-b835-fa695c75893b\"\n else:\n kwargs[\"headers\"][\"Ubi-AppId\"] = self.appid\n kwargs[\"headers\"][\"Ubi-SessionId\"] = self.sessionid\n kwargs[\"headers\"][\"Connection\"] = \"keep-alive\"\n if referer is not None:\n if isinstance(referer, Player):\n referer = \"https://game-rainbow6.ubi.com/en-gb/uplay/player-statistics/%s/multiplayer\" % referer.id\n kwargs[\"headers\"][\"Referer\"] = str(referer)\n #print(\"=====REQUEST=====\")\n #print(args)\n #print(kwargs)\n #print(\"=====END REQUEST=====\")\n resp = yield from self.session.get(*args, **kwargs)\n #print(\"=====RESPONSE=====\")\n #print(resp)\n #print(\"=====END RESPONSE=====\")\n if json:\n try:\n data = yield from resp.json()\n #print(\"=====DATA=====\")\n #print(data)\n #print(\"=====END DATA=====\")\n except:\n text = yield from resp.text()\n\n message = text.split(\"h1>\")\n if len(message) > 1:\n message = message[1][:-2]\n code = 0\n if \"502\" in message: code = 502\n else:\n message = text\n\n raise InvalidRequest(\"Received a text response, expected JSON response. Message: %s\" % message, code=code)\n\n if \"httpCode\" in data:\n if data[\"httpCode\"] == 401:\n if retries >= self.max_connect_retries:\n # wait 30 seconds before sending another request\n self._login_cooldown = time.time() + 60\n raise FailedToConnect\n yield from self.connect()\n result = yield from self.get(*args, retries=retries+1, **kwargs)\n return result\n else:\n msg = data.get(\"message\", \"\")\n if data[\"httpCode\"] == 404: msg = \"missing resource %s\" % data.get(\"resource\", args[0])\n raise InvalidRequest(\"HTTP Code: %s, Message: %s\" % (data[\"httpCode\"], msg), code=data[\"httpCode\"])\n \n return data\n else:\n text = yield from resp.text()\n return text\n\n @asyncio.coroutine\n def get_players(self, name=None, platform=None, uid=None):\n \"\"\"|coro|\n\n get a list of players matching the term on that platform,\n exactly one of uid and name must be given, platform must be given,\n this list almost always has only 1 element, so it's easier to use get_player\n\n Parameters\n ----------\n name : str\n the name of the player you're searching for\n platform : str\n the name of the platform you're searching on (See :class:`Platforms`)\n uid : str\n the uid of the player you're searching for\n\n Returns\n -------\n list[:class:`Player`]\n list of found players\"\"\"\n\n if name is None and uid is None:\n raise TypeError(\"name and uid are both None, exactly one must be given\")\n\n if name is not None and uid is not None:\n raise TypeError(\"cannot search by uid and name at the same time, please give one or the other\")\n\n if platform is None:\n raise TypeError(\"platform cannot be None\")\n\n if \"platform\" not in self.cache: self.cache[platform] = {}\n\n if name:\n cache_key = \"NAME:%s\" % name\n else:\n cache_key = \"UID:%s\" % uid\n\n if platform == \"uplay_test\":\n platform = \"uplay\"\n realplatform = \"uplay_test\"\n else:\n realplatform = platform\n\n if platform not in self.cache: self.cache[platform] = {}\n\n if cache_key in self.cache[platform]:\n if self.cachetime > 0 and self.cache[platform][cache_key][0] < time.time():\n del self.cache[platform][cache_key]\n else:\n return self.cache[platform][cache_key][1]\n\n if name:\n data = yield from self.get(\"https://public-ubiservices.ubi.com/v2/profiles?nameOnPlatform=%s&platformType=%s\" % (parse.quote(name), parse.quote(platform)), platform=realplatform)\n else:\n data = yield from self.get(\"https://public-ubiservices.ubi.com/v2/users/%s/profiles?platformType=%s\" % (uid, parse.quote(platform)), platform=realplatform)\n\n if \"profiles\" in data:\n #TODO: add support to call for multipleplayers at once\n data[\"profiles\"][0][\"platformType\"] = realplatform #here we only add this for one user\n results = [Player(self, x) for x in data[\"profiles\"] if x.get(\"platformType\", \"\") == realplatform]\n if len(results) == 0: raise InvalidRequest(\"No results\")\n if self.cachetime != 0:\n self.cache[platform][cache_key] = [time.time() + self.cachetime, results]\n return results\n else:\n raise InvalidRequest(\"Missing key profiles in returned JSON object %s\" % str(data))\n\n @asyncio.coroutine\n def get_player(self, name=None, platform=None, uid=None):\n \"\"\"|coro|\n\n Calls get_players and returns the first element,\n exactly one of uid and name must be given, platform must be given\n\n Parameters\n ----------\n name : str\n the name of the player you're searching for\n platform : str\n the name of the platform you're searching on (See :class:`Platforms`)\n uid : str\n the uid of the player you're searching for\n\n Returns\n -------\n :class:`Player`\n player found\"\"\"\n\n results = yield from self.get_players(name=name, platform=platform, uid=uid)\n return results[0]\n\n @asyncio.coroutine\n def get_operator_definitions(self):\n \"\"\"|coro|\n\n Retrieves a list of information about operators - their badge, unique statistic, etc.\n\n Returns\n -------\n dict\n operators\"\"\"\n if self._op_definitions is not None:\n return self._op_definitions\n\n resp = yield from self.session.get(\"https://s3.amazonaws.com/r6operators.azarus.io/operators.json\")\n\n data = yield from resp.json()\n self._op_definitions = data\n return data\n\n @asyncio.coroutine\n def get_operator_index(self, name):\n \"\"\"|coro|\n\n Gets the operators index from the operator definitions dict\n\n Returns\n -------\n str\n the operator index\"\"\"\n opdefs = yield from self.get_operator_definitions()\n\n name = name.lower()\n if name not in opdefs:\n return None\n\n return opdefs[name][\"index\"]\n\n @asyncio.coroutine\n def get_operator_statistic(self, name):\n \"\"\"|coro|\n\n Gets the operator unique statistic from the operator definitions dict\n\n Returns\n -------\n str\n the name of the operator unique statistic\"\"\"\n opdefs = yield from self.get_operator_definitions()\n\n name = name.lower()\n if name not in opdefs:\n return None\n\n return opdefs[name][\"uniqueStatistic\"][\"pvp\"][\"statisticId\"]\n\n @asyncio.coroutine\n def get_operator_badge(self, name):\n \"\"\"|coro|\n\n Gets the operator badge URL\n\n Returns\n -------\n str\n the operators badge URL\"\"\"\n opdefs = yield from self.get_operator_definitions()\n\n name = name.lower()\n if name not in opdefs:\n return None\n\n badge = opdefs[name][\"badge\"]\n\n if not badge.startswith(\"http\"):\n badge = \"https://game-rainbow6.ubi.com/\" + badge\n\n return badge\n\n\n @asyncio.coroutine\n def get_definitions(self):\n \"\"\"|coro|\n\n Retrieves the list of api definitions, downloading it from Ubisoft if it hasn't been fetched all ready\n Primarily for internal use, but could contain useful information.\n\n Returns\n -------\n dict\n definitions\"\"\"\n if self._definitions is not None:\n return self._definitions\n\n resp = yield from self.session.get(\"https://ubistatic-a.akamaihd.net/0058/prod/assets/data/statistics.definitions.eb165e13.json\")\n\n data = yield from resp.json()\n self._definitions = data\n return data\n\n @asyncio.coroutine\n def get_object_index(self, key):\n \"\"\"|coro|\n\n Mainly for internal use with get_operator,\n returns the \"location\" index for the key in the definitions\n\n Returns\n -------\n str\n the object's location index\"\"\"\n defns = yield from self.get_definitions()\n\n for x in defns:\n if key in x and \"objectIndex\" in defns[x]:\n return defns[x][\"objectIndex\"]\n\n return None\n\n\nclass Rank:\n \"\"\"Contains information about your rank\n\n Attributes\n ----------\n RANKS : list[str]\n Names of the ranks\n RANK_CHARMS : list[str]\n URLs for the rank charms\n UNRANKED : int\n the unranked bracket id\n COPPER : int\n the copper bracket id\n BRONZE : int\n the bronze bracket id\n SILVER : int\n the silver bracket id\n GOLD : int\n the gold bracket id\n PLATINUM : int\n the platinum bracket id\n DIAMOND : int\n the diamond bracket id\n max_mmr : int\n the maximum MMR the player has achieved\n mmr : int\n the MMR the player currently has\n wins : int\n the number of wins this player has this season\n losses : int\n the number of losses this player has this season\n abandons : int\n the number of abandons this player has this season\n\n rank_id : int\n the id of the players current rank\n rank : str\n the name of the players current rank\n max_rank : int\n the id of the players max rank\n next_rank_mmr : int\n the mmr required for the player to achieve their next rank\n season : int\n the season this rank is for\n region : str\n the region this rank is for\n skill_mean : float\n the mean for this persons skill\n skill_stdev : float\n the standard deviation for this persons skill\n \"\"\"\n RANKS = [\"Unranked\",\n \"Copper 4\", \"Copper 3\", \"Copper 2\", \"Copper 1\",\n \"Bronze 4\", \"Bronze 3\", \"Bronze 2\", \"Bronze 1\",\n \"Silver 4\", \"Silver 3\", \"Silver 2\", \"Silver 1\",\n \"Gold 4\", \"Gold 3\", \"Gold 2\", \"Gold 1\",\n \"Platinum 3\", \"Platinum 2\", \"Platinum 1\", \"Diamond\"]\n\n RANK_CHARMS = [\n \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/season02%20-%20copper%20charm.44c1ede2.png\",\n \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/season02%20-%20bronze%20charm.5edcf1c6.png\",\n \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/season02%20-%20silver%20charm.adde1d01.png\",\n \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/season02%20-%20gold%20charm.1667669d.png\",\n \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/season02%20-%20platinum%20charm.d7f950d5.png\",\n \"https://ubistatic-a.akamaihd.net/0058/prod/assets/images/season02%20-%20diamond%20charm.e66cad88.png\"\n ]\n\n RANK_ICONS = [\n \"https://i.imgur.com/sB11BIz.png\", # unranked\n \"https://i.imgur.com/ehILQ3i.jpg\", # copper 4\n \"https://i.imgur.com/6CxJoMn.jpg\", # copper 3\n \"https://i.imgur.com/eI11lah.jpg\", # copper 2\n \"https://i.imgur.com/0J0jSWB.jpg\", # copper 1\n \"https://i.imgur.com/42AC7RD.jpg\", # bronze 4\n \"https://i.imgur.com/QD5LYD7.jpg\", # bronze 3\n \"https://i.imgur.com/9AORiNm.jpg\", # bronze 2\n \"https://i.imgur.com/hmPhPBj.jpg\", # bronze 1\n \"https://i.imgur.com/D36ZfuR.jpg\", # silver 4\n \"https://i.imgur.com/m8GToyF.jpg\", # silver 3\n \"https://i.imgur.com/EswGcx1.jpg\", # silver 2\n \"https://i.imgur.com/KmFpkNc.jpg\", # silver 1\n \"https://i.imgur.com/6Qg6aaH.jpg\", # gold 4\n \"https://i.imgur.com/B0s1o1h.jpg\", # gold 3\n \"https://i.imgur.com/ELbGMc7.jpg\", # gold 2\n \"https://i.imgur.com/ffDmiPk.jpg\", # gold 1\n \"https://i.imgur.com/Sv3PQQE.jpg\", # plat 3\n \"https://i.imgur.com/Uq3WhzZ.jpg\", # plat 2\n \"https://i.imgur.com/xx03Pc5.jpg\", # plat 1\n \"https://i.imgur.com/nODE0QI.jpg\" # diamond\n ]\n\n @staticmethod\n def bracket_from_rank(rank_id):\n if rank_id == 0: return 0\n elif rank_id <= 4: return 1\n elif rank_id <= 8: return 2\n elif rank_id <= 12: return 3\n elif rank_id <= 16: return 4\n elif rank_id <= 19: return 5\n else: return 6\n\n @staticmethod\n def bracket_name(bracket):\n if bracket == 0: return \"Unranked\"\n elif bracket == 1: return \"Copper\"\n elif bracket == 2: return \"Bronze\"\n elif bracket == 3: return \"Silver\"\n elif bracket == 4: return \"Gold\"\n elif bracket == 5: return \"Platinum\"\n else: return \"Diamond\"\n\n\n UNRANKED = 0\n COPPER = 1\n BRONZE = 2\n SILVER = 3\n GOLD = 4\n PLATINUM = 5\n DIAMOND = 6\n\n def __init__(self, data):\n self.max_mmr = data.get(\"max_mmr\")\n self.mmr = data.get(\"mmr\")\n self.wins = data.get(\"wins\")\n self.losses = data.get(\"losses\")\n self.rank_id = data.get(\"rank\", 0)\n self.rank = Rank.RANKS[self.rank_id]\n self.max_rank = data.get(\"max_rank\")\n self.next_rank_mmr = data.get(\"next_rank_mmr\")\n self.season = data.get(\"season\")\n self.region = data.get(\"region\")\n self.abandons = data.get(\"abandons\")\n self.skill_mean = data.get(\"skill_mean\")\n self.skill_stdev = data.get(\"skill_stdev\")\n\n def get_icon_url(self):\n \"\"\"Get URL for this rank's icon\n\n Returns\n -------\n :class:`str`\n the URL for the rank icon\"\"\"\n return self.RANK_ICONS[self.rank_id]\n\n def get_charm_url(self):\n \"\"\"Get charm URL for the bracket this rank is in\n\n Returns\n -------\n :class:`str`\n the URL for the charm\n\n \"\"\"\n if self.rank_id <= 4: return self.RANK_CHARMS[0]\n if self.rank_id <= 8: return self.RANK_CHARMS[1]\n if self.rank_id <= 12: return self.RANK_CHARMS[2]\n if self.rank_id <= 16: return self.RANK_CHARMS[3]\n if self.rank_id <= 19: return self.RANK_CHARMS[4]\n return self.RANK_CHARMS[5]\n\n def get_bracket(self):\n \"\"\"Get rank bracket\n\n Returns\n -------\n :class:`int`\n the id for the rank bracket this rank is in\n\n \"\"\"\n return Rank.bracket_from_rank(self.rank_id)\n\n\nclass Operator:\n \"\"\"Contains information about an operator\n\n Attributes\n ----------\n name : str\n the name of the operator\n wins : int\n the number of wins the player has on this operator\n losses : int\n the number of losses the player has on this operator\n kills : int\n the number of kills the player has on this operator\n deaths : int\n the number of deaths the player has on this operator\n headshots : int\n the number of headshots the player has on this operator\n melees : int\n the number of melee kills the player has on this operator\n dbnos : int\n the number of DBNO (down-but-not-out)'s the player has on this operator\n xp : int\n the total amount of xp the player has on this operator\n time_played : int\n the amount of time the player has played this operator for in seconds\n statistic : int\n the value for this operators unique statistic\n statistic_name : str\n the human-friendly name for this operators statistic\"\"\"\n def __init__(self, name, data):\n self.name = name.lower()\n\n self.wins = data.get(\"roundwon\", 0)\n self.losses = data.get(\"roundlost\", 0)\n self.kills = data.get(\"kills\", 0)\n self.deaths = data.get(\"death\", 0)\n self.headshots = data.get(\"headshot\", 0)\n self.melees = data.get(\"meleekills\", 0)\n self.dbnos = data.get(\"dbno\", 0)\n self.xp = data.get(\"totalxp\", 0)\n self.time_played = data.get(\"timeplayed\", 0)\n\n if \"__statistic_name\" in data:\n self.statistic = data.get(data.get(\"__statistic_name\"), 0)\n else:\n self.statistic = 0\n\n self.statistic_name = OperatorStatisticNames[self.name.upper()]\n\n\nclass Weapon:\n \"\"\"Contains information about a weapon\n\n Attributes\n ----------\n type : int\n the weapon type\n name : str\n the human-friendly name for this weapon type\n kills : int\n the number of kills the player has for this weapon\n headshots : int\n the number of headshots the player has for this weapon\n hits : int\n the number of bullet this player has hit with this weapon\n shots : int\n the number of bullets this player has shot with this weapon\n\n \"\"\"\n def __init__(self, type):\n self.type = type\n self.name = WeaponNames[self.type]\n\n self.kills = 0\n self.headshots = 0\n self.hits = 0\n self.shots = 0\n\n\nclass Gamemode:\n \"\"\"Contains information about a gamemode\n\n Attributes\n ----------\n type : str\n the gamemode id\n name : str\n the human-readable name for this gamemode\n won : int\n the number of wins the player has on this gamemode\n lost : int\n the number of losses the player has on this gamemode\n played : int\n the number of games this player has played on this gamemode\n best_score : int\n the best score this player has achieved on this gamemode\"\"\"\n def __init__(self, type):\n self.type = type\n self.name = GamemodeNames[self.type]\n\n self.won = 0\n self.lost = 0\n self.played = 0\n self.best_score = 0\n\n\nclass GameQueue:\n \"\"\"Contains information about a specific game queue\n\n Attributes\n ----------\n name : str\n the name for this gamemode (always either \"ranked\" or \"casual\"\n won : int\n the number of wins the player has on this gamemode\n lost : int\n the number of losses the player has on this gamemode\n time_played : int\n the amount of time in seconds the player has spent playing on this gamemode\n played : int\n the number of games the player has played on this gamemode\n kills : int\n the number of kills the player has on this gamemode\n deaths : int\n the number of deaths the player has on this gamemode\"\"\"\n def __init__(self, name):\n self.name = name\n\n self.won = 0\n self.lost = 0\n self.time_played = 0\n self.played = 0\n self.kills = 0\n self.deaths = 0\n\n\ndef format_time(time_played, format):\n hours = time_played // 3600\n minutes = (time_played - (hours * 3600)) // 60\n seconds = time_played - ((hours * 3600) + (minutes * 60))\n\n return format.replace(\"%h\", str(hours)).replace(\"%m\", str(minutes)).replace(\"%s\", str(seconds))\n\n\nclass Player:\n \"\"\"Contains information about a specific player\n\n Attributes\n ----------\n auth : :class:`Auth`\n the auth object used to find this player\n id : str\n the players profile id\n userid : str\n the players user id\n platform : str\n the platform this player is on\n platform_url : str\n the URL name for this platform (used internally)\n id_on_platform : str\n the players ID on the platform\n name : str\n the players name on the platform\n url : str\n a link to the players profile\n icon_url : str\n a link to the players avatar\n xp : int\n the amount of xp the player has, must call check_level or load_level first\n level : int\n the level of the player, must call check_level or load_level first\n ranks : dict\n dict containing already found ranks (\"region_name:season\": :class:`Rank`)\n operators : dict\n dict containing already found operators (operator_name: :class:`Operator`)\n gamemodes : dict\n dict containing already found gamemodes (gamemode_id: :class:`Gamemode`)\n weapons : dict\n dict containing already found weapons (weapon_id: :class:`Weapon`)\n casual : :class:`GameQueue`\n stats for the casual queue, must call load_queues or check_queues first\n ranked : :class:`GameQueue`\n stats for the ranked queue, must call load_queues or check_queues first\n deaths : int\n the number of deaths the player has (must call load_general or check_general first)\n kills : int\n the number of kills the player has (must call load_general or check_general first)\n kill_assists : int\n the number of kill assists the player has (must call load_general or check_general first)\n penetration_kills : int\n the number of penetration kills the player has (must call load_general or check_general first)\n melee_kills : int\n the number of melee kills the player has (must call load_general or check_general first)\n revives : int\n the number of revives the player has (must call load_general or check_general first)\n matches_won : int\n the number of matches the player has won (must call load_general or check_general first)\n matches_lost : int\n the number of matches the player has lost (must call load_general or check_general first)\n matches_played : int\n the number of matches the player has played (must call load_general or check_general first)\n time_played : int\n the amount of time in seconds the player has played for (must call load_general or check_general first)\n bullets_fired : int\n the amount of bullets the player has fired (must call load_general or check_general first)\n bullets_hit : int\n the amount of bullets the player has hit (must call load_general or check_general first)\n headshots : int\n the amount of headshots the player has hit (must call load_general or check_general first)\n terrorist_hunt : :class:`GameQueue`\n contains all of the above state (from deaths to headshots) inside a gamequeue object.\n \"\"\"\n\n def __init__(self, auth, data):\n self.auth = auth\n #print(data)\n\n self.id = data.get(\"profileId\")\n self.userid = data.get(\"userId\")\n self.platform = data.get(\"platformType\")\n self.platform_url = PlatformURLNames[self.platform]\n self.id_on_platform = data.get(\"idOnPlatform\")\n self.name = data.get(\"nameOnPlatform\")\n\n self.url = \"https://game-rainbow6.ubi.com/en-us/%s/player-statistics/%s/multiplayer\" % (self.platform, self.id)\n self.icon_url = \"https://ubisoft-avatars.akamaized.net/%s/default_146_146.png\" % (self.id)\n\n self.ranks = {}\n self.operators = {}\n self.gamemodes = {}\n self.weapons = []\n\n self.casual = None\n self.ranked = None\n self.terrorist_hunt = None\n\n @property\n def spaceid(self):\n return self.auth.spaceids[self.platform]\n\n @asyncio.coroutine\n def _fetch_statistics(self, *statsitics):\n data = yield from self.auth.get(\"https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/playerstats2/statistics?populations=%s&statistics=%s\" % (self.spaceid, self.platform_url, self.id, \",\".join(statsitics)))\n\n if not \"results\" in data or not self.id in data[\"results\"]:\n raise InvalidRequest(\"Missing results key in returned JSON object %s\" % str(data))\n\n data = data[\"results\"][self.id]\n stats = {}\n\n for x in data:\n statistic = x.split(\":\")[0]\n if statistic in statsitics:\n stats[statistic] = data[x]\n\n return stats\n\n @asyncio.coroutine\n def load_level(self):\n \"\"\"|coro|\n\n Load the players XP and level\"\"\"\n data = yield from self.auth.get(\"https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/r6playerprofile/playerprofile/progressions?profile_ids=%s\" % (self.spaceid, self.platform_url, self.id))\n\n if \"player_profiles\" in data and len(data[\"player_profiles\"]) > 0:\n self.xp = data[\"player_profiles\"][0].get(\"xp\", 0)\n self.level = data[\"player_profiles\"][0].get(\"level\", 0)\n else:\n raise InvalidRequest(\"Missing key player_profiles in returned JSON object %s\" % str(data))\n\n @asyncio.coroutine\n def check_level(self):\n \"\"\"|coro|\n\n Check the players XP and level, only loading it if it hasn't been loaded yet\"\"\"\n if not hasattr(self, \"level\"):\n yield from self.load_level()\n\n @asyncio.coroutine\n def load_rank(self, region, season=-1):\n \"\"\"|coro|\n Loads the players rank for this region and season\n\n Parameters\n ----------\n region : str\n the name of the region you want to get the rank for\n season : Optional[int]\n the season you want to get the rank for (defaults to -1, latest season)\n\n Returns\n -------\n :class:`Rank`\n the players rank for this region and season\"\"\"\n data = yield from self.auth.get(\"https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/r6karma/players?board_id=pvp_ranked&profile_ids=%s®ion_id=%s&season_id=%s\" % (self.spaceid, self.platform_url, self.id, region, season))\n\n if \"players\" in data and self.id in data[\"players\"]:\n regionkey = \"%s:%s\" % (region, season)\n self.ranks[regionkey] = Rank(data[\"players\"][self.id])\n return self.ranks[regionkey]\n else:\n raise InvalidRequest(\"Missing players key in returned JSON object %s\" % str(data))\n\n @asyncio.coroutine\n def get_rank(self, region, season=-1):\n \"\"\"|coro|\n\n Checks the players rank for this region, only loading it if it hasn't already been found\n\n Parameters\n ----------\n region : str\n the name of the region you want to get the rank for\n season : Optional[int]\n the season you want to get the rank for (defaults to -1, latest season)\n\n Returns\n -------\n :class:`Rank`\n the players rank for this region and season\"\"\"\n cache_key = \"%s:%s\" % (region, season)\n if cache_key in self.ranks:\n return self.ranks[cache_key]\n\n result = yield from self.load_rank(region, season)\n return result\n\n @asyncio.coroutine\n def load_all_operators(self):\n \"\"\"|coro|\n\n Loads the player stats for all operators\n\n Returns\n -------\n dict[:class:`Operator`]\n the dictionary of all operators found\"\"\"\n statistics = \"operatorpvp_kills,operatorpvp_death,operatorpvp_roundwon,operatorpvp_roundlost,operatorpvp_meleekills,operatorpvp_totalxp,operatorpvp_headshot,operatorpvp_timeplayed,operatorpvp_dbno\"\n\n for operator in OperatorStatisticNames:\n operator_key = yield from self.auth.get_operator_statistic(operator)\n if operator_key:\n statistics += \",\" + operator_key\n\n data = yield from self.auth.get(\"https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/playerstats2/statistics?populations=%s&statistics=%s\" % (self.spaceid, self.platform_url, self.id, statistics))\n\n if \"results\" not in data or not self.id in data[\"results\"]:\n raise InvalidRequest(\"Missing results key in returned JSON object %s\" % str(data))\n\n data = data[\"results\"][self.id]\n\n for operator in OperatorStatisticNames:\n location = yield from self.auth.get_operator_index(operator.lower())\n op_data = {x.split(\":\")[0].split(\"_\")[1]: data[x] for x in data if x is not None and location in x}\n operator_key = yield from self.auth.get_operator_statistic(operator)\n op_data[\"__statistic_name\"] = operator_key.split(\"_\")[1]\n\n self.operators[operator.lower()] = Operator(operator.lower(), op_data)\n\n return self.operators\n\n @asyncio.coroutine\n def get_all_operators(self):\n \"\"\"|coro|\n\n Checks the player stats for all operators, loading them all again if any aren't found\n This is significantly more efficient than calling get_operator for every operator name.\n\n Returns\n -------\n dict[:class:`Operator`]\n the dictionary of all operators found\"\"\"\n if len(self.operators) >= len(OperatorStatisticNames):\n return self.operators\n\n result = yield from self.load_all_operators()\n return result\n\n @asyncio.coroutine\n def load_operator(self, operator):\n \"\"\"|coro|\n\n Loads the players stats for the operator\n\n Parameters\n ----------\n operator : str\n the name of the operator\n\n Returns\n -------\n :class:`Operator`\n the operator object found\"\"\"\n location = yield from self.auth.get_operator_index(operator)\n if location is None:\n raise ValueError(\"invalid operator %s\" % operator)\n\n operator_key = yield from self.auth.get_operator_statistic(operator)\n if operator_key is not None:\n operator_key = \",\" + operator_key\n else:\n operator_key = \"\"\n\n data = yield from self.auth.get(\"https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/playerstats2/statistics?populations=%s&statistics=operatorpvp_kills,operatorpvp_death,operatorpvp_roundwon,operatorpvp_roundlost,operatorpvp_meleekills,operatorpvp_totalxp,operatorpvp_headshot,operatorpvp_timeplayed,operatorpvp_dbno%s\" % (self.spaceid, self.platform_url, self.id, operator_key))\n\n if not \"results\" in data or not self.id in data[\"results\"]:\n raise InvalidRequest(\"Missing results key in returned JSON object %s\" % str(data))\n\n data = data[\"results\"][self.id]\n\n data = {x.split(\":\")[0].split(\"_\")[1]: data[x] for x in data if x is not None and location in x}\n data[\"__statistic_name\"] = operator_key.split(\"_\")[1]\n\n #if len(data) < 5:\n # raise InvalidRequest(\"invalid number of results for operator in JSON object %s\" % data)\n\n oper = Operator(operator, data)\n self.operators[operator] = oper\n return oper\n\n @asyncio.coroutine\n def get_operator(self, operator):\n \"\"\"|coro|\n\n Checks the players stats for this operator, only loading them if they haven't already been found\n\n Parameters\n ----------\n operator : str\n the name of the operator\n\n Returns\n -------\n :class:`Operator`\n the operator object found\"\"\"\n if operator in self.operators:\n return self.operators[operator]\n\n result = yield from self.load_operator(operator)\n return result\n\n @asyncio.coroutine\n def load_weapons(self):\n \"\"\"|coro|\n\n Load the players weapon stats\n\n Returns\n -------\n list[:class:`Weapon`]\n list of all the weapon objects found\"\"\"\n data = yield from self.auth.get(\"https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/playerstats2/statistics?populations=%s&statistics=weapontypepvp_kills,weapontypepvp_headshot,weapontypepvp_bulletfired,weapontypepvp_bullethit\" % (self.spaceid, self.platform_url, self.id))\n\n if not \"results\" in data or not self.id in data[\"results\"]:\n raise InvalidRequest(\"Missing key results in returned JSON object %s\" % str(data))\n\n data = data[\"results\"][self.id]\n self.weapons = [Weapon(i) for i in range(7)]\n\n for x in data:\n spl = x.split(\":\")\n category = spl[0].split(\"_\")[1]\n try:\n weapontype = int(spl[1]) - 1\n weapon = self.weapons[weapontype]\n if category == \"kills\": weapon.kills = data[x]\n elif category == \"headshot\": weapon.headshots = data[x]\n elif category == \"bulletfired\": weapon.shots = data[x]\n elif category == \"bullethit\": weapon.hits = data[x]\n except (ValueError, TypeError, IndexError):\n pass\n\n return self.weapons\n\n @asyncio.coroutine\n def check_weapons(self):\n \"\"\"|coro|\n\n Check the players weapon stats, only loading them if they haven't already been found\n\n Returns\n -------\n list[:class:`Weapon`]\n list of all the weapon objects found\"\"\"\n if len(self.weapons) == 0:\n yield from self.load_weapons()\n return self.weapons\n\n @asyncio.coroutine\n def load_gamemodes(self):\n \"\"\"|coro|\n\n Loads the players gamemode stats\n\n Returns\n -------\n dict\n dict of all the gamemodes found (gamemode_name: :class:`Gamemode`)\"\"\"\n\n stats = yield from self._fetch_statistics(\"secureareapvp_matchwon\", \"secureareapvp_matchlost\", \"secureareapvp_matchplayed\",\n \"secureareapvp_bestscore\", \"rescuehostagepvp_matchwon\", \"rescuehostagepvp_matchlost\",\n \"rescuehostagepvp_matchplayed\", \"rescuehostagepvp_bestscore\", \"plantbombpvp_matchwon\",\n \"plantbombpvp_matchlost\", \"plantbombpvp_matchplayed\", \"plantbombpvp_bestscore\",\n \"generalpvp_servershacked\", \"generalpvp_serverdefender\", \"generalpvp_serveraggression\",\n \"generalpvp_hostagerescue\", \"generalpvp_hostagedefense\")\n\n self.gamemodes = {x: Gamemode(x) for x in GamemodeNames}\n for name in self.gamemodes:\n statname, gamemode = name + \"pvp_\", self.gamemodes[name]\n\n gamemode.best_score = stats.get(statname + \"bestscore\", 0)\n gamemode.lost = stats.get(statname + \"matchlost\", 0)\n gamemode.won = stats.get(statname + \"matchwon\", 0)\n gamemode.played = stats.get(statname + \"matchplayed\", 0)\n\n if name == \"securearea\":\n gamemode.areas_secured = stats.get(\"generalpvp_servershacked\", 0)\n gamemode.areas_defended = stats.get(\"generalpvp_serverdefender\", 0)\n gamemode.areas_contested = stats.get(\"generalpvp_serveraggression\", 0)\n elif name == \"rescuehostage\":\n gamemode.hostages_rescued = stats.get(\"generalpvp_hostagerescue\", 0)\n gamemode.hostages_defended = stats.get(\"generalpvp_hostagedefense\", 0)\n\n\n\n return self.gamemodes\n\n @asyncio.coroutine\n def check_gamemodes(self):\n \"\"\"|coro|\n\n Checks the players gamemode stats, only loading them if they haven't already been found\n\n Returns\n -------\n dict\n dict of all the gamemodes found (gamemode_name: :class:`Gamemode`)\"\"\"\n if len(self.gamemodes) == 0:\n yield from self.load_gamemodes()\n return self.gamemodes\n\n @asyncio.coroutine\n def load_general(self):\n \"\"\"|coro|\n\n Loads the players general stats\"\"\"\n\n stats = yield from self._fetch_statistics(\"generalpvp_timeplayed\", \"generalpvp_matchplayed\", \"generalpvp_matchwon\",\n \"generalpvp_matchlost\", \"generalpvp_kills\", \"generalpvp_death\",\n \"generalpvp_bullethit\", \"generalpvp_bulletfired\", \"generalpvp_killassists\",\n \"generalpvp_revive\", \"generalpvp_headshot\", \"generalpvp_penetrationkills\",\n \"generalpvp_meleekills\", \"generalpvp_dbnoassists\", \"generalpvp_suicide\",\n \"generalpvp_barricadedeployed\", \"generalpvp_reinforcementdeploy\", \"generalpvp_totalxp\",\n \"generalpvp_rappelbreach\", \"generalpvp_distancetravelled\", \"generalpvp_revivedenied\",\n \"generalpvp_dbno\", \"generalpvp_gadgetdestroy\", \"generalpvp_blindkills\")\n\n statname = \"generalpvp_\"\n self.deaths = stats.get(statname + \"death\", 0)\n self.penetration_kills = stats.get(statname + \"penetrationkills\", 0)\n self.matches_won = stats.get(statname + \"matchwon\", 0)\n self.bullets_hit = stats.get(statname + \"bullethit\", 0)\n self.melee_kills = stats.get(statname + \"meleekills\", 0)\n self.bullets_fired = stats.get(statname + \"bulletfired\", 0)\n self.matches_played = stats.get(statname + \"matchplayed\", 0)\n self.kill_assists = stats.get(statname + \"killassists\", 0)\n self.time_played = stats.get(statname + \"timeplayed\", 0)\n self.revives = stats.get(statname + \"revive\", 0)\n self.kills = stats.get(statname + \"kills\", 0)\n self.headshots = stats.get(statname + \"headshot\", 0)\n self.matches_lost = stats.get(statname + \"matchlost\", 0)\n self.dbno_assists = stats.get(statname + \"dbnoassists\", 0)\n self.suicides = stats.get(statname + \"suicide\", 0)\n self.barricades_deployed = stats.get(statname + \"barricadedeployed\", 0)\n self.reinforcements_deployed = stats.get(statname + \"reinforcementdeploy\", 0)\n self.total_xp = stats.get(statname + \"totalxp\", 0)\n self.rappel_breaches = stats.get(statname + \"rappelbreach\", 0)\n self.distance_travelled = stats.get(statname + \"distancetravelled\", 0)\n self.revives_denied = stats.get(statname + \"revivedenied\", 0)\n self.dbnos = stats.get(statname + \"dbno\", 0)\n self.gadgets_destroyed = stats.get(statname + \"gadgetdestroy\", 0)\n self.blind_kills = stats.get(statname + \"blindkills\")\n\n\n @asyncio.coroutine\n def check_general(self):\n \"\"\"|coro|\n\n Checks the players general stats, only loading them if they haven't already been found\"\"\"\n if not hasattr(self, \"kills\"):\n yield from self.load_general()\n\n @asyncio.coroutine\n def load_queues(self):\n \"\"\"|coro|\n\n Loads the players game queues\"\"\"\n\n stats = yield from self._fetch_statistics(\"casualpvp_matchwon\", \"casualpvp_matchlost\", \"casualpvp_timeplayed\",\n \"casualpvp_matchplayed\", \"casualpvp_kills\", \"casualpvp_death\",\n \"rankedpvp_matchwon\", \"rankedpvp_matchlost\", \"rankedpvp_timeplayed\",\n \"rankedpvp_matchplayed\", \"rankedpvp_kills\", \"rankedpvp_death\")\n\n self.ranked = GameQueue(\"ranked\")\n self.casual = GameQueue(\"casual\")\n\n for gq in (self.ranked, self.casual):\n statname = gq.name + \"pvp_\"\n\n gq.won = stats.get(statname + \"matchwon\", 0)\n gq.lost = stats.get(statname + \"matchlost\", 0)\n gq.time_played = stats.get(statname + \"timeplayed\", 0)\n gq.played = stats.get(statname + \"matchplayed\", 0)\n gq.kills = stats.get(statname + \"kills\", 0)\n gq.deaths = stats.get(statname + \"death\", 0)\n\n\n @asyncio.coroutine\n def check_queues(self):\n \"\"\"|coro|\n\n Checks the players game queues, only loading them if they haven't already been found\"\"\"\n if self.casual is None:\n yield from self.load_queues()\n\n @asyncio.coroutine\n def load_terrohunt(self):\n \"\"\"|coro|\n\n Loads the player's general stats for terrorist hunt\"\"\"\n stats = yield from self._fetch_statistics(\"generalpve_dbnoassists\", \"generalpve_death\", \"generalpve_revive\",\n \"generalpve_matchwon\", \"generalpve_suicide\", \"generalpve_servershacked\",\n \"generalpve_serverdefender\", \"generalpve_barricadedeployed\", \"generalpve_reinforcementdeploy\",\n \"generalpve_kills\", \"generalpve_hostagedefense\", \"generalpve_bulletfired\",\n \"generalpve_matchlost\", \"generalpve_killassists\", \"generalpve_totalxp\",\n \"generalpve_hostagerescue\", \"generalpve_penetrationkills\", \"generalpve_meleekills\",\n \"generalpve_rappelbreach\", \"generalpve_distancetravelled\", \"generalpve_matchplayed\",\n \"generalpve_serveraggression\", \"generalpve_timeplayed\", \"generalpve_revivedenied\",\n \"generalpve_dbno\", \"generalpve_bullethit\", \"generalpve_blindkills\", \"generalpve_headshot\",\n \"generalpve_gadgetdestroy\", \"generalpve_accuracy\")\n\n self.terrorist_hunt = GameQueue(\"terrohunt\")\n\n statname = \"generalpve_\"\n self.terrorist_hunt.deaths = stats.get(statname + \"death\", 0)\n self.terrorist_hunt.penetration_kills = stats.get(statname + \"penetrationkills\", 0)\n self.terrorist_hunt.matches_won = stats.get(statname + \"matchwon\", 0)\n self.terrorist_hunt.bullets_hit = stats.get(statname + \"bullethit\", 0)\n self.terrorist_hunt.melee_kills = stats.get(statname + \"meleekills\", 0)\n self.terrorist_hunt.bullets_fired = stats.get(statname + \"bulletfired\", 0)\n self.terrorist_hunt.matches_played = stats.get(statname + \"matchplayed\", 0)\n self.terrorist_hunt.kill_assists = stats.get(statname + \"killassists\", 0)\n self.terrorist_hunt.time_played = stats.get(statname + \"timeplayed\", 0)\n self.terrorist_hunt.revives = stats.get(statname + \"revive\", 0)\n self.terrorist_hunt.kills = stats.get(statname + \"kills\", 0)\n self.terrorist_hunt.headshots = stats.get(statname + \"headshot\", 0)\n self.terrorist_hunt.matches_lost = stats.get(statname + \"matchlost\", 0)\n self.terrorist_hunt.dbno_assists = stats.get(statname + \"dbnoassists\", 0)\n self.terrorist_hunt.suicides = stats.get(statname + \"suicide\", 0)\n self.terrorist_hunt.barricades_deployed = stats.get(statname + \"barricadedeployed\", 0)\n self.terrorist_hunt.reinforcements_deployed = stats.get(statname + \"reinforcementdeploy\", 0)\n self.terrorist_hunt.total_xp = stats.get(statname + \"totalxp\", 0)\n self.terrorist_hunt.rappel_breaches = stats.get(statname + \"rappelbreach\", 0)\n self.terrorist_hunt.distance_travelled = stats.get(statname + \"distancetravelled\", 0)\n self.terrorist_hunt.revives_denied = stats.get(statname + \"revivedenied\", 0)\n self.terrorist_hunt.dbnos = stats.get(statname + \"dbno\", 0)\n self.terrorist_hunt.gadgets_destroyed = stats.get(statname + \"gadgetdestroy\", 0)\n self.terrorist_hunt.areas_secured = stats.get(statname + \"servershacked\", 0)\n self.terrorist_hunt.areas_defended = stats.get(statname + \"serverdefender\", 0)\n self.terrorist_hunt.areas_contested = stats.get(statname + \"serveraggression\", 0)\n self.terrorist_hunt.hostages_rescued = stats.get(statname + \"hostagerescue\", 0)\n self.terrorist_hunt.hostages_defended = stats.get(statname + \"hostagedefense\", 0)\n self.terrorist_hunt.blind_kills = stats.get(statname + \"blindkills\", 0)\n\n return self.terrorist_hunt\n\n @asyncio.coroutine\n def check_terrohunt(self):\n \"\"\"|coro|\n\n Checks the players general stats for terrorist hunt, only loading them if they haven't been loaded already\"\"\"\n if self.terrorist_hunt is None:\n yield from self.load_terrohunt()\n return self.terrorist_hunt\n\n","sub_path":"r6sapi/r6sapi.py","file_name":"r6sapi.py","file_ext":"py","file_size_in_byte":61399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"17344158","text":"\"\"\"\nVariant Processing\n\"\"\"\nimport re\nimport sys\n\nfrom Bio.SeqUtils import seq3\nfrom bioservices import KEGG\n\nfrom gff2neo.dbconn import create_known_mutation_nodes\n\nkegg = KEGG(verbose=False)\n\n\ndef get_drug_info(drug_name):\n \"\"\"\n Get Drug Info\n :param drug_name:\n :return:\n \"\"\"\n drug_groups = [\"aminoglycosides\", \"fluoroquinolones\"]\n drugbank_dict, drugbank_id, drug_info = dict(), None, dict()\n if 'aminosalicylic_acid' in drug_name:\n drug_name = 'Aminosalicylic acid'\n if drug_name not in drugbank_dict.values() or drug_groups:\n k_drug = kegg.find(\"drug\", str(drug_name))\n drug_id = k_drug.split('\\t')[0]\n drug_info = kegg.parse(kegg.get(drug_id))\n if not isinstance(drug_info, int):\n dblinks = drug_info.get(\"DBLINKS\", None)\n if dblinks:\n drugbank_id = dblinks.get(\"DrugBank\", None)\n if drugbank_id:\n drugbank_dict[drugbank_id] = drug_name\n else:\n for drug_id, name in drugbank_dict.items():\n if drug_name == name:\n drugbank_id = drug_id\n\n return drugbank_id\n\n\ndef _process_coll_mutations(in_file, cset_name):\n \"\"\"\n Load Coll et al. mutation Library\n :param in_file:\n :param cset_name:\n :return:\n \"\"\"\n sys.stdout.write(\"\\nProcessing {cset}...\\n\".format(cset=cset_name))\n drugbank_id, biotype = None, ''\n vset_name = \"10.1186/s13073-015-0164-0\"\n vset_owner = \"Coll, F. et al.\"\n for line in in_file:\n tab_split = line.strip().split('\\t')\n drug_name = tab_split[9].lower()\n drugbank_id = get_drug_info(drug_name)\n\n variant_pos = tab_split[1]\n # gi|444893469|emb|AL123456.3|\t1674484/1674485\tinhA\tRv1484\t283/284\t95\tA/T/C/C\tATT/CCT\tI/P\tISONIAZID\tMUBII-TB-DB\n # check base pair length\n # ref_allele, alt_allele = \"\", \"\"\n bps = tab_split[6]\n bp_mid = len(bps.split(\"/\")) / 2\n bps = bps.replace(\"/\", \"\")\n ref_allele = bps[:bp_mid]\n alt_allele = bps[bp_mid:]\n\n # amino acid change\n gene_cord = tab_split[4]\n codon_number = tab_split[5]\n # 'L/P' to ['Leu', 'Pro']\n amino_change = [seq3(a, custom_map={\"*\": \"Stop\"}, undef_code='-') for a in tab_split[8].strip().split(\"/\")]\n if len(amino_change) > 1 and amino_change[0] == amino_change[1]:\n biotype = 'synonymous'\n elif len(amino_change) > 1 and amino_change[0] is not amino_change[1]:\n biotype = 'non-synonymous'\n elif len(ref_allele) is not len(alt_allele):\n biotype = \"indel\"\n\n # ['Leu', 'Pro'] to ['Leu', 123,'Pro']\n amino_change.insert(1, codon_number)\n # ['Leu', 123, 'Pro'] to 'Leu123Pro'\n consequence = ''.join(amino_change) if biotype is not \"indel\" else ref_allele + gene_cord + alt_allele\n # some string manipulation kung-fu\n sources = tab_split[10].translate(None, \"()\").replace('\"', '')\n\n if \"_promoter\" in tab_split[2]:\n promoter = tab_split[2]\n gene_name = tab_split[2].split(\"_\")[0]\n consequence = ref_allele + gene_cord + alt_allele\n biotype = 'promoter'\n else:\n gene_name = tab_split[2]\n promoter = None\n\n create_known_mutation_nodes(chrom=\"Chr1\", pos=variant_pos, ref_allele=str(ref_allele),\n alt_allele=str(alt_allele), gene=gene_name, promoter=promoter,\n pk=str(drug_name + consequence +\n variant_pos + ref_allele + alt_allele).lower(),\n consequence=consequence, vset_name=vset_name, vset_owner=vset_owner,\n cset_name=cset_name, sources=sources,\n drugbank_id=drugbank_id, drug_name=drug_name, biotype=biotype)\n\n\ndef _process_tbprofiler_mutations(in_file, cset_name):\n \"\"\"\n Load TBProfiler mutation Library\n :param in_file:\n :param cset_name:\n :return:\n \"\"\"\n sys.stdout.write(\"\\nProcessing {cset}...\\n\".format(cset=cset_name))\n drugbank_id, biotype = None, ''\n vset_name = \"TBProfiler\"\n vset_owner = \"https://github.com/jodyphelan\"\n for line in in_file:\n tab_split = line.split('\\t')\n drug_name = tab_split[0].lower()\n drugbank_id = get_drug_info(drug_name)\n\n variant_pos = tab_split[1]\n ref_allele = tab_split[2]\n alt_allele = tab_split[3]\n if \"_promoter\" in tab_split[4]:\n promoter = tab_split[4]\n gene_name = tab_split[4].split(\"_\")[0]\n biotype = \"promoter\"\n else:\n gene_name = tab_split[4]\n promoter = None\n # amino acid change\n consequence = tab_split[5].strip()\n # Pro241Pro to ['Pro', '241', 'Pro']\n amino_change = re.split('(\\d+)', consequence)\n if amino_change[0] == amino_change[2] and consequence.isalnum() and any(c.islower() for c in consequence):\n biotype = \"synonymous\"\n elif amino_change[0] is not amino_change[2] and consequence.isalnum() and any(c.islower() for c in consequence):\n biotype = \"non-synonymous\"\n elif consequence.isupper() and not any(c.islower() for c in consequence) and '-' not in consequence:\n biotype = \"indel\"\n\n create_known_mutation_nodes(chrom=\"Chr1\", pos=variant_pos, ref_allele=str(ref_allele),\n alt_allele=str(alt_allele), gene=gene_name, promoter=promoter,\n pk=str(drug_name + consequence +\n variant_pos + ref_allele + alt_allele).lower(),\n consequence=consequence, vset_name=vset_name, vset_owner=vset_owner,\n cset_name=cset_name,\n drugbank_id=drugbank_id, drug_name=drug_name, biotype=biotype)\n\n\ndef process_mutation_file(in_file):\n \"\"\"\n Process mutation file\n :param in_file:\n :return:\n \"\"\"\n\n if in_file and in_file.endswith(\".txt\"):\n with open(in_file) as in_file:\n next(in_file)\n cset_name = str(in_file.name).split('/')[-1]\n if 'coll' in cset_name:\n # pass\n _process_coll_mutations(in_file=in_file, cset_name=cset_name)\n elif 'drdb' in cset_name:\n # pass\n _process_tbprofiler_mutations(in_file=in_file, cset_name=cset_name)\n elif 'phyresse' in cset_name:\n pass\n # _process_phyresse_mutations(in_file=in_file, cset_name=cset_name)\n elif 'tgstb' in cset_name:\n pass\n # _process_tgstb_mutations(in_file=in_file, cset_name=cset_name)\n","sub_path":"gff2neo/mutations.py","file_name":"mutations.py","file_ext":"py","file_size_in_byte":6842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"76122276","text":"# 1) performance 25% \n\n# def solution(A):\n# max_profit = 0\n# for i in range(len(A)):\n# profit = max(A[i:]) - A[i]\n# if profit > max_profit:\n# max_profit = profit\n# return max_profit\n\n# 2) correctness 60% performance 100% \n# def solution(A):\n# if A:\n# max_p = max(A)\n# min_p = min(A)\n# max_idx = A.index(max_p)\n# min_idx = A.index(min_p)\n# max_profit = 0\n# if max_idx > min_idx:\n# return max_p - min_p\n# elif max_idx < min_idx:\n# if max_idx > 0:\n# max_profit = A[max_idx] - min(A[:max_idx])\n# if min_idx < len(A)-1:\n# profit = max(A[min_idx:]) - A[min_idx]\n# if profit > max_profit:\n# max_profit = profit\n# return max_profit\n# return 0\n\n#3) 80% 25% ....(local min, local maxes 다 담기)\ndef solution(A):\n if A:\n global_max = max(A)\n global_min = min(A)\n max_idx = A.index(global_max)\n min_idx = A.index(global_min)\n diff_list = []\n local_min_max = []\n max_profit = 0\n if max_idx > min_idx:\n return global_max - global_min\n elif max_idx < min_idx:\n for i in range(len(A)-1):\n diff_list.append(A[i+1] - A[i])\n for i in range(len(diff_list)-1):\n if (diff_list[i] < 0 and diff_list[i+1] > 0) or (diff_list[i] > 0 and diff_list[i+1] < 0):\n local_min_max.append(A[i+1])\n for i in range(len(local_min_max)):\n profit = max(A[i:]) - A[i]\n if profit > max_profit:\n max_profit = profit\n return max_profit\n return 0\n\n#test\nprint(solution([]))","sub_path":"codility/9. Maximum slice problem/9-1.(ing)max_profit.py","file_name":"9-1.(ing)max_profit.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"149823514","text":"\n## script to run caiman normcorr motion correction on quest\nimport logging\n#import matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\nlogging.basicConfig(format=\n \"%(relativeCreated)12d [%(filename)s:%(funcName)20s():%(lineno)s] [%(process)d] %(message)s\",\n # filename=\"/tmp/caiman.log\",\n level=logging.DEBUG)\n\nimport caiman as cm\nfrom caiman.source_extraction import cnmf\nfrom caiman.utils.utils import download_demo\nfrom caiman.utils.visualization import inspect_correlation_pnr\nfrom caiman.motion_correction import MotionCorrect\nfrom caiman.source_extraction.cnmf import params as params\nfrom caiman.utils.visualization import plot_contours, nb_view_patches, nb_plot_contour\nimport cv2\nimport os\n\ntry:\n cv2.setNumThreads(0)\nexcept:\n pass\nimport bokeh.plotting as bpl\nbpl.output_notebook()\n\n\nfolder = sys.argv[1]\n#reg_exp = sys.argv[2]\n#file start is automatically 1 \nfile_start = 1\n#run all tiff files in directory mating regexp\nfile_end = len([f for f in os.listdir(folder) if \".tif\" in f])\nnum_procs = int(sys.argv[2])\n\nfnames = [folder+f for f in os.listdir(folder) if \".tif\" in f]\nprint(fnames)\nfnames.sort()\n#for i in range(file_start, file_end):\n# fnames.append(str(folder+reg_exp+str(i)+'.tif')) # input filenames as a list\n\nprint('sorted_order')\nprint(fnames)\n\nif 'dview' in locals():\n cm.stop_server(dview=dview)\nc, dview, n_processes = cm.cluster.setup_cluster(\n backend='local', n_processes=num_procs, single_thread=False)\n\nfrate = 20 # movie frame rate\ndecay_time = 0.4 # length of a typical transient in seconds\n\n# motion correction parameters\nmotion_correct = True # flag for performing motion correction\npw_rigid = False # flag for performing piecewise-rigid motion correction (otherwise just rigid)\ngSig_filt = (3, 3) # size of high pass spatial filtering, used in 1p data\nmax_shifts = (5, 5) # maximum allowed rigid shift\nstrides = (48, 48) # start a new patch for pw-rigid motion correction every x pixels\noverlaps = (24, 24) # overlap between pathes (size of patch strides+overlaps)\nmax_deviation_rigid = 3 # maximum deviation allowed for patch with respect to rigid shifts\nborder_nan = 'copy' # replicate values along the boundaries\n\nmc_dict = {\n 'fnames': fnames,\n 'fr': frate,\n 'decay_time': decay_time,\n 'pw_rigid': pw_rigid,\n 'max_shifts': max_shifts,\n 'gSig_filt': gSig_filt,\n 'strides': strides,\n 'overlaps': overlaps,\n 'max_deviation_rigid': max_deviation_rigid,\n 'border_nan': border_nan\n}\n\nopts = params.CNMFParams(params_dict=mc_dict)\n\nif motion_correct:\n # do motion correction rigid\n mc = MotionCorrect(fnames, dview=dview, **opts.get_group('motion'))\n mc.motion_correct(save_movie=True)\n fname_mc = mc.fname_tot_els if pw_rigid else mc.fname_tot_rig\n if pw_rigid:\n bord_px = np.ceil(np.maximum(np.max(np.abs(mc.x_shifts_els)),\n np.max(np.abs(mc.y_shifts_els)))).astype(np.int)\n else:\n bord_px = np.ceil(np.max(np.abs(mc.shifts_rig))).astype(np.int)\n #plt.subplot(1, 2, 1); plt.imshow(mc.total_template_rig) # % plot template\n #plt.subplot(1, 2, 2); plt.plot(mc.shifts_rig) # % plot rigid shifts\n #plt.legend(['x shifts', 'y shifts'])\n #plt.xlabel('frames')\n #plt.ylabel('pixels')\n\n bord_px = 0 if border_nan is 'copy' else bord_px\n fname_new = cm.save_memmap(fname_mc, base_name='memmap_', order='C',\n border_to_0=bord_px)\nelse: # if no motion correction just memory map the file\n fname_new = cm.save_memmap(fnames, base_name='memmap_',\n order='C', border_to_0=0, dview=dview)\n\n\n","sub_path":"caiman_motion_correction_normcorr_e_script_directory.py","file_name":"caiman_motion_correction_normcorr_e_script_directory.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"565154685","text":"from web3.auto import w3\nfrom secp256k1 import PrivateKey, PublicKey\nfrom eth_keys import keys\nfrom eth_utils import keccak\nfrom rlp.utils import decode_hex\nimport string\nimport random\nfrom web3 import Web3, HTTPProvider, TestRPCProvider, IPCProvider\nimport time\nfrom web3.middleware import geth_poa_middleware\n\nimport warnings\n\n\nimport json\n\nLOG = 0\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\ndef print_color(text):\n print(bcolors.BOLD + text + bcolors.ENDC)\n\ndef log(a, *args, **kwargs):\n if not LOG:\n return None\n\n print(a, args, kwargs)\n\n# we are assuming that contract is already deployed, if not deploy it somewhere else (geth) and put rides_address here\n\nRIDES_ADDRESS =\"0x75834b763a4ddccf67f9af8302427a1567613ff4\"\n\nRIDES_ABI_FILE = open('OpenRide_sol_Rides.abi')\nUSERS_ABI_FILE = open('OpenRide_sol_Users.abi')\nUSER_ABI_FILE = open('OpenRide_sol_User.abi')\nRIDE_ABI_FILE = open('OpenRide_sol_Ride.abi')\n\nWAIT_FOR_TRANSACTION_CONF = 1\n\n\ndef create_account(password):\n w3.eth.enable_unaudited_features()\n\n acct = w3.eth.account.create(password)\n\n return acct.address, acct.privateKey.hex()\n\n\n# this should be done first time\nACCOUNT_ADDRESS, ACCOUNT_PRIVATE_KEY = create_account(\"PASSWD\")\n\n# gas example\ngas_limit = 250000\ngas_price = 60\n\n\n\ndef generate_private_key():\n return PrivateKey().private_key.hex()\n\ndef send_transaction(transaction):\n txnCount = web3.eth.getTransactionCount(ACCOUNT_ADDRESS)\n transaction['nonce'] = web3.toHex(txnCount)\n\n #transaction['nonce']\n #transaction['gas'] = gas_limit,\n #transaction['gasPrice'] = int(gas_price * (10 ** 9)),\n signed = web3.eth.account.signTransaction(transaction, ACCOUNT_PRIVATE_KEY)\n\n return web3.eth.sendRawTransaction(signed.rawTransaction)\n\ndef to_32byte_hex(val):\n return Web3.toHex(Web3.toBytes(val).rjust(32, b'\\0'))\n\ndef my_eth_sign_sha3(data):\n \"\"\"\n eth_sign/recover compatible hasher\n Prefixes data with \"\\x19Ethereum Signed Message:\\n<len(data)>\"\n \"\"\"\n prefix = \"0x19457468657265756d205369676e6564204d6573736167653a0a000000000000\"[2:]\n\n length = len(data)\n length = hex(length)[2:].zfill(64) # we need to fill it with zeros on the left up to maximum length == 64\n\n #length = \"0x0000000000000000000000000000000000000000000000000000000000000004\"\n #data = \"0x3230313800000000000000000000000000000000000000000000000000000000\"\n\n # text needs zeros on the right in soldity, don't ask me why, so we invert twice ...\n data = ''.join(r'{0:x}'.format(ord(c)) for c in data)[::-1].zfill(64)[::-1]\n\n\n #my_hash = decode_hex(prefix[2:].zfill(64)) + decode_hex(length[2:].zfill(64))\n concat = decode_hex(prefix) + decode_hex(length) + decode_hex(data)\n\n hash = \"0x\" + keccak(concat).hex()\n\n log(\"Data as stored in blockchain\", \"0x\" + data)\n return hash\n\ndef get_public_key(priv_key):\n privkey = PrivateKey(bytes(bytearray.fromhex(priv_key)), raw=True)\n private_key = keys.PrivateKey(privkey.private_key)\n\n return private_key.public_key\n\ndef sign_message_preparing_for_ec_recover(msg, priv_key):\n privkey = PrivateKey(bytes(bytearray.fromhex(priv_key)), raw=True)\n private_key = keys.PrivateKey(privkey.private_key)\n\n address = private_key.public_key.to_checksum_address()\n\n #log(\"address\", address)\n\n message_hash = my_eth_sign_sha3(msg)\n\n\n #log(Web3.toHex(message_hash))\n\n signed_message = web3.eth.account.signHash(message_hash, private_key=private_key)\n\n #log(signed_message)\n\n ec_recover_args = (msghash, v, r, s) = (\n Web3.toHex(signed_message.messageHash), signed_message.v, to_32byte_hex(signed_message.r),\n to_32byte_hex(signed_message.s))\n\n return ec_recover_args\n\ndef prepare_random_bytes32():\n msg = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32))\n\n return msg\n\ndef sign_stuff():\n msg = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32))\n log(\"Random generated is\", msg)\n #msg = keccak(msg.1())\n #msg = msg\n #log(msg)\n\n priv_key = \"31a84594060e103f5a63eb742bd46cf5f5900d8406e2726dedfc61c7cf43ebad\"\n public_key = get_public_key(priv_key)\n\n log(sign_message_preparing_for_ec_recover(msg, priv_key))\n log(\"public key\", public_key)\n\ndef convert_string_to_bytes32(msg):\n return ''.join(r'{0:x}'.format(ord(c)) for c in msg)\n\ndef ethereum_load_Users_Rides():\n RIDES_ABI_FILE.seek(0)\n USERS_ABI_FILE.seek(0)\n\n rides_abi = json.load(RIDES_ABI_FILE)\n users_abi = json.load(USERS_ABI_FILE)\n\n # let's fetch Rides 0x972a1b41266a7d55e8bf0fa19464af497bde0cd2\n rides_address = web3.toChecksumAddress(RIDES_ADDRESS)\n Rides = web3.eth.contract(address=rides_address, abi=rides_abi)\n\n log(\"Adress of Rides\", rides_address)\n\n # let's fetch Users now, call() is for free, transaction() is paid\n # https://ethereum.stackexchange.com/questions/765/what-is-the-difference-between-a-transaction-and-a-call\n\n users_address = Rides.functions.get_users_address().call()\n users_address = web3.toChecksumAddress(users_address)\n\n log(\"Address of Users\", users_address)\n\n Users = web3.eth.contract(address=users_address, abi=users_abi)\n\n return Users, Rides\n\ndef get_returned_address(contract, unique_id, ttl=255):\n # we don't want to use events, since events are not supported on most of the public nodes\n if ttl == 0: # ttl\n return None\n\n result = contract.functions.get_return_address(unique_id).call()\n\n if result and result != '0x0000000000000000000000000000000000000000':\n return result;\n\n log (\"there is no returned address yet in the events, let's try again\")\n # if we found nothing, let's wait a little and try again\n time.sleep(2)\n return get_returned_address(contract, unique_id, ttl-1)\n\ndef get_user_detail(address_of_user):\n USER_ABI_FILE.seek(0)\n\n user_abi = json.load(USER_ABI_FILE)\n\n # let's fetch Rides\n user = web3.eth.contract(address=address_of_user, abi=user_abi)\n\n return(user.functions.get_public_key().call())\n\n\ndef get_username(address_of_user):\n USER_ABI_FILE.seek(0)\n\n user_abi = json.load(USER_ABI_FILE)\n\n # let's fetch Rides\n user = web3.eth.contract(address=address_of_user, abi=user_abi)\n\n return(user.functions.get_username().call()).split(b'\\0', 1)[0]\n\ndef wait_for_transaction(tx):\n if not WAIT_FOR_TRANSACTION_CONF:\n return None\n\n log(\"Waiting for transaction {} to be mined\".format(tx.hex()))\n while(True):\n receipt = web3.eth.getTransactionReceipt(tx)\n\n if receipt:\n log(\"Transaction {} has been mined in block: {}\".format(tx.hex(), receipt.blockNumber))\n\n return receipt\n\n time.sleep(0.1)\n\ndef add_user(Users, username, priv_key, driver=False):\n # let's add first rider\n public_key = str(get_public_key(priv_key))\n log(\"public_key of the user {}: {}\".format(username, get_public_key(priv_key)))\n username = \"0x\" + convert_string_to_bytes32(username)\n\n #log(username, public_key)\n\n # this needs to be transaction\n if driver:\n transaction = Users.functions.add_driver(username, public_key).buildTransaction()\n else:\n transaction = Users.functions.add_rider(username, public_key).buildTransaction()\n\n user_tx = send_transaction(transaction)\n\n role = { 0: \"rider\", 1 : \"driver\"}\n\n log(\"User with role ({}) added in transaction {}\".format(role[driver], user_tx.hex()))\n\n #wait_for_transaction(user_tx)\n # i don't like this way\n user_address = get_returned_address(Users, username)\n\n #log(web3.eth.getTransactionReceipt(user1_tx))\n return user_address\n #receipt = web3.eth.waitForTransactionReceipt(user1)\n\ndef get_rider(username, Users):\n username = \"0x\" + convert_string_to_bytes32(username)\n return Users.functions.get_rider(username).call()\n\ndef get_driver(username, Users):\n username = \"0x\" + convert_string_to_bytes32(username)\n return Users.functions.get_driver(username).call()\n\ndef convert_to_address(address):\n if not address.startswith(\"0x\"):\n return \"0x\" + address\n\ndef convert_to_bytes32(data):\n return convert_to_address(data)\n\ndef add_ride(Rides, rider_address, priv_key, location, onion_address):\n log(\"add_ride()\")\n ride_address = \"\"\n\n #rider_address = rider_address.encode().hex() # address\n rider_adderss = convert_to_address(rider_address)\n location = convert_to_bytes32(location.encode().hex()) # bytes32\n onion_address = convert_to_bytes32(onion_address.encode().hex()) # string\n\n\n msgh = \"\" # bytes32\n v = \"\" # uint\n r = \"\" # bytes32\n s = \"\" # bytes32\n random_used = \"\" # bytes32\n\n # preparing authentication data\n random_used = prepare_random_bytes32()\n (msgh, v, r, s) = sign_message_preparing_for_ec_recover(random_used, priv_key)\n random_used = \"0x\" + random_used.encode().hex()\n\n # convert stuff\n '''random_used = random_used.encode().hex()\n msgh = msgh.encode().hex()\n r = r.encode().hex()\n s = s.encode().hex()\n location = location.encode().hex()\n '''\n #(rider_address, location, onion_address, msgh, r, s, random_used) = (\"\", \"\", \"\", \"\", \"\", \"\", '\"')\n # = 0\n\n try:\n transaction = Rides.functions.add_ride(rider_address, location, onion_address, msgh, v, r, s, random_used).buildTransaction()\n tx_hash = send_transaction(transaction)\n except ValueError:\n log(\"CRASH!!! It looks like something went wrong while checking signature\")\n return None\n\n wait_for_transaction(tx_hash)\n # argument 3\n #v=11\n #random_used = '0x585538534b345451484e4843594b353434573354435555554f4456453654444b'\n ride_address = get_returned_address(Rides, random_used) # TODO I don't like this that much, I think if we do it by events, when we post even we should be able to corealte input with event without a doubt (state)\n\n log(\"Ride address\", ride_address)\n\n return ride_address\n\ndef get_rides_near_me(Rides, current_location):\n current_location = convert_to_bytes32(current_location.encode().hex())\n rides_close = Rides.functions.get_ride_near_me(current_location).call()\n\n #log(\"rides_close\", rides_close)\n\n return rides_close\n\ndef get_ride_location(ride_address):\n RIDE_ABI_FILE.seek(0)\n ride_abi = json.load(RIDE_ABI_FILE)\n ride_address = web3.toChecksumAddress(ride_address)\n\n Ride = web3.eth.contract(address=ride_address, abi=ride_abi)\n\n return Ride.functions.get_ordering_location().call().split(b'\\0', 1)[0].decode('utf-8')\n\ndef review_driver(ride_address, review, rider_priv_key):\n RIDE_ABI_FILE.seek(0)\n ride_abi = json.load(RIDE_ABI_FILE)\n ride_address = web3.toChecksumAddress(ride_address)\n\n Ride = web3.eth.contract(address=ride_address, abi=ride_abi)\n\n # preparing authentication data\n random_used = prepare_random_bytes32()\n (msgh, v, r, s) = sign_message_preparing_for_ec_recover(random_used, rider_priv_key)\n random_used = \"0x\" + random_used.encode().hex()\n\n transaction = Ride.functions.review_driver(review, msgh, v, r, s, random_used).buildTransaction()\n tx_hash = send_transaction(transaction)\n\n wait_for_transaction(tx_hash)\n\ndef review_rider(ride_address, review, driver_priv_key):\n RIDE_ABI_FILE.seek(0)\n ride_abi = json.load(RIDE_ABI_FILE)\n ride_address = web3.toChecksumAddress(ride_address)\n\n Ride = web3.eth.contract(address=ride_address, abi=ride_abi)\n\n # preparing authentication data\n random_used = prepare_random_bytes32()\n (msgh, v, r, s) = sign_message_preparing_for_ec_recover(random_used, driver_priv_key)\n random_used = \"0x\" + random_used.encode().hex()\n\n transaction = Ride.functions.review_rider(review, msgh, v, r, s, random_used).buildTransaction()\n tx_hash = send_transaction(transaction)\n\n wait_for_transaction(tx_hash)\n\ndef is_ride_finished(ride_address):\n RIDE_ABI_FILE.seek(0)\n ride_abi = json.load(RIDE_ABI_FILE)\n ride_address = web3.toChecksumAddress(ride_address)\n\n Ride = web3.eth.contract(address=ride_address, abi=ride_abi)\n\n return Ride.functions.is_finished().call()\n\ndef finish_ride(ride_address, rider_priv_key):\n RIDE_ABI_FILE.seek(0)\n ride_abi = json.load(RIDE_ABI_FILE)\n ride_address = web3.toChecksumAddress(ride_address)\n\n Ride = web3.eth.contract(address=ride_address, abi=ride_abi)\n\n # preparing authentication data\n random_used = prepare_random_bytes32()\n (msgh, v, r, s) = sign_message_preparing_for_ec_recover(random_used, rider_priv_key)\n random_used = \"0x\" + random_used.encode().hex()\n\n transaction = Ride.functions.finish_ride(msgh, v, r, s, random_used).buildTransaction()\n tx_hash = send_transaction(transaction)\n\n wait_for_transaction(tx_hash)\n\ndef get_rider(ride_address):\n RIDE_ABI_FILE.seek(0)\n ride_abi = json.load(RIDE_ABI_FILE)\n ride_address = web3.toChecksumAddress(ride_address)\n\n Ride = web3.eth.contract(address=ride_address, abi=ride_abi)\n\n return Ride.functions.get_rider().call()\n\ndef get_ride_driver(ride_address):\n RIDE_ABI_FILE.seek(0)\n ride_abi = json.load(RIDE_ABI_FILE)\n ride_address = web3.toChecksumAddress(ride_address)\n\n Ride = web3.eth.contract(address=ride_address, abi=ride_abi)\n\n return Ride.functions.get_driver().call()\n\n\ndef get_user_review(user_address):\n USER_ABI_FILE.seek(0)\n\n user_abi = json.load(USER_ABI_FILE)\n\n # let's fetch Rides\n user = web3.eth.contract(address=user_address, abi=user_abi)\n\n return(user.functions.get_review().call())\n\ndef is_driver_set(ride_address):\n RIDE_ABI_FILE.seek(0)\n ride_abi = json.load(RIDE_ABI_FILE)\n ride_address = web3.toChecksumAddress(ride_address)\n\n Ride = web3.eth.contract(address=ride_address, abi=ride_abi)\n\n return Ride.functions.is_driver_set().call()\n\ndef accept_ride(Rides, ride_address, driver_address, priv_key):\n random_used = prepare_random_bytes32()\n (msgh, v, r, s) = sign_message_preparing_for_ec_recover(random_used, priv_key)\n random_used = \"0x\" + random_used.encode().hex()\n\n #tx_hash = Rides.functions.accept_ride(ride_address, driver_address, msgh, v, r, s, random_used).transact()\n transaction = Rides.functions.accept_ride(ride_address, driver_address, msgh, v, r, s, random_used).buildTransaction()\n\n tx_hash = send_transaction(transaction)\n\n wait_for_transaction(tx_hash)\n log('rides accepted (was it? probably we should have event here)', tx_hash.hex())\n\ndef web3_init():\n\n # probably we should go into https://infura.io/\n web3 = Web3(HTTPProvider('https://rinkeby.infura.io'))\n\n #web3 = Web3(IPCProvider(\"/Users/pkupisie/Library/Ethereum/rinkeby/geth.ipc\"))\n\n #web3.eth.defaultAccount = w3.eth.accounts[0]\n\n web3.eth.enable_unaudited_features()\n\n # needed for rinkeby: https://ethereum.stackexchange.com/questions/44130/rinkeby-failure-with-web3-py-could-not-format-value-0x-as-field-extrada/44131#44131\n web3.middleware_stack.inject(geth_poa_middleware, layer=0)\n\n return web3\n\ndef test():\n web3 = web3_init()\n\n # let's get users and rides\n Users, Rides = ethereum_load_Users_Rides()\n\n # let's try to add test user\n priv_key = \"31a84594060e103f5a63eb742bd46cf5f5900d8406e2726dedfc61c7cf43ebad\"\n rider_username = \"michal3\"\n driver_username = \"radek3\"\n\n # ------- create user\n rider_address = add_user(Users, rider_username, priv_key, driver=False)\n driver_address = add_user(Users, driver_username, priv_key, driver=True)\n\n # ------- read existing user from DB\n #rider_address = get_rider(rider_username, Users)\n #driver_address = get_driver(driver_username, Users)\n\n # ------- CLIENT SIDE\n\n # ------- add ride\n #log(\"rider_address\", rider_address)\n #ride_address = add_ride(Rides, rider_address, priv_key, \"location\", \"onion_address.onion\" )\n # ride address 0x5e3622e5E1783C9dE1A546A93710e5187bE9D76d\n\n\n # ------- DRIVER SIDE\n\n # ------- get rides without a driver close to me\n current_location = \"0x6666\"\n rides_close = get_rides_near_me(Rides, current_location)\n\n # ------- let's pick first one\n # ride address 0xc2edFF8D1AfEF9f577130F7eEa07ee6C904b791C\n\n if len(rides_close) == 0:\n log(\" no rides anymore\")\n exit(1)\n\n ride_address = rides_close[0]\n\n # ------- display location\n #ride_address = \"0xc2edFF8D1AfEF9f577130F7eEa07ee6C904b791C\"\n #location = get_ride_location(ride_address)\n\n log(\"is driver set: \", is_driver_set(ride_address))\n log(\"accepting the ride by driver\", driver_address)\n # accept the ride\n accept_ride(Rides, ride_address, driver_address, priv_key)\n\n log(\"is driver set: \", is_driver_set(ride_address))\n\n # we probably should check, that this is really us who accepted it, since they might be hazard\n\n # check if it's accepted\n\n # do the tor magic\n # payment and review\n\nweb3 = web3_init()\n","sub_path":"openride.py","file_name":"openride.py","file_ext":"py","file_size_in_byte":16952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"300896564","text":"from ltp import LTP\nfrom .doccompiler.compiler import LTP_PatternExtractor, DocumentCompiler\nfrom .lexer import Lexer, Keyword\nfrom .question import DataQuestion, DivideQuestion, TemporalSumQuestion, BadQuestion\nfrom .node import Datatype, Qualifier, Date\nfrom inspect import isclass\n\n\nclass QuestionParser:\n def __init__(self, dicts_dir):\n self.lexer = Lexer(dicts_dir)\n\n def parse(self, text):\n def match_pattern(tokens, cls_or_kws):\n if len(tokens) != len(cls_or_kws):\n return False\n for token, cls_or_kw in zip(tokens, cls_or_kws):\n if isclass(cls_or_kw) and not isinstance(token, cls_or_kw):\n return False\n elif not isclass(cls_or_kw) and token != cls_or_kw:\n return False\n return True\n\n def make_answer_ndatum_edatum(raw_answer):\n if 'ndatum' in raw_answer:\n value = raw_answer['ndatum']['value']\n value_str = f'{value:.2f}' if isinstance(value, float) else str(value)\n return f\"{value_str}{raw_answer['ndatum']['unit']}\"\n else:\n return ','.join([edatum['label'] for edatum in raw_answer['edata']])\n\n def make_answer_times(raw_answer):\n return f\"{raw_answer['quotient']:.2f}倍\"\n\n tokens = self.lexer.lex(text)\n if match_pattern(tokens, [Date, Datatype]):\n return DataQuestion(tokens[1], [], tokens[0]), \\\n make_answer_ndatum_edatum,\n elif match_pattern(tokens, [Date, Qualifier, Datatype]):\n return DataQuestion(tokens[2], [tokens[1]], tokens[0]), \\\n make_answer_ndatum_edatum,\n elif match_pattern(tokens, [Date, Qualifier, Qualifier, Datatype]):\n return DataQuestion(tokens[3], [tokens[1], tokens[2]], tokens[0]), \\\n make_answer_ndatum_edatum,\n elif match_pattern(tokens, [Date, Qualifier, Qualifier, Qualifier, Datatype]):\n return DataQuestion(tokens[4], [tokens[1], tokens[2], tokens[3]], tokens[0]), \\\n make_answer_ndatum_edatum,\n elif match_pattern(tokens, [Date, Datatype, Date, Keyword.TIMES]):\n return DivideQuestion(DataQuestion(tokens[1], [], tokens[0]),\n DataQuestion(tokens[1], [], tokens[2])), \\\n make_answer_times,\n elif match_pattern(tokens, [Date, Qualifier, Datatype, Date, Keyword.TIMES]):\n return DivideQuestion(DataQuestion(tokens[2], [tokens[1]], tokens[0]),\n DataQuestion(tokens[2], [tokens[1]], tokens[3])), \\\n make_answer_times,\n elif match_pattern(tokens, [Date, Qualifier, Qualifier, Datatype, Date, Keyword.TIMES]):\n return DivideQuestion(DataQuestion(tokens[3], [tokens[1], tokens[2]], tokens[0]),\n DataQuestion(tokens[3], [tokens[1], tokens[2]], tokens[4])), \\\n make_answer_times,\n elif match_pattern(tokens, [Date, Qualifier, Qualifier, Qualifier, Datatype, Date, Keyword.TIMES]):\n return DivideQuestion(DataQuestion(tokens[4], [tokens[1], tokens[2], tokens[3]], tokens[0]),\n DataQuestion(tokens[4], [tokens[1], tokens[2], tokens[3]], tokens[5])), \\\n make_answer_times,\n elif Keyword.TOTAL in tokens:\n tokens.remove(Keyword.TOTAL)\n if match_pattern(tokens, [Date, Keyword.TO, Date, Datatype]):\n return TemporalSumQuestion(tokens[3], [], tokens[0], tokens[2]), \\\n make_answer_ndatum_edatum,\n elif match_pattern(tokens, [Date, Keyword.TO, Date, Qualifier, Datatype]):\n return TemporalSumQuestion(tokens[4], [tokens[3]], tokens[0], tokens[2]), \\\n make_answer_ndatum_edatum,\n elif match_pattern(tokens, [Date, Keyword.TO, Date, Qualifier, Qualifier, Datatype]):\n return TemporalSumQuestion(tokens[5], [tokens[3], tokens[4]], tokens[0], tokens[2]), \\\n make_answer_ndatum_edatum,\n elif match_pattern(tokens, [Date, Keyword.TO, Date, Qualifier, Qualifier, Qualifier, Datatype]):\n return TemporalSumQuestion(tokens[6], [tokens[3], tokens[4], tokens[5]], tokens[0], tokens[2]), \\\n make_answer_ndatum_edatum,\n else:\n return BadQuestion(), \\\n lambda raw_answer: '无法解析问题。'\n else:\n return BadQuestion(), \\\n lambda raw_answer: '无法解析问题。'\n\n\nclass DocumentParser:\n def __init__(self, dicts_dir):\n ltp_extractor = LTP_PatternExtractor(LTP())\n self.document_compiler = DocumentCompiler([ltp_extractor], dicts_dir)\n\n def parse(self, text):\n return self.document_compiler.compile(text)\n","sub_path":"core/algorithm/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":4923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"505456208","text":"'''\nCreated on Aug 5, 2019\n\n@author: nboutin\n'''\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.label import Label\nfrom kivy.uix.togglebutton import ToggleButton\n\n\nclass TimeControllerWidget(BoxLayout):\n\n def __init__(self, game_system, **k):\n super().__init__(**k)\n\n self.game_system = game_system\n\n self.size = (180, 30)\n self.size_hint = (None, None)\n\n self._btn_play_pause = ToggleButton(text=\"Pause\")\n btn_step = Button(text=\"Step\")\n btn_speed_down = Button(text='-', size_hint=(.5, 1))\n btn_speed_up = Button(text='+', size_hint=(.5, 1))\n self._lb_speed = Label(\n size_hint=(.5, 1), text='{}'.format(self.game_system.speed))\n\n self._btn_play_pause.bind(state=self._on_play_pause_state)\n btn_step.bind(on_press=lambda x: self.game_system.step())\n btn_speed_down.bind(on_press=self._on_speed_down)\n btn_speed_up.bind(on_press=self._on_speed_up)\n\n for b in [btn_speed_down, self._btn_play_pause, btn_step, btn_speed_up, self._lb_speed]:\n self.add_widget(b)\n\n def _on_speed_down(self, _):\n self.game_system.speed_down()\n self._lb_speed.text = '{}'.format(self.game_system.speed)\n\n def _on_speed_up(self, _):\n self.game_system.speed_up()\n self._lb_speed.text = '{}'.format(self.game_system.speed)\n\n def _on_play_pause_state(self, widget, value):\n\n if value == 'down':\n self._btn_play_pause.text = 'Play'\n self.game_system.pause()\n elif value == 'normal':\n self._btn_play_pause.text = 'Pause'\n self.game_system.play()\n","sub_path":"evoflatworld/time_controller_widget.py","file_name":"time_controller_widget.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"312152295","text":"import smtplib\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nfrom oauth2 import get_oauth_string, get_oauth2_info\n\ndef sendmail(sender, receiver, msg, oauth2_info = get_oauth2_info()):\n\n message = MIMEText(msg['content'], 'html', 'utf-8')\n message['From'] = Header(sender, 'utf-8')\n message['To'] = Header(receiver['name'], 'utf-8')\n message['Subject'] = Header(msg['title'], 'utf-8')\n \n try:\n server = smtplib.SMTP('smtp.gmail.com', 587)\n auth_string = get_oauth_string(oauth2_info)\n server.ehlo(oauth2_info[\"google_client_id\"])\n server.starttls()\n server.docmd(\"AUTH\", \"XOAUTH2 \" + auth_string)\n\n server.sendmail(oauth2_info[\"email_address\"], [receiver['email']], message.as_string())\n print('Have sended to {}'.format(receiver['email']))\n except smtplib.SMTPException as e:\n print(e)\n","sub_path":"sendmail.py","file_name":"sendmail.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"137563965","text":"from spiderLib import Main\n\nurl = 'https://www.banban.cn/gupiao/list_sh.html'\nget_rule = '<li>.*?<a href=\"/gupiao/\\d.*?\">([\\u4e00-\\u9fa5]+).*?</a>'\nobj = Main.Main(url, get_rule)\nres = obj.main()\nstr_res = \",\".join(res)\n\nf = open('../companyName.txt', 'w')\nf.write(str_res)\nf.close()\n\n","sub_path":"getCompanySpider/Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"329914724","text":"'''\n输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是\n某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)\n'''\n\n\ndef solution(pusharray,poparray):\n pushindex = 0\n while poparray:\n print(pusharray)\n if (pushindex<len(pusharray)) and (pusharray[pushindex] != poparray[0]):\n pushindex +=1\n elif (pushindex<len(pusharray)) and (pusharray[pushindex] == poparray[0]):\n pusharray.pop(pushindex)\n poparray.pop(0)\n pushindex -= 1\n else:\n return False\n return True\n\n# -*- coding:utf-8 -*-\nclass Solution:\n\n def IsPopOrder(self, pushV, popV):\n # stack中存入pushV中取出的数据\n stack = []\n while popV:\n # 如果第一个元素相等,直接都弹出,根本不用压入stack\n if pushV and popV[0] == pushV[0]:\n popV.pop(0)\n pushV.pop(0)\n # 如果stack的最后一个元素与popV中第一个元素相等,将两个元素都弹出\n elif stack and stack[-1] == popV[0]:\n stack.pop()\n popV.pop(0)\n # 如果pushV中有数据,压入stack\n elif pushV:\n stack.append(pushV.pop(0))\n # 上面情况都不满足,直接返回false。\n else:\n return False\n return True\n\n\nif __name__ == '__main__':\n pusharray = [1,2,3,4,5]\n poparray = [4,5,3,2,1]\n print(solution(pusharray,poparray))\n","sub_path":"入栈出栈.py","file_name":"入栈出栈.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"578527612","text":"# -*- coding: utf-8 -*-\nimport os\nimport io\nfrom subprocess import call\nimport unicodedata2 as uc\nimport requests\nimport json\n\nphone_map = {\n\t\t\t\tu\"\\u0901\" \t: u\"AH N\",\t\t\t\t\n\t\t\t\tu\"\\u0902\"\t: u\"N\",\t\t\t\t\t\t\n\t\t\t\tu\"\\u0903\"\t: u\"AH HH AH\",\t\t\t\n\t\t\t\tu\"\\u0904\"\t: u\"EY\",\t\t\t\n\t\t\t\tu\"\\u0905\"\t: u\"AH\",\n\t\t\t\tu\"\\u0906\"\t: u\"AA\",\n\t\t\t\tu\"\\u0907\"\t: u\"IH\",\n\t\t\t\tu\"\\u0908\"\t: u\"IY\",\n\t\t\t\tu\"\\u0909\"\t: u\"UH\",\n\t\t\t\tu\"\\u090A\"\t: u\"UW\",\n\t\t\t\tu\"\\u090B\"\t: u\"R IH\",\n\t\t\t\tu\"\\u090C\"\t: u\"L R IH\",\n\t\t\t\tu\"\\u090D\"\t: u\"AE\",\n\t\t\t\tu\"\\u090E\"\t: u\"EY\",\n\t\t\t\tu\"\\u090F\"\t: u\"EY\",\n\t\t\t\tu\"\\u0910\"\t: u\"AE\",\n\t\t\t\tu\"\\u0911\"\t: u\"AO\",\n\t\t\t\tu\"\\u0912\"\t: u\"OW\",\n\t\t\t\tu\"\\u0913\"\t: u\"OW\",\n\t\t\t\tu\"\\u0914\"\t: u\"AO\",\n\t\t\t\tu\"\\u0915\"\t: u\"K\",\n\t\t\t\tu\"\\u0916\"\t: u\"K HH\",\n\t\t\t\tu\"\\u0917\"\t: u\"G\",\n\t\t\t\tu\"\\u0918\"\t: u\"G HH\",\n\t\t\t\tu\"\\u0919\"\t: u\"N\",\n\t\t\t\tu\"\\u091A\"\t: u\"CH\",\n\t\t\t\tu\"\\u091B\"\t: u\"CH HH\",\n\t\t\t\tu\"\\u091C\"\t: u\"JH\",\n\t\t\t\tu\"\\u091D\"\t: u\"JH HH\",\n\t\t\t\tu\"\\u091E\"\t: u\"N\",\n\t\t\t\tu\"\\u091F\"\t: u\"T\",\n\t\t\t\tu\"\\u0920\"\t: u\"TH\",\n\t\t\t\tu\"\\u0921\"\t: u\"D\",\n\t\t\t\tu\"\\u0922\"\t: u\"DH\",\n\t\t\t\tu\"\\u0923\"\t: u\"N\",\n\t\t\t\tu\"\\u0924\"\t: u\"T\",\n\t\t\t\tu\"\\u0925\"\t: u\"TH\",\n\t\t\t\tu\"\\u0926\"\t: u\"D\",\n\t\t\t\tu\"\\u0927\"\t: u\"DH\",\n\t\t\t\tu\"\\u0928\"\t: u\"N\",\n\t\t\t\tu\"\\u0929\"\t: u\"N\",\n\t\t\t\tu\"\\u092A\"\t: u\"P\",\n\t\t\t\tu\"\\u092B\"\t: u\"F\",\n\t\t\t\tu\"\\u092C\"\t: u\"B\",\n\t\t\t\tu\"\\u092D\"\t: u\"B HH\",\n\t\t\t\tu\"\\u092E\"\t: u\"M\",\n\t\t\t\tu\"\\u092F\"\t: u\"Y\",\n\t\t\t\tu\"\\u0930\"\t: u\"R\",\n\t\t\t\tu\"\\u0931\"\t: u\"R\",\n\t\t\t\tu\"\\u0932\"\t: u\"L\",\n\t\t\t\tu\"\\u0933\"\t: u\"L\",\n\t\t\t\tu\"\\u0934\"\t: u\"L\",\n\t\t\t\tu\"\\u0935\"\t: u\"W\",\n\t\t\t\tu\"\\u0936\"\t: u\"SH\",\n\t\t\t\tu\"\\u0937\"\t: u\"SH\",\n\t\t\t\tu\"\\u0938\"\t: u\"S\",\n\t\t\t\tu\"\\u0939\"\t: u\"HH\",\n\t\t\t\tu\"\\u093A\"\t: u\"\",\n\t\t\t\tu\"\\u093B\"\t: u\"\",\n\t\t\t\tu\"\\u093C\"\t: u\"\",\n\t\t\t\tu\"\\u093D\"\t: u\"AA\",\n\t\t\t\tu\"\\u093E\"\t: u\"AA\",\n\t\t\t\tu\"\\u093F\"\t: u\"IH\",\n\t\t\t\tu\"\\u0940\"\t: u\"IY\",\n\t\t\t\tu\"\\u0941\"\t: u\"UH\",\n\t\t\t\tu\"\\u0942\"\t: u\"UW\",\n\t\t\t\tu\"\\u0943\"\t: u\"R IH\",\n\t\t\t\tu\"\\u0944\"\t: u\"\",\n\t\t\t\tu\"\\u0945\"\t: u\"AE\",\n\t\t\t\tu\"\\u0946\"\t: u\"EY\",\n\t\t\t\tu\"\\u0947\"\t: u\"EY\",\n\t\t\t\tu\"\\u0948\"\t: u\"AE\",\n\t\t\t\tu\"\\u0949\"\t: u\"AO\",\n\t\t\t\tu\"\\u094A\"\t: u\"OW\",\n\t\t\t\tu\"\\u094B\"\t: u\"OW\",\n\t\t\t\tu\"\\u094C\"\t: u\"AO\",\n\t\t\t\tu\"\\u094D\"\t: u\"\",\n\t\t\t\tu\"\\u094E\"\t: u\"\",\n\t\t\t\tu\"\\u0950\"\t: u\"OW M\",\n\t\t\t\tu\"\\u0951\"\t: u\"\",\n\t\t\t\tu\"\\u0952\"\t: u\"\",\n\t\t\t\tu\"\\u0953\"\t: u\"\",\n\t\t\t\tu\"\\u0954\"\t: u\"\",\n\t\t\t\tu\"\\u0955\"\t: u\"\",\n\t\t\t\tu\"\\u0956\"\t: u\"\",\n\t\t\t\tu\"\\u0957\"\t: u\"\",\n\t\t\t\tu\"\\u0958\"\t: u\"K\",\n\t\t\t\tu\"\\u0959\"\t: u\"K HH\",\n\t\t\t\tu\"\\u095A\"\t: u\"G\",\n\t\t\t\tu\"\\u095B\"\t: u\"Z\",\n\t\t\t\tu\"\\u095C\"\t: u\"D\",\n\t\t\t\tu\"\\u095D\"\t: u\"DH\",\n\t\t\t\tu\"\\u095E\"\t: u\"F\",\n\t\t\t\tu\"\\u095F\"\t: u\"Y\",\n\t\t\t\tu\":\"\t\t: u\"AH HH\",\n\t\t\t\tu\"!\"\t\t: u\"\",\n\t\t\t\tu\"'\"\t\t: u\"\",\n\t\t\t\tu\"‘\"\t\t: u\"\",\n\t\t\t\tu\"\\u2019\"\t: u\"\",\n\t\t\t\tu\"\\u200C\"\t: u\"\",\n\t\t\t\tu\"\\u200D\"\t: u\"\",\n\t\t\t\tu'\\u2013'\t: u\"\",\t\t\t\t\n\t\t\t\tu'/'\t\t: u\"\",\n\t\t\t\tu'['\t\t: u\"\",\n\t\t\t\tu']'\t\t: u\"\",\n\t\t\t\tu'*'\t\t: u\"\",\n\t\t\t\tu'\\u0964'\t: u\"\",\t\t\t\t\t\t\t\n\t\t\t\tu\"\\u0A81\" \t: u\"AH N\",\t\t\t\t\n\t\t\t\tu\"\\u0A82\"\t: u\"N\",\t\t\t\t\t\t\n\t\t\t\tu\"\\u0A83\"\t: u\"AH HH AH\",\t\t\t\n\t\t\t\tu\"\\u0A84\"\t: u\"EY\",\t\t\t\n\t\t\t\tu\"\\u0A85\"\t: u\"AH\",\n\t\t\t\tu\"\\u0A86\"\t: u\"AA\",\n\t\t\t\tu\"\\u0A87\"\t: u\"IH\",\n\t\t\t\tu\"\\u0A88\"\t: u\"IY\",\n\t\t\t\tu\"\\u0A89\"\t: u\"UH\",\n\t\t\t\tu\"\\u0A8A\"\t: u\"UW\",\n\t\t\t\tu\"\\u0A8B\"\t: u\"R IH\",\n\t\t\t\tu\"\\u0A8C\"\t: u\"L R IH\",\n\t\t\t\tu\"\\u0A8D\"\t: u\"AE\",\n\t\t\t\tu\"\\u0A8E\"\t: u\"EY\",\n\t\t\t\tu\"\\u0A8F\"\t: u\"EY\",\n\t\t\t\tu\"\\u0A90\"\t: u\"AE\",\n\t\t\t\tu\"\\u0A91\"\t: u\"AO\",\n\t\t\t\tu\"\\u0A92\"\t: u\"OW\",\n\t\t\t\tu\"\\u0A93\"\t: u\"OW\",\n\t\t\t\tu\"\\u0A94\"\t: u\"AO\",\n\t\t\t\tu\"\\u0A95\"\t: u\"K\",\n\t\t\t\tu\"\\u0A96\"\t: u\"K HH\",\n\t\t\t\tu\"\\u0A97\"\t: u\"G\",\n\t\t\t\tu\"\\u0A98\"\t: u\"G HH\",\n\t\t\t\tu\"\\u0A99\"\t: u\"N\",\n\t\t\t\tu\"\\u0A9A\"\t: u\"CH\",\n\t\t\t\tu\"\\u0A9B\"\t: u\"CH HH\",\n\t\t\t\tu\"\\u0A9C\"\t: u\"JH\",\n\t\t\t\tu\"\\u0A9D\"\t: u\"JH HH\",\n\t\t\t\tu\"\\u0A9E\"\t: u\"N\",\n\t\t\t\tu\"\\u0A9F\"\t: u\"T\",\n\t\t\t\tu\"\\u0AA0\"\t: u\"TH\",\n\t\t\t\tu\"\\u0AA1\"\t: u\"D\",\n\t\t\t\tu\"\\u0AA2\"\t: u\"DH\",\n\t\t\t\tu\"\\u0AA3\"\t: u\"N\",\n\t\t\t\tu\"\\u0AA4\"\t: u\"T\",\n\t\t\t\tu\"\\u0AA5\"\t: u\"TH\",\n\t\t\t\tu\"\\u0AA6\"\t: u\"D\",\n\t\t\t\tu\"\\u0AA7\"\t: u\"DH\",\n\t\t\t\tu\"\\u0AA8\"\t: u\"N\",\n\t\t\t\tu\"\\u0AA9\"\t: u\"N\",\n\t\t\t\tu\"\\u0AAA\"\t: u\"P\",\n\t\t\t\tu\"\\u0AAB\"\t: u\"F\",\n\t\t\t\tu\"\\u0AAC\"\t: u\"B\",\n\t\t\t\tu\"\\u0AAD\"\t: u\"B HH\",\n\t\t\t\tu\"\\u0AAE\"\t: u\"M\",\n\t\t\t\tu\"\\u0AAF\"\t: u\"Y\",\n\t\t\t\tu\"\\u0AB0\"\t: u\"R\",\n\t\t\t\tu\"\\u0AB1\"\t: u\"R\",\n\t\t\t\tu\"\\u0AB2\"\t: u\"L\",\n\t\t\t\tu\"\\u0AB3\"\t: u\"L\",\n\t\t\t\tu\"\\u0AB4\"\t: u\"L\",\n\t\t\t\tu\"\\u0AB5\"\t: u\"W\",\n\t\t\t\tu\"\\u0AB6\"\t: u\"SH\",\n\t\t\t\tu\"\\u0AB7\"\t: u\"SH\",\n\t\t\t\tu\"\\u0AB8\"\t: u\"S\",\n\t\t\t\tu\"\\u0AB9\"\t: u\"HH\",\n\t\t\t\tu\"\\u0ABA\"\t: u\"\",\n\t\t\t\tu\"\\u0ABB\"\t: u\"\",\n\t\t\t\tu\"\\u0ABC\"\t: u\"\",\n\t\t\t\tu\"\\u0ABD\"\t: u\"AA\",\n\t\t\t\tu\"\\u0ABE\"\t: u\"AA\",\n\t\t\t\tu\"\\u0ABF\"\t: u\"IH\",\n\t\t\t\tu\"\\u0AC0\"\t: u\"IY\",\n\t\t\t\tu\"\\u0AC1\"\t: u\"UH\",\n\t\t\t\tu\"\\u0AC2\"\t: u\"UW\",\n\t\t\t\tu\"\\u0AC3\"\t: u\"R IH\",\n\t\t\t\tu\"\\u0AC4\"\t: u\"\",\n\t\t\t\tu\"\\u0AC5\"\t: u\"AE\",\n\t\t\t\tu\"\\u0AC6\"\t: u\"EY\",\n\t\t\t\tu\"\\u0AC7\"\t: u\"EY\",\n\t\t\t\tu\"\\u0AC8\"\t: u\"AE\",\n\t\t\t\tu\"\\u0AC9\"\t: u\"AO\",\n\t\t\t\tu\"\\u0ACA\"\t: u\"OW\",\n\t\t\t\tu\"\\u0ACB\"\t: u\"OW\",\n\t\t\t\tu\"\\u0ACC\"\t: u\"AO\",\n\t\t\t\tu\"\\u0ACD\"\t: u\"\",\n\t\t\t\tu\"\\u0ACE\"\t: u\"\",\n\t\t\t\tu\"\\u0ACF\"\t: u\"\",\n\t\t\t\tu\"\\u0AD0\"\t: u\"OW M\",\n\t\t\t\tu\"\\u0AD1\"\t: u\"\",\n\t\t\t\tu\"\\u0AD2\"\t: u\"\",\n\t\t\t\tu\"\\u0AD3\"\t: u\"\",\n\t\t\t\tu\"\\u0AD4\"\t: u\"\",\n\t\t\t\tu\"\\u0AD5\"\t: u\"\",\n\t\t\t\tu\"\\u0AD6\"\t: u\"\",\n\t\t\t\tu\"\\u0AD7\"\t: u\"\",\n\t\t\t\tu\"\\u0AD8\"\t: u\"K\",\n\t\t\t\tu\"\\u0AD9\"\t: u\"K HH\",\n\t\t\t\tu\"\\u0ADA\"\t: u\"G\",\n\t\t\t\tu\"\\u0ADB\"\t: u\"Z\",\n\t\t\t\tu\"\\u0ADC\"\t: u\"D\",\n\t\t\t\tu\"\\u0ADD\"\t: u\"DH\",\n\t\t\t\tu\"\\u0ADE\"\t: u\"F\",\n\t\t\t\tu\"\\u0ADF\"\t: u\"Y\",\n\t\t\t\tu\"\\u0AE0\"\t: u\"R IY\",\n\t\t\t\tu\"\\uFEFF\"\t: u\"\",\n\n\n\n\n\t\t\t}\n\t\t\t\nvw_map = [\n\t\t\t\tu\"\\u0904\", u\"\\u0905\", u\"\\u0906\", u\"\\u0907\", u\"\\u0908\", u\"\\u0909\",\n\t\t\t\tu\"\\u090A\", u\"\\u090B\", u\"\\u090C\", u\"\\u090D\", u\"\\u090E\", u\"\\u090F\",\n\t\t\t\tu\"\\u0910\", u\"\\u0911\", u\"\\u0912\", u\"\\u0913\", u\"\\u0914\"\n\n\t\t\t\tu\"\\u0A84\", u\"\\u0A85\", u\"\\u0A86\", u\"\\u0A87\", u\"\\u0A88\", u\"\\u0A89\",\n\t\t\t\tu\"\\u0A8A\", u\"\\u0A8B\", u\"\\u0A8C\", u\"\\u0A8D\", u\"\\u0A8E\", u\"\\u0A8F\",\n\t\t\t\tu\"\\u0A90\", u\"\\u0A91\", u\"\\u0A92\", u\"\\u0A93\", u\"\\u0A94\"\n\t\t ]\n\t\t \n\t\t\t\t\nmatra_map = {\n\t\t\t\tu\"\\u0901\", u\"\\u0902\", u\"\\u0903\", u\"\\u093D\", u\"\\u093E\", u\"\\u093F\", u\"\\u0940\",\n\t\t\t\tu\"\\u0941\", u\"\\u0942\", u\"\\u0943\", u\"\\u0944\", u\"\\u0945\", u\"\\u0946\", u\"\\u0947\",\n\t\t\t\tu\"\\u0948\", u\"\\u0949\", u\"\\u094A\", u\"\\u094B\", u\"\\u094C\", u\"\\u094D\", u\":\",\n\n\t\t\t\tu\"\\u0A81\", u\"\\u0A82\", u\"\\u0A83\", u\"\\u0ABD\", u\"\\u0ABE\", u\"\\u0ABF\", u\"\\u0AC0\",\n\t\t\t\tu\"\\u0AC1\", u\"\\u0AC2\", u\"\\u0AC3\", u\"\\u0AC4\", u\"\\u0AC5\", u\"\\u0AC6\", u\"\\u0AC7\",\n\t\t\t\tu\"\\u0AC8\", u\"\\u0AC9\", u\"\\u0ACA\", u\"\\u0ACB\", u\"\\u0ACC\", u\"\\u0ACD\", u\":\",\n\t\t\t}\n\n\nsrcdir = \"/home/pankaj/Downloads/audio_corpus/train\"\nfile_list = [\n\t\t\t\t\t\t[\"agra\",\"avdheshkumar/script_c1\",\"avdheshkumar_c1.raw\",\"avdheshkumar_c1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"avdheshkumar/script_c2\",\"avdheshkumar_c2.raw\",\"avdheshkumar_c2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"bhojraj/script_b1\",\"bhojraj_b1.raw\",\"bhojraj_b1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"deepak/script_b1\",\"deepak_b1.raw\",\"deepak_b1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"harimohan/script_d1\",\"harimohan_d1.raw\",\"harimohan_d1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"Jeetu/script_b2\",\"jeetu_b2.raw\",\"jeetu_b2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"Jeetu/script_b3\",\"jeetu_b3.raw\",\"jeetu_b3.txt\"],\n\t\t\t\t\t\t[\"agra\",\"Jeetu/script_d1\",\"jeetu_d1.raw\",\"jeetu_d1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"nandini/script_d2\",\"nandini_d2.raw\",\"nandini_d2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"nitesh/script_c1\",\"nitesh_c1.raw\",\"nitesh_c1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"nitesh/script_c2\",\"nitesh_c2.raw\",\"nitesh_c2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"nitesh/script_c3\",\"nitesh_c3.raw\",\"nitesh_c3.txt\"],\n\t\t\t\t\t\t[\"agra\",\"nitesh/script_c4\",\"nitesh_c4.raw\",\"nitesh_c4.txt\"],\n\t\t\t\t\t\t[\"agra\",\"nitesh/script_c5\",\"nitesh_c5.raw\",\"nitesh_c5.txt\"],\n\t\t\t\t\t\t[\"agra\",\"nitesh/script_e1\",\"nitesh_e1.raw\",\"nitesh_e1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_a1\",\"pankaj_a1.raw\",\"pankaj_a1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_a2\",\"pankaj_a2.raw\",\"pankaj_a2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_a3\",\"pankaj_a3.raw\",\"pankaj_a3.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_a4\",\"pankaj_a4.raw\",\"pankaj_a4.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_a5\",\"pankaj_a5.raw\",\"pankaj_a5.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_b1\",\"pankaj_b1.raw\",\"pankaj_b1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_b2\",\"pankaj_b2.raw\",\"pankaj_b2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_b3\",\"pankaj_b3.raw\",\"pankaj_b3.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_b4\",\"pankaj_b4.raw\",\"pankaj_b4.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_b5\",\"pankaj_b5.raw\",\"pankaj_b5.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_c1\",\"pankaj_c1.raw\",\"pankaj_c1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_c2\",\"pankaj_c2.raw\",\"pankaj_c2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_c3\",\"pankaj_c3.raw\",\"pankaj_c3.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_c4\",\"pankaj_c4.raw\",\"pankaj_c4.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_c5\",\"pankaj_c5.raw\",\"pankaj_c5.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_d1\",\"pankaj_d1.raw\",\"pankaj_d1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_d2\",\"pankaj_d2.raw\",\"pankaj_d2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_d3\",\"pankaj_d3.raw\",\"pankaj_d3.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_d4\",\"pankaj_d4.raw\",\"pankaj_d4.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_d5\",\"pankaj_d5.raw\",\"pankaj_d5.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_e1\",\"pankaj_e1.raw\",\"pankaj_e1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"pankaj/script_e2\",\"pankaj_e2.raw\",\"pankaj_e2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"ramavtar/script_e1\",\"ramavtar_e1.raw\",\"ramavtar_e1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"seema/script_d3\",\"seema_d3.raw\",\"seema_d3.txt\"],\n\t\t\t\t\t\t[\"agra\",\"swasti/script_d4\",\"swasti_d4.raw\",\"swasti_d4.txt\"],\n\t\t\t\t\t\t[\"agra\",\"yogendra/script_c5\",\"yogendra_c5.raw\",\"yogendra_c5.txt\"],\n\t\t\t\t\t\t[\"agra\",\"sanjay/script_a1\",\"sanjay_a1.raw\",\"sanjay_a1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"sanjay/script_a2\",\"sanjay_a2.raw\",\"sanjay_a2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"sanjay/script_a2\",\"sanjay_a2.raw\",\"sanjay_a2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"tarni/script_d1\",\"tarni_d1.raw\",\"tarni_d1.txt\"],\n\t\t\t\t\t\t[\"agra\",\"tarni/script_d2\",\"tarni_d2.raw\",\"tarni_d2.txt\"],\n\t\t\t\t\t\t[\"agra\",\"tarni/script_d3\",\"tarni_d3.raw\",\"tarni_d3.txt\"],\n\t\t\t\t\t\t[\"agra\",\"tarni/script_d4\",\"tarni_d4.raw\",\"tarni_d4.txt\"],\n\t\t\t\t\t\t[\"agra\",\"tarni/script_d5\",\"tarni_d5.raw\",\"tarni_d5.txt\"],\n\t\t\t\t\t\t[\"agra\",\"utsav/script_e5\",\"utsav_e5.raw\",\"utsav_e5.txt\"],\n\t\t\t\t\t\t[\"agra\",\"utsav/script_e4\",\"utsav_e4.raw\",\"utsav_e4.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb7_0\",\"amarjeet_hyb7_0.raw\",\"amarjeet_hyb7_0.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb7_1\",\"amarjeet_hyb7_1.raw\",\"amarjeet_hyb7_1.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb7_2\",\"amarjeet_hyb7_2.raw\",\"amarjeet_hyb7_2.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb7_3\",\"amarjeet_hyb7_3.raw\",\"amarjeet_hyb7_3.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb7_4\",\"amarjeet_hyb7_4.raw\",\"amarjeet_hyb7_4.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb8_0\",\"amarjeet_hyb8_0.raw\",\"amarjeet_hyb8_0.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb8_1\",\"amarjeet_hyb8_1.raw\",\"amarjeet_hyb8_1.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb8_2\",\"amarjeet_hyb8_2.raw\",\"amarjeet_hyb8_2.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb8_3\",\"amarjeet_hyb8_3.raw\",\"amarjeet_hyb8_3.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amarjeet/hyb8_4\",\"amarjeet_hyb8_4.raw\",\"amarjeet_hyb8_4.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"arunjeyan/eng0_0\",\"arunjeyan_eng0_0.raw\",\"arunjeyan_eng0_0.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amogh/eng0_1\",\"amogh_eng0_1.raw\",\"amogh_eng0_1.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"avinash/hyb0_0\",\"avinash_hyb0_0.raw\",\"avinash_hyb0_0.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"bhupen/hyb6_0\",\"bhupen_hyb6_0.raw\",\"bhupen_hyb6_0.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"gitika/hyb5_0\",\"gitika_hyb5_0.raw\",\"gitika_hyb5_0.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"pakhi/hyb1_0\",\"pakhi_hyb1_0.raw\",\"pakhi_hyb1_0.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"ranvijay/hyb2_0\",\"ranvijay_hyb2_0.raw\",\"ranvijay_hyb2_0.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"ranvijay/hyb2_1\",\"ranvijay_hyb2_1.raw\",\"ranvijay_hyb2_1.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"saikiran/eng1_4\",\"saikiran_eng1_4.raw\",\"saikiran_eng1_4.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"tinku/hyb2_0\",\"tinku_hyb2_0.raw\",\"tinku_hyb2_0.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"vivek/hyb9_0\",\"vivek_hyb9_0.raw\",\"vivek_hyb9_0.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"vivek/hyb9_1\",\"vivek_hyb9_1.raw\",\"vivek_hyb9_1.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"vivek/hyb9_2\",\"vivek_hyb9_2.raw\",\"vivek_hyb9_2.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"vivek/hyb9_3\",\"vivek_hyb9_3.raw\",\"vivek_hyb9_3.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"vivek/hyb9_4\",\"vivek_hyb9_4.raw\",\"vivek_hyb9_4.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"sneha/set_g\",\"sneha_set_g.raw\",\"sneha_set_g.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"sneha/set_h\",\"sneha_set_h.raw\",\"sneha_set_h.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"sneha/set_i\",\"sneha_set_i.raw\",\"sneha_set_i.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"sneha/set_n\",\"sneha_set_n.raw\",\"sneha_set_n.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"sabith/set_m\",\"sabith_set_m.raw\",\"sabith_set_m.txt\"],\t\t\n\t\t\t\t\t\t[\"reverie\",\"amit_dave/set_a\",\"amit_set_a.raw\",\"amit_set_a.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amit_dave/set_b\",\"amit_set_b.raw\",\"amit_set_b.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amit_dave/set_c\",\"amit_set_c.raw\",\"amit_set_c.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amit_dave/set_d\",\"amit_set_d.raw\",\"amit_set_d.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amit_dave/set_e\",\"amit_set_e.raw\",\"amit_set_e.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amit_dave/set_e\",\"amit_set_e.raw\",\"amit_set_e.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"amit_dave/set_f\",\"amit_set_f.raw\",\"amit_set_f.txt\"],\n\t\t\t\t\t\t[\"others\",\"anurag_sharma/andher\",\"andher.raw\",\"andher.txt\"],\n\t\t\t\t\t\t[\"others\",\"anurag_sharma/gharjamai\",\"gharjamai.raw\",\"gharjamai.txt\"],\n\t\t\t\t\t\t[\"others\",\"anurag_sharma/kheti\",\"kheti.raw\",\"kheti.txt\"],\n\t\t\t\t\t\t[\"others\",\"anurag_sharma/ukhade_khambe\",\"ukhade_khambe.raw\",\"ukhade_khambe.txt\"], \n\t\t\t\t\t\t[\"others\",\"3553/pankaj\",\"3553_pankaj.raw\",\"3553_pankaj.txt\"],\n\t\t\t\t\t\t[\"others\",\"accomodation/pankaj\",\"accomodation_pankaj.raw\",\"accomodation_pankaj.txt\"],\n\t\t\t\t\t\t[\"others\",\"around_town/pankaj\",\"around_town_pankaj.raw\",\"around_town_pankaj.txt\"],\n\t\t\t\t\t\t[\"others\",\"conversations/pankaj\",\"conversations_pankaj.raw\",\"conversations_pankaj.txt\"],\n\t\t\t\t\t\t[\"others\",\"converse_reception/pankaj\",\"converse_reception_pankaj.raw\", \"converse_reception_pankaj.txt\"],\n\t\t\t\t\t\t[\"others\",\"indic_tts/hindi/male_mono\",\"hindi_male_mono.raw\",\"hindi_male_mono.txt\"],\n\t\t\t\t\t\t[\"others\",\"indic_tts/hindi/female_mono\",\"hindi_female_mono.raw\",\"hindi_female_mono.txt\"],\n\t\t\t\t\t\t[\"others\",\"indic_tts/gujarati/male_mono\",\"gujarati_male_mono.raw\",\"gujarati_male_mono.txt\"],\n\t\t\t\t\t\t[\"others\",\"indic_tts/rajasthani/male_mono\",\"rajasthani_male_mono.raw\",\"rajasthani_male_mono.txt\"],\n\t\t\t\t\t\t[\"others\",\"indic_tts/marathi/male_mono\",\"marathi_male_mono.raw\",\"marathi_male_mono.txt\"],\n\t\t\t\t\t\t[\"others\",\"indic_tts/marathi/female_mono\",\"marathi_female_mono.raw\",\"marathi_female_mono.txt\"],\n\t\t\t\t\t\t[\"others\",\"cmu_indic_hi/axb\",\"cmu_indic_hi_axb.raw\",\"cmu_indic_hi_axb.txt\"],\n\t\t\t\t\t\t[\"others\",\"cmu_indic_hi/sxs\",\"cmu_indic_hi_axb.sxs\",\"cmu_indic_hi_sxs.txt\"],\n\t\t\t\t\t\t[\"others\",\"cmu_indic_mr/aup\",\"cmu_indic_mr_aup.raw\",\"cmu_indic_mr_aup.txt\"],\n\t\t\t\t\t\t[\"others\",\"cmu_indic_mr/slp\",\"cmu_indic_mr_slp.sxs\",\"cmu_indic_mr_slp.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/chat0\",\"pankaj_chat0.raw\",\"pankaj_chat0.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/chat1\",\"pankaj_chat1.raw\",\"pankaj_chat1.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/misc0\",\"pankaj_misc0.raw\",\"pankaj_misc0.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/story0_0\",\"taali.raw\",\"taali.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/story1_0\",\"story1_0.raw\",\"story1_0.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/ith0\",\"pankaj_ith0.raw\",\"pankaj_ith0.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/ith1\",\"pankaj_ith1.raw\",\"pankaj_ith1.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/ith2\",\"pankaj_ith2.raw\",\"pankaj_ith2.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/ith3\",\"pankaj_ith3.raw\",\"pankaj_ith3.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/karmabhumi_0\",\"karmabhumi_0.raw\",\"karmabhumi_0.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/karmabhumi_1\",\"karmabhumi_1.raw\",\"karmabhumi_1.txt\"],\n\t\t\t\t\t\t[\"reverie\",\"pankaj/karmabhumi_2\",\"karmabhumi_2.raw\",\"karmabhumi_2.txt\"],\t\t\t\t\t\t \n\t\t\t\t[\"test\",\"pankaj/set_a\",\"pankaj_test_set_a.raw\",\"pankaj_test_set_a.txt\"],\t\t\t\n\t\t\t\t\t\t\n\t\t\t]\n\n\ndef pronounce(inword):\n\tprint(inword)\n\tprint(\"length of in word is %d\"%(len(inword)))\n\twl = list(inword)\n\tnw = []\n\twrdlen = len(wl)\n\tchcnt = 0;\n\tprint(wrdlen)\n\twhile chcnt < wrdlen:\n\t\tprint(\"chcnt %d\"%(chcnt))\n\t\tch = wl[chcnt]\n\t\tprint(ch)\n\t\tchcnt += 1\n\t\tprint(chcnt)\n\t\tif chcnt == wrdlen:\n\t\t\tif wrdlen == 1:\n\t\t\t\tif ch in matra_map:\n\t\t\t\t\tprint(u\"error\")\n\t\t\t\telse:\n\t\t\t\t\tif ch in vw_map:\n\t\t\t\t\t\tnw.append(phone_map[ch])\n\t\t\t\t\telse:\n\t\t\t\t\t\tnw.append(phone_map[ch])\n\t\t\t\t\t\tnw.append(phone_map[u\"अ\"])\n\t\t\telse:\n\t\t\t\tnw.append(phone_map[ch])\n\t\telse:\n\t\t\tif ch in vw_map:\n\t\t\t\tprint(\"ch in vw_map\")\n\t\t\t\tprint(ch)\n\t\t\t\tnw.append(phone_map[ch])\n\t\t\telse: \n\t\t\t\tif ch not in matra_map:\n\t\t\t\t\tprint(ch)\n\t\t\t\t\tprint(\"ch not in matra map\")\n\t\t\t\t\tprint(chcnt)\n\t\t\t\t\tif \tchcnt < wrdlen: \n\t\t\t\t\t\tnch = wl[chcnt]\n\t\t\t\t\t\tprint(nch)\n\t\t\t\t\t\tif nch in matra_map:\n\t\t\t\t\t\t\tprint(\"nch in matra map\")\n\t\t\t\t\t\t\tnw.append(phone_map[ch])\n\t\t\t\t\t\t\tnw.append(phone_map[nch])\n\t\t\t\t\t\t\tchcnt += 1\n\t\t\t\t\t\t\tprint(chcnt)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tnw.append(phone_map[ch])\n\t\t\t\t\t\t\tnw.append(phone_map[u\"अ\"])\n\t\t\t\telse:\n\t\t\t\t\tnw.append(phone_map[ch])\n\t\t\t\t\n\t\t\t\t\t\t\t\n\treturn \" \".join(' '.join(nw).split())\n\nrootdir = srcdir\nwavdirs_and_files = file_list\npron_file = \"app_pro.dict\"\nprdict = {}\n\nfor entry in wavdirs_and_files:\n\tifn = rootdir + \"/\" + entry[0] + \"/\" + entry[1] + \"/\" + entry[3].replace(\".\",\"_dev.\")\n\tinf = io.open(ifn,\"r\",encoding=\"utf-8\")\n\tfor line in iter(inf):\n\t\twlist = line.lower().replace(\".\",\"\").split()\n\t\tfor w in wlist:\n\t\t\tif w not in prdict:\n\t\t\t\tprdict[w] = pronounce(w)\n\tinf.close()\n\t\npf = io.open(pron_file,\"w\",encoding=\"utf-8\")\nfor key in sorted(prdict):\n\tpf.write(key + \"\\t\" + prdict[key] +\"\\n\")\npf.close()\t\n\n","sub_path":"utils/make_pro_dict.py","file_name":"make_pro_dict.py","file_ext":"py","file_size_in_byte":16335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"306670929","text":"'''\nhttps://leetcode.com/problems/two-sum/\nGiven an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\nYou can return the answer in any order.\n'''\n'''\nMethod below uses hashtable.\nTime:O(n)\nSpace:O(n)\n'''\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n d = defaultdict(int)\n for i, ch in enumerate(nums):\n if target-ch not in d:\n d[ch] = i\n else:\n return [i, d[target-ch]]\n \n'''\nMethod below uses brute force.\nTime:O(n**2)\nSpace:O(1)\n'''\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n for i in range(0,len(nums)):\n for j in range(i+1, len(nums)):\n if nums[i]+nums[j]==target:\n return [i, j]\n","sub_path":"1.Two_Sum.py","file_name":"1.Two_Sum.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"268390119","text":"import argparse\nimport datetime\nimport inspect\nimport os\nimport pickle\nimport re\nfrom hashlib import sha256\nfrom pathlib import Path\nfrom typing import Tuple, Dict\n\nimport humanize\nimport pystan\nfrom IPython.core.magic import Magics, cell_magic, magics_class\nfrom IPython.utils.capture import capture_output\nimport shutil\n\n\nclass StanModelCacheClass(object):\n def __init__(self):\n self.cache_path = os.path.join(Path.home(), '.cache', 'stan')\n os.makedirs(self.cache_path, exist_ok=True)\n\n @classmethod\n def compile_and_store(cls, model_code, model_name, cache_fn, **kwargs):\n sm = pystan.StanModel(model_code=model_code, model_name=model_name, **kwargs)\n with open(cache_fn, 'wb') as f:\n pickle.dump(sm, f)\n return sm\n\n def get_or_create(self, model_code, cache_file_name=None, recompile=False, model_name=None, **kwargs):\n \"\"\"Use just as you would `stan`\"\"\"\n\n cache_file_name = cache_file_name or 'model-{digest}.pkl'\n normalized_code = re.sub(r'\\s+', ' ', model_code).strip().encode('ascii')\n hasher = sha256(normalized_code)\n hasher.update(repr(kwargs).encode('ascii'))\n digest = hasher.hexdigest()\n\n cache_fn = cache_file_name.format(digest=digest, model_name=kwargs.get('model_name'))\n cache_fn = os.path.join(self.cache_path, cache_fn)\n\n if recompile:\n sm = self.compile_and_store(model_code, model_name, cache_fn, **kwargs)\n created = True\n else:\n try:\n sm = pickle.load(open(cache_fn, 'rb'))\n except Exception as e:\n if not isinstance(e, FileNotFoundError):\n pystan.logger.warning(\"Problems loading cached model. Recompiling.\")\n sm = self.compile_and_store(model_code, model_name, cache_fn, **kwargs)\n created = True\n else:\n pystan.logger.debug(\"Using cached StanModel '{}'\".format(cache_fn))\n created = False\n\n return sm, created\n\n def clean(self):\n shutil.rmtree(self.cache_path)\n os.makedirs(self.cache_path, exist_ok=True)\n\n\nStanModelCache = StanModelCacheClass()\n\n\ndef parse_args(argstring: str) -> Tuple[str, Dict]:\n # users can separate arguments with commas and/or whitespace\n parser = argparse.ArgumentParser(description=\"Process pystan arguments.\")\n\n parser.add_argument(\"variable_name\", nargs=\"?\", default=\"_stan_model\")\n signature = inspect.signature(pystan.StanModel)\n\n for arg in ('model_name', 'stanc_ret', 'boost_lib', 'eigen_lib', 'extra_compile_args', 'include_paths'):\n if arg in signature.parameters:\n parser.add_argument('--{}'.format(arg.replace('_', '-')))\n\n parser.add_argument(\"--verbose\", action=\"store_true\")\n parser.add_argument(\"--recompile\", \"-v\", action=\"store_true\")\n\n if 'obfuscate_model_name' in signature.parameters:\n parser.add_argument(\"--obfuscate-model-name\", dest='obfuscate_model_name', action=\"store_true\")\n parser.add_argument(\"--no-obfuscate-model-name\", dest='obfuscate_model_name', action=\"store_false\")\n\n kwargs = vars(parser.parse_args(argstring.split()))\n\n variable_name = kwargs.pop(\"variable_name\")\n\n if not variable_name.isidentifier():\n raise ValueError(f\"The variable name {variable_name} is not a valid python variable name.\")\n\n # set defaults:\n if kwargs.get('model_name') is None:\n kwargs[\"model_name\"] = variable_name\n\n return variable_name, kwargs\n\n\n@magics_class\nclass StanMagics(Magics):\n def __init__(self, shell):\n super(StanMagics, self).__init__(shell)\n\n @cell_magic\n def stan(self, line, cell):\n \"\"\"\n Allow jupyter notebook cells create a pystan.StanModel object from\n Stan code in a cell that begins with %%stan. The pystan.StanModel\n gets assigned to a variable in the notebook's namespace, either\n named _stan_model (the default), or a custom name (specified\n by writing %%stan <variable_name>).\n \"\"\"\n\n variable_name, stan_opts = parse_args(line)\n\n pystan.logger.debug(\"StanModel options: {!r}\".format(stan_opts))\n\n start = datetime.datetime.now()\n try:\n with capture_output(display=False) as capture:\n stan_model, created = StanModelCache.get_or_create(model_code=cell, **stan_opts)\n except Exception:\n pystan.logger.error(\"Error creating Stan model: {}\".format(capture))\n raise\n end = datetime.datetime.now()\n delta = humanize.naturaldelta(end - start)\n\n self.shell.user_ns[variable_name] = stan_model\n if created:\n pystan.logger.info(f\"StanModel available as '{variable_name}' ({delta} compilation time).\")\n else:\n stan_model.model_name = stan_opts.get('model_name')\n pystan.logger.info(f\"StanModel available as '{variable_name}' (got from cache).\")\n\n\ndef load_ipython_extension(ipython):\n ipython.register_magics(StanMagics)\n\n\ndef unload_ipython_extension(ipython):\n # ipython.user_global_ns.pop('_stan_vars', None)\n pass\n","sub_path":"jupyterstan/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"165775564","text":"#!/usr/bin/env python3\n\nimport sys\nimport libzhengxc.usage as uTools\nimport logging\nimport pysam \nimport os \nimport pdb\ndef ConvetVcf2Bed(v,expand=0):\n \n '''\n read a vcf file and convert it to bed file\n paramter expand should be one of \"RefAltMax(-1)\" \"Expand(0...)\"\n default is \"Expand x base\"\n \"expand = -1\" will expand the max length of Alt and Ref base both left and right side. \n '''\n out = []\n with open(v,'r') as fv:\n for record in fv.readlines():\n if not record.strip().startswith('#'):\n l = record.strip().split(\"\\t\")\n chr = l[0].strip() \n pos = int(l[1].strip())\n ref_len = len(l[3].strip())\n alt_len = len(l[4].strip())\n\n if expand == -1 :\n e = max(ref_len,alt_len)\n else:\n e = expand \n start = max(0,(pos - e)) # restrict valut > 0 \n end = pos + e\n\n assert start > 0 ,\"the start is {0}, must > 0 \".format(start)\n assert end > 0 , \" the end is {0},must > 0\".format(end)\n logging.info(\"the start is {0},the end is {0}\".format(start,end))\n \n out.append([chr,str(start),str(end)])\n return(out)\n\ndef NomalizeVariants(refpath,vcffile):\n \n '''\n input is a ref genome path and a vcf file\n '''\n if not os.path.exists(refpath):\n raise Exception(\"reference file does not exists: {0}\".format(refpath))\n if not os.path.exists(vcffile):\n raise Exception(\"vcf file does not exists: {0}\".format(vcffile))\n\n try:\n ref= pysam.FastaFile(filename =refpath)\n except:\n raise Exception(\"pysam can not open ref genome\")\n \n vcf = []\n with open(vcffile,'r') as vfh:\n for record in vfh:\n if record.startswith('#'):\n continue\n chro,pos,qual,ref,alt = record.strip().split(\"\\t\")[0:5]\n nor = __NormVarAlgrithm(ref,chro,int(pos.strip()),ref.strip(),alt.strip())\n print(\"\\t\".join([str(i) for i in nor]))\n\ndef __NormVarAlgrithm(rfh,chro,pos,ref,alt):\n '''\n algrithm for variant normalization\n '''\n \n ref = ref.upper()\n alt = alt.upper()\n pos = int(pos)\n if ref == \"-\" or ref == \".\":\n ref = \"\"\n if alt == \"-\" or alt == \".\":\n alt = \"\"\n while(True):\n#$ print(\"\\t\".join([str(pos),ref,alt]))\n fref = ref\n falt = alt \n fpos = pos \n if ref == \"\" or alt == \"\":\n base1 = rfh.fetch(reference = chro ,start = pos-1,end = pos)\n ref = base1 + ref \n alt = base1 + alt \n elif fref.endswith(falt[-1]):\n ref = ref[:-1]\n alt = alt[:-1]\n if ref == fref and alt == falt:\n break\n while(True):\n fref = ref\n falt = alt \n fpos = pos \n if min(len(ref),len(alt))>=2 and ref.startswith(alt[0]):\n ref = ref[1:]\n alt = alt[1:]\n if ref ==fref and alt == falt:\n break\n return(chro,fpos,fref,falt) \n\nif __name__==\"__main__\":\n a = pysam.FastaFile(filename =\"/mnt/dist81/pnas/wangqf_group/database/RefDB/UCSC_hg19/Sequence/WholeGenomeFasta/genome.fa\")\n #pdb.set_trace()\n # print(__NormVarAlgrithm(a,\"chr1\",51244,\"CA\",'-'))\n # print(\"--\")\n # print(__NormVarAlgrithm(a,\"chr1\",1244,\"CTGA\",'Ac'))\n # print(\"--\")\n # print(__NormVarAlgrithm(a,\"chr1\",1244,\"ACTGA\",'-'))\n # print(\"--\")\n # print(__NormVarAlgrithm(a,\"chr1\",1244,\"ACTGA\",'-'))\n # print(\"--\")\n NomalizeVariants(\"/home/zhengxc/genome.fa\",\"../test/subset.vcf\") \n\n\n","sub_path":"zbio/ManipulateVcf.py","file_name":"ManipulateVcf.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"322263907","text":"import neat\nimport os\nimport random\nimport time\nimport pygame\n\npygame.font.init()\n\nWIN_WIDTH = 500\nWIN_HEIGHT = 800\n\nGEN = 0\n\nBIRD_IMGS = [pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\", \"bird1.png\"))) , pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\", \"bird2.png\"))), pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\", \"bird3.png\")))]\nPIPE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\", \"pipe.png\")))\nBASE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\", \"base.png\")))\nBG_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\", \"bg.png\")))\n\nSTAT_FONT = pygame.font.SysFont(\"comicsans\", 50)\nclass Bird:\n IMGS = BIRD_IMGS\n MAX_ROTATION = 25\n ROT_VEL = 20\n ANIMATION_TIME = 5\n \n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.tilt = 0\n self.tick_count = 0\n self.vel = 0\n self.height = self.y\n self.img_count = 0\n self.img = self.IMGS[0]\n\n def jump(self):\n self.vel = -10.5\n self.tick_count = 0\n self.height = self.y\n \n def move(self):\n self.tick_count += 1\n displacement = self.vel * self.tick_count + 1.5 * self.tick_count**2\n\n if displacement >= 16:\n displacement = 16\n if displacement < 0 :\n displacement-=2\n\n self.y = self.y + displacement\n\n if displacement < 0 or self.y < self.height + 50:\n if self.tilt < self.MAX_ROTATION:\n self.tilt = self.MAX_ROTATION\n else:\n if self.tilt > -90:\n self.tilt -= self.ROT_VEL\n \n def draw(self, win):\n self.img_count +=1\n \n if self.img_count < self.ANIMATION_TIME:\n self.img = self.IMGS[0]\n elif self.img_count < self.ANIMATION_TIME * 2:\n self.img = self.IMGS[1]\n elif self.img_count < self.ANIMATION_TIME * 3:\n self.img = self.IMGS[2]\n elif self.img_count < self.ANIMATION_TIME * 4:\n self.img = self.IMGS[1]\n elif self.img_count == self.ANIMATION_TIME * 4 + 1:\n self.img = self.IMGS[0]\n self.img_count = 0\n\n if self.tilt <= -80:\n self.img = self.IMGS[1] \n self.img_count = self.ANIMATION_TIME*2\n\n rotated_image = pygame.transform.rotate(self.img, self.tilt)\n new_rect = rotated_image.get_rect(center=self.img.get_rect(topleft = (self.x, self.y)).center) \n win.blit(rotated_image, new_rect.topleft)\n\n def get_mask(self):\n return pygame.mask.from_surface(self.img)\n\nclass Pipe:\n GAP = 200 #Space between pipes\n VEL = 5 #speed pipes move to bird\n\n def __init__(self,x):\n self.x = x\n self.height = 0\n\n self.top = 0 #Where top part of pipe is drawn\n self.bottom = 0 #Where bottom part of pipe is drawn\n self.PIPE_TOP = pygame.transform.flip(PIPE_IMG, False, True) #Flipping pipe so it lookes upside down. # the top pipe is flipped\n self.PIPE_BOTTOM = PIPE_IMG #Bottom pipe image does not need to be flipped\n\n self.passed = False #Check if the bird has passed the pipe\n self.set_height()\n\n def set_height(self):\n self.height = random.randrange(50, 450) #Random height between 50 and 450\n self.top = self.height - self.PIPE_TOP.get_height() #Figure out top left position. Probably drawing in a negative location\n self.bottom = self.height + self.GAP #Adds gap position to the height. \n \n def move(self):\n self.x -= self.VEL\n\n def draw(self, win):\n win.blit(self.PIPE_TOP, (self.x, self.top))#Draws top pipe at the x and top coordinates\n win.blit(self.PIPE_BOTTOM, (self.x, self.bottom)) #Draws bottom pipe at the x and bottom coordinates\n\n def collide(self, bird):\n bird_mask = bird.get_mask()\n top_mask = pygame.mask.from_surface(self.PIPE_TOP)\n bottom_mask = pygame.mask.from_surface(self.PIPE_BOTTOM)\n\n top_offset = (self.x - bird.x, self.top - round(bird.y)) # cant have decimal numbers so bird is rounded. \n bottom_offset = (self.x - bird.x, self.bottom - round(bird.y)) #no dedimals \n #Offsets are how far away the top left corners are from each other\n\n b_point = bird_mask.overlap(bottom_mask, bottom_offset) # Check if masks collide. Find point of collision. If they don't collide then the overlap function will return none.\n t_point = bird_mask.overlap(top_mask, top_offset)\n\n if t_point or b_point:\n #return true if bird collided with either tube\n return True \n \n return False\n\nclass Base:\n VEL = 5 #Needs to be the same as the pipe so it doesn't look like they are moving at different speeds\n WIDTH = BASE_IMG.get_width() #Gets width of base image\n IMG = BASE_IMG\n\n def __init__(self, y):\n self.y = y\n self.x1 = 0\n self.x2 = self.WIDTH\n \n def move(self):\n self.x1 -= self.VEL\n self.x2 -= self.VEL\n #Moves the two bases at two velocities to the left.\n\n if self.x1 + self.WIDTH < 0:\n #Checks if the first base has gone of the screen and when it does it brings it behind the second base \n self.x1 = self.x2 + self.WIDTH\n\n if self.x2 + self.WIDTH < 0:\n #Checks if the second base has gone of the screen and when it does it brings it behind the first base \n self.x2 = self.x1 + self.WIDTH\n def draw(self, win):\n win.blit(self.IMG, (self.x1, self.y)) #Draws first base\n win.blit(self.IMG, (self.x2, self.y)) #Draws second base\n\ndef draw_window(win, birds, pipes, base, score, gen):\n win.blit(BG_IMG, (0,0))\n\n for pipe in pipes:\n pipe.draw(win)\n\n text = STAT_FONT.render(\"Score: \"+ str(score), 1, (255,255,255))\n win.blit(text,(WIN_WIDTH - 10 - text.get_width(), 10)) #Will always fit on screen. Drawn 10 pixels large\n\n text = STAT_FONT.render(\"Generation: \"+ str(gen), 1, (255,255,255))\n win.blit(text,(10, 10)) #Drawn at 10,10 Drawn 10 pixels large\n\n base.draw(win)\n\n for bird in birds:\n bird.draw(win)\n pygame.display.update()\n\ndef main(genomes, config):\n global GEN\n GEN += 1\n nets = [] #neural networks tracking\n ge = [] #genome tracking\n birds =[] \n #genomes is a tupple with a genome id. Ex. (1, genome object) only care about genome object\n for _,g in genomes:\n net = neat.nn.FeedForwardNetwork.create(g, config)\n nets.append(net)\n birds.append(Bird(230, 350))\n g.fitness = 0\n ge.append(g)\n \n\n base = Base(730)\n pipes = [Pipe(600)]\n win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))\n clock = pygame.time.Clock()\n\n score = 0\n\n run = True\n while run:\n clock.tick(30) # ticks 30 times per second. \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n pygame.quit()\n quit()\n\n # bird.move()\n pipe_ind = 0\n if len(birds) > 0:\n if len(pipes) > 1 and birds[0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width():\n #if first pipe is passed then focus on second pipe\n pipe_ind = 1\n else:\n #if no birds left stop running\n run = False\n break\n \n for x, bird in enumerate(birds):\n bird.move()\n ge[x].fitness += 0.1 #every second it gets one fitness point. Encourage survival\n\n output = nets[x].activate((bird.y, abs(bird.y - pipes[pipe_ind].height), abs(bird.y - pipes[pipe_ind].bottom))) #creates output determined by bird's y position, bird's distance to top pipe, and birds distance to bottom pipe.\n #output is a list. There is only one output for this program but other programs could have more in the list\n if output[0] > 0.5:\n bird.jump() #bird will jump if output is greater than .5\n add_pipe = False\n rem =[] #list of pipes to remove\n for pipe in pipes:\n for x, bird in enumerate(birds):\n if pipe.collide(bird):\n #if bird collides\n ge[x].fitness -=1 # Every time bird hits pipe 1 fitness is removed\n birds.pop(x)\n nets.pop(x)\n ge.pop(x) #removes bird from lists\n \n if not pipe.passed and pipe.x < bird.x:\n #Check if bird passed the pipe\n pipe.passed = True\n add_pipe = True\n\n if pipe.x + pipe.PIPE_TOP.get_width() < 0:\n #If the pipe is totally off the screen\n rem.append(pipe) #Adds pipe to the remove list for removal\n\n pipe.move()\n\n if add_pipe:\n score +=1 # adds score\n for g in ge:\n g.fitness += 5\n pipes.append(Pipe(600)) #Adds a pipe to the pipes list with x position of 700. I need to add variables \n for r in rem:\n pipes.remove(r) #removes pipe. might need to be random\n \n for x, bird in enumerate(birds):\n if bird.y + bird.img.get_height() > 730 or bird.y <0:\n #if bird hits the ground or flies off the screen\n birds.pop(x)\n nets.pop(x)\n ge.pop(x)\n\n \n\n base.move()\n draw_window(win, birds, pipes, base, score, GEN)\n\ndef run(config_path):\n config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path) # tell properties that are being set.\n \n pop = neat.Population(config) #Generate population based on config file\n\n pop.add_reporter(neat.StdOutReporter(True)) #Gives stats about populations\n stats = neat.StatisticsReporter()\n pop.add_reporter(stats) #give output for last 3 lines\n\n winner = pop.run(main,50) #fitness function , generations\n\n\nif __name__ ==\"__main__\":\n local_dir = os.path.dirname(__file__) # give path to current directory. Used for loading config file\n config_path = os.path.join(local_dir, \"altconfig.txt\")#Find absolute path to file\n run(config_path)","sub_path":"flappy_bird_alt.py","file_name":"flappy_bird_alt.py","file_ext":"py","file_size_in_byte":10271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"428625799","text":"# encoding: utf-8\n\n# author: BrikerMan\n# contact: eliyar917@gmail.com\n# blog: https://eliyar.biz\n\n# file: callbacks.py\n# time: 2019-05-22 15:00\n\nfrom sklearn import metrics\nfrom kashgari import macros\nfrom tensorflow.python import keras\nfrom kashgari.tasks.base_model import BaseModel\nfrom seqeval import metrics as seq_metrics\n\n\nclass EvalCallBack(keras.callbacks.Callback):\n\n def __init__(self, kash_model: BaseModel, valid_x, valid_y, step=5, batch_size=256, path=\"\"):\n \"\"\"\n Evaluate callback, calculate precision, recall and f1\n Args:\n kash_model: the kashgari model to evaluate\n valid_x: feature data\n valid_y: label data\n step: step, default 5\n batch_size: batch size, default 256\n \"\"\"\n super(EvalCallBack, self).__init__()\n self.kash_model = kash_model\n self.valid_x = valid_x\n self.valid_y = valid_y\n self.step = step\n self.batch_size = batch_size\n self.logs = {}\n\n self.average = 'weighted'\n self.path=path\n\n def on_epoch_end(self, epoch, logs=None):\n if (epoch + 1) % self.step == 0:\n y_pred = self.kash_model.predict_word(self.valid_x, batch_size=self.batch_size)\n\n if self.kash_model.task == macros.TaskType.LABELING:\n y_true = [seq[:len(y_pred[index])] for index, seq in enumerate(self.valid_y)]\n precision = seq_metrics.precision_score(y_true, y_pred)#在被识别为正类别的样本中,确实为正类别的比例是多少?\n recall = seq_metrics.recall_score(y_true, y_pred)#在所有正类别样本中,被正确识别为正类别的比例是多少?\n f1 = seq_metrics.f1_score(y_true, y_pred)\n else:\n y_true = self.valid_y\n precision = metrics.precision_score(y_true, y_pred, average=self.average)\n recall = metrics.recall_score(y_true, y_pred, average=self.average)\n f1 = metrics.f1_score(y_true, y_pred, average=self.average)\n\n self.logs[epoch] = {\n 'precision': precision,\n 'recall': recall,\n 'f1': f1\n }\n print(f\"\\nepoch: {epoch} precision: {precision:.6f}, recall: {recall:.6f}, f1: {f1:.6f}\")\n self.kash_model.save(self.path)\n\nif __name__ == \"__main__\":\n print(\"Hello world\")\n config_path = '/Users/brikerman/Desktop/python/Kashgari/tests/test-data/bert/bert_config.json'\n check_point_path = '/Users/brikerman/Desktop/python/Kashgari/tests/test-data/bert/bert_model.ckpt'\n","sub_path":"kashgari/callbacks_word.py","file_name":"callbacks_word.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"389989088","text":"# mmcls:: means we use the default settings from MMClassification\n_base_ = [\n 'mmcls::_base_/datasets/imagenet_bs64_swin_224.py',\n 'mmcls::_base_/schedules/imagenet_bs1024_adamw_swin.py',\n 'mmcls::_base_/default_runtime.py'\n]\n# Fine-tuning 30 epoch is for models which have intermediate fine-tuning\n# on ImageNet-21k after self-supervised pretrain.\n\n# model settings\nmodel = dict(\n type='ImageClassifier',\n backbone=dict(\n type='BEiT',\n arch='base',\n img_size=224,\n patch_size=16,\n drop_path_rate=0.1,\n avg_token=True,\n output_cls_token=False,\n use_abs_pos_emb=False,\n use_rel_pos_bias=True,\n use_shared_rel_pos_bias=False),\n neck=None,\n head=dict(\n type='LinearClsHead',\n num_classes=1000,\n in_channels=768,\n loss=dict(\n type='LabelSmoothLoss', label_smooth_val=0.1, mode='original'),\n init_cfg=[dict(type='TruncNormal', layer='Linear', std=0.02)]),\n)\n\ntrain_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='RandomResizedCrop',\n scale=224,\n backend='pillow',\n interpolation='bicubic'),\n dict(type='RandomFlip', prob=0.5, direction='horizontal'),\n dict(\n type='RandAugment',\n policies='timm_increasing',\n num_policies=2,\n total_level=10,\n magnitude_level=9,\n magnitude_std=0.5,\n hparams=dict(pad_val=[104, 116, 124], interpolation='bicubic')),\n dict(\n type='RandomErasing',\n erase_prob=0.25,\n mode='rand',\n min_area_ratio=0.02,\n max_area_ratio=0.3333333333333333,\n fill_color=[103.53, 116.28, 123.675],\n fill_std=[57.375, 57.12, 58.395]),\n dict(type='PackClsInputs')\n]\ntest_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='ResizeEdge',\n scale=256,\n edge='short',\n backend='pillow',\n interpolation='bicubic'),\n dict(type='CenterCrop', crop_size=224),\n dict(type='PackClsInputs')\n]\n\ntrain_dataloader = dict(batch_size=128, dataset=dict(pipeline=train_pipeline))\nval_dataloader = dict(batch_size=128, dataset=dict(pipeline=test_pipeline))\ntest_dataloader = val_dataloader\n\n# optimizer wrapper\noptim_wrapper = dict(\n optimizer=dict(\n type='AdamW',\n lr=5e-5,\n weight_decay=0.05,\n eps=1e-8,\n betas=(0.9, 0.999),\n model_type='vit', # layer-wise lr decay type\n layer_decay_rate=0.75), # layer-wise lr decay factor\n constructor='mmselfsup.LearningRateDecayOptimWrapperConstructor',\n paramwise_cfg=dict(\n _delete_=True,\n custom_keys={\n # the following configurations are designed for BEiTs\n '.ln': dict(decay_mult=0.0),\n '.bias': dict(decay_mult=0.0),\n 'q_bias': dict(decay_mult=0.0),\n 'v_bias': dict(decay_mult=0.0),\n '.cls_token': dict(decay_mult=0.0),\n '.pos_embed': dict(decay_mult=0.0),\n '.gamma': dict(decay_mult=0.0),\n }))\n\n# learning rate scheduler\nparam_scheduler = [\n dict(\n type='LinearLR',\n start_factor=1e-4,\n by_epoch=True,\n begin=0,\n end=20,\n convert_to_iter_based=True),\n dict(\n type='CosineAnnealingLR',\n by_epoch=True,\n begin=20,\n end=30,\n eta_min=1e-6,\n convert_to_iter_based=True)\n]\n\n# runtime settings\ndefault_hooks = dict(\n # save checkpoint per epoch.\n checkpoint=dict(type='CheckpointHook', interval=1, max_keep_ckpts=2))\n\ntrain_cfg = dict(by_epoch=True, max_epochs=30)\n\nrandomness = dict(seed=0)\n","sub_path":"configs/selfsup/beitv2/classification/vit-base-p16_ft-8xb128-coslr-30e_in1k.py","file_name":"vit-base-p16_ft-8xb128-coslr-30e_in1k.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"387161388","text":"\"\"\"\nBuildspecParser: testing functions\n\"\"\"\n\nimport pytest\nimport os\n\n\nfrom buildtest.buildsystem.builders import Builder\nfrom buildtest.buildsystem.parser import BuildspecParser\nfrom buildtest.exceptions import BuildTestError\nfrom buildtest.utils.file import walk_tree\n\ntestroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nhere = os.path.dirname(os.path.abspath(__file__))\n\n\ndef test_BuildspecParser(tmp_path):\n\n # Invalid path to buildspec file should exit\n with pytest.raises(BuildTestError):\n BuildspecParser(\"\")\n\n # Passing 'None' will raise an error\n with pytest.raises(BuildTestError):\n BuildspecParser(None)\n\n directory = os.path.join(here, \"invalid_buildspecs\")\n builders = []\n for buildspec in walk_tree(directory, \".yml\"):\n buildspecfile = os.path.join(directory, buildspec)\n print(\"Processing buildspec: \", buildspecfile)\n with pytest.raises(BuildTestError):\n BuildspecParser(buildspecfile)\n\n # Examples folder\n valid_buildspecs_directory = os.path.join(here, \"valid_buildspecs\")\n\n # A directory is not allowed either, this will raise an error.\n with pytest.raises(BuildTestError):\n BuildspecParser(valid_buildspecs_directory)\n\n # Test loading Buildspec files\n for buildspec in walk_tree(valid_buildspecs_directory, \".yml\"):\n buildspecfile = os.path.join(valid_buildspecs_directory, buildspec)\n bp = BuildspecParser(buildspecfile)\n assert bp.recipe\n assert bp.buildspec\n assert bp.executors\n\n filters = {\"tags\": None, \"executors\": None}\n\n builders = Builder(bp, filters=filters, testdir=tmp_path)\n builders = builders.get_builders()\n assert builders\n\n for builder in builders:\n\n # Builders (on init) set up metadata attribute\n assert builder.metadata\n\n # Invoking build will build the test script\n # and write test\n builder.build()\n","sub_path":"tests/buildsystem/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"575203287","text":"\"\"\"\nfunctions to read the a CSV file\nand put it into a dictionary\n\"\"\"\nimport os\nimport csv\n\ndef read_palette_from_file(palette_filename):\n \"\"\"\n read the palette from the csv file.\n Each row is a key and an RGB triple. Make that RGB triple\n into a TUPLE and then put into a dictionary with the key.\n \"\"\"\n dictionary = {}\n with open(palette_filename, 'r') as f:\n csv_reader = csv.reader(f)\n\n for row in csv_reader:\n key = int(row[0])\n\n R_value = int(row[1])\n G_value = int(row[2])\n B_value = int(row[3])\n\n RGB_tuple = (R_value, G_value, B_value)\n\n\n dictionary[key] = RGB_tuple\n\n\n return(dictionary)\n","sub_path":"palette_import_lib.py","file_name":"palette_import_lib.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"610346907","text":"import os, subprocess, time, argparse, re\n\n# https://stackoverflow.com/questions/431684/how-do-i-change-directory-cd-in-python\nclass cd:\n \"\"\"Context manager for changing the current working directory\"\"\"\n def __init__(self, newPath):\n self.newPath = os.path.expanduser(newPath)\n\n def __enter__(self):\n self.savedPath = os.getcwd()\n\n try:\n os.chdir(self.newPath)\n except OSError:\n # make the directory and then chdir\n os.makedirs(self.newPath)\n os.chdir(self.newPath)\n\n def __exit__(self, etype, value, traceback):\n os.chdir(self.savedPath)\n\n\ndef qc_sim(sim_cmd, print_sim=False):\n sim_result = subprocess.check_output(sim_cmd, shell=True)\n if (print_sim):\n print(sim_result)\n\n # parse sim result to determine output\n # require some x% confidence after y runs\n\n # get the measurement info string from sim output\n meas_regex = re.compile(\"measurement register\\s*:\\s*([0-9\\|\\s]+)\")\n meas_match = meas_regex.search(sim_result)\n assert(meas_match)\n\n # extract the bits from the string\n meas_regex = re.compile(\"\\d\")\n meas_match = meas_match.group(1)\n\n # accrue bits\n bits = []\n for bit in meas_regex.finditer(meas_match):\n bit_val = int(bit.group(0))\n bits.append(bit_val)\n\n return bits\n\n# convert bit array to an integer value\ndef bits_to_val(bit_array):\n val = 0\n for i in range(len(bit_array)):\n val += bit_array[i] << i\n return val\n\ndef get_majority(vals):\n # create sparse histogram\n bins = {}\n for i in range(len(vals)):\n val = vals[i]\n if val in bins:\n bins[val] += 1\n else:\n bins[val] = 1\n\n # then figure out majority\n best_val = 0\n best_count = 0\n for k,v in bins.items():\n if (v > best_count):\n best_val = k\n best_count = v\n\n return (best_val, float(best_count) / float(len(vals)))\n\n\n# https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data\n# given data=[], and confidence value\n# ret (mean, stdev, confidence interval as two values)\ndef mean_confidence_interval(data, confidence=0.95):\n import numpy as np\n import scipy.stats\n\n a = 1.0 * np.array(data)\n n = len(a)\n m, se = np.mean(a), scipy.stats.sem(a)\n h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)\n return m, se, m-h, m+h","sub_path":"workflow/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"85112950","text":"from rest_framework import routers\n\nfrom . import api_views, views\n\nRoute = routers.Route\n\nclass APIRouter(routers.DefaultRouter):\n routes = [\n # List route.\n Route(\n url=r'^{prefix}{trailing_slash}$',\n mapping={\n 'get': 'list',\n 'post': 'create'\n },\n name='{basename}-list',\n initkwargs={'suffix': 'List'}\n ),\n # Detail route.\n Route(\n url=r'^{prefix}/{lookup}{trailing_slash}$',\n mapping={\n 'get': 'retrieve',\n 'put': 'update',\n 'patch': 'partial_update',\n 'delete': 'destroy'\n },\n name='{basename}-detail',\n initkwargs={'suffix': 'Instance'}\n ),\n # Dynamically generated routes.\n # Generated using @action or @link decorators on methods of the viewset.\n Route(\n url=r'^{prefix}/{lookup}/{methodname}{trailing_slash}$',\n mapping={\n '{httpmethod}': '{methodname}',\n },\n name='{basename}-{methodnamehyphen}',\n initkwargs={}\n ),\n Route(\n url=r'^{prefix}/{methodname}{trailing_slash}$',\n mapping={\n '{httpmethod}': '{toplevelmethodname}',\n },\n name='{basename}-{methodnamehyphen}',\n initkwargs={}\n ),\n ]\n\n def get_routes(self, viewset):\n ret = super(APIRouter, self).get_routes(viewset)\n\n toplevel_dynamic_routes = []\n for methodname in dir(viewset):\n attr = getattr(viewset, methodname)\n httpmethods = getattr(attr, 'toplevel_bind_to_methods', None)\n if httpmethods:\n httpmethods = [method.lower() for method in httpmethods]\n toplevel_dynamic_routes.append((httpmethods, methodname))\n \n extra_ret = []\n for route in self.routes:\n if route.mapping == {'{httpmethod}': '{toplevelmethodname}'}:\n for httpmethods, methodname in toplevel_dynamic_routes:\n initkwargs = route.initkwargs.copy()\n initkwargs.update(getattr(viewset, methodname).kwargs)\n extra_ret.append(Route(\n url=routers.replace_methodname(route.url, methodname),\n mapping=dict((httpmethod, methodname) for httpmethod in httpmethods),\n name=routers.replace_methodname(route.name, methodname),\n initkwargs=initkwargs,\n ))\n\n extra_ret.extend(ret)\n\n return extra_ret\n","sub_path":"cintranet/ticketing/api_router.py","file_name":"api_router.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"146722368","text":"#coding=utf-8\nimport os\nimport random\nimport commands\nfrom products.netUtils.xutils import nbPath as _p\nclass ExportReport(object):\n \"\"\"\n 报表导出\n \"\"\"\n baseDir = _p(\"/nbfiles/imgs/reportImgs/\")\n def __init__(self,userid):\n \"\"\"\n 初始化\n \"\"\"\n self.exportName=\"%s%s\"%(userid,random.randint(1,1000))\n \n\n def exportReport(self,etype='pdf',htmlContent=''):\n \"\"\"\n 报表导出\n \"\"\"\n self.createHtml(htmlContent)\n toPath=self.createExportFile(etype)\n return toPath\n\n def createHtml(self, htmlContent=\"\"):\n \"\"\"\n 创建html\n \"\"\"\n exportHtmlPath=self.baseDir + '%sexport.html'%self.exportName\n htmlContent = htmlContent.replace(\"/chart_images/reportImgs\",self.baseDir)\n html= \"\"\"\n <!DOCTYPE html>\n <html>\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n </head>\n <body>\n %s\n </body>\n </html>\n \"\"\"%htmlContent\n ff = open(exportHtmlPath,'w+')\n ff.write(html);\n ff.close()\n \n def createExportFile(self, ftype=\"pdf\"):\n \"\"\"\n 创建输出文件\n 生成pdf命令:wkhtmltopdf-amd64\n 生成图片命令:wkhtmltoimage-amd64\n \"\"\"\n wktype=ftype\n if ftype in [\"jpg\",\"png\"]:wktype=\"image\"\n htmlPath=\"%s%sexport.html\"%(self.baseDir,self.exportName)\n toPath=\"%s%sexport.%s\"%(self.baseDir,self.exportName,ftype)\n cmd = _p(r\"/libexec/wkhtmlto%s-amd64 %s %s\" %(wktype,htmlPath,toPath))\n commands.getoutput(cmd)\n if not os.path.exists(toPath):return None\n return toPath","sub_path":"products/netReport/exportReport.py","file_name":"exportReport.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"538917838","text":"import numpy as np\nimport pdb\nimport scipy.constants as ct\nfrom scipy.special import ellipk as EllipticK\nfrom scipy.special import ellipe as EllipticE\nfrom mpmath import ellippi\n\nCos = np.cos\nPi = np.pi\nSqrt = np.sqrt\nMsun = 1.989e30\n\ndef EllipticPi(n, m):\n\treturn float(ellippi(n, Pi/2., m))\n\ndef KerrGeoFreqs_vectorized(a, p, e, theta_inc, M=1):\n\tKGF_vec = np.frompyfunc(KerrGeoFreqs_scalar, 4, 4)\n\t#pdb.set_trace()\n\treturn KGF_vec(a, p, e, theta_inc)\n\ndef convert_to_Hz(Mf, M):\n\tM_time = M*Msun*ct.G/ct.c**3\n\treturn Mf/M\n\ndef KerrGeoELQ(a, p, e, theta_inc):\n\t\"\"\"\n\tKerrGeoELQ[a_(*/;Abs[a]<=1*), p_, e_, \\[Theta]inc1_?NumericQ] := Module[{M=1,f, g, h, d, fp, gp, hp, dp, r, rp, ra, zm, \\[CapitalDelta], \\[Rho], \\[Kappa], \\[Epsilon], \\[Eta], \\[Sigma], En, L, Q, E1, Em1, f1, g1, h1, d1, f2, g2, h2, d2, L1, L2,r0,\\[CapitalDelta]0,Z,\\[Theta]min,\\[Theta]inc=\\[Theta]inc1},\n\n\t\n\t\\[Theta]inc=Mod[\\[Theta]inc,2\\[Pi]];\n\tIf[\\[Theta]inc>\\[Pi], \\[Theta]inc=2\\[Pi]-\\[Theta]inc];\n\tIf[\\[Theta]inc <= \\[Pi]/2 , \\[Theta]min = \\[Pi]/2-\\[Theta]inc, \\[Theta]min=-\\[Pi]/2+\\[Theta]inc];\n\n\tIf[Mod[\\[Theta]inc,\\[Pi]]==\\[Pi]/2 && e!=0,Print[\"Polar, non-spherical orbits not yet implemented\"]; Return[]];\n\n\t\"\"\"\n\tif theta_inc <= Pi/2.:\n\t\ttheta_min = Pi/2. - theta_inc\n\n\telif theta_inc != Pi/2.:\n\t\ttheta_min = Pi/2. + theta_inc\n\n\telse:\n\t\traise Exception(\"Polar, non-spherical orbits not yet implemented\")\n\n\n\trp = p/(1 + e)\n\tra = p/(1 - e)\n\n\tzm = Cos(theta_min)\n \n \n\tDelta_r = lambda r : r**2 - 2*r + a**2\n \n \n\tf = lambda r : r**4 + a**2*(r*(r+2) + zm**2 * Delta_r(r))\n\tg = lambda r : 2*a*r\n\th = lambda r : r*(r - 2) + zm**2/(1 - zm**2) * Delta_r(r)\n\td = lambda r : (r**2 + a**2 * zm**2) * Delta_r(r)\n \n\tfp = lambda r : 4*r**3 + 2*a**2 ((1 + zm**2)*r + (1 - zm**2))\n\tgp = 2*a\n\thp = lambda r : 2*(r - 1)/(1 - zm**2)\n\tdp = lambda r : 2*(2*r - 3) * r**2 + 2*a**2 ((1 + zm**2)*r - zm**2)\n \n\tf1, g1, h1, d1 = f(rp), g(rp), h(rp), d(rp)\n \n\tif e != 0:\n\t\tf2, g2, h2, d2 = f(ra), g(ra), h(ra), d(ra)\n\telse:\n\t\tf2, g2, h2, d2 = fp(ra), gp(ra), hp(ra), dp(ra)\n \n\tKappa = d1*h2 - h1*d2\n\tEpsilon = d1*g2 - g1*d2\n\tRho = f1*h2 - h1*f2\n\tEta = f1*g2 - g1*f2\n\tSigma = g1*h2 - h1*g2\n \n\tpm = 1\n\tEn = Sqrt((Kappa*Rho + 2*Epsilon * Sigma - pm*2*Sqrt(Sigma*(Sigma*Epsilon**2 + Rho*Epsilon*Kappa - Eta * Kappa**2)))/(Rho**2 + 4*Eta*Sigma))\n\n\tL = -(En*g1/h1) + pm*Sqrt((g1*En/h1)**2 + (f1*En**2 - d1)/h1)\n\n\tQ = zm**2 * (a**2 * (1 - En**2) + L**2/(1 - zm**2))\n\n\treturn En, L, Q\n\ndef KerrGeoRadialRoots(a, p, e, theta_inc, M=1):\n\tEn,L,Q=KerrGeoELQ(a,p,e,theta_inc)\n\n\tr1=p/(1-e)\n\tr2=p/(1+e)\n\tAplusB=(2*M)/(1-En**2)-(r1+r2) #(*Eq. (11)*)\n\tAB=(a**2 * Q)/((1-En**2)*r1 * r2) #(*Eq. (11)*)\n\tr3=(AplusB+Sqrt((AplusB)**2-4*AB))/2. #(*Eq. (11)*)\n\tr4=AB/r3\n\n\treturn r1,r2,r3,r4\n\ndef KerrGeoPolarRoots(a,p,e, theta_inc):\n En,L,Q = KerrGeoELQ(a, p, e, theta_inc)\n theta_min=(Pi/2-theta_inc)/np.sign(L)\n zm = Cos(theta_min)\n zp = (a**2 * (1-En**2)+L**2/(1-zm**2))**(1/2)\n return zp,zm\n\n\ndef KerrGeoFreqs_scalar(a, p, e, theta_inc, M=1):\n\t\"\"\"\n\tKerrGeoFreqs[a_/;Abs[a]<1,p_,e_,\\[Theta]inc1_?NumericQ]:=Module[{M=1,En,L,Q,r1,r2,AplusB,AB,r3,r4,\\[Epsilon]0,zm,kr,k\\[Theta],Upsilon_r,Upsilon_theta,\\[CapitalUpsilon]\\[Phi],\\[CapitalGamma],rp,rm,hp,hm,hr,EnLQ,a2zp,epsilon_0zp,zmOverZp,\\[Theta]min,\\[Theta]inc=\\[Theta]inc1},\n\t\"\"\"\n\t#theta_inc=Mod[\\[Theta]inc,2\\[Pi]];\n\tif theta_inc > Pi:\n\t\ttheta_inc = 2*Pi-theta_inc\n\n\tif theta_inc == Pi/2:\n\t\traise Exception(\"Equations for polar orbits not implemented yet\")\n\t\n\n\tEn,L,Q=KerrGeoELQ(a,p,e,theta_inc)\n\n\ttheta_min=(Pi/2-theta_inc)/np.sign(L);\n\n\tr1,r2,r3,r4 = KerrGeoRadialRoots(a,p,e,theta_inc)\n\n\t\n\tepsilon_0= a**2 * (1-En**2)/L**2\n\tzm=Cos(theta_min)**2\n\ta2zp=(L**2+a**2 * (-1+En**2) * (-1+zm))/((-1+En**2) *(-1+zm))\n\n\tepsilon_0zp=-((L**2+a**2 * (-1+En**2) * (-1+zm))/(L**2 * (-1+zm)))\n\n\tif a == 0.0:\n\t\tzmOverZp = 0.0\n\telse:\n\t\tzmOverZp = zm/((L**2+a**2 * (-1+En**2) * (-1+zm))/(a**2 * (-1+En**2) * (-1+zm)))\n\n\tkr=Sqrt((r1-r2)/(r1-r3)*(r3-r4)/(r2-r4)) #(*Eq.(13)*)\n\tktheta =Sqrt(zmOverZp) #(*Eq.(13)*)\n\tUpsilon_r =(Pi * Sqrt((1-En**2)*(r1-r3)*(r2-r4)))/(2*EllipticK(kr**2)) #(*Eq.(15)*)\n\tUpsilon_theta =(Pi * L * Sqrt(\n\t\tepsilon_0zp))/(2*EllipticK(ktheta**2)) #(*Eq.(15)*)\n\n\trp=M+Sqrt(M**2-a**2)\n\trm=M-Sqrt(M**2-a**2)\n\thr=(r1-r2)/(r1-r3)\n\thp=((r1-r2)*(r3-rp))/((r1-r3)*(r2-rp))\n\thm=((r1-r2)*(r3-rm))/((r1-r3)*(r2-rm))\n\n\tUpsilon_phi=(2*Upsilon_theta)/(Pi * Sqrt(epsilon_0zp)) * EllipticPi(zm,ktheta**2)+(2*a* Upsilon_r)/(Pi*(rp-rm)*Sqrt((1-En**2)*(r1-r3)*(r2-r4))) * ((2* M * En * rp - a * L)/(r3-rp) * (EllipticK(kr**2)-(r2-r3)/(r2-rp) * EllipticPi(hp,kr**2))-(2*M * En * rm - a * L)/(r3-rm) * (EllipticK(kr**2)-(r2-r3)/(r2-rm) * EllipticPi(hm,kr**2))) #(*Eq. (21)*)\n\n\n\t#(*Convert to frequencies w.r.t BL time using Fujita and Hikida's formula Eq. (21)*)\n\tGamma = 4*M**2 * En + (2*a2zp * En * Upsilon_theta)/(Pi * L * Sqrt(epsilon_0zp)) * (EllipticK(ktheta**2)- EllipticE(ktheta**2)) + (2*Upsilon_r)/(Pi* Sqrt((1-En**2)*(r1-r3)*(r2-r4))) * (En/2 * ((r3*(r1+r2+r3)-r1 * r2)*EllipticK(kr**2)+(r2-r3)*(r1+r2+r3+r4)*EllipticPi(hr,kr**2)+(r1-r3)*(r2-r4)*EllipticE(kr**2))+2*M * En*(r3 * EllipticK(kr**2)+(r2-r3)*EllipticPi(hr,kr**2))+(2*M)/(rp-rm) * (((4*M**2 * En-a * L)*rp-2*M* a**2 * En)/(r3-rp) * (EllipticK(kr**2)-(r2-r3)/(r2-rp) *EllipticPi(hp,kr**2))-((4*M**2 * En-a * L)*rm-2*M * a**2 * En)/(r3-rm) * (EllipticK(kr**2)-(r2-r3)/(r2-rm) * EllipticPi(hm,kr**2))))\n\n\t#(*Output the BL frequencies by dividing the Mino time frequencies by the conversion factor \\[CapitalGamma]*)\n\treturn Upsilon_r/Gamma, np.fabs(Upsilon_theta/Gamma),Upsilon_phi/Gamma, Gamma\n\ndef KerrGeoFreqs(a, p, e, theta_inc, M=1):\n\treturn KerrGeoFreqs_vectorized(a, p, e, theta_inc)\n\n\nif __name__ == \"__main__\":\n\n\tmu = 10.0\n\tM = 1e6*1.989e30*ct.G/ct.c**2\n\tnum = 100\n\ta = np.full(num,0.44)\n\tp = np.full(num, 7.7) #really p/M\n\te = np.full(num, 0.7)\n\tiota = np.full(num, np.pi/5.)\n\n\ta = 0.732\n\tp = 8.7\n\te = 0.6\n\tiota = Pi/2.5\n\t\n\n\timport time\n\tst = time.time()\n\tcheck = KerrGeoFreqs_vectorized(a, p, e, iota)\n\tprint(time.time()-st)\n\tprint(check)\n\tpdb.set_trace()\n","sub_path":"mkatz/EMRI_fundamental_frequencies.py","file_name":"EMRI_fundamental_frequencies.py","file_ext":"py","file_size_in_byte":6002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"245483879","text":"import math\nimport re\nimport datetime\nimport os\n\nfrom src.python import configs\nfrom src.python.configs import logger\nfrom socket import gethostname\nfrom socket import gethostbyname\ntry:\n from functools import cache\nexcept ImportError:\n def cache(f):\n def inner(*args, **kwargs):\n return f(*args, **kwargs)\n return f\n\nall_patterns = (\n re.compile(r\"(?P<cmd>\\bhow)\\s*?(?P<subcmd>to)\\s*(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bshare)\\s*?(?P<subcmd>this)\"),\n re.compile(r\"(?P<cmd>\\bshare)\\s*?(?P<subcmd>status)\"),\n re.compile(r\"(?P<cmd>\\bzone)\\s*?(?P<subcmd>info)\"),\n re.compile(r\"(?P<cmd>\\bshare)\\s+?(?P<arg>.+)\\s+?(?P<subcmd>with)\\s+?(?P<subarg>.+)\"),\n re.compile(r\"(?P<cmd>\\bshare)\\s+?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bview)\\s+?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bcollect)\\s+?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bcancel)\\s*?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\busername)\\s*?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bvisit)\\s+?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bselect)\\s*?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bunselect)\\s*?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bprotect)\\s*?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bunprotect)\\s*?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bchat)\\s(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bthrow)\\s*?(?P<arg>.+)?\"),\n re.compile(r\"(?P<cmd>\\bdetails)\\s*?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bkick)\\s*?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bhelp)\\s*?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bhelp\\b)\"),\n re.compile(r\"(?P<cmd>\\bcd)\\s+(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bhome)\\s+?(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\bhome\\b)\"),\n re.compile(r\"(?P<cmd>\\bpwd\\b)\"),\n re.compile(r\"(?P<cmd>\\bdirmap)\\s*?(?P<arg>.+)?\"),\n re.compile(r\"(?P<cmd>\\bls\\b)\"),\n re.compile(r\"(?P<cmd>\\bcopy)\\s*(?P<arg>.+?)\\s+to\\s*(?P<subarg>.+)\"),\n re.compile(r\"(?P<cmd>\\bmove)\\s*(?P<arg>.+?)\\s+to\\s*(?P<subarg>.+)\"),\n re.compile(r\"(?P<cmd>\\brename)\\s*(?P<arg>.+?)\\s+to\\s*(?P<subarg>.+)\"),\n re.compile(r\"(?P<cmd>\\bdelete)\\s*(?P<arg>.+)\"),\n re.compile(r\"\"\"(?P<cmd>\\bset)\\s*\n(?P<subarg1>[ma])?\\s*\n(?P<arg>\\S+?)\\s+\n(?P<subarg0>\n(?:now|today|yesterday|\\d\\d[-./]\\d\\d[-./]\\d{2,4})\\s*\n(?:\\d\\d(?::\\d\\d(?::\\d\\d))?)?\n)\n\"\"\", re.VERBOSE),\n re.compile(r\"(?P<cmd>search)\\s+(?P<arg>.+)\\s+in\\s*(?P<subarg>.+)\"),\n re.compile(r\"(?P<cmd>\\bsearch)\\s+(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>diff)(?:erence)?\\s*(?P<arg>.+)\\s+(?P<subarg>.+)\"),\n re.compile(r\"(?P<cmd>\\bsearch)\\s*(?P<arg>.+)\"),\n re.compile(r\"(?P<cmd>\\breturn\\b)\"),\n re.compile(r\"(?P<cmd>\\babout\\b)\"),\n re.compile(r\"(?P<cmd>\\bleave\\b)\"),\n re.compile(r\"(?P<cmd>\\bclose\\b)\"),\n re.compile(r\"(?P<cmd>\\bexit\\b)\"),\n re.compile(r\"(?P<cmd>\\busername\\b)\"),\n re.compile(r\"(?P<cmd>\\bstart\\b)\"),\n re.compile(r\"(?P<cmd>\\bclear\\b)\"),\n re.compile(r\"(?P<cmd>\\bjoin\\b)\\s*?(?P<arg>[\\w\\d]{3} [\\w\\d]{4} [\\w\\d]{4})\"),\n)\nnow = datetime.datetime.now()\ntoday = datetime.datetime.strptime(now.strftime(\"%d-%m-%Y\"), \"%d-%m-%Y\")\ntime_pat = re.compile(r\"\"\"\n\\b(?:tm|time):(?P<time1>(:?now|today|yesterday|\\d{2}\\s*[./-]\\s*\\d{2}\\s*[./-]\\s*\\d{2,4})\n(?:\\s+\\d{2}(?:\\s*:\\s*\\d{2}(?:\\s*:\\s*\\d{2})?)?)?\n)\n(?:\n\\s*-\\s*\n(?P<time2>(:?now|today|yesterday|\\d{2}\\s*[./-]\\s*\\d{2}\\s*[./-]\\s*\\d{2,4})\n(?:\\s+\\d{2}(?:\\s*:\\s*\\d{2}(?:\\s*:\\s*\\d{2})?)?)?\n)\n)?\\b\n\"\"\", re.VERBOSE) #tm:(now|today|yesterday|dd-mm-yyyy (hh:mm:ss)?)(-now|today|yesterday|dd-mm-yyyy (hh:mm:ss)?)? #5\ntimelimit_pat = re.compile(r\"\\bin:(\\d+)([YyMmWwDdHhSs]|min|Min|MIN)\\b\") #in:{n}[yYmMdYHhsS]|min|Min|MIN #8\nage_pat = re.compile(r\"\\b(new|old):(\\d+)\") #new|old:n #9\nitem_pat = re.compile(r\"\\b(?:i|item):(\\d+\\s*-\\s*\\d+|\\d+(?:[\\s,]+\\d+)*)\\b\") #(i|item):n|m,n,o...|m-p #7\nkw_pat1 = re.compile(r\"\\b('.+?'|\\\".+?\\\")\\b\") #'...'|\"..\" #1\nkw_pat2 = re.compile(r\"([^\\s\\n\\t]+)\") #..... #11\nrange_pat = re.compile(r\"\\bcons(?:ider)?:(\\d+\\s*-\\s*\\d+|\\d+(?:[\\s,]+\\d+)*)\\b\") #cons:(m-p|m, n, o, p) #3\ntakeonly_pat = re.compile(r\"\\b(?:tp|type):(photo|image|audio|video|doc|\\.[\\d\\w_]+|file|folder|dir)(?:ectory)?\\b\") #type:photo|image|audio|video|doc|file|folder|dir|{extention} #6\ncount_pat = re.compile(r\"\\b(?:t|take):(f|l|\\d+)?-(\\d+)\\b\") #t:f-n|-n|l-n|m-n #6\nignore_pat = re.compile(r\"\\b(?:ign|ignore):(.+)$\") #ignore:.....$ #2\nsize_pat = re.compile(r\"\\b(?:s|size):(\\d+(?:\\.\\d+)?(?:b|kb|mb|gb|B|KB|MB|GB)?)(?:\\s*-\\s*(\\d+(?:\\.\\d+)?(?:b|kb|mb|gb|B|KB|MB|GB)?))?\") #s:{n}b|kb|mb|gb|-{n}b|kb|mb|gb| #10\n\nimage_ext = (\"jpg\", \"jpeg\", \"png\", \"gif\", \"bmp\", \"tiff\", \"raw\", \"webp\", \"tif\", \"psg\", \"dds\")\nvideo_ext = (\"mp4\", \"3gp\", \"ogg\", \"wmv\", \"webm\", \"flv\", \"3g2\", \"asf\", \"avi\", \"mov\", \"rm\", \"srt\", \"swf\", \"m4v\", \"vob\")\naudio_ext = (\"m4a\", \"mp3\", \"flac\", \"wav\", \"wma\", \"aac\", \"aif\", \"iff\", \"m3u\", \"mid\", \"mpa\")\ndoc_ext = (\"pdf\", \"txt\", \"epub\", \"word\", \"doc\", \"docx\", \"mobi\", \"chm\", \"djvu\", \"odt\", \"rtf\", \"fb2\", \"azw\")\n\ntypes = {\n \"doc\": \"Microsoft Word Document\",\n \"docx\": \"Microsoft Word Open XML Document\",\n \"log\": \"Log File\",\n \"msg\": \"Outlook Mail Message\",\n \"odt\": \"OpenDocument Text Document\",\n \"pages\": \"Pages Document\",\n \"rtf\": \"Rich Text Format File\",\n \"tex\": \"LaTeX Source Document\",\n \"tif\": \"Tagged Image File\",\n \"tiff\": \"Tagged Image File Format\",\n \"txt\": \"Plain Text File\",\n \"wpd\": \"WordPerfect Document\",\n \"wps\": \"Microsoft Works Word Processor Document\",\n \"csv\": \"Comma Separated Values File\",\n \"dat\": \"Data File\",\n \"ged\": \"GEDCOM Genealogy Data File\",\n \"key\": \"Keynote Presentation\",\n \"keychain\": \"Mac OS X Keychain File\",\n \"pps\": \"PowerPoint Slide Show\",\n \"ppt\": \"PowerPoint Presentation\",\n \"pptx\": \"PowerPoint Open XML Presentation\",\n \"sdf\": \"Standard Data File\",\n \"tar\": \"Consolidated Unix File Archive\",\n \"tax2016\": \"TurboTax 2016 Tax Return\",\n \"tax2019\": \"TurboTax 2019 Tax Return\",\n \"vcf\": \"vCard File\",\n \"xml\": \"XML File\",\n \"aif\": \"Audio Interchange File Format\",\n \"iff\": \"Interchange File Format\",\n \"m3u\": \"Media Playlist File\",\n \"m4a\": \"MPEG-4 Audio File\",\n \"mid\": \"MIDI File\",\n \"mp3\": \"MP3 Audio File\",\n \"mpa\": \"MPEG-2 Audio File\",\n \"wav\": \"WAVE Audio File\",\n \"wma\": \"Windows Media Audio File\",\n \"3g2\": \"3GPP2 Multimedia File\",\n \"3gp\": \"3GPP Multimedia File\",\n \"asf\": \"Advanced Systems Format File\",\n \"avi\": \"Audio Video Interleave File\",\n \"flv\": \"Flash Video File\",\n \"m4v\": \"iTunes Video File\",\n \"mov\": \"Apple QuickTime Movie\",\n \"mp4\": \"MPEG-4 Video File\",\n \"mpg\": \"MPEG Video File\",\n \"rm\": \"RealMedia File\",\n \"srt\": \"SubRip Subtitle File\",\n \"swf\": \"Shockwave Flash Movie\",\n \"vob\": \"DVD Video Object File\",\n \"wmv\": \"Windows Media Video File\",\n \"3dm\": \"Rhino 3D Model\",\n \"3ds\": \"3D Studio Scene\",\n \"max\": \"3ds Max Scene File\",\n \"obj\": \"Wavefront 3D Object File\",\n \"bmp\": \"Bitmap Image File\",\n \"dds\": \"DirectDraw Surface\",\n \"gif\": \"Graphical Interchange Format File\",\n \"heic\": \"High Efficiency Image Format\",\n \"jpg\": \"JPEG Image\",\n \"png\": \"Portable Network Graphic\",\n \"psd\": \"Adobe Photoshop Document\",\n \"pspimage\": \"PaintShop Pro Image\",\n \"tga\": \"Targa Graphic\",\n \"thm\": \"Thumbnail Image File\",\n \"yuv\": \"YUV Encoded Image File\",\n \"ai\": \"Adobe Illustrator File\",\n \"eps\": \"Encapsulated PostScript File\",\n \"svg\": \"Scalable Vector Graphics File\",\n \"indd\": \"Adobe InDesign Document\",\n \"pct\": \"Picture File\",\n \"pdf\": \"Portable Document Format File\",\n \"xlr\": \"Works Spreadsheet\",\n \"xls\": \"Excel Spreadsheet\",\n \"xlsx\": \"Microsoft Excel Open XML Spreadsheet\",\n \"accdb\": \"Access 2007 Database File\",\n \"db\": \"Database File\",\n \"dbf\": \"Database File\",\n \"mdb\": \"Microsoft Access Database\",\n \"pdb\": \"Program Database\",\n \"sql\": \"Structured Query Language Data File\",\n \"apk\": \"Android Package File\",\n \"app\": \"macOS Application\",\n \"bat\": \"DOS Batch File\",\n \"cgi\": \"Common Gateway Interface Script\",\n \"com\": \"DOS Command File\",\n \"exe\": \"Windows Executable File\",\n \"gadget\": \"Windows Gadget\",\n \"jar\": \"Java Archive File\",\n \"wsf\": \"Windows Script File\",\n \"b\": \"Grand Theft Auto 3 Saved Game File\",\n \"dem\": \"Video Game Demo File\",\n \"gam\": \"Saved Game File\",\n \"nes\": \"Nintendo (NES) ROM File\",\n \"rom\": \"N64 Game ROM File\",\n \"sav\": \"Saved Game\",\n \"dwg\": \"AutoCAD Drawing Database File\",\n \"dxf\": \"Drawing Exchange Format File\",\n \"gpx\": \"GPS Exchange File\",\n \"kml\": \"Keyhole Markup Language File\",\n \"kmz\": \"Google Earth Placemark File\",\n \"asp\": \"Active Server Page\",\n \"aspx\": \"Active Server Page Extended File\",\n \"cer\": \"Internet Security Certificate\",\n \"cfm\": \"ColdFusion Markup File\",\n \"crdownload\": \"Chrome Partially Downloaded File\",\n \"csr\": \"Certificate Signing Request File\",\n \"css\": \"Cascading Style Sheet\",\n \"dcr\": \"Shockwave Media File\",\n \"htm\": \"Hypertext Markup Language File\",\n \"html\": \"Hypertext Markup Language File\",\n \"js\": \"JavaScript File\",\n \"jsp\": \"Java Server Page\",\n \"php\": \"PHP Source Code File\",\n \"rss\": \"Rich Site Summary\",\n \"xhtml\": \"Extensible Hypertext Markup Language File\",\n \"crx\": \"Chrome Extension\",\n \"plugin\": \"Mac OS X Plugin\",\n \"fnt\": \"Windows Font File\",\n \"fon\": \"Windows Font Library\",\n \"otf\": \"OpenType Font\",\n \"ttf\": \"TrueType Font\",\n \"cab\": \"Windows Cabinet File\",\n \"cpl\": \"Windows Control Panel Item\",\n \"cur\": \"Windows Cursor\",\n \"deskthemepack\": \"Windows 8 Desktop Theme Pack File\",\n \"dll\": \"Dynamic Link Library\",\n \"dmp\": \"Windows Memory Dump\",\n \"drv\": \"Device Driver\",\n \"icns\": \"macOS Icon Resource File\",\n \"ico\": \"Icon File\",\n \"lnk\": \"Windows Shortcut\",\n \"sys\": \"Windows System File\",\n \"cfg\": \"Configuration File\",\n \"ini\": \"Windows Initialization File\",\n \"prf\": \"Outlook Profile File\",\n \"hqx\": \"BinHex 4.0 Encoded File\",\n \"mim\": \"Multi-Purpose Internet Mail Message File\",\n \"uue\": \"Uuencoded File\",\n \"7z\": \"7-Zip Compressed File\",\n \"cbr\": \"Comic Book RAR Archive\",\n \"deb\": \"Debian Software Package\",\n \"gz\": \"Gnu Zipped Archive\",\n \"pkg\": \"Mac OS X Installer Package\",\n \"rar\": \"WinRAR Compressed Archive\",\n \"rpm\": \"Red Hat Package Manager File\",\n \"sitx\": \"StuffIt X Archive\",\n \"tar.gz\": \"Compressed Tarball File\",\n \"zip\": \"Zipped File\",\n \"zipx\": \"Extended Zip Archive\",\n \"bin\": \"Binary Disc Image\",\n \"cue\": \"Cue Sheet File\",\n \"dmg\": \"Apple Disk Image\",\n \"iso\": \"Disc Image File\",\n \"mdf\": \"Media Disc Image File\",\n \"toast\": \"Toast Disc Image\",\n \"vcd\": \"Virtual CD\",\n \"c\": \"C/C++ Source Code File\",\n \"class\": \"Java Class File\",\n \"cpp\": \"C++ Source Code File\",\n \"cs\": \"C# Source Code File\",\n \"dtd\": \"Document Type Definition File\",\n \"fla\": \"Adobe Animate Animation\",\n \"h\": \"C/C++/Objective-C Header File\",\n \"java\": \"Java Source Code File\",\n \"lua\": \"Lua Source File\",\n \"m\": \"Objective-C Implementation File\",\n \"pl\": \"Perl Script\",\n \"py\": \"Python Script\",\n \"sh\": \"Bash Shell Script\",\n \"sln\": \"Visual Studio Solution File\",\n \"swift\": \"Swift Source Code File\",\n \"vb\": \"Visual Basic Project Item File\",\n \"vcxproj\": \"Visual C++ Project\",\n \"xcodeproj\": \"Xcode Project\",\n \"bak\": \"Backup File\",\n \"tmp\": \"Temporary File\",\n \"ics\": \"Calendar File\",\n \"msi\": \"Windows Installer Package\",\n \"part\": \"Partially Downloaded File\",\n \"torrent\": \"BitTorrent File\"\n}\n\n@cache\ndef decimal(num: str, base: int=2):\n \n dec = 0\n negative = False\n for pow, n in enumerate(num[::-1]):\n if n.isalpha():\n n = 10 + (ord(n.upper()) - 65)\n else:\n n = int(n)\n k = n * (base ** pow)\n dec += k\n if negative:\n dec *= -1\n return dec\n\n@cache\ndef non_decimal(dec: int, base: int=2):\n \n non_dec = \"\"\n negative = False\n dec = int(dec)\n while dec != 0:\n k = dec % base\n dec = dec // base\n if k > 9:\n l = chr(65 + (k - 10))\n non_dec += l\n else:\n non_dec += str(k)\n non_dec = non_dec[::-1]\n if negative:\n non_dec = \"-\" + non_dec\n return non_dec\n\n@cache\ndef get_id(addr: tuple):\n \n ip, port = addr\n ip = [\"{:0>3}\".format(part) for part in ip.split(\".\")]\n ip = \"\".join(ip)\n as_str = \"{}{:0>5}\".format(ip, port)\n as_int = int(as_str)\n digits = list(non_decimal(as_int, 36))\n digits.insert(3, \" \")\n digits.insert(8, \" \")\n key = \"\".join(digits)\n return key\n\n@cache\ndef get_addr(key: str):\n \n key = key.replace(\" \", \"\").upper()\n addr = str(decimal(key, 36))\n ip, port = addr[:-5], addr[-5:]\n port = int(port)\n ip_parts = ip[:3], ip[3:6], ip[6:9], ip[9:]\n ip_parts = map(int, ip_parts)\n ip_parts = map(str, ip_parts)\n ip = \".\".join(ip_parts)\n return ip, port\n\n@cache\ndef min_ip(ip1, ip2):\n \n if ip1 == ip2:\n return ip1\n if not ip1 or not all(c.isdigit() or c == \".\" for c in ip1):\n return ip2\n if not ip2 or not all(c.isdigit() or c == \".\" for c in ip2):\n return ip1\n ip1 = ip1.strip()\n ip2 = ip2.strip()\n ip1_parts = map(int, ip1.split(\".\"))\n ip2_parts = map(int, ip2.split(\".\"))\n for ip1_part, ip2_part in zip(ip1_parts, ip2_parts):\n if ip1_part == ip2_part:\n continue\n return ip1 if ip1_part < ip2_part else ip2\n\n@cache\ndef pretify_time(seconds):\n \n seconds = int(seconds)\n years, months, days, hours, minutes = 0, 0, 0, 0, 0\n if seconds >= 60:\n minutes = seconds // 60\n seconds = seconds % 60\n if minutes >= 60:\n hours = minutes // 60\n minutes = minutes % 60\n if hours >= 24:\n days = hours // 24\n hours = hours % 24\n if days >= 30:\n months = days // 30\n days = days % 30\n if months >= 12:\n years = months // 12\n months = months % 12\n as_str = ''\n if years:\n as_str += f\"{years} year\"\n as_str = as_str + 's' if years > 1 else as_str\n as_str += \" \"\n if days:\n days -= years * 5\n days -= years // 4\n if months:\n as_str += f\"{months} month\"\n as_str = as_str + 's' if months > 1 else as_str\n as_str += \" \"\n if days:\n as_str += f\"{days} day\"\n as_str = as_str + 's' if days > 1 else as_str\n as_str += \" \"\n if hours:\n as_str += f\"{hours} hour\"\n as_str = as_str + 's' if hours > 1 else as_str\n as_str += \" \"\n if minutes:\n as_str += f\"{minutes} minute\"\n as_str = as_str + 's' if minutes > 1 else as_str\n as_str += \" \"\n if seconds:\n as_str += f\"{seconds} second\"\n as_str = as_str + 's' if seconds > 1 else as_str\n return as_str\n\ndef is_accessable(path, for_visitor=False):\n logger.debug(path)\n if not os.path.exists(path):\n return False\n if not for_visitor:\n if os.path.isfile(path):\n dirname = os.path.dirname(os.path.abspath(path))\n return not dirname or is_accessable(dirname)\n try:\n cwd = os.getcwd()\n os.chdir(path)\n os.listdir()\n except Exception as exc:\n logger.error(exc)\n os.chdir(cwd)\n return False\n os.chdir(cwd)\n return True\n if path in configs.data['protected'] or not is_accessable(path):\n return False\n parts = split_path(path)\n for i in range(1, len(parts) + 1):\n sub_path = os.path.join(*parts[:i])\n if sub_path in configs.data['protected'] or not is_accessable(path):\n return False\n return True\n\n@cache\ndef available_drives():\n try:\n import win32api\n except ImportError:\n return []\n drives = win32api.GetLogicalDriveStrings()\n drives = drives.split('\\000')[:-1]\n return drives\n\n@cache\ndef pretify_timestamp(timestamp, fmt=\"%A %d %B %Y %I:%M:%S %p\"):\n dt = datetime.datetime.fromtimestamp(timestamp)\n return dt.strftime(fmt)\n\n@cache\ndef minimum_path(path):\n with lock:\n cwd = os.getcwd()\n lwd = cwd\n while True:\n try:\n os.chdir(\"..\")\n os.listdir()\n lwd = os.getcwd()\n except:\n os.chdir(cwd)\n return lwd\n\n@cache\ndef total_size(path):\n if os.path.isfile(path):\n return os.path.getsize(path)\n size = 0\n for f in list(traverse_dir(path)):\n if os.path.isfile(f):\n size += os.path.getsize(f)\n return size\n\n@cache\ndef pretify(m, do_round=True):\n \n try:\n m = float(int(m))\n except:\n return \"0 byte\"\n measures = ['byte', 'kb', 'mb', 'gb']\n i = 0\n while m and m >= (i + 1) * 1024:\n m = m / 1024\n i += 1\n if i >= 3:\n break\n if m % 1024 == 0 and m >= 1024 and i < 3:\n i += 1\n m /= 1024\n return f\"{round(m, 2) if not m.is_integer() else int(m)} {measures[i]}\" if do_round else str(m) + measures[i]\n\n@cache\ndef real_size(size):\n pat = r\"(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|B|KB|MB|GB)\"\n match = re.search(pat, size)\n if match:\n n, unit = match.groups()\n n = float(n)\n unit = unit.lower()\n to_multiply = {'b': 1, \"kb\": 1024, \"mb\": (1024 * 1024), \"gb\": 1024 * 1024 * 1024}\n return n * to_multiply.get(unit, 1)\n\n@cache\ndef pretify_path(path):\n if path.startswith(\"/storage\"):\n if \"/storage/emulated/0\" in path:\n path = path.replace(\"/storage/emulated/0\", \"Internal Storage\", 1)\n else:\n path = os.path.join(\"SD Card\", *split_path(path)[3:])\n return path\n\n@cache\ndef real_path(f):\n if \"internal storage\" in f.lower() or \"sd card\" in f.lower():\n folders = split_path(f)\n if \"internal storage\" in f.lower():\n i = [folder.lower() for folder in folders].index(\"internal storage\")\n folders.pop(i)\n folders.insert(0, \"0\")\n folders.insert(0, \"emulated\")\n folders.insert(0, \"/storage\")\n path = os.path.join(*folders)\n logger.debug(path)\n if os.path.exists(path):\n return path\n elif \"sd card\" in f.lower():\n try:\n cwd = os.getcwd()\n while os.getcwd() != \"/storage\":\n os.chdir(\"..\")\n dirs = os.listdir()\n dirs.remove(\"emulated\")\n dirs.remove(\"self\")\n if dirs:\n sd_card = dirs[0]\n i = [folder.lower() for folder in folders].index(\"sd card\")\n folders.pop(i)\n folders.insert(0, sd_card)\n folders.insert(0, \"/storage\")\n path = os.path.join(*folders)\n logger.debug(path)\n if os.path.exists(path):\n return path\n except Exception as exc:\n logger.error(exc)\n return f\n\n@cache\ndef split_path(path):\n \n splited = os.path.split(path)\n paths = list()\n while splited[1]:\n path, base = splited\n if base not in paths:\n paths.append(base)\n splited = os.path.split(path)\n if splited:\n paths.append(splited[0])\n paths.reverse()\n return paths\n\ndef _traverse_dir(path, depth):\n prev_wd = os.getcwd()\n try:\n os.chdir(path)\n items = os.listdir()\n except:\n items = []\n \n for f in items:\n if os.path.isfile(f):\n yield os.path.abspath(f)\n elif depth < 0 or depth != 0:\n yield from _traverse_dir(f, depth - 1)\n os.chdir(prev_wd)\n\ndef traverse_dir(path: str, depth=-1):\n if os.path.abspath(path) == \"/storage\":\n return list(_traverse_dir(path, depth)) + traverse_dir(\"/storage/emulated/0\") \n return list(_traverse_dir(path, depth))\n\ndef dirmap(dr, level=0, ignore=[], fillchar=\"\\t\"):\n \n if not os.path.exists(dr):\n return \"\"\n if os.path.isfile(dr):\n if os.path.abspath(dr) in ignore:\n return ''\n return os.path.basename(dr)\n prev_wd = os.getcwd()\n dr = os.path.abspath(dr)\n os.chdir(dr)\n dirmap_str = (fillchar * level) + os.path.split(dr)[1] + \":\\n\"\n items = os.listdir()\n items.sort(key=lambda item: item.startswith(\".\"))\n for f in items:\n if os.path.abspath(f) in ignore:\n continue\n if os.path.isfile(f):\n basename = os.path.basename(f)\n dirmap_str += fillchar * (level + 1) + basename + \"\\n\"\n for f in items:\n if os.path.abspath(f) in ignore:\n continue\n if os.path.isdir(f):\n basename = os.path.basename(f)\n dirmap_str += dirmap(f, level + 1, ignore, fillchar)\n os.chdir(prev_wd)\n return dirmap_str\n\ndef parse_dirmap(dirmap: str):\n \n paths = []\n lines = dirmap.splitlines()\n folders = [\"\"] * dirmap.count(\":\")\n for i, line in enumerate(lines):\n if line.endswith(\":\"):\n folder = line.strip()[:-1]\n level = line.count(\"\\t\")\n folders[level] = folder\n if i < len(lines) - 1 and lines[i + 1].count(\"\\t\") == level:\n path = os.path.join(*folders[:level], folder, \"\")\n paths.append(path)\n else:\n level = line.count(\"\\t\")\n file = line.strip()\n path = os.path.join(*folders[:level], file)\n paths.append(path)\n \n return paths\n\ndef parse_command(cmd_str):\n command = ''\n args = []\n for pattern in all_patterns:\n match = pattern.fullmatch(cmd_str)\n if match:\n groups = match.groupdict()\n for grp in sorted(groups):\n if groups[grp] is None:\n continue\n if grp == \"cmd\":\n command = groups[grp]\n elif grp.startswith(\"subcmd\"):\n command += \" \" + groups[grp]\n elif \"arg\" in grp:\n args.append(groups[grp])\n while None in args:\n args.remove(None)\n return (command, args)\n return (None, [])\n\ndef flexible_select(f, items=None, return_exact=False):\n if return_exact:\n items = os.listdir() if items is None else items.copy()\n else:\n items = [os.path.abspath(item) for item in os.listdir()] if items is None else items.copy()\n not_to_take = set()\n match = kw_pat1.search(f)\n f = kw_pat1.sub(\"\", f)\n if match is not None:\n kw = match.group(1)[1:-1]\n logger.warning((\"quoted keyword\", kw, f))\n pat = re.compile(kw)\n for item in items:\n if pat.search(os.path.basename) is None:\n not_to_take.add(item)\n ignore = ignore_pat.search(f)\n f = ignore_pat.sub(\"\", f)\n if ignore is not None:\n logger.warning((\"ignore\", ignore.group(1), f))\n for item in flexible_select(ignore.group(1), items):\n if item in items:\n items.remove(item)\n match = range_pat.search(f)\n f = range_pat.sub(\"\", f)\n if match is not None:\n f_str = match.group(1)\n logger.warning((\"consider\", f_str, f))\n targets = list(map(int, re.findall(r\"(\\d+)\", f_str)))\n logger.warning(targets)\n if re.fullmatch(r\"\\d+\\s*-\\s*\\d+\", f_str):\n targets = list(range(targets[0], targets[1] + 1))\n items = [items[i] for i in targets]\n takeonly = takeonly_pat.search(f)\n f = takeonly_pat.sub(\"\", f)\n takeonly = takeonly.group(1) if takeonly is not None else None\n for item in items:\n if takeonly is None:\n continue\n if takeonly == \"file\":\n if not os.path.isfile(item):\n not_to_take.add(item)\n elif takeonly in (\"folder\", \"dir\") and not os.path.isdir(item):\n not_to_take.add(item)\n else:\n ext = os.path.splitext(item)[1][1:].strip()\n if takeonly.startswith(\".\"):\n if not (ext == takeonly[1:].strip()):\n not_to_take.add(item)\n elif takeonly in (\"image\", \"photo\") and ext not in image_ext:\n not_to_take.add(item)\n elif takeonly == \"audio\" and ext not in audio_ext:\n not_to_take.add(item)\n elif takeonly == \"video\" and ext not in video_ext:\n not_to_take.add(item)\n elif takeonly == \"doc\" and ext not in doc_ext:\n not_to_take.add(item)\n for item in not_to_take:\n if item in items:\n items.remove(item)\n match = time_pat.search(f)\n f = time_pat.sub(\"\", f)\n if match:\n times = match.groupdict()\n logger.warning((\"time\", match.group(), f))\n start, end = times['time1'], times['time2']\n if \"now\" in start:\n start = datetime.datetime.now.timestamp()\n if end is None:\n end = start + 1\n elif \"today\" in start:\n m = re.search(r\"(\\d{2})(?::(\\d{2})(?::(\\d{2}))?)?\", start)\n logger.warning(m)\n extras = 0\n limit = 86400\n if m:\n h, m, s = m.groups()\n if h is not None:\n extras += int(h) * 3600\n limit = 3600\n if m is not None:\n extras += int(m) * 60\n limit = 60\n if s is not None:\n extras += int(s)\n limit = 1\n logger.warning(extras)\n start = today.timestamp()\n start = start + extras\n if end is None:\n end = start + limit\n elif \"yesterday\" in start:\n m = re.search(r\"(\\d{2})(?::(\\d{2})(?::(\\d{2}))?)?\", start)\n extras = 0\n limit = 86400\n if m:\n h, m, s = m.groups()\n if h is not None:\n extras += int(h) * 3600\n limit = 3600\n if m is not None:\n extras += int(m) * 60\n limit = 60\n if s is not None:\n extras += int(s)\n limit = 1\n start = today.timestamp() - 86400\n start += extras\n if end is None:\n end = start + limit\n else:\n pat = r\"(\\d{1,2})\\s*[./-]\\s*(\\d{1,2})\\s*[./-]\\s*(\\d{1,4})(?:\\s+(\\d{1,2})(?:\\s*:\\s*(\\d{1,2})(?:\\s*:\\s*(\\d{1,2}))?)?)?\"\n date = re.search(pat, match.group(0))\n if date is None:\n start = 0\n else:\n timetuple = list(date.groups())\n limit = 60 if timetuple[5] is None else None\n limit = 3600 if timetuple[4] is None else limit\n limit = 86400 if timetuple[3] is None else limit\n limit = 1 if limit is None else limit\n for i in range(len(timetuple)):\n if timetuple[i] is None:\n timetuple[i] = \"00\"\n prettydate = \"{}-{}-{} {}:{}:{}\".format(*timetuple)\n fmt = \"%d-%m-%Y %H:%M:%S\" if len(timetuple[2]) > 2 else \"%d-%m-%y %H:%M:%S\"\n start = datetime.datetime.strptime(prettydate, fmt).timestamp()\n logger.warning(\"start \" + datetime.datetime.fromtimestamp(start).strftime(\"%d-%m-%Y %H:%M:%S\"))\n if type(end) is float:\n pass\n elif \"now\" in end:\n end = datetime.datetime.now.timestamp()\n elif \"today\" in end:\n m = re.search(r\"(\\d{2})(?::(\\d{2})(?::(\\d{2}))?)?\", end)\n extras = 0\n if m:\n h, m, s = m.groups()\n if h is not None:\n extras += int(h) * 3600\n if m is not None:\n extras += int(m) * 60\n if s is not None:\n extras += int(s)\n end = today.timestamp() + 86399 - extras\n elif \"yesterday\" in end:\n m = re.search(r\"(\\d{2})(?::(\\d{2})(?::(\\d{2}))?)?\", end)\n extras = 0\n if m:\n h, m, s = m.groups()\n if h is not None:\n extras += int(h) * 3600\n if m is not None:\n extras += int(m) * 60\n if s is not None:\n extras += int(s)\n end = today.timestamp() - 1 - extras\n elif type(end) is not float:\n pat = r\"(\\d{1,2})\\s*[./-]\\s*(\\d{1,2})\\s*[./-]\\s*(\\d{1,4})(?:\\s+(\\d{1,2})(?:\\s*:\\s*(\\d{1,2})(?:\\s*:\\s*(\\d{1,2}))?)?)?\"\n date = re.search(pat, match.group(0))\n if date is None:\n end = datetime.datetime.now().timestamp()\n else:\n timetuple = list(date.groups())\n for i in range(len(timetuple)):\n if timetuple[i] is None:\n timetuple[i] = \"00\"\n prettydate = \"{}-{}-{} {}:{}:{}\".format(*timetuple)\n fmt = \"%d-%m-%Y %H:%M:%S\" if len(timetuple[2]) > 2 else \"%d-%m-%y %H:%M:%S\"\n end = datetime.datetime.strptime(prettydate, fmt).timestamp()\n logger.warning(\"end \" + datetime.datetime.fromtimestamp(end).strftime(\"%d-%m-%Y %H:%M:%S\"))\n if start is not None and end is not None:\n logger.warning((start, end))\n for item in items:\n stat = os.stat(item)\n ctime, mtime = stat.st_ctime, stat.st_mtime\n remove = True\n if start <= ctime and ctime <= end:\n remove = False\n if start <= mtime and mtime <= end:\n remove = False\n if remove:\n logger.warning((item, ctime, mtime))\n not_to_take.add(item)\n take = count_pat.search(f)\n f = count_pat.sub(\" \", f)\n take = take.groups() if take is not None else None\n logger.warning((\"take\", take, f))\n match = item_pat.search(f)\n f = item_pat.sub(\"\", f)\n if match is not None:\n f_str = match.group(1)\n logger.warning((\"items\", f_str, f))\n targets = list(map(int, re.findall(r\"(\\d+)\", f_str)))\n logger.warning(targets)\n if re.fullmatch(r\"\\d+\\s*-\\s*\\d+\", f_str):\n targets = list(range(targets[0], targets[1] + 1))\n for i in range(len(items)):\n if (i + 1) not in targets:\n not_to_take.add(items[i])\n match = timelimit_pat.search(f)\n f = timelimit_pat.sub(\"\", f)\n if match:\n logger.warning((\"timelimit\", match.group(), f))\n time_intervals = {'y': (86400 * 365), 'm': (86400 * 30), 'w': 86400 * 7, 'd': 86400, 'h': 3600, 'min': 60, 's': 1}\n param = match.group(2).lower()\n coefficient = int(match.group(1))\n max_interval = coefficient * time_intervals[param]\n logger.warning((\"max_interval\", max_interval))\n for item in items:\n stat = os.stat(item)\n if abs(stat.st_ctime - now.timestamp()) > max_interval and abs(stat.st_mtime - now.timestamp()) > max_interval:\n not_to_take.add(item)\n match = age_pat.search(f)\n f = age_pat.sub(\"\", f)\n if match:\n items.sort(key=lambda item: os.stat(item).st_ctime )\n if match.group(1) == \"new\":\n items.reverse()\n logger.debug(\"taking recents\")\n logger.debug(match.group())\n items = items[:int(match.group(2))]\n match = size_pat.search(f)\n f = size_pat.sub(\"\", f)\n if match:\n logger.warning(match.group())\n min_, max_ = match.groups()\n if max_ is None:\n size, unit = re.search(r\"(\\d+(?:\\.\\d+)?)([kmgKMB]?[bB])?\", min_).groups()\n unit = \"b\" if unit is None else unit\n size = float(size)\n x = size\n p = 1\n while not x.is_integer():\n x *= 10\n p *= 10\n size += (1 / p)\n size = str(size)\n max_ = size + unit\n logger.warning(max_)\n min_ = real_size(min_)\n max_ = real_size(max_)\n logger.warning((pretify(min_), pretify(max_, False), min_, max_))\n for item in items:\n size = total_size(item)\n if min_ <= size and size <= max_:\n continue\n not_to_take.add(item)\n match = kw_pat2.search(f)\n f = kw_pat2.sub(\"\", f)\n if match is not None and match.group(1) != \"all\":\n pat = re.compile(match.group(1))\n logger.warning((\"keyword\", match.group(1), f))\n for item in items:\n if pat.search(os.path.basename(item)) is None:\n not_to_take.add(item)\n for item in not_to_take:\n if item in items:\n items.remove(item)\n if take is not None:\n from_ = take[0]\n if from_ == \"l\":\n from_ = len(items) - int(take[1])\n to = len(items)\n elif from_ == \"f\" or from_ is None:\n from_ = 0\n to = int(take[1])\n else:\n n = int(take[1])\n if n == 0:\n return []\n from_ = (n * (int(take[0]) - 1))\n to = int(take[0]) * n\n logger.warning((\"taking\", from_, to, len(items)))\n items = items[from_ : to]\n return items\n \nclass Message:\n \n def __init__(self, content, headers={}):\n \n self.type = type(content)\n self.headers = {}\n if type(content) is str:\n self.body = content.encode(\"utf-8\")\n self.content = content\n self.headers['type'] = \"str\"\n elif type(content) is bytes:\n self.body = content\n self.content = content\n self.headers['type'] = \"bytes\"\n \n else:\n self.body = b''\n self.content = ''\n self.headers['type'] = 'unknown'\n self.headers['length'] = len(content)\n self.headers[\"sent_time\"] = str(int(datetime.datetime.now().timestamp()))\n self.headers[\"sender\"] = configs.data[\"name\"]\n self.headers[\"min_ip\"] = configs.min_ip\n self.headers.update(headers)\n \n @classmethod\n def from_bytes(cls, msg: bytes):\n \n headers_instr = msg[:configs.HEADER_SIZE].strip(configs.FILLCHAR.encode(\"utf-8\")).decode(\"utf-8\")\n body = msg[configs.HEADER_SIZE:]\n headers = {}\n \n for line in headers_instr.split(configs.HEADER_SEP):\n if line.isspace() or configs.HEADER_DELIMITER not in line:\n continue\n key, value = line.split(configs.HEADER_DELIMITER)\n headers[key] = value\n info = {}\n if headers['type'] == \"bytes\":\n return cls(body, headers)\n body = body.decode(\"utf-8\")\n if headers.get(\"type\") in (\"info\", \"response\", \"request\", \"intro\"):\n for line in body.split(configs.INFO_LINE_SEP):\n if line.isspace() or configs.INFO_DELIMITER not in line:\n continue\n key, value = line.split(configs.INFO_DELIMITER)\n info[key] = value.strip()\n return cls.info(info, headers)\n \n return cls(body, headers)\n \n @classmethod\n def info(cls, data: dict, headers={}):\n \n body = []\n for key, value in data.items():\n body.append(f\"{key}{configs.INFO_DELIMITER}{value}\")\n body = configs.INFO_LINE_SEP.join(body)\n body = body.encode(\"utf-8\")\n if \"type\" not in headers:\n headers[\"type\"] = \"info\"\n if \"length\" not in headers:\n headers[\"length\"] = str(len(body))\n s = cls(\"\", headers)\n s.type = dict\n s.content = data\n s.body = body\n return s\n \n def get_headers(self, *headers):\n \n res = []\n if not headers:\n return self.headers.copy()\n for header in headers:\n res.append(self.headers.get(header))\n return tuple(res)\n \n def __bytes__(self):\n headers = \"\"\n for key, value in self.headers.items():\n headers += f\"{key}{configs.HEADER_DELIMITER}{value}\\n\"\n headers = headers.ljust(configs.HEADER_SIZE, configs.FILLCHAR)\n headers = headers.encode(\"utf-8\")\n msg = headers + self.body\n return msg\n \n def __repr__(self):\n return str(bytes(self))\n\n\n#name: parsers.py\n#updated: 1612149066\n","sub_path":"src/python/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":36201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"592649516","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 ('store', '0002_auto_20150427_1943'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='item',\n name='condition',\n field=models.CharField(default=b'brand new', max_length=32, choices=[(b'brand new', b'Brand New'), (b'second owner', b'Second Owner'), (b'third owner', b'Third Owner'), (b'slightly used', b'Slightly Used')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"store/migrations/0003_auto_20150427_2009.py","file_name":"0003_auto_20150427_2009.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"584493348","text":"'''\ndo configuration.\n'''\n__author__='luibebetter'\n\nimport config_default\n\nclass Dict(dict):\n def __init__(self,names=(),values=(),**kw):\n super(Dict,self).__init__(**kw)\n for k,v in zip(names,values):\n self[k]=v\n def __getattr__(self,key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError('%s has no attribute %s'%(self.__class__.__name__,key))\n def __setattr__(self,key,value):\n self[key]=value\n\ndef toDict(d):\n D=Dict()\n for k,v in d.items():\n if isinstance(v,dict):\n D[k]=toDict(v)\n else:\n D[k]=v\n return D\n\n\n\ndef merge(default,override):\n '''\n merge configurations.\n '''\n result={}\n for k,v in default.items():\n if k in override:\n if isinstance(v,dict):\n merge(v,override.get(k))\n else:\n result[k]=override[k]\n else:\n result[k]=v\n for k,v in override.items():\n if k not in default:\n result[k]=v\n return result \n\nconfigs=config_default.configs\ntry:\n import config_override\n configs=merge(configs,config_override.configs)\nexcept ImportError:\n pass\n\nconfigs=toDict(configs)\n","sub_path":"www/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"35325076","text":"## 3 Ejercicio Crear un Formulario que usando el control Treeview muestre la una lista con los nombre de\n## Ciudades Argentinas y su código postal ( por lo menos 5 ciudades ) .\n\nfrom tkinter import *\nfrom tkinter import ttk\n\nroot = Tk()\nroot.configure(background=\"white\")\nroot.title(\"Lista de Ciudades\")\nroot.geometry(\"200x300\")\nroot.resizable(False, False)\n# Centra la ventana.\nroot.geometry(\n \"+{}+{}\".format(\n int(root.winfo_screenwidth() / 2 - root.winfo_reqwidth() / 2),\n int(root.winfo_screenheight() / 2 - root.winfo_reqheight() / 2),\n )\n)\nroot.protocol(\"WM_DELETE_WINDOW\", lambda: closeWindow(root))\n\n\ndef closeWindow(window):\n window.destroy()\n window.quit()\n\n\ndef createControls():\n treeView = ttk.Treeview(root, show=\"tree\")\n treeView.pack(fill=\"both\", expand=True)\n item = treeView.insert(\"\", END, text=\"Ciudades\")\n subitem = treeView.insert(item, END, text=\"Armstrong\")\n treeView.insert(subitem, END, text=\"CP 2508\")\n subitem = treeView.insert(item, END, text=\"Buenos Aires\")\n treeView.insert(subitem, END, text=\"CP 1000\")\n subitem = treeView.insert(item, END, text=\"Córdoba\")\n treeView.insert(subitem, END, text=\"CP 5000\")\n subitem = treeView.insert(item, END, text=\"La Plata\")\n treeView.insert(subitem, END, text=\"CP 1900\")\n subitem = treeView.insert(item, END, text=\"Mar del Plata\")\n treeView.insert(subitem, END, text=\"CP 7600\")\n subitem = treeView.insert(item, END, text=\"Rosario\")\n treeView.insert(subitem, END, text=\"CP 2000\")\n\n\nif __name__ == \"__main__\":\n createControls()\n root.mainloop()\n","sub_path":"practico_04/ejercicio03.py","file_name":"ejercicio03.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"186974949","text":"from .category import Category\n\n\nclass Product:\n def __init__(self, category_id, description, price, title, favorite, img_url):\n self.category_id = category_id\n self.description = description\n self.price = price\n self.title = title\n self.favorite = \"1\" if favorite == \"on\" else \"0\"\n self.img_url = img_url\n","sub_path":"entities/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"226489337","text":"global TestList\nTestList = [1, 2, 3]\ndef reverse(items):\n if isinstance(items,list):\n length_of_list = len (items)\n reversedList = []\n counter = 0\n while counter < length_of_list:\n buffer = items[length_of_list-1-counter]\n reversedList.append(buffer)\n counter +=1\n counter = 0\n while counter < length_of_list:\n TestList[counter] = reversedList[counter]\n counter +=1\n del reversedList\n else:\n print ('Given argument is non a list')\nreverse(TestList)\nprint (TestList)\nassert TestList == [3, 2, 1]\n\n\n","sub_path":"Reverse3.py","file_name":"Reverse3.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"560668546","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUnit tests for the GPFA analysis.\n\n:copyright: Copyright 2014-2016 by the Elephant team, see AUTHORS.txt.\n:license: Modified BSD, see LICENSE.txt for details.\n\"\"\"\n\nimport sys\nimport unittest\n\nimport neo\nimport numpy as np\nimport quantities as pq\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom elephant.spike_train_generation import homogeneous_poisson_process\n\ntry:\n import sklearn\nexcept ImportError:\n HAVE_SKLEARN = False\nelse:\n HAVE_SKLEARN = True\n from elephant.gpfa_src import gpfa_util\n from elephant.gpfa import gpfa\n\npython_version_major = sys.version_info.major\n\n\n@unittest.skipUnless(HAVE_SKLEARN, 'requires sklearn')\nclass GPFATestCase(unittest.TestCase):\n def setUp(self):\n def gen_gamma_spike_train(k, theta, t_max):\n x = []\n for i in range(int(3 * t_max / (k*theta))):\n x.append(np.random.gamma(k, theta))\n s = np.cumsum(x)\n return s[s < t_max]\n\n def gen_test_data(rates, durs, shapes=(1, 1, 1, 1)):\n s = gen_gamma_spike_train(shapes[0], 1./rates[0], durs[0])\n for i in range(1, 4):\n s_i = gen_gamma_spike_train(shapes[i], 1./rates[i], durs[i])\n s = np.concatenate([s, s_i + np.sum(durs[:i])])\n return s\n\n self.n_iters = 10\n self.bin_size = 20 * pq.ms\n\n # generate data1\n rates_a = (2, 10, 2, 2)\n rates_b = (2, 2, 10, 2)\n durs = (2.5, 2.5, 2.5, 2.5)\n self.data1 = []\n for tr in range(1):\n np.random.seed(tr)\n n1 = neo.SpikeTrain(gen_test_data(rates_a, durs), units=1*pq.s,\n t_start=0*pq.s, t_stop=10*pq.s)\n n2 = neo.SpikeTrain(gen_test_data(rates_a, durs), units=1*pq.s,\n t_start=0*pq.s, t_stop=10*pq.s)\n n3 = neo.SpikeTrain(gen_test_data(rates_b, durs), units=1*pq.s,\n t_start=0*pq.s, t_stop=10*pq.s)\n n4 = neo.SpikeTrain(gen_test_data(rates_b, durs), units=1*pq.s,\n t_start=0*pq.s, t_stop=10*pq.s)\n self.data1.append((tr, [n1, n2, n3, n4]))\n self.x_dim = 4\n\n # generate data2\n np.random.seed(27)\n self.data2 = []\n n_trials = 10\n n_channels = 20\n for trial in range(n_trials):\n rates = np.random.randint(low=1, high=100, size=n_channels)\n spike_times = [homogeneous_poisson_process(rate=rate*pq.Hz)\n for rate in rates]\n self.data2.append((trial, spike_times))\n\n def test_data1(self):\n params_est, seqs_train, fit_info = gpfa(\n self.data1, x_dim=self.x_dim, em_max_iters=self.n_iters)\n self.assertEqual(fit_info['bin_size'], 20*pq.ms)\n self.assertEqual(fit_info['min_var_frac'], 0.01)\n self.assertTrue(np.all(fit_info['has_spikes_bool']))\n self.assertAlmostEqual(fit_info['log_likelihood'], -27.222600197474762)\n # Since data1 is inherently 2 dimensional, only the first two\n # dimensions of xorth should have finite power.\n for i in [0, 1]:\n self.assertNotEqual(seqs_train['xorth'][0][i].mean(), 0)\n self.assertNotEqual(seqs_train['xorth'][0][i].var(), 0)\n for i in [2, 3]:\n self.assertEqual(seqs_train['xorth'][0][i].mean(), 0)\n self.assertEqual(seqs_train['xorth'][0][i].var(), 0)\n\n def test_invalid_input_data(self):\n invalid_data = [(0, [0, 1, 2])]\n invalid_bin_size = 10\n with self.assertRaises(ValueError):\n gpfa(data=invalid_data)\n with self.assertRaises(ValueError):\n gpfa(data=[])\n with self.assertRaises(ValueError):\n gpfa(data=self.data2, bin_size=invalid_bin_size)\n\n def test_data2(self):\n params_est, seqs_train, fit_info = gpfa(\n self.data2, bin_size=self.bin_size, x_dim=8,\n em_max_iters=self.n_iters)\n self.assertEqual(fit_info['bin_size'], self.bin_size,\n \"Input and output bin_size don't match\")\n n_trials = len(self.data2)\n t_start = self.data2[0][1][0].t_stop\n t_stop = self.data2[0][1][0].t_start\n n_bins = int(((t_start - t_stop) / self.bin_size).magnitude)\n assert_array_equal(seqs_train['T'], [n_bins,] * n_trials)\n assert_array_equal(seqs_train['trialId'], np.arange(n_trials))\n for key in ['y', 'xsm', 'Vsm', 'VsmGP', 'xorth']:\n self.assertEqual(len(seqs_train[key]), n_trials,\n msg=\"Failed ndarray field {0}\".format(key))\n self.assertEqual(len(seqs_train), n_trials)\n\n def test_get_seq_sqrt(self):\n data = [self.data2[0]]\n seqs = gpfa_util.get_seq(data, bin_size=self.bin_size)\n seqs_not_sqrt = gpfa_util.get_seq(data, bin_size=self.bin_size,\n use_sqrt=False)\n for common_key in ('trialId', 'T'):\n self.assertEqual(seqs[common_key], seqs_not_sqrt[common_key])\n self.assertEqual(seqs['y'].shape, seqs_not_sqrt['y'].shape)\n\n def test_cut_trials_inf(self):\n same_data = gpfa_util.cut_trials(self.data2, seg_length=np.Inf)\n assert same_data is self.data2\n\n def test_cut_trials_zero_length(self):\n seqs = gpfa_util.get_seq(self.data2, bin_size=self.bin_size)\n with self.assertRaises(ValueError):\n gpfa_util.cut_trials(seqs, seg_length=0)\n\n def test_cut_trials_same_length(self):\n data = [self.data2[0]]\n seqs = gpfa_util.get_seq(data, bin_size=self.bin_size)\n seg_length = seqs[0]['T']\n seqs_cut = gpfa_util.cut_trials(seqs, seg_length=seg_length)\n assert_array_almost_equal(seqs[0]['y'], seqs_cut[0]['y'])\n\n @unittest.skipUnless(python_version_major == 3, \"assertWarns requires 3.2\")\n def test_cut_trials_larger_length(self):\n data = [self.data2[0]]\n seqs = gpfa_util.get_seq(data, bin_size=self.bin_size)\n seg_length = seqs[0]['T'] + 1\n with self.assertWarns(UserWarning):\n gpfa_util.cut_trials(seqs, seg_length=seg_length)\n\n def test_logdet(self):\n np.random.seed(27)\n # generate a positive definite matrix\n matrix = np.random.randn(20, 20)\n matrix = matrix.dot(matrix.T)\n logdet_fast = gpfa_util.logdet(matrix)\n logdet_ground_truth = np.log(np.linalg.det(matrix))\n assert_array_almost_equal(logdet_fast, logdet_ground_truth)\n\n\ndef suite():\n suite = unittest.makeSuite(GPFATestCase, 'test')\n return suite\n\n\ndef run():\n runner = unittest.TextTestRunner(verbosity=2)\n runner.run(suite())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"elephant/test/test_gpfa.py","file_name":"test_gpfa.py","file_ext":"py","file_size_in_byte":6774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"171273143","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport derivatives as der\r\ndef bisection_auto(lower,upper,function,epsilon=1e-6,max_iteration=100000):\r\n \"\"\"\r\n condition\r\n |f(xn)|<epsilon\r\n xn=approximation of zero of function\r\n \"\"\"\r\n temp=2*epsilon\r\n itr=0\r\n while abs(temp)>epsilon:\r\n c=(upper+lower)/2\r\n temp=function(c)\r\n if temp==0:\r\n return c\r\n elif temp*function(upper)<0:\r\n if function(lower)==0:\r\n return lower\r\n lower=c\r\n else:\r\n if function(upper)==0:\r\n return upper\r\n upper=c\r\n if itr>max_iteration:\r\n print('bisection auto method may not converge')\r\n return c\r\n itr=itr+1\r\n return c\r\ndef bisection_itr(lower,upper,function,delta=1e-6):\r\n \"\"\"\r\n condition\r\n |xn-s|<delta\r\n s=true zero of function\r\n xn=approximation of zero of function\r\n \"\"\"\r\n max_itr=int(np.log(abs(upper-lower)/(2*delta))/np.log(2))+1\r\n for i in range(max_itr):\r\n c=(upper+lower)/2\r\n temp=function(c)\r\n if temp==0:\r\n return c\r\n elif temp*function(upper)<0:\r\n if function(lower)==0:\r\n return lower\r\n lower=c\r\n else:\r\n if function(upper)==0:\r\n return upper\r\n upper=c\r\n return c\r\ndef newton_rapshon(start,function,epsilon=1e-6,h=0.001,max_iteration=10000):\r\n \"\"\"\r\n condition\r\n |f(xn)|<epsilon\r\n xn=approximation of zero of function\r\n \r\n \"\"\"\r\n temp=2*epsilon\r\n x=start\r\n itr=0\r\n if function(x)==0:\r\n return x\r\n while abs(temp)>epsilon:\r\n x=x-function(x)/der.derivative_3p(x,function,h)\r\n temp=function(x)\r\n if itr>max_iteration:\r\n print('newton rapshon method may not converging')\r\n return x\r\n itr=itr+1\r\n\r\n return x\r\n\r\ndef newton_rapshon_2d(x1_start,x2_start,function1,function2,epsilon=1e-6,h=0.001,max_iteration=100000):\r\n \"\"\"\r\n function1 = lambda x1,x2:f1(x1,x2)\r\n function2 = lambda x1,x2:f2(x1,x2)\r\n max_iteration = maximum iteration to run for newton rapshon if exceed then stop method may not converge\r\n \"\"\"\r\n temp1,temp2=2*epsilon,2*epsilon\r\n x1=x1_start\r\n x2=x2_start\r\n if function1(x1,x2)==0 and function1(x1,x2)==0:\r\n return x1,x2\r\n x=np.array([x1,x2]).reshape(2,1)\r\n f=np.zeros((2,1))\r\n empty=np.zeros((2,2))\r\n itr=0\r\n while (abs(temp1)>epsilon and abs(temp2)>epsilon):\r\n f[0,0],f[1,0]=function1(x[0,0],x[1,0]),function2(x[0,0],x[1,0])\r\n empty[0,0],empty[0,1]=der.partial_derivative_3p(x[0,0],x[1,0],function1,h)\r\n empty[1,0],empty[1,1]=der.partial_derivative_3p(x[0,0],x[1,0],function2,h)\r\n x=x-np.dot(np.linalg.inv(empty),f)\r\n temp1,temp2=function1(x[0,0],x[1,0]),function2(x[0,0],x[1,0])\r\n if itr>max_iteration:\r\n print('newton rapshon 2d method may not converging')\r\n return x[0,0],x[1,0]\r\n itr=itr+1\r\n return x[0,0],x[1,0]\r\n\r\ndef extremum(lower,upper,function,epsilon=1e-6,h=0.001,method='newton_rapshon',max_iteration=100000,step=2,kind=False):\r\n \"\"\"\r\n function = lambda x:f(x)\r\n method = newton_rapshon,bisection_itr,bisection_auto\r\n lower=lower value for bisection method, start value for newton rapshon\r\n upper=upper value for bisection method , give any random value for newton rapshon\r\n max_iteration = maximum iteration to run for newton rapshon or bisection auto if exceed then stop method may not converge\r\n step = number of step taken to check extremum\r\n return extremum point , kind of extremum :: if kind = True\r\n return extremum point :: if kind =False\r\n \"\"\"\r\n if method=='newton_rapshon':\r\n ext=newton_rapshon(lower,lambda x:der.derivative_3p(x,function,h),epsilon,h,max_iteration)\r\n elif method=='bisection_auto':\r\n ext=bisection_auto(lower,upper,lambda x:der.derivative_3p(x,function,h),epsilon,max_iteration)\r\n elif method=='bisection_itr':\r\n ext=bisection_itr(lower,upper,lambda x:der.derivative_3p(x,function,h),epsilon)\r\n t1=function(ext-h*step)\r\n t2=function(ext)\r\n t3=function(ext+h*step)\r\n if t1>t2 and t3>t2:\r\n kind = 'minima'\r\n elif t2>t1 and t2>t3:\r\n kind = 'maxima'\r\n else:\r\n kind = 'saddle'\r\n if kind:\r\n return ext,kind\r\n else:\r\n return ext\r\n\r\n\r\n\r\n\r\n","sub_path":"code/function_zeros.py","file_name":"function_zeros.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"635675269","text":"import json\nimport os\nfrom tempfile import mkdtemp\n\nimport pytest\nfrom regipy.hive_types import NTUSER_HIVE_TYPE\nfrom regipy.plugins.utils import dump_hive_to_json\n\nfrom regipy.recovery import apply_transaction_logs\nfrom regipy.regdiff import compare_hives\nfrom regipy.registry import RegistryHive, NKRecord\n\n\ndef test_parse_header(ntuser_hive):\n registry_hive = RegistryHive(ntuser_hive)\n\n assert isinstance(registry_hive, RegistryHive)\n assert registry_hive.header.primary_sequence_num == 744\n assert registry_hive.header.secondary_sequence_num == 744\n assert registry_hive.header.last_modification_time == 129782982453388850\n assert registry_hive.header.major_version == 1\n assert registry_hive.header.minor_version == 3\n assert registry_hive.header.root_key_offset == 32\n assert registry_hive.header.hive_bins_data_size == 733184\n assert registry_hive.header.minor_version == 3\n assert registry_hive.header.file_name == '?\\\\C:\\\\Users\\\\vibranium\\\\ntuser.dat'\n assert registry_hive.header.checksum == 448714443\n\n\ndef test_parse_root_key(ntuser_hive):\n registry_hive = RegistryHive(ntuser_hive)\n\n assert isinstance(registry_hive, RegistryHive)\n assert isinstance(registry_hive.root, NKRecord)\n assert registry_hive.root.name == 'CMI-CreateHive{6A1C4018-979D-4291-A7DC-7AED1C75B67C}'\n assert registry_hive.root.subkey_count == 11\n assert dict(registry_hive.root.header) == {\n 'access_bits': b'\\x00\\x00\\x00\\x00',\n 'class_name_offset': 4294967295,\n 'class_name_size': 0,\n 'flags': {\n 'KEY_COMP_NAME': True,\n 'KEY_HIVE_ENTRY': True,\n 'KEY_HIVE_EXIT': False,\n 'KEY_NO_DELETE': True,\n 'KEY_PREDEF_HANDLE': False,\n 'KEY_SYM_LINK': False,\n 'KEY_VOLATILE': False\n },\n 'key_name_size': 52,\n 'key_name_string': b'CMI-CreateHive{6A1C4018-979D-4291-A7DC-7AED1C75B67C}',\n 'largest_sk_class_name': 0,\n 'largest_sk_name': 40,\n 'largest_value_name': 0,\n 'last_modified': 129780243434537497,\n 'largest_value_data': 0,\n 'parent_key_offset': 1656,\n 'security_list_offset': 1376,\n 'subkey_count': 11,\n 'subkeys_list_offset': 73760,\n 'values_count': 0,\n 'values_list_offset': 4294967295,\n 'volatile_subkey_count': 2,\n 'volatile_subkeys_list_offset': 2147486280\n }\n\n\ndef test_find_keys_ntuser(ntuser_hive):\n registry_hive = RegistryHive(ntuser_hive)\n run_key = registry_hive.get_key(r'\\Software\\Microsoft\\Windows\\CurrentVersion\\Run')\n\n assert run_key.name == 'Run'\n assert run_key.header.last_modified == 129779615948377168\n\n values = [x for x in run_key.iter_values(as_json=True)]\n assert values[0].name == 'Sidebar'\n assert values[0].value_type == 'REG_EXPAND_SZ'\n\n\ndef test_find_keys_partial_ntuser_hive(ntuser_software_partial):\n registry_hive = RegistryHive(ntuser_software_partial, hive_type=NTUSER_HIVE_TYPE, partial_hive_path=r'\\Software')\n\n run_key = registry_hive.get_key(r'\\Software\\Microsoft\\Windows\\CurrentVersion\\Run')\n assert run_key.name == 'Run'\n assert run_key.header.last_modified == 132024690510209250\n\n values = [x for x in run_key.iter_values(as_json=True)]\n assert values[0].name == 'OneDrive'\n assert values[0].value_type == 'REG_SZ'\n\n\ndef test_ntuser_timeline(ntuser_hive):\n registry_hive = RegistryHive(ntuser_hive)\n # TODO\n pass\n\n\ndef test_regdiff(ntuser_hive, second_hive_path):\n found_differences = compare_hives(ntuser_hive, second_hive_path, verbose=True)\n assert len(found_differences) == 2\n assert len([x for x in found_differences if x[0] == 'new_subkey']) == 1\n assert len([x for x in found_differences if x[0] == 'new_value']) == 1\n\n\ndef test_ntuser_emojis(transaction_ntuser):\n # There are some cases where the Registry stores utf-16 emojis as subkey names :)\n registry_hive = RegistryHive(transaction_ntuser)\n international = registry_hive.get_key(r'\\Control Panel\\International')\n subkeys = [x.name for x in international.iter_subkeys()]\n assert subkeys == ['Geo', 'User Profile', 'User Profile System Backup', '🌎🌏🌍']\n\n\ndef test_recurse_ntuser(ntuser_hive):\n registry_hive = RegistryHive(ntuser_hive)\n\n value_types = {\n 'REG_BINARY': 0,\n 'REG_DWORD': 0,\n 'REG_EXPAND_SZ': 0,\n 'REG_MULTI_SZ': 0,\n 'REG_NONE': 0,\n 'REG_QWORD': 0,\n 'REG_SZ': 0\n }\n\n subkey_count = 0\n values_count = 0\n for subkey in registry_hive.recurse_subkeys(as_json=True):\n subkey_values = subkey.values\n subkey_count += 1\n values_count += len(subkey_values or [])\n if subkey_values:\n for x in subkey_values:\n value_types[x['value_type']] += 1\n\n assert subkey_count == 1807\n assert values_count == 4088\n assert value_types == {\n 'REG_BINARY': 531,\n 'REG_DWORD': 1336,\n 'REG_EXPAND_SZ': 93,\n 'REG_MULTI_SZ': 303,\n 'REG_NONE': 141,\n 'REG_QWORD': 54,\n 'REG_SZ': 1630\n }\n\n\ndef test_recurse_partial_ntuser(ntuser_software_partial):\n registry_hive = RegistryHive(ntuser_software_partial, hive_type=NTUSER_HIVE_TYPE, partial_hive_path=r'\\Software')\n for subkey_count, subkey in enumerate(registry_hive.recurse_subkeys(as_json=True)):\n assert subkey.actual_path.startswith(registry_hive.partial_hive_path)\n assert subkey_count == 6395\n\n\ndef test_recurse_amcache(amcache_hive):\n registry_hive = RegistryHive(amcache_hive)\n\n value_types = {\n 'REG_BINARY': 0,\n 'REG_DWORD': 0,\n 'REG_EXPAND_SZ': 0,\n 'REG_MULTI_SZ': 0,\n 'REG_NONE': 0,\n 'REG_QWORD': 0,\n 'REG_SZ': 0\n }\n subkey_count = 0\n values_count = 0\n for subkey in registry_hive.recurse_subkeys():\n subkey_count += 1\n subkey_values = subkey.values\n values_count += len(subkey_values or [])\n if subkey_values:\n for x in subkey_values:\n value_types[x.value_type] += 1\n assert subkey_count == 2105\n assert values_count == 17539\n assert value_types == {\n 'REG_BINARY': 56,\n 'REG_DWORD': 1656,\n 'REG_EXPAND_SZ': 0,\n 'REG_MULTI_SZ': 140,\n 'REG_NONE': 0,\n 'REG_QWORD': 1254,\n 'REG_SZ': 14433\n }\n\n\ndef test_ntuser_apply_transaction_logs(transaction_ntuser, transaction_log):\n output_path = os.path.join(mkdtemp(), 'recovered_hive.dat')\n restored_hive_path, recovered_dirty_pages_count = apply_transaction_logs(transaction_ntuser, transaction_log,\n restored_hive_path=output_path)\n assert recovered_dirty_pages_count == 132\n\n found_differences = compare_hives(transaction_ntuser, restored_hive_path)\n assert len(found_differences) == 588\n assert len([x for x in found_differences if x[0] == 'new_subkey']) == 527\n assert len([x for x in found_differences if x[0] == 'new_value']) == 60\n\n\ndef test_system_apply_transaction_logs(transaction_system, system_tr_log_1, system_tr_log_2):\n output_path = os.path.join(mkdtemp(), 'recovered_hive.dat')\n restored_hive_path, recovered_dirty_pages_count = apply_transaction_logs(transaction_system,\n primary_log_path=system_tr_log_1,\n secondary_log_path=system_tr_log_2,\n restored_hive_path=output_path)\n assert recovered_dirty_pages_count == 315\n\n found_differences = compare_hives(transaction_system, restored_hive_path)\n assert len(found_differences) == 2506\n assert len([x for x in found_differences if x[0] == 'new_subkey']) == 2458\n assert len([x for x in found_differences if x[0] == 'new_value']) == 48\n\n\ndef test_system_apply_transaction_logs_2(transaction_usrclass, usrclass_tr_log_1, usrclass_tr_log_2):\n output_path = os.path.join(mkdtemp(), 'recovered_hive.dat')\n restored_hive_path, recovered_dirty_pages_count = apply_transaction_logs(transaction_usrclass,\n primary_log_path=usrclass_tr_log_1,\n secondary_log_path=usrclass_tr_log_2,\n restored_hive_path=output_path)\n assert recovered_dirty_pages_count == 158\n\n found_differences = compare_hives(transaction_usrclass, restored_hive_path)\n assert len(found_differences) == 225\n assert len([x for x in found_differences if x[0] == 'new_subkey']) == 93\n assert len([x for x in found_differences if x[0] == 'new_value']) == 132\n\n\ndef test_hive_serialization(ntuser_hive, temp_output_file):\n registry_hive = RegistryHive(ntuser_hive)\n dump_hive_to_json(registry_hive, temp_output_file, registry_hive.root, verbose=False)\n counter = 0\n with open(temp_output_file, 'r') as dumped_hive:\n for x in dumped_hive.readlines():\n assert json.loads(x)\n counter += 1\n assert counter == 1807\n\n\ndef test_get_key(software_hive):\n \"\"\"\n # Refers to https://github.com/mkorman90/regipy/issues/144\n \"\"\"\n registry_hive = RegistryHive(software_hive)\n # We verify the registry headers are similar, because this is the same subkey.\n assert registry_hive.get_key('ODBC').header == registry_hive.root.get_subkey('ODBC').header\n assert registry_hive.root.get_subkey('ODBC').header == registry_hive.get_key('SOFTWARE\\ODBC').header\n","sub_path":"regipy_tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":9720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"115371201","text":"import colors\nimport pygame\nimport settings\n\n\nclass background(object):\n X_SPACING = 100\n Y_SPACING = 100\n LINE_THICKNESS = 1\n\n BACKGROUND_COLOR = colors.WARM_WHITE\n SECONDARY_COLOR = colors.GRAY126\n OUTZONE_COLOR = colors.LIGHT_PINK\n\n def __init__(self, min_x, max_x, min_y, max_y, width, height, line_thickness=None, x_spacing=None, y_spacing=None):\n self.width = width\n self.height = height\n\n self.mix_x = min_x\n self.max_x = max_x\n self.min_y = min_y\n self.max_y = max_y\n\n self.line_thickness = line_thickness or background.LINE_THICKNESS\n self.x_spacing = x_spacing or background.X_SPACING\n self.y_spacing = y_spacing or background.Y_SPACING\n\n def draw(self, surface, camera_x, camera_y, scl):\n camera_x, camera_y = camera_x * scl, camera_y * scl\n width, height = self.width, self.height\n top = int(camera_y - height / 2)\n right = int(camera_x - width / 2)\n buttom = int(camera_y + height / 2)\n left = int(camera_x + width / 2)\n\n surface.fill(background.BACKGROUND_COLOR)\n for x in filter(lambda x: x % int((self.line_thickness + self.x_spacing) * scl) == 0, xrange(right, left + 1)):\n pygame.draw.line(surface, background.SECONDARY_COLOR,\n (x - right, 0), (x - right, height), self.line_thickness)\n\n for y in filter(lambda y: y % int((self.line_thickness + self.y_spacing) * scl) == 0, xrange(top, buttom + 1)):\n pygame.draw.line(surface, background.SECONDARY_COLOR,\n (0, y - top), (width, y - top), self.line_thickness)\n\n for x in filter(lambda x: x < self.mix_x or x > self.max_x, xrange(right, left + 1)):\n pygame.draw.line(surface, background.OUTZONE_COLOR,\n (x - right, 0), (x - right, height), 1)\n\n for y in filter(lambda y: y < self.min_y or y > self.max_y, xrange(top, buttom + 1)):\n pygame.draw.line(surface, background.OUTZONE_COLOR,\n (0, y - top), (width, y - top), 1)\n\n\ndef message_display(surface, text, x, y, size):\n font = pygame.font.Font('freesansbold.ttf', size)\n textSurface = font.render(text, True, colors.GRAY25)\n TextRect = textSurface.get_rect()\n TextRect.center = (x, y)\n surface.blit(textSurface, TextRect)\n","sub_path":"client/src/Version_1/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"501310030","text":"import gym\nfrom gym import error, spaces, utils, GoalEnv\nfrom gym.utils import seeding\nfrom gym import spaces\nimport numpy as np\nfrom bp_action_space import BPActionSpace\nimport random\n\n\nclass BPEnv(gym.Env):\n metadata = {'render.modes': ['human']}\n\n def __init__(self):\n self.bprogram_generator = None\n self.action_space = None\n self.observation_space = None\n self.last_state = None\n self.bprogram = None\n self.np_random = None\n self.last_event = None\n self.hot_states = None\n self.episode_timeout = None\n self.steps_counter = None\n self.action_mapper = None\n\n def step(self, action):\n #print(action)\n if isinstance(self.action_space, spaces.Discrete):\n action_name = self.action_mapper[action]\n l = self.bprogram.event_selection_strategy.selectable_events(self.bprogram.tickets)\n action_options = [x for x in l if x.name == action_name]\n if len(action_options) == 0:\n #reward = self._reward()\n reward = -1\n self.steps_counter += 1\n return self.last_state, reward, True, {}\n else:\n action = action_options[0]\n\n self.bprogram.advance_bthreads(action)\n if self.observation_space:\n new_state = self.state_to_gym_space(False)\n else:\n new_state = \"_\".join([str(x.get('state', 'D')) for x in self.bprogram.tickets])\n reward = self._reward()\n self.steps_counter += 1\n bprogram_done = self.bprogram.event_selection_strategy.selectable_events(self.bprogram.tickets).__len__() == 0\n #bprogram_done = bprogram_done or self.steps_counter == self.episode_timeout \n bprogram_done = bprogram_done or self.steps_counter == self.episode_timeout or (self.last_state == new_state).all() or reward > 0\n self.last_state = new_state\n #print(new_state)\n return new_state, reward, bprogram_done, {}\n\n def reset(self):\n self.steps_counter = 0\n self.last_event = None\n self.bprogram = self.bprogram_generator()\n #self.action_space.bprogram = self.bprogram\n self.bprogram.setup()\n if self.observation_space:\n state = self.state_to_gym_space(True)\n else:\n state = \"_\".join([str(x.get('state', 'D')) for x in self.bprogram.tickets])\n self.hot_states = [False] * len(self.bprogram.tickets)\n self.last_state = state\n #print(state)\n return state\n\n def render(self, mode='human', close=False):\n raise NotImplementedError\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def set_bprogram_generator(self, bprogram_generator):\n self.bprogram_generator = bprogram_generator\n\n def must_finish(self):\n return [x.get('must_finish', False) for x in self.bprogram.tickets]\n\n def state_to_gym_space(self, initial):\n bt_states = [str(x.get('state')) for x in self.bprogram.tickets if 'state' in x]\n if initial:\n bt_states.append(\"1\")\n else:\n bt_states.append(\"0\")\n return np.array(\"_\".join(bt_states).split(\"_\")).astype(np.float32)\n\n def _reward(self):\n reward = 0\n new_hot_states = self.must_finish()\n for j in range(len(self.hot_states)):\n if self.hot_states[j] and not new_hot_states[j]:\n reward += 1\n if not self.hot_states[j] and new_hot_states[j]:\n reward += -1\n self.hot_states = new_hot_states\n # if reward == 0 and any(new_hot_states):\n # reward = -0.001\n return reward\n \n def replace_if_disabled(self, action):\n action_name = self.action_mapper[action]\n l = self.bprogram.event_selection_strategy.selectable_events(self.bprogram.tickets)\n action_options = [x for x in l if x.name == action_name]\n if len(action_options) == 0:\n possible_keys = []\n for n in l:\n possible_keys.append([k for k,v in self.action_mapper.items() if n.name == v][0])\n return random.choice(possible_keys)\n else:\n return action\n","sub_path":"bp_env.py","file_name":"bp_env.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"468974129","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = \"Kevin M. Jablonka\"\n_license__ = \"MIT\"\n__version__ = \"0.1.0\"\n__email__ = \"kevin.jablonka@epfl.ch\"\n__status__ = \"Dev\"\n\nimport concurrent.futures\nfrom .utils import get_structure_list\nfrom tqdm.autonotebook import tqdm\nimport logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nfrom pymatgen import Structure\nimport pandas as pd\nfrom .filter_metal_channels import get_channels, get_metallic_substructure, \\\n get_structure_properties, get_metal_metadata, get_channel_dimensionality\nfrom structure_comp.checker import Checker\nfrom functools import partial\nfrom .utils import get_bibliometric_information\nfrom .utils import isnotebook\n\nclass ScreenMetalChannel():\n def __init__(self,\n structure_list: list,\n njobs: int = 2,\n feature_mode: str = 'cheap',\n other_metals: list = ['Al', 'In', 'Ga']\n ):\n self.structure_list = structure_list\n self.njobs = njobs\n self.feature_mode = feature_mode\n self.other_metals = other_metals\n\n if isnotebook():\n logger.warning('the code is untested in notebook enviornments and is likely to not work there')\n\n @classmethod\n def from_folders(cls,\n folder_1: str,\n extension: str = 'cif',\n njobs=2,\n feature_mode: str = 'cheap'):\n \"\"\"Constructor method for a ScreenMetalChannel object\"\"\"\n sl_1 = get_structure_list(folder_1, extension)\n return cls(sl_1, njobs=njobs, feature_mode=feature_mode)\n\n @staticmethod\n def _check_structure(structure_path: str,\n feature_mode: str = 'cheap', other_metals: list=['Al', 'In', 'Ga']) -> int:\n \"\"\"\n Gets number of channels for one cif file.\n\n Args:\n structure_path (str): path to structure file\n feature_mode (str): mode for feature calculation\n other_metals (list): list of metals that should be considered as metals in addition to\n transition metals and lanthanides\n\n Returns:\n\n \"\"\"\n s = Structure.from_file(structure_path)\n s1_metall1, s1_nonmetall = get_metallic_substructure(\n s, return_non_metal_structure=True, other_metals=other_metals)\n\n num_channels = get_channels(s1_metall1, s1_nonmetall)\n if len(num_channels) > 0:\n # Now also calculate some features that might be interesting for selection or later analysis\n metadata = get_metal_metadata(s1_metall1, num_channels[0][0])\n structure_features = get_structure_properties(s, mode=feature_mode)\n\n structure_features['num_channels'] = len(num_channels)\n structure_features['channel_indices'] = num_channels\n structure_features.update(metadata)\n problems = Checker.flag_potential_problems(structure_path,\n clashing_threshold=0.5,\n bond_threshold=2.0,\n unbound_mode='naive',\n hydrogen_mode='CH')\n structure_features.update(problems)\n planes = get_channel_dimensionality(num_channels, s1_metall1)\n structure_features['planes'] = planes\n bib = get_bibliometric_information(structure_path)\n if bib['clean_formula'] == structure_features['splitted_formula']:\n structure_features['identical_formulas'] = True\n else:\n structure_features['identical_formulas'] = False\n structure_features.update(bib)\n return structure_features\n else:\n return None\n\n def run(self):\n channel_list = []\n with concurrent.futures.ProcessPoolExecutor(\n max_workers=self.njobs) as executor:\n\n partial_structure_check = partial(\n ScreenMetalChannel._check_structure,\n feature_mode=self.feature_mode, other_metals=self.other_metals)\n\n i = 0\n for structure, structure_features in tqdm(\n zip(\n self.structure_list,\n executor.map(partial_structure_check,\n self.structure_list)),\n total=len(self.structure_list)):\n if structure_features:\n structure_features['name'] = structure\n channel_list.append(structure_features)\n i += 1\n\n if i % 100 == 0:\n df = pd.DataFrame(channel_list)\n df.to_csv('backup_{}.csv'.format(i))\n\n return pd.DataFrame(channel_list)\n","sub_path":"filter_metal_channels/screening.py","file_name":"screening.py","file_ext":"py","file_size_in_byte":4877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"530247859","text":"from pathlib import Path\n\nimport fire\n\n\ntry:\n from .utils import calculate_bleu, calculate_rouge, load_json, save_json, write_txt_file\nexcept ImportError:\n from utils import calculate_bleu, calculate_rouge, load_json, save_json, write_txt_file\n\n\ndef combine_partial_results(\n result_dir: str, save_dir: str = None, save_prefix=None, calc_bleu=False, just_metrics=False\n):\n \"\"\"Write first n lines of each file f in src_dir to dest_dir/f \"\"\"\n src_dir = Path(result_dir)\n save_dir = Path(save_dir)\n save_dir.mkdir(exist_ok=True)\n paths_to_combine = list(src_dir.glob(\"rank*.json\"))\n records = []\n for partial_result in paths_to_combine:\n records.extend(load_json(partial_result))\n preds = [x[\"pred\"] for x in records]\n labels = [x[\"label\"] for x in records]\n score_fn = calculate_bleu if calc_bleu else calculate_rouge\n metrics = score_fn(preds, labels)\n save_json(metrics, save_dir.joinpath(\"metrics.json\")) # better would be be {prefix}_{rouge|bleu}.json\n print(metrics)\n if just_metrics:\n return\n\n if save_prefix is None:\n save_prefix = \"generated\"\n print(\"using generated as prefix\")\n\n tgt_path = save_dir.joinpath(f\"{save_prefix}.target\")\n write_txt_file(labels, tgt_path)\n pred_path = save_dir.joinpath(f\"{save_prefix}.pred_target\")\n write_txt_file(preds, pred_path)\n if \"source\" in records[0]:\n src_path = save_dir.joinpath(f\"{save_prefix}.source\")\n write_txt_file([x[\"source\"] for x in records], src_path)\n\n\nif __name__ == \"__main__\":\n fire.Fire(combine_partial_results)\n","sub_path":"examples/seq2seq/aggregate_distributed_results.py","file_name":"aggregate_distributed_results.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"445532682","text":"from skimage.io import imread\nimport torch\nfrom model import ModelCountception\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = ModelCountception().to(device)\nmodel.eval()\nprint(\"Loading weights...\")\nfrom_before = torch.load('checkpoints/after_49_epochs.model')\nmodel_weights = from_before['model_weights']\nmodel.load_state_dict(model_weights)\n\nfor filename in os.listdir(\"/home/techgarage/count-ception_mbm/utils/Test/\"):\n im = imread(\"/home/techgarage/count-ception_mbm/utils/Test/\" + filename)\n print(im.shape)\n if(len(im.shape)==2):\n img = np.stack((im,)*3, axis=-1)\n else:\n img = im\n img = torch.from_numpy(img).float()\n img = img.permute(2, 0, 1).unsqueeze(0)\n img = img.to(device)\n output = model.forward(img)\n patch_size = 32\n ef = ((patch_size / 1) ** 2.0)\n output_count = (output.cpu().detach().numpy() / ef).sum(axis=(2, 3))\n print(output_count)\n output_arr = output[0].cpu().detach().numpy()\n #print(np.concatenate(output_arr, axis=1)[16:272,16:272].shape)\n plt.imshow(im)\n plt.imshow(np.concatenate(output_arr, axis=1)[16:272,16:272],alpha=0.5)\n plt.show()\n plt.savefig('test_outputs/samples_{0}'.format(filename))","sub_path":"singleimagetest.py","file_name":"singleimagetest.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"219906357","text":"import json\nimport logging\n\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponse\nfrom django.views.generic import View\n\nfrom apuntes.forms import FeedbackForm\nfrom apuntes.models import FeedbackMessage\n\nlogger = logging.getLogger(__name__)\n\n\nclass FeedbackEndpoint(LoginRequiredMixin, View):\n def post(self, request, *args, **kwargs):\n\n instance = FeedbackMessage(user=request.user)\n\n feedback_form = FeedbackForm(request.POST, instance=instance)\n\n if feedback_form.is_valid():\n feedback = feedback_form.save(commit=False)\n feedback.user = request.user\n feedback.save()\n\n report = {\n 'result': 'ok'\n }\n\n logger.info('Created feedback message: %s', feedback)\n else:\n report = {\n 'result': 'error',\n 'error': feedback_form.errors\n }\n\n logger.warning('Error when saving feedback message: ' + str(feedback_form.errors))\n\n return HttpResponse(content=json.dumps(report), content_type='application/json')\n","sub_path":"apuntes/views/api/FeedbackEndpoint.py","file_name":"FeedbackEndpoint.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"87061023","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2016, Digital Reasoning\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#\nfrom __future__ import print_function\n\nimport os\n\nimport yaml\nfrom django.core.exceptions import ImproperlyConfigured\n\n\nclass StackdioConfig(dict):\n CONFIG_FILE = os.path.expanduser('~/.stackdio/config')\n REQUIRED_FIELDS = (\n 'user',\n 'db_dsn',\n 'storage_root',\n 'django_secret_key',\n 'create_ssh_users',\n 'salt_bootstrap_args',\n )\n\n def __init__(self):\n super(StackdioConfig, self).__init__()\n self._load_stackdio_config()\n\n def _load_stackdio_config(self):\n if not os.path.isfile(self.CONFIG_FILE):\n raise ImproperlyConfigured(\n 'Missing stackdio configuration file. To create the file, you '\n 'may use `stackdio init`')\n with open(self.CONFIG_FILE) as f:\n config = yaml.safe_load(f)\n\n if not config:\n raise ImproperlyConfigured(\n 'stackdio configuration file appears to be empty or not '\n 'valid yaml.')\n\n errors = []\n for k in self.REQUIRED_FIELDS:\n if k not in config:\n errors.append('Missing parameter `{0}`'.format(k))\n\n if errors:\n msg = 'stackdio configuration errors:\\n'\n for err in errors:\n msg += ' - {0}\\n'.format(err)\n raise ImproperlyConfigured(msg)\n\n self.update(config)\n\n # additional helper attributes\n self.salt_root = os.path.join(self.storage_root)\n self.salt_config_root = os.path.join(self.salt_root, 'etc', 'salt')\n self.salt_master_config = os.path.join(self.salt_config_root, 'master')\n self.salt_cloud_config = os.path.join(self.salt_config_root, 'cloud')\n self.salt_core_states = os.path.join(self.storage_root, 'core_states')\n self.salt_providers_dir = os.path.join(self.salt_config_root,\n 'cloud.providers.d')\n self.salt_profiles_dir = os.path.join(self.salt_config_root,\n 'cloud.profiles.d')\n\n if '{salt_version}' not in self.salt_bootstrap_args:\n raise ImproperlyConfigured('salt_bootstrap_args must contain `{salt_version}`')\n\n # defaults\n if not self.salt_master_log_level: # pylint: disable=access-member-before-definition\n self.salt_master_log_level = 'info'\n\n def __getattr__(self, k):\n return self.get(k)\n\n def __setattr__(self, k, v):\n self[k] = v\n\nif __name__ == '__main__':\n config = StackdioConfig()\n print(config.user)\n","sub_path":"stackdio/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"107424904","text":"import json\nimport logging\nimport os\nimport re\nfrom json import dumps\n\nfrom six import string_types\n\nfrom galaxy import model\nfrom galaxy.jobs.actions.post import ActionBox\nfrom galaxy.model import LibraryDatasetDatasetAssociation, WorkflowRequestInputParameter\nfrom galaxy.model.dataset_collections.builder import CollectionBuilder\nfrom galaxy.model.none_like import NoneDataset\nfrom galaxy.objectstore import ObjectStorePopulator\nfrom galaxy.tools.parameters import update_dataset_ids\nfrom galaxy.tools.parameters.basic import DataCollectionToolParameter, DataToolParameter, RuntimeValue\nfrom galaxy.tools.parameters.wrapped import WrappedParameters\nfrom galaxy.util import ExecutionTimer\nfrom galaxy.util.odict import odict\nfrom galaxy.util.template import fill_template\nfrom galaxy.web import url_for\n\nlog = logging.getLogger(__name__)\n\n\nclass ToolExecutionCache(object):\n \"\"\" An object mean to cache calculation caused by repeatedly evaluting\n the same tool by the same user with slightly different parameters.\n \"\"\"\n\n def __init__(self, trans):\n self.trans = trans\n self.current_user_roles = trans.get_current_user_roles()\n self.chrom_info = {}\n\n def get_chrom_info(self, tool_id, input_dbkey):\n genome_builds = self.trans.app.genome_builds\n custom_build_hack_get_len_from_fasta_conversion = tool_id != 'CONVERTER_fasta_to_len'\n if custom_build_hack_get_len_from_fasta_conversion and input_dbkey in self.chrom_info:\n return self.chrom_info[input_dbkey]\n\n chrom_info_pair = genome_builds.get_chrom_info(input_dbkey, trans=self.trans, custom_build_hack_get_len_from_fasta_conversion=custom_build_hack_get_len_from_fasta_conversion)\n if custom_build_hack_get_len_from_fasta_conversion:\n self.chrom_info[input_dbkey] = chrom_info_pair\n\n return chrom_info_pair\n\n\nclass ToolAction(object):\n \"\"\"\n The actions to be taken when a tool is run (after parameters have\n been converted and validated).\n \"\"\"\n\n def execute(self, tool, trans, incoming=None, set_output_hid=True):\n incoming = incoming or {}\n raise TypeError(\"Abstract method\")\n\n\nclass DefaultToolAction(object):\n \"\"\"Default tool action is to run an external command\"\"\"\n\n def _collect_input_datasets(self, tool, param_values, trans, history, current_user_roles=None, dataset_collection_elements=None, collection_info=None):\n \"\"\"\n Collect any dataset inputs from incoming. Returns a mapping from\n parameter name to Dataset instance for each tool parameter that is\n of the DataToolParameter type.\n \"\"\"\n if current_user_roles is None:\n current_user_roles = trans.get_current_user_roles()\n input_datasets = odict()\n all_permissions = {}\n\n def record_permission(action, role_id):\n if action not in all_permissions:\n all_permissions[action] = set()\n all_permissions[action].add(role_id)\n\n def visitor(input, value, prefix, parent=None, **kwargs):\n\n def process_dataset(data, formats=None):\n if not data or isinstance(data, RuntimeValue):\n return None\n if formats is None:\n formats = input.formats\n if not data.datatype.matches_any(formats):\n # Need to refresh in case this conversion just took place, i.e. input above in tool performed the same conversion\n trans.sa_session.refresh(data)\n target_ext, converted_dataset = data.find_conversion_destination(formats)\n if target_ext:\n if converted_dataset:\n data = converted_dataset\n else:\n data = data.get_converted_dataset(trans, target_ext, target_context=parent, history=history)\n\n input_name = prefix + input.name\n # Checked security of whole collection all at once if mapping over this input, else\n # fetch dataset details for this input from the database.\n if collection_info and collection_info.is_mapped_over(input_name):\n action_tuples = collection_info.map_over_action_tuples(input_name)\n if not trans.app.security_agent.can_access_datasets(current_user_roles, action_tuples):\n raise Exception(\"User does not have permission to use a dataset provided for input.\")\n for action, role_id in action_tuples:\n record_permission(action, role_id)\n else:\n if not trans.app.security_agent.can_access_dataset(current_user_roles, data.dataset):\n raise Exception(\"User does not have permission to use a dataset (%s) provided for input.\" % data.id)\n permissions = trans.app.security_agent.get_permissions(data.dataset)\n for action, roles in permissions.items():\n for role in roles:\n record_permission(action.action, model.cached_id(role))\n return data\n if isinstance(input, DataToolParameter):\n if isinstance(value, list):\n # If there are multiple inputs with the same name, they\n # are stored as name1, name2, ...\n for i, v in enumerate(value):\n processed_dataset = process_dataset(v)\n if i == 0:\n # Allow copying metadata to output, first item will be source.\n input_datasets[prefix + input.name] = processed_dataset\n input_datasets[prefix + input.name + str(i + 1)] = processed_dataset\n conversions = []\n for conversion_name, conversion_extensions, conversion_datatypes in input.conversions:\n new_data = process_dataset(input_datasets[prefix + input.name + str(i + 1)], conversion_datatypes)\n if not new_data or new_data.datatype.matches_any(conversion_datatypes):\n input_datasets[prefix + conversion_name + str(i + 1)] = new_data\n conversions.append((conversion_name, new_data))\n else:\n raise Exception('A path for explicit datatype conversion has not been found: %s --/--> %s' % (input_datasets[prefix + input.name + str(i + 1)].extension, conversion_extensions))\n if parent:\n parent[input.name][i] = input_datasets[prefix + input.name + str(i + 1)]\n for conversion_name, conversion_data in conversions:\n # allow explicit conversion to be stored in job_parameter table\n parent[conversion_name][i] = conversion_data.id # a more robust way to determine JSONable value is desired\n else:\n param_values[input.name][i] = input_datasets[prefix + input.name + str(i + 1)]\n for conversion_name, conversion_data in conversions:\n # allow explicit conversion to be stored in job_parameter table\n param_values[conversion_name][i] = conversion_data.id # a more robust way to determine JSONable value is desired\n else:\n input_datasets[prefix + input.name] = process_dataset(value)\n conversions = []\n for conversion_name, conversion_extensions, conversion_datatypes in input.conversions:\n new_data = process_dataset(input_datasets[prefix + input.name], conversion_datatypes)\n if not new_data or new_data.datatype.matches_any(conversion_datatypes):\n input_datasets[prefix + conversion_name] = new_data\n conversions.append((conversion_name, new_data))\n else:\n raise Exception('A path for explicit datatype conversion has not been found: %s --/--> %s' % (input_datasets[prefix + input.name].extension, conversion_extensions))\n target_dict = parent\n if not target_dict:\n target_dict = param_values\n target_dict[input.name] = input_datasets[prefix + input.name]\n for conversion_name, conversion_data in conversions:\n # allow explicit conversion to be stored in job_parameter table\n target_dict[conversion_name] = conversion_data.id # a more robust way to determine JSONable value is desired\n elif isinstance(input, DataCollectionToolParameter):\n if not value:\n return\n\n collection = None\n child_collection = False\n if hasattr(value, 'child_collection'):\n # if we are mapping a collection over a tool, we only require the child_collection\n child_collection = True\n collection = value.child_collection\n else:\n # else the tool takes a collection as input so we need everything\n collection = value.collection\n\n action_tuples = collection.dataset_action_tuples\n if not trans.app.security_agent.can_access_datasets(current_user_roles, action_tuples):\n raise Exception(\"User does not have permission to use a dataset provided for input.\")\n for action, role_id in action_tuples:\n record_permission(action, role_id)\n\n replace_collection = False\n processed_dataset_dict = {}\n for i, v in enumerate(collection.dataset_instances):\n processed_dataset = process_dataset(v)\n if processed_dataset is not v:\n replace_collection = True\n processed_dataset_dict[v] = processed_dataset\n input_datasets[prefix + input.name + str(i + 1)] = processed_dataset\n\n if replace_collection:\n collection_type_description = trans.app.dataset_collections_service.collection_type_descriptions.for_collection_type(collection.collection_type)\n collection_builder = CollectionBuilder(collection_type_description)\n collection_builder.replace_elements_in_collection(\n template_collection=collection,\n replacement_dict=processed_dataset_dict,\n )\n new_collection = collection_builder.build()\n if child_collection:\n value.child_collection = new_collection\n else:\n value.collection = new_collection\n\n tool.visit_inputs(param_values, visitor)\n return input_datasets, all_permissions\n\n def collect_input_dataset_collections(self, tool, param_values):\n def append_to_key(the_dict, key, value):\n if key not in the_dict:\n the_dict[key] = []\n the_dict[key].append(value)\n\n input_dataset_collections = dict()\n\n def visitor(input, value, prefix, parent=None, prefixed_name=None, **kwargs):\n if isinstance(input, DataToolParameter):\n values = value\n if not isinstance(values, list):\n values = [value]\n for i, value in enumerate(values):\n if isinstance(value, model.HistoryDatasetCollectionAssociation) or isinstance(value, model.DatasetCollectionElement):\n append_to_key(input_dataset_collections, prefixed_name, (value, True))\n target_dict = parent\n if not target_dict:\n target_dict = param_values\n # This is just a DataToolParameter, so replace this\n # collection with individual datasets. Database will still\n # record collection which should be enought for workflow\n # extraction and tool rerun.\n if hasattr(value, 'child_collection'):\n # if we are mapping a collection over a tool, we only require the child_collection\n dataset_instances = value.child_collection.dataset_instances\n else:\n # else the tool takes a collection as input so we need everything\n dataset_instances = value.collection.dataset_instances\n if i == 0:\n target_dict[input.name] = []\n target_dict[input.name].extend(dataset_instances)\n elif isinstance(input, DataCollectionToolParameter):\n append_to_key(input_dataset_collections, prefix + input.name, (value, False))\n\n tool.visit_inputs(param_values, visitor)\n return input_dataset_collections\n\n def _check_access(self, tool, trans):\n assert tool.allow_user_access(trans.user), \"User (%s) is not allowed to access this tool.\" % (trans.user)\n\n def _collect_inputs(self, tool, trans, incoming, history, current_user_roles, collection_info):\n \"\"\" Collect history as well as input datasets and collections. \"\"\"\n app = trans.app\n # Set history.\n if not history:\n history = tool.get_default_history_by_trans(trans, create=True)\n if history not in trans.sa_session:\n history = trans.sa_session.query(app.model.History).get(history.id)\n\n # Track input dataset collections - but replace with simply lists so collect\n # input datasets can process these normally.\n inp_dataset_collections = self.collect_input_dataset_collections(tool, incoming)\n # Collect any input datasets from the incoming parameters\n inp_data, all_permissions = self._collect_input_datasets(tool, incoming, trans, history=history, current_user_roles=current_user_roles, collection_info=collection_info)\n\n # grap tags from incoming HDAs\n preserved_tags = {}\n for data in inp_data.values():\n if not data:\n continue\n for tag in data.auto_propagated_tags:\n preserved_tags[tag.value] = tag\n\n # grap tags from incoming HDCAs\n for collection_pairs in inp_dataset_collections.values():\n for collection, _ in collection_pairs:\n # if sub-collection mapping, this will be an DC not an HDCA\n # (e.g. part of collection not a collection instance) and thus won't have tags.\n if hasattr(collection, \"tags\"):\n for tag in collection.auto_propagated_tags:\n preserved_tags[tag.value] = tag\n return history, inp_data, inp_dataset_collections, preserved_tags, all_permissions\n\n def execute(self, tool, trans, incoming=None, return_job=False, set_output_hid=True, history=None, job_params=None, rerun_remap_job_id=None, execution_cache=None, dataset_collection_elements=None, completed_job=None, collection_info=None):\n \"\"\"\n Executes a tool, creating job and tool outputs, associating them, and\n submitting the job to the job queue. If history is not specified, use\n trans.history as destination for tool's output datasets.\n \"\"\"\n trans.check_user_activation()\n incoming = incoming or {}\n self._check_access(tool, trans)\n app = trans.app\n if execution_cache is None:\n execution_cache = ToolExecutionCache(trans)\n current_user_roles = execution_cache.current_user_roles\n history, inp_data, inp_dataset_collections, preserved_tags, all_permissions = self._collect_inputs(tool, trans, incoming, history, current_user_roles, collection_info)\n # Build name for output datasets based on tool name and input names\n on_text = self._get_on_text(inp_data)\n\n # format='input\" previously would give you a random extension from\n # the input extensions, now it should just give \"input\" as the output\n # format.\n input_ext = 'data' if tool.profile < 16.04 else \"input\"\n input_dbkey = incoming.get(\"dbkey\", \"?\")\n for name, data in reversed(list(inp_data.items())):\n if not data:\n data = NoneDataset(datatypes_registry=app.datatypes_registry)\n continue\n\n # Convert LDDA to an HDA.\n if isinstance(data, LibraryDatasetDatasetAssociation) and not completed_job:\n data = data.to_history_dataset_association(None)\n inp_data[name] = data\n\n if tool.profile < 16.04:\n input_ext = data.ext\n\n if data.dbkey not in [None, '?']:\n input_dbkey = data.dbkey\n\n identifier = getattr(data, \"element_identifier\", None)\n if identifier is not None:\n incoming[\"%s|__identifier__\" % name] = identifier\n\n # Collect chromInfo dataset and add as parameters to incoming\n (chrom_info, db_dataset) = execution_cache.get_chrom_info(tool.id, input_dbkey)\n\n if db_dataset:\n inp_data.update({\"chromInfo\": db_dataset})\n incoming[\"chromInfo\"] = chrom_info\n\n if not completed_job:\n # Determine output dataset permission/roles list\n existing_datasets = [inp for inp in inp_data.values() if inp]\n if existing_datasets:\n output_permissions = app.security_agent.guess_derived_permissions(all_permissions)\n else:\n # No valid inputs, we will use history defaults\n output_permissions = app.security_agent.history_get_default_permissions(history)\n\n # Add the dbkey to the incoming parameters\n incoming[\"dbkey\"] = input_dbkey\n # wrapped params are used by change_format action and by output.label; only perform this wrapping once, as needed\n wrapped_params = self._wrapped_params(trans, tool, incoming, inp_data)\n\n out_data = odict()\n input_collections = dict((k, v[0][0]) for k, v in inp_dataset_collections.items())\n output_collections = OutputCollections(\n trans,\n history,\n tool=tool,\n tool_action=self,\n input_collections=input_collections,\n dataset_collection_elements=dataset_collection_elements,\n on_text=on_text,\n incoming=incoming,\n params=wrapped_params.params,\n job_params=job_params,\n tags=preserved_tags,\n )\n\n # Keep track of parent / child relationships, we'll create all the\n # datasets first, then create the associations\n parent_to_child_pairs = []\n child_dataset_names = set()\n object_store_populator = ObjectStorePopulator(app)\n\n def handle_output(name, output, hidden=None):\n if output.parent:\n parent_to_child_pairs.append((output.parent, name))\n child_dataset_names.add(name)\n # What is the following hack for? Need to document under what\n # conditions can the following occur? (james@bx.psu.edu)\n # HACK: the output data has already been created\n # this happens i.e. as a result of the async controller\n if name in incoming:\n dataid = incoming[name]\n data = trans.sa_session.query(app.model.HistoryDatasetAssociation).get(dataid)\n assert data is not None\n out_data[name] = data\n else:\n ext = determine_output_format(\n output,\n wrapped_params.params,\n inp_data,\n inp_dataset_collections,\n input_ext,\n python_template_version=tool.python_template_version,\n )\n create_datasets = True\n dataset = None\n\n if completed_job:\n for output_dataset in completed_job.output_datasets:\n if output_dataset.name == name:\n create_datasets = False\n completed_data = output_dataset.dataset\n dataset = output_dataset.dataset.dataset\n break\n\n data = app.model.HistoryDatasetAssociation(extension=ext, dataset=dataset, create_dataset=create_datasets, flush=False)\n if create_datasets:\n from_work_dir = output.from_work_dir\n if from_work_dir is not None:\n data.dataset.created_from_basename = os.path.basename(from_work_dir)\n if hidden is None:\n hidden = output.hidden\n if not hidden and dataset_collection_elements is not None: # Mapping over a collection - hide datasets\n hidden = True\n if hidden:\n data.visible = False\n if dataset_collection_elements is not None and name in dataset_collection_elements:\n dataset_collection_elements[name].hda = data\n trans.sa_session.add(data)\n if not completed_job:\n trans.app.security_agent.set_all_dataset_permissions(data.dataset, output_permissions, new=True)\n data.copy_tags_to(preserved_tags)\n\n if not completed_job and trans.app.config.legacy_eager_objectstore_initialization:\n # Must flush before setting object store id currently.\n trans.sa_session.flush()\n object_store_populator.set_object_store_id(data)\n\n # This may not be neccesary with the new parent/child associations\n data.designation = name\n # Copy metadata from one of the inputs if requested.\n\n # metadata source can be either a string referencing an input\n # or an actual object to copy.\n metadata_source = output.metadata_source\n if metadata_source:\n if isinstance(metadata_source, string_types):\n metadata_source = inp_data.get(metadata_source)\n\n if metadata_source is not None:\n data.init_meta(copy_from=metadata_source)\n else:\n data.init_meta()\n # Take dbkey from LAST input\n data.dbkey = str(input_dbkey)\n # Set state\n if completed_job:\n data.blurb = completed_data.blurb\n data.peek = completed_data.peek\n data._metadata = completed_data._metadata\n else:\n data.blurb = \"queued\"\n # Set output label\n data.name = self.get_output_name(output, data, tool, on_text, trans, incoming, history, wrapped_params.params, job_params)\n # Store output\n out_data[name] = data\n if output.actions:\n # Apply pre-job tool-output-dataset actions; e.g. setting metadata, changing format\n output_action_params = dict(out_data)\n output_action_params.update(incoming)\n output.actions.apply_action(data, output_action_params)\n # Also set the default values of actions of type metadata\n self.set_metadata_defaults(output, data, tool, on_text, trans, incoming, history, wrapped_params.params, job_params)\n # Flush all datasets at once.\n return data\n\n for name, output in tool.outputs.items():\n if not filter_output(output, incoming):\n handle_output_timer = ExecutionTimer()\n if output.collection:\n collections_manager = app.dataset_collections_service\n element_identifiers = []\n known_outputs = output.known_outputs(input_collections, collections_manager.type_registry)\n created_element_datasets = []\n # Just to echo TODO elsewhere - this should be restructured to allow\n # nested collections.\n for output_part_def in known_outputs:\n # Add elements to top-level collection, unless nested...\n current_element_identifiers = element_identifiers\n current_collection_type = output.structure.collection_type\n\n for parent_id in (output_part_def.parent_ids or []):\n # TODO: replace following line with formal abstractions for doing this.\n current_collection_type = \":\".join(current_collection_type.split(\":\")[1:])\n name_to_index = dict((value[\"name\"], index) for (index, value) in enumerate(current_element_identifiers))\n if parent_id not in name_to_index:\n if parent_id not in current_element_identifiers:\n index = len(current_element_identifiers)\n current_element_identifiers.append(dict(\n name=parent_id,\n collection_type=current_collection_type,\n src=\"new_collection\",\n element_identifiers=[],\n ))\n else:\n index = name_to_index[parent_id]\n current_element_identifiers = current_element_identifiers[index][\"element_identifiers\"]\n\n effective_output_name = output_part_def.effective_output_name\n element = handle_output(effective_output_name, output_part_def.output_def, hidden=True)\n created_element_datasets.append(element)\n # TODO: this shouldn't exist in the top-level of the history at all\n # but for now we are still working around that by hiding the contents\n # there.\n # Following hack causes dataset to no be added to history...\n child_dataset_names.add(effective_output_name)\n trans.sa_session.add(element)\n current_element_identifiers.append({\n \"__object__\": element,\n \"name\": output_part_def.element_identifier,\n })\n\n history.add_datasets(trans.sa_session, created_element_datasets, set_hid=set_output_hid, quota=False, flush=True)\n if output.dynamic_structure:\n assert not element_identifiers # known_outputs must have been empty\n element_kwds = dict(elements=collections_manager.ELEMENTS_UNINITIALIZED)\n else:\n element_kwds = dict(element_identifiers=element_identifiers)\n output_collections.create_collection(\n output=output,\n name=name,\n **element_kwds\n )\n log.info(\"Handled collection output named %s for tool %s %s\" % (name, tool.id, handle_output_timer))\n else:\n handle_output(name, output)\n log.info(\"Handled output named %s for tool %s %s\" % (name, tool.id, handle_output_timer))\n\n add_datasets_timer = ExecutionTimer()\n # Add all the top-level (non-child) datasets to the history unless otherwise specified\n datasets_to_persist = []\n for name, data in out_data.items():\n if name not in child_dataset_names and name not in incoming: # don't add children; or already existing datasets, i.e. async created\n datasets_to_persist.append(data)\n # Set HID and add to history.\n # This is brand new and certainly empty so don't worry about quota.\n history.add_datasets(trans.sa_session, datasets_to_persist, set_hid=set_output_hid, quota=False, flush=False)\n\n # Add all the children to their parents\n for parent_name, child_name in parent_to_child_pairs:\n parent_dataset = out_data[parent_name]\n child_dataset = out_data[child_name]\n parent_dataset.children.append(child_dataset)\n\n log.info(\"Added output datasets to history %s\" % add_datasets_timer)\n job_setup_timer = ExecutionTimer()\n # Create the job object\n job, galaxy_session = self._new_job_for_session(trans, tool, history)\n self._record_inputs(trans, tool, job, incoming, inp_data, inp_dataset_collections)\n self._record_outputs(job, out_data, output_collections)\n job.object_store_id = object_store_populator.object_store_id\n if job_params:\n job.params = dumps(job_params)\n if completed_job:\n job.set_copied_from_job_id(completed_job.id)\n trans.sa_session.add(job)\n # Now that we have a job id, we can remap any outputs if this is a rerun and the user chose to continue dependent jobs\n # This functionality requires tracking jobs in the database.\n if app.config.track_jobs_in_database and rerun_remap_job_id is not None:\n self._remap_job_on_rerun(trans=trans,\n galaxy_session=galaxy_session,\n rerun_remap_job_id=rerun_remap_job_id,\n current_job=job,\n out_data=out_data)\n log.info(\"Setup for job %s complete, ready to be enqueued %s\" % (job.log_str(), job_setup_timer))\n\n # Some tools are not really executable, but jobs are still created for them ( for record keeping ).\n # Examples include tools that redirect to other applications ( epigraph ). These special tools must\n # include something that can be retrieved from the params ( e.g., REDIRECT_URL ) to keep the job\n # from being queued.\n if 'REDIRECT_URL' in incoming:\n # Get the dataset - there should only be 1\n for name in inp_data.keys():\n dataset = inp_data[name]\n redirect_url = tool.parse_redirect_url(dataset, incoming)\n # GALAXY_URL should be include in the tool params to enable the external application\n # to send back to the current Galaxy instance\n GALAXY_URL = incoming.get('GALAXY_URL', None)\n assert GALAXY_URL is not None, \"GALAXY_URL parameter missing in tool config.\"\n redirect_url += \"&GALAXY_URL=%s\" % GALAXY_URL\n # Job should not be queued, so set state to ok\n job.set_state(app.model.Job.states.OK)\n job.info = \"Redirected to: %s\" % redirect_url\n trans.sa_session.add(job)\n trans.sa_session.flush()\n trans.response.send_redirect(url_for(controller='tool_runner', action='redirect', redirect_url=redirect_url))\n else:\n # Dispatch to a job handler. enqueue() is responsible for flushing the job\n app.job_manager.enqueue(job, tool=tool)\n trans.log_event(\"Added job to the job queue, id: %s\" % str(job.id), tool_id=job.tool_id)\n return job, out_data\n\n def _remap_job_on_rerun(self, trans, galaxy_session, rerun_remap_job_id, current_job, out_data):\n \"\"\"\n Re-connect dependent datasets for a job that is being rerun (because it failed initially).\n\n If a job fails, the user has the option to try the job again with changed parameters.\n To be able to resume jobs that depend on this jobs output datasets we change the dependent's job\n input datasets to be those of the job that is being rerun.\n \"\"\"\n try:\n old_job = trans.sa_session.query(trans.app.model.Job).get(rerun_remap_job_id)\n assert old_job is not None, '(%s/%s): Old job id is invalid' % (rerun_remap_job_id, current_job.id)\n assert old_job.tool_id == current_job.tool_id, '(%s/%s): Old tool id (%s) does not match rerun tool id (%s)' % (old_job.id, current_job.id, old_job.tool_id, current_job.tool_id)\n if trans.user is not None:\n assert old_job.user_id == trans.user.id, '(%s/%s): Old user id (%s) does not match rerun user id (%s)' % (old_job.id, current_job.id, old_job.user_id, trans.user.id)\n elif trans.user is None and type(galaxy_session) == trans.model.GalaxySession:\n assert old_job.session_id == galaxy_session.id, '(%s/%s): Old session id (%s) does not match rerun session id (%s)' % (old_job.id, current_job.id, old_job.session_id, galaxy_session.id)\n else:\n raise Exception('(%s/%s): Remapping via the API is not (yet) supported' % (old_job.id, current_job.id))\n # Duplicate PJAs before remap.\n for pjaa in old_job.post_job_actions:\n current_job.add_post_job_action(pjaa.post_job_action)\n if old_job.workflow_invocation_step:\n replacement_dict = {}\n for parameter in old_job.workflow_invocation_step.workflow_invocation.input_parameters:\n if parameter.type == WorkflowRequestInputParameter.types.REPLACEMENT_PARAMETERS:\n replacement_dict[parameter.name] = parameter.value\n for pja in old_job.workflow_invocation_step.workflow_step.post_job_actions:\n # execute immediate actions here, with workflow context.\n if pja.action_type in ActionBox.immediate_actions:\n ActionBox.execute(trans.app, trans.sa_session, pja, current_job, replacement_dict)\n for p in old_job.parameters:\n if p.name.endswith('|__identifier__'):\n current_job.parameters.append(p.copy())\n remapped_hdas = self.__remap_data_inputs(old_job=old_job, current_job=current_job)\n for jtod in old_job.output_datasets:\n for (job_to_remap, jtid) in [(jtid.job, jtid) for jtid in jtod.dataset.dependent_jobs]:\n if (trans.user is not None and job_to_remap.user_id == trans.user.id) or (\n trans.user is None and job_to_remap.session_id == galaxy_session.id):\n self.__remap_parameters(job_to_remap, jtid, jtod, out_data)\n trans.sa_session.add(job_to_remap)\n trans.sa_session.add(jtid)\n job_to_remap.resume()\n jtod.dataset.visible = False\n trans.sa_session.add(jtod)\n for jtodc in old_job.output_dataset_collection_instances:\n # Update JobToOutputDatasetCollectionAssociation to the current job\n jtodc.job = current_job\n hdca = jtodc.dataset_collection_instance\n hdca.collection.replace_failed_elements(remapped_hdas)\n if hdca.implicit_collection_jobs:\n for job in hdca.implicit_collection_jobs.jobs:\n if job.job_id == old_job.id:\n job.job_id = current_job.id\n except Exception:\n log.exception('Cannot remap rerun dependencies.')\n\n def __remap_data_inputs(self, old_job, current_job):\n \"\"\"Record output datasets from old_job and build a dictionary that maps the old output HDAs to the new output HDAs.\"\"\"\n remapped_hdas = {}\n old_output_datasets = {jtod.name: jtod.dataset for jtod in old_job.output_datasets}\n for jtod in current_job.output_datasets:\n remapped_hdas[old_output_datasets[jtod.name]] = jtod.dataset\n return remapped_hdas\n\n def __remap_parameters(self, job_to_remap, jtid, jtod, out_data):\n input_values = dict([(p.name, json.loads(p.value)) for p in job_to_remap.parameters])\n old_dataset_id = jtod.dataset_id\n new_dataset_id = out_data[jtod.name].id\n input_values = update_dataset_ids(input_values, {old_dataset_id: new_dataset_id}, src='hda')\n for p in job_to_remap.parameters:\n p.value = json.dumps(input_values[p.name])\n jtid.dataset = out_data[jtod.name]\n jtid.dataset.hid = jtod.dataset.hid\n log.info('Job %s input HDA %s remapped to new HDA %s' % (job_to_remap.id, jtod.dataset.id, jtid.dataset.id))\n\n def _wrapped_params(self, trans, tool, incoming, input_datasets=None):\n wrapped_params = WrappedParameters(trans, tool, incoming, input_datasets=input_datasets)\n return wrapped_params\n\n def _get_on_text(self, inp_data):\n input_names = []\n for data in reversed(list(inp_data.values())):\n if getattr(data, \"hid\", None):\n input_names.append('data %s' % data.hid)\n\n return on_text_for_names(input_names)\n\n def _new_job_for_session(self, trans, tool, history):\n job = trans.app.model.Job()\n galaxy_session = None\n\n if hasattr(trans, \"get_galaxy_session\"):\n galaxy_session = trans.get_galaxy_session()\n # If we're submitting from the API, there won't be a session.\n if type(galaxy_session) == trans.model.GalaxySession:\n job.session_id = model.cached_id(galaxy_session)\n if trans.user is not None:\n job.user_id = model.cached_id(trans.user)\n job.history_id = model.cached_id(history)\n job.tool_id = tool.id\n try:\n # For backward compatibility, some tools may not have versions yet.\n job.tool_version = tool.version\n except AttributeError:\n job.tool_version = \"1.0.0\"\n job.dynamic_tool = tool.dynamic_tool\n return job, galaxy_session\n\n def _record_inputs(self, trans, tool, job, incoming, inp_data, inp_dataset_collections):\n # FIXME: Don't need all of incoming here, just the defined parameters\n # from the tool. We need to deal with tools that pass all post\n # parameters to the command as a special case.\n reductions = {}\n for name, dataset_collection_info_pairs in inp_dataset_collections.items():\n for (dataset_collection, reduced) in dataset_collection_info_pairs:\n if reduced:\n if name not in reductions:\n reductions[name] = []\n reductions[name].append(dataset_collection)\n\n # TODO: verify can have multiple with same name, don't want to lose traceability\n if isinstance(dataset_collection, model.HistoryDatasetCollectionAssociation):\n # FIXME: when recording inputs for special tools (e.g. ModelOperationToolAction),\n # dataset_collection is actually a DatasetCollectionElement, which can't be added\n # to a jobs' input_dataset_collection relation, which expects HDCA instances\n job.add_input_dataset_collection(name, dataset_collection)\n\n # If this an input collection is a reduction, we expanded it for dataset security, type\n # checking, and such, but the persisted input must be the original collection\n # so we can recover things like element identifier during tool command evaluation.\n def restore_reduction_visitor(input, value, prefix, parent=None, prefixed_name=None, **kwargs):\n if prefixed_name in reductions and isinstance(input, DataToolParameter):\n target_dict = parent\n if not target_dict:\n target_dict = incoming\n\n target_dict[input.name] = []\n for reduced_collection in reductions[prefixed_name]:\n if hasattr(reduced_collection, \"child_collection\"):\n target_dict[input.name].append({'id': model.cached_id(reduced_collection), 'src': 'dce'})\n else:\n target_dict[input.name].append({'id': model.cached_id(reduced_collection), 'src': 'hdca'})\n\n if reductions:\n tool.visit_inputs(incoming, restore_reduction_visitor)\n\n for name, value in tool.params_to_strings(incoming, trans.app).items():\n job.add_parameter(name, value)\n self._record_input_datasets(trans, job, inp_data)\n\n def _record_outputs(self, job, out_data, output_collections):\n out_collections = output_collections.out_collections\n out_collection_instances = output_collections.out_collection_instances\n for name, dataset in out_data.items():\n job.add_output_dataset(name, dataset)\n for name, dataset_collection in out_collections.items():\n job.add_implicit_output_dataset_collection(name, dataset_collection)\n for name, dataset_collection_instance in out_collection_instances.items():\n job.add_output_dataset_collection(name, dataset_collection_instance)\n dataset_collection_instance.job = job\n\n def _record_input_datasets(self, trans, job, inp_data):\n for name, dataset in inp_data.items():\n # TODO: figure out why can't pass dataset_id here.\n job.add_input_dataset(name, dataset=dataset)\n\n def get_output_name(self, output, dataset, tool, on_text, trans, incoming, history, params, job_params):\n if output.label:\n params['tool'] = tool\n params['on_string'] = on_text\n return fill_template(output.label, context=params, python_template_version=tool.python_template_version)\n else:\n return self._get_default_data_name(dataset, tool, on_text=on_text, trans=trans, incoming=incoming, history=history, params=params, job_params=job_params)\n\n def set_metadata_defaults(self, output, dataset, tool, on_text, trans, incoming, history, params, job_params):\n \"\"\"\n This allows to map names of input files to metadata default values. Example:\n\n <data format=\"tabular\" name=\"output\" label=\"Tabular output, aggregates data from individual_inputs\" >\n <actions>\n <action name=\"column_names\" type=\"metadata\" default=\"${','.join([input.name for input in $individual_inputs ])}\" />\n </actions>\n </data>\n \"\"\"\n if output.actions:\n for action in output.actions.actions:\n if action.tag == \"metadata\" and action.default:\n metadata_new_value = fill_template(action.default, context=params, python_template_version=tool.python_template_version).split(\",\")\n dataset.metadata.__setattr__(str(action.name), metadata_new_value)\n\n def _get_default_data_name(self, dataset, tool, on_text=None, trans=None, incoming=None, history=None, params=None, job_params=None, **kwd):\n name = tool.name\n if on_text:\n name += (\" on \" + on_text)\n return name\n\n\nclass OutputCollections(object):\n \"\"\" Keeps track of collections (DC or HDCA) created by actions.\n\n Actions do fairly different things depending on whether we are creating\n just part of an collection or a whole output collection (mapping_over_collection\n parameter).\n \"\"\"\n\n def __init__(self, trans, history, tool, tool_action, input_collections, dataset_collection_elements, on_text, incoming, params, job_params, tags):\n self.trans = trans\n self.history = history\n self.tool = tool\n self.tool_action = tool_action\n self.input_collections = input_collections\n self.dataset_collection_elements = dataset_collection_elements\n self.on_text = on_text\n self.incoming = incoming\n self.params = params\n self.job_params = job_params\n self.out_collections = {}\n self.out_collection_instances = {}\n self.tags = tags\n\n def create_collection(self, output, name, collection_type=None, **element_kwds):\n input_collections = self.input_collections\n collections_manager = self.trans.app.dataset_collections_service\n collection_type = collection_type or output.structure.collection_type\n if collection_type is None:\n collection_type_source = output.structure.collection_type_source\n if collection_type_source is None:\n # TODO: Not a new problem, but this should be determined\n # sooner.\n raise Exception(\"Could not determine collection type to create.\")\n if collection_type_source not in input_collections:\n raise Exception(\"Could not find collection type source with name [%s].\" % collection_type_source)\n\n # Using the collection_type_source string we get the DataCollectionToolParameter\n data_param = self.tool.inputs\n groups = collection_type_source.split('|')\n for group in groups:\n values = group.split('_')\n if values[-1].isdigit():\n key = (\"_\".join(values[0:-1]))\n # We don't care about the repeat index, we just need to find the correct DataCollectionToolParameter\n else:\n key = group\n if isinstance(data_param, odict):\n data_param = data_param.get(key)\n else:\n data_param = data_param.inputs.get(key)\n collection_type_description = data_param._history_query(self.trans).can_map_over(input_collections[collection_type_source])\n if collection_type_description:\n collection_type = collection_type_description.collection_type\n else:\n collection_type = input_collections[collection_type_source].collection.collection_type\n\n if \"elements\" in element_kwds:\n def check_elements(elements):\n if hasattr(elements, \"items\"): # else it is ELEMENTS_UNINITIALIZED object.\n for value in elements.values():\n # Either a HDA (if) or a DatasetCollection or a recursive dict.\n if getattr(value, \"history_content_type\", None) == \"dataset\":\n assert value.history is not None or value.history_id is not None\n elif hasattr(value, \"dataset_instances\"):\n for dataset in value.dataset_instances:\n assert dataset.history is not None or dataset.history_id is not None\n else:\n assert value[\"src\"] == \"new_collection\"\n check_elements(value[\"elements\"])\n\n elements = element_kwds[\"elements\"]\n check_elements(elements)\n\n if self.dataset_collection_elements is not None:\n dc = collections_manager.create_dataset_collection(\n self.trans,\n collection_type=collection_type,\n **element_kwds\n )\n if name in self.dataset_collection_elements:\n self.dataset_collection_elements[name].child_collection = dc\n # self.trans.sa_session.add(self.dataset_collection_elements[name])\n self.out_collections[name] = dc\n else:\n hdca_name = self.tool_action.get_output_name(\n output,\n None,\n self.tool,\n self.on_text,\n self.trans,\n self.incoming,\n self.history,\n self.params,\n self.job_params,\n )\n hdca = collections_manager.create(\n self.trans,\n self.history,\n name=hdca_name,\n collection_type=collection_type,\n trusted_identifiers=True,\n tags=self.tags,\n **element_kwds\n )\n # name here is name of the output element - not name\n # of the hdca.\n self.out_collection_instances[name] = hdca\n\n\ndef on_text_for_names(input_names):\n # input_names may contain duplicates... this is because the first value in\n # multiple input dataset parameters will appear twice once as param_name\n # and once as param_name1.\n unique_names = []\n for name in input_names:\n if name not in unique_names:\n unique_names.append(name)\n input_names = unique_names\n\n # Build name for output datasets based on tool name and input names\n if len(input_names) == 1:\n on_text = input_names[0]\n elif len(input_names) == 2:\n on_text = '%s and %s' % tuple(input_names[0:2])\n elif len(input_names) == 3:\n on_text = '%s, %s, and %s' % tuple(input_names[0:3])\n elif len(input_names) > 3:\n on_text = '%s, %s, and others' % tuple(input_names[0:2])\n else:\n on_text = \"\"\n return on_text\n\n\ndef filter_output(output, incoming):\n for filter in output.filters:\n try:\n if not eval(filter.text.strip(), globals(), incoming):\n return True # do not create this dataset\n except Exception as e:\n log.debug('Dataset output filter failed: %s' % e)\n return False\n\n\ndef get_ext_or_implicit_ext(hda):\n if hda.implicitly_converted_parent_datasets:\n # implicitly_converted_parent_datasets is a list of ImplicitlyConvertedDatasetAssociation\n # objects, and their type is the target_ext, so this should be correct even if there\n # are multiple ImplicitlyConvertedDatasetAssociation objects (meaning 2 datasets had been converted\n # to produce a dataset with the required datatype)\n return hda.implicitly_converted_parent_datasets[0].type\n return hda.ext\n\n\ndef determine_output_format(output, parameter_context, input_datasets, input_dataset_collections, random_input_ext, python_template_version='3'):\n \"\"\" Determines the output format for a dataset based on an abstract\n description of the output (galaxy.tool_util.parser.ToolOutput), the parameter\n wrappers, a map of the input datasets (name => HDA), and the last input\n extensions in the tool form.\n\n TODO: Don't deal with XML here - move this logic into ToolOutput.\n TODO: Make the input extension used deterministic instead of random.\n \"\"\"\n # the type should match the input\n ext = output.format\n if ext == \"input\":\n ext = random_input_ext\n format_source = output.format_source\n if format_source is not None and format_source in input_datasets:\n try:\n input_dataset = input_datasets[output.format_source]\n ext = get_ext_or_implicit_ext(input_dataset)\n except Exception:\n pass\n elif format_source is not None:\n element_index = None\n collection_name = format_source\n if re.match(r\"^[^\\[\\]]*\\[[^\\[\\]]*\\]$\", format_source):\n collection_name, element_index = format_source[0:-1].split(\"[\")\n # Treat as json to interpret \"forward\" vs 0 with type\n # Make it feel more like Python, single quote better in XML also.\n element_index = element_index.replace(\"'\", '\"')\n element_index = json.loads(element_index)\n\n if collection_name in input_dataset_collections:\n try:\n input_collection = input_dataset_collections[collection_name][0][0]\n input_collection_collection = input_collection.collection\n if element_index is None:\n # just pick the first HDA\n input_dataset = input_collection_collection.dataset_instances[0]\n else:\n try:\n input_element = input_collection_collection[element_index]\n except KeyError:\n for element in input_collection_collection.dataset_elements:\n if element.element_identifier == element_index:\n input_element = element\n break\n input_dataset = input_element.element_object\n ext = get_ext_or_implicit_ext(input_dataset)\n except Exception as e:\n log.debug(\"Exception while trying to determine format_source: %s\", e)\n pass\n\n # process change_format tags\n if output.change_format is not None:\n new_format_set = False\n for change_elem in output.change_format:\n for when_elem in change_elem.findall('when'):\n check = when_elem.get('input', None)\n if check is not None:\n try:\n if '$' not in check:\n # allow a simple name or more complex specifications\n check = '${%s}' % check\n if fill_template(check, context=parameter_context, python_template_version=python_template_version) == when_elem.get('value', None):\n ext = when_elem.get('format', ext)\n except Exception: # bad tag input value; possibly referencing a param within a different conditional when block or other nonexistent grouping construct\n continue\n else:\n check = when_elem.get('input_dataset', None)\n if check is not None:\n check = input_datasets.get(check, None)\n # At this point check is a HistoryDatasetAssociation object.\n check_format = when_elem.get('format', ext)\n check_value = when_elem.get('value', None)\n check_attribute = when_elem.get('attribute', None)\n if check is not None and check_value is not None and check_attribute is not None:\n # See if the attribute to be checked belongs to the HistoryDatasetAssociation object.\n if hasattr(check, check_attribute):\n if str(getattr(check, check_attribute)) == str(check_value):\n ext = check_format\n new_format_set = True\n break\n # See if the attribute to be checked belongs to the metadata associated with the\n # HistoryDatasetAssociation object.\n if check.metadata is not None:\n metadata_value = check.metadata.get(check_attribute, None)\n if metadata_value is not None:\n if str(metadata_value) == str(check_value):\n ext = check_format\n new_format_set = True\n break\n if new_format_set:\n break\n return ext\n","sub_path":"lib/galaxy/tools/actions/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":55401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"274761551","text":"import random\n\ndef bot_actions(bot_posi, BTN_card, BB_card):\n if bot_posi == \"BTN\":\n if BTN_card == \"A\":\n action = \"bet\"\n if BTN_card == \"Q\":\n action = random.choice([\"check\", \"bet\"])\n if bot_posi == \"BB\":\n action = random.choice([\"call\", \"fold\"])\n\n return action\n\ndef player_choise() :\n player_posi = input(\"Are you BTN or BB\")\n return player_posi\n\ndef cardDeal(AQlist):\n #BTN_card = random.choice(AQlist)\n BTN_card = AQlist.pop()\n BB_card = \"K\"\n return BTN_card, BB_card, AQlist\n\ndef cardOpen(BTN_card, BB_card):\n card_rank = [\"Q\", \"K\", \"A\"]\n BTN_card_rank = card_rank.index(BTN_card)\n BB_card_rank = card_rank.index(BB_card)\n if BTN_card_rank > BB_card_rank:\n winner = \"BTN\"\n else:\n winner = \"BB\"\n return winner\n \ndef betChip(better, player_posi, bot_action):\n if better == \"BTN\":\n if player_posi == \"BTN\":\n bet_history = input(\"BTN check or bet?:\")\n return bet_history\n else:\n bet_history = bot_action\n return bet_history\n if better == \"BB\":\n if player_posi == \"BB\":\n bet_history = input(\"BB call or fold?:\")\n return bet_history\n else:\n bet_history = bot_action\n return bet_history\n\n\ndef takeChipWinner(winner, player_posi, bet_history, player_win_money):\n # posi is BB\n if player_posi == \"BTN\":\n if bet_history == \"check\":\n if winner == \"BTN\":\n player_win_money += 1\n else:\n player_win_money -= 1\n elif bet_history == \"fold\":\n player_win_money += 1\n elif bet_history == \"call\":\n if winner == \"BTN\":\n player_win_money += 3\n else:\n player_win_money -= 3\n\n if player_posi == \"BB\":\n if bet_history == \"check\":\n if winner == \"BB\":\n player_win_money += 1\n else:\n player_win_money -= 1\n elif bet_history == \"fold\":\n player_win_money -= 1\n elif bet_history == \"call\":\n if winner == \"BB\":\n player_win_money += 3\n else:\n player_win_money -= 3\n return player_win_money\n\ndef main():\n turn = 1\n player_win_money = 0\n # decide position\n player_posi = \"BB\"\n bot_posi = \"BTN\"\n # make card box\n AQlist = [\"A\"] * 25 + [\"Q\"] * 25\n random.shuffle(AQlist)\n #oponent_money = 10\n while(turn < 10):\n turn_flag = False\n print('turn :', turn)\n # deal cards\n BTN_card, BB_card, AQlist = cardDeal(AQlist)\n print(\"BTN card is \" + BTN_card + \"| BB card is \" + BB_card)\n\n # decide bot action\n bot_action = bot_actions(bot_posi, BTN_card, BB_card)\n\n # BTN bets chip\n better = \"BTN\"\n bet_history = betChip(better, player_posi, bot_action)\n print(\"BTN \" + bet_history)\n # BB bets chip\n if bet_history == \"bet\":\n better = \"BB\"\n bet_history = betChip(better, player_posi, bot_action)\n print(\"BB \" + bet_history)\n \n\n # decide a winner\n winner = cardOpen(BTN_card, BB_card)\n\n # winner take chips\n player_win_money = takeChipWinner(winner,player_posi, bet_history, player_win_money)\n\n # turn end\n turn += 1\n print(\"player_win_money is \" + str(player_win_money))\n turn_flag = True\n input('go to next')\n print('thank you')\n\nif __name__ == '__main__':\n main()\n","sub_path":"console_app/toy-poker.py","file_name":"toy-poker.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"70600520","text":"#!/usr/bin/env python3\nimport os\nimport numpy as np\n\nfrom common.numpy_fast import clip\nfrom common.realtime import sec_since_boot\nfrom selfdrive.swaglog import cloudlog\nfrom selfdrive.controls.lib.drive_helpers import LON_MPC_N as N\nfrom selfdrive.modeld.constants import T_IDXS\n\nfrom pyextra.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver\nfrom casadi import SX, vertcat\n\n\n\n\nLONG_MPC_DIR = os.path.dirname(os.path.abspath(__file__))\nEXPORT_DIR = os.path.join(LONG_MPC_DIR, \"c_generated_code\")\nJSON_FILE = \"acados_ocp_long.json\"\n\n\ndef gen_long_model():\n model = AcadosModel()\n model.name = 'long'\n\n # set up states & controls\n x_ego = SX.sym('x_ego')\n v_ego = SX.sym('v_ego')\n a_ego = SX.sym('a_ego')\n model.x = vertcat(x_ego, v_ego, a_ego)\n\n # controls\n j_ego = SX.sym('j_ego')\n model.u = vertcat(j_ego)\n\n # xdot\n x_ego_dot = SX.sym('x_ego_dot')\n v_ego_dot = SX.sym('v_ego_dot')\n a_ego_dot = SX.sym('a_ego_dot')\n model.xdot = vertcat(x_ego_dot, v_ego_dot, a_ego_dot)\n\n # dynamics model\n f_expl = vertcat(v_ego, a_ego, j_ego)\n model.f_impl_expr = model.xdot - f_expl\n model.f_expl_expr = f_expl\n return model\n\n\ndef gen_long_mpc_solver():\n ocp = AcadosOcp()\n ocp.model = gen_long_model()\n\n Tf = np.array(T_IDXS)[N]\n\n # set dimensions\n ocp.dims.N = N\n\n # set cost module\n ocp.cost.cost_type = 'NONLINEAR_LS'\n ocp.cost.cost_type_e = 'NONLINEAR_LS'\n\n QR = np.diag([0.0, 0.0, 0.0, 0.0])\n Q = np.diag([0.0, 0.0, 0.0])\n\n ocp.cost.W = QR\n ocp.cost.W_e = Q\n\n x_ego, v_ego, a_ego = ocp.model.x[0], ocp.model.x[1], ocp.model.x[2]\n j_ego = ocp.model.u[0]\n\n ocp.cost.yref = np.zeros((4, ))\n ocp.cost.yref_e = np.zeros((3, ))\n # TODO hacky weights to keep behavior the same\n ocp.model.cost_y_expr = vertcat(x_ego, v_ego, a_ego, j_ego)\n ocp.model.cost_y_expr_e = vertcat(x_ego, v_ego, a_ego)\n\n # set constraints\n ocp.constraints.constr_type = 'BGH'\n ocp.constraints.idxbx = np.array([0, 1,2])\n ocp.constraints.lbx = np.array([0., 0, -1.2])\n ocp.constraints.ubx = np.array([10000, 100., 1.2])\n ocp.constraints.Jsbx = np.eye(3)\n x0 = np.array([0.0, 0.0, 0.0])\n ocp.constraints.x0 = x0\n\n l2_penalty = 1.0\n l1_penalty = 0.0\n weights = np.array([0.0, 1e4, 1e4])\n ocp.cost.Zl = l2_penalty * weights\n ocp.cost.Zu = l2_penalty * weights\n ocp.cost.zl = l1_penalty * weights\n ocp.cost.zu = l1_penalty * weights\n\n ocp.solver_options.qp_solver = 'PARTIAL_CONDENSING_HPIPM'\n ocp.solver_options.hessian_approx = 'GAUSS_NEWTON'\n ocp.solver_options.integrator_type = 'ERK'\n ocp.solver_options.nlp_solver_type = 'SQP_RTI'\n ocp.solver_options.qp_solver_iter_max = 2\n\n # set prediction horizon\n ocp.solver_options.tf = Tf\n ocp.solver_options.shooting_nodes = np.array(T_IDXS)[:N+1]\n\n ocp.code_export_directory = EXPORT_DIR\n return ocp\n\n\nclass LongitudinalMpc():\n def __init__(self):\n self.solver = AcadosOcpSolver('long', N, EXPORT_DIR)\n self.x_sol = np.zeros((N+1, 3))\n self.u_sol = np.zeros((N, 1))\n self.set_weights()\n\n self.v_solution = [0.0 for i in range(len(T_IDXS))]\n self.a_solution = [0.0 for i in range(len(T_IDXS))]\n self.j_solution = [0.0 for i in range(len(T_IDXS)-1)]\n self.yref = np.zeros((N+1, 4))\n self.solver.cost_set_slice(0, N, \"yref\", self.yref[:N])\n self.solver.cost_set(N, \"yref\", self.yref[N][:3])\n self.T_IDXS = np.array(T_IDXS[:N+1])\n self.min_a = -1.2\n self.max_a = 1.2\n self.mins = np.tile(np.array([0.0, 0.0, self.min_a])[None], reps=(N-1,1))\n self.maxs = np.tile(np.array([0.0, 100.0, self.max_a])[None], reps=(N-1,1))\n self.x0 = np.zeros(3)\n self.reset()\n\n def reset(self):\n self.last_cloudlog_t = 0\n self.status = True\n self.solution_status = 0\n for i in range(N+1):\n self.solver.set(i, 'x', self.x0)\n\n def set_weights(self):\n W = np.diag([0.0, 1.0, 0.0, 50.0])\n Ws = np.tile(W[None], reps=(N,1,1))\n self.solver.cost_set_slice(0, N, 'W', Ws, api='old')\n #TODO hacky weights to keep behavior the same\n self.solver.cost_set(N, 'W', (3/20.)*W[:3,:3])\n\n def set_accel_limits(self, min_a, max_a):\n self.min_a = min_a\n self.max_a = max_a\n self.mins[:,2] = self.min_a\n self.maxs[:,2] = self.max_a\n self.solver.constraints_set_slice(1, N, \"lbx\", self.mins, api='old')\n self.solver.constraints_set_slice(1, N, \"ubx\", self.maxs, api='old')\n\n def set_cur_state(self, v, a):\n self.x0[1] = v\n self.x0[2] = a\n self.solver.constraints_set(0, \"lbx\", self.x0)\n self.solver.constraints_set(0, \"ubx\", self.x0)\n\n def update(self, carstate, model, v_cruise):\n v_cruise_clipped = clip(v_cruise, self.x0[1] - 10., self.x0[1] + 10.0)\n position = v_cruise_clipped * self.T_IDXS\n speed = v_cruise_clipped * np.ones(N+1)\n accel = np.zeros(N+1)\n self.update_with_xva(position, speed, accel)\n\n def update_with_xva(self, position, speed, accel):\n self.yref[:,0] = position\n self.yref[:,1] = speed\n self.yref[:,2] = accel\n self.solver.cost_set_slice(0, N, \"yref\", self.yref[:N])\n self.solver.cost_set(N, \"yref\", self.yref[N][:3])\n\n self.solution_status = self.solver.solve()\n self.solver.fill_in_slice(0, N+1, 'x', self.x_sol)\n self.solver.fill_in_slice(0, N, 'u', self.u_sol)\n #self.solver.print_statistics()\n\n self.v_solution = list(self.x_sol[:,1])\n self.a_solution = list(self.x_sol[:,2])\n self.j_solution = list(self.u_sol[:,0])\n\n t = sec_since_boot()\n if self.solution_status != 0:\n if t > self.last_cloudlog_t + 5.0:\n self.last_cloudlog_t = t\n cloudlog.warning(f'Longitudinal model mpc reset, solution status: {self.solution_status}')\n self.reset()\n\n\nif __name__ == \"__main__\":\n ocp = gen_long_mpc_solver()\n AcadosOcpSolver.generate(ocp, json_file=JSON_FILE, build=False)\n","sub_path":"selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py","file_name":"long_mpc.py","file_ext":"py","file_size_in_byte":5730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"111114627","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 13 13:40:36 2019\r\n\r\n@author: finn\r\n\"\"\"\r\n\r\nimport datetime\r\nimport wechatsogou\r\nimport webbrowser\r\nimport os.path\r\nimport werkzeug.exceptions # pyinstaller doesn't include this module\r\n\r\ndef gzh_update(subscription_file='wechat_subscriptions.txt', headline=False, original=False, timedel=1, add_account=None):\r\n '''Get updated articles for your WeChat subscriptions.\r\n \r\n Parameters\r\n --------------------\r\n subscription_file: str. location of text file which holds your subscriptions\r\n headline: bool. filter headlines\r\n original: bool. filter origins\r\n timedel: int. days to filter most recent articles\r\n add_account: list or None. update subscription list with given account(s)\r\n \r\n Returns\r\n --------------------\r\n article list: articles are held in dicts\r\n '''\r\n with open(subscription_file, 'r', encoding='utf8') as f:\r\n accounts = [account.strip() for account in f.readlines()]\r\n if add_account is not None:\r\n for new_account in add_account: \r\n if new_account not in accounts:\r\n accounts.append(new_account)\r\n with open(subscription_file, 'a', encoding='utf8') as f:\r\n f.write(new_account + '\\n')\r\n else:\r\n print('Got duplicate ' + new_account)\r\n ws_api = wechatsogou.WechatSogouAPI(captcha_break_time=3)\r\n articles, account_nohit = [], []\r\n for account in accounts:\r\n contents_ = ws_api.get_gzh_article_by_history(keyword=account)\r\n if contents_ != dict():\r\n articles_ = contents_['article']\r\n for article_ in articles_:\r\n article_['Account name'] = contents_['gzh']['wechat_name']\r\n articles.extend(articles_)\r\n else:\r\n account_nohit.append(account)\r\n # filter time\r\n timestamp = int((datetime.datetime.now()-datetime.timedelta(days=timedel)).timestamp())\r\n articles = [article for article in articles if article['datetime'] > timestamp]\r\n # filter headlines\r\n if headline:\r\n articles = [article for article in articles if article['main'] == 1]\r\n # filter origins\r\n if original:\r\n articles = [article for article in articles if article['copyright_stat'] == 100] \r\n # Final formatting\r\n articles_ = []\r\n for article in articles:\r\n time_str = datetime.datetime.fromtimestamp(article['datetime']).ctime()\r\n articles_.extend([{'Title': article['title'], 'Abstract': article['abstract'], \r\n 'Account name': article['Account name'], 'Publication time': time_str, \r\n 'url': article['content_url']}])\r\n return articles_, account_nohit\r\n \r\ndef to_html(articles, account_nohit=list(), html_file='wechat_portal.html'):\r\n html_header = ['<!DOCTYPE HTML>', '<html>', '<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />', \r\n '<head>', '<title>Wechat Portal', '', \r\n '', '', '
', 'About   ', \r\n 'Contact', \r\n '
', '
', '

WELCOME

', \r\n '

Below are most recent activities of your WeChat subsciptions.

', '
', \r\n '', '', '', '', \r\n '', '', '', '', \r\n '', '', '', '', '', '', \r\n '', '', '']\r\n html_body = []\r\n for i, article in enumerate(articles, start=1):\r\n html_body.extend(['''\\n\\n\\n\\n\\n\\n''' % \r\n (i, article['url'], article['Title'], article['Abstract'], article['Account name'], article['Publication time'])])\r\n if account_nohit == list():\r\n html_footer = ['', '
No.TitleAbstractSubscription NamePublication Time
%s%s%s%s
', '', '']\r\n else:\r\n nohit_ = '

' + ', '.join(account_nohit) + '

'\r\n warning_ = ['

These subscriptions did NOT return any article:

', nohit_, \r\n '

If this is not normal, please recheck names of these subscriptions in file wechat_subscriptions.txt.

', \r\n '

If problem persists, feel free to contact me.

']\r\n html_footer = ['', '
']\r\n html_footer.extend(warning_)\r\n html_footer.extend(['
', ''])\r\n with open(html_file, 'w', encoding='utf8') as f:\r\n f.write('\\n'.join(html_header))\r\n for artc in html_body:\r\n f.write(artc)\r\n f.write('\\n'.join(html_footer))\r\n webbrowser.open_new_tab(os.path.abspath(html_file))\r\n \r\ndef main():\r\n articles, _nohit = gzh_update(subscription_file='wechat_subscriptions.txt', \r\n headline=False, original=False, timedel=1, add_account=None)\r\n to_html(articles, account_nohit=_nohit, html_file='wechat_portal.html')\r\n \r\nif __name__ == '__main__':\r\n main()","sub_path":"wechatAggregator.py","file_name":"wechatAggregator.py","file_ext":"py","file_size_in_byte":5778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"561222897","text":"from __future__ import division\r\n\r\nfrom flask import render_template, request\r\n\r\nfrom app import app\r\nfrom chatbot.config import basedir\r\n\r\nimport tensorflow as tf\r\nimport tensorlayer as tl\r\nfrom tensorlayer.layers import *\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport re\r\nimport os\r\n\r\nimport pickle\r\n\r\nCONTRACTIONS = {\r\n \"i ain't\": \"am not\",\r\n \"you ain't\": \"you are not\",\r\n \"they ain't\": \"they are not\",\r\n \"she ain't\": \"she is not\",\r\n \"he ain't\": \"he is not\",\r\n \"aren't\": \"are not\",\r\n \"can't\": \"cannot\",\r\n \"can't've\": \"cannot have\",\r\n \"'cause\": \"because\",\r\n \"could've\": \"could have\",\r\n \"couldn't\": \"could not\",\r\n \"couldn't've\": \"could not have\",\r\n \"didn't\": \"did not\",\r\n \"doesn't\": \"does not\",\r\n \"don't\": \"do not\",\r\n \"hadn't\": \"had not\",\r\n \"hadn't've\": \"had not have\",\r\n \"hasn't\": \"has not\",\r\n \"haven't\": \"have not\",\r\n \"he'd\": \"he would\",\r\n \"he'd've\": \"he would have\",\r\n \"he'll\": \"he will\",\r\n \"he'll've\": \"he will have\",\r\n \"he's\": \"he is\",\r\n \"how'd\": \"how did\",\r\n \"how'd'y\": \"how do you\",\r\n \"how'll\": \"how will\",\r\n \"how's\": \"how is\",\r\n \"i'd\": \"i would\",\r\n \"i'd've\": \"i would have\",\r\n \"i'll\": \"i will\",\r\n \"i'll've\": \"i will have\",\r\n \"i'm\": \"i am\",\r\n \"i've\": \"i have\",\r\n \"isn't\": \"is not\",\r\n \"it'd\": \"it would\",\r\n \"it'd've\": \"it would have\",\r\n \"it'll\": \"it will\",\r\n \"it'll've\": \"it will have\",\r\n \"it's\": \"it is\",\r\n \"let's\": \"let us\",\r\n \"ma'am\": \"madam\",\r\n \"mayn't\": \"may not\",\r\n \"might've\": \"might have\",\r\n \"mightn't\": \"might not\",\r\n \"mightn't've\": \"might not have\",\r\n \"must've\": \"must have\",\r\n \"mustn't\": \"must not\",\r\n \"mustn't've\": \"must not have\",\r\n \"needn't\": \"need not\",\r\n \"needn't've\": \"need not have\",\r\n \"o'clock\": \"of the clock\",\r\n \"oughtn't\": \"ought not\",\r\n \"oughtn't've\": \"ought not have\",\r\n \"shan't\": \"shall not\",\r\n \"sha'n't\": \"shall not\",\r\n \"shan't've\": \"shall not have\",\r\n \"she'd\": \"she would\",\r\n \"she'd've\": \"she would have\",\r\n \"she'll\": \"she will\",\r\n \"she'll've\": \"she will have\",\r\n \"she's\": \"she is\",\r\n \"should've\": \"should have\",\r\n \"shouldn't\": \"should not\",\r\n \"shouldn't've\": \"should not have\",\r\n \"so've\": \"so have\",\r\n \"so's\": \"so is\",\r\n \"that'd\": \"that had\",\r\n \"that'd've\": \"that would have\",\r\n \"that's\": \"that is\",\r\n \"there'd\": \"there would\",\r\n \"there'd've\": \"there would have\",\r\n \"there's\": \"there is\",\r\n \"they'd\": \"they would\",\r\n \"they'd've\": \"they would have\",\r\n \"they'll\": \"they will\",\r\n \"they'll've\": \"they will have\",\r\n \"they're\": \"they are\",\r\n \"they've\": \"they have\",\r\n \"to've\": \"to have\",\r\n \"wasn't\": \"was not\",\r\n \"we'd\": \"we would\",\r\n \"we'd've\": \"we would have\",\r\n \"we'll\": \"we will\",\r\n \"we'll've\": \"we will have\",\r\n \"we're\": \"we are\",\r\n \"we've\": \"we have\",\r\n \"weren't\": \"were not\",\r\n \"what'll\": \"what will\",\r\n \"what'll've\": \"what will have\",\r\n \"what're\": \"what are\",\r\n \"what's\": \"what is\",\r\n \"what've\": \"what have\",\r\n \"when's\": \"when is\",\r\n \"when've\": \"when have\",\r\n \"where'd\": \"where did\",\r\n \"where's\": \"where is\",\r\n \"where've\": \"where have\",\r\n \"who'll\": \"who will\",\r\n \"who'll've\": \"who will have\",\r\n \"who's\": \"who is\",\r\n \"who've\": \"who have\",\r\n \"why's\": \"why is\",\r\n \"why've\": \"why have\",\r\n \"will've\": \"will have\",\r\n \"won't\": \"will not\",\r\n \"won't've\": \"will not have\",\r\n \"would've\": \"would have\",\r\n \"wouldn't\": \"would not\",\r\n \"wouldn't've\": \"would not have\",\r\n \"y'all\": \"you all\",\r\n \"y'all'd\": \"you all would\",\r\n \"y'all'd've\": \"you all would have\",\r\n \"y'all're\": \"you all are\",\r\n \"y'all've\": \"you all have\",\r\n \"you'd\": \"you would\",\r\n \"you'd've\": \"you would have\",\r\n \"you'll\": \"you will\",\r\n \"you'll've\": \"you will have\",\r\n \"you're\": \"you are\",\r\n \"you've\": \"you have\"\r\n}\r\nCONTRACTIONS_RE = re.compile('(%s)' % '|'.join(CONTRACTIONS.keys()))\r\nNAME_LIST = pd.read_csv(os.path.join(basedir, \"data/firstnames.csv\"))[\"firstname\"].tolist()\r\n\r\ndef model(encode_seqs, decode_seqs, is_train=True, reuse=False):\r\n with tf.variable_scope(\"model\", reuse=reuse):\r\n # for chatbot, you can use the same embedding layer,\r\n # for translation, you may want to use 2 separated embedding layers\r\n with tf.variable_scope(\"embedding\") as vs:\r\n net_encode = EmbeddingInputlayer(\r\n inputs=encode_seqs,\r\n vocabulary_size=xvocab_size,\r\n embedding_size=emb_dim,\r\n name='seq_embedding')\r\n\r\n vs.reuse_variables()\r\n tl.layers.set_name_reuse(True)\r\n\r\n net_decode = EmbeddingInputlayer(\r\n inputs=decode_seqs,\r\n vocabulary_size=xvocab_size,\r\n embedding_size=emb_dim,\r\n name='seq_embedding')\r\n\r\n net_rnn = Seq2Seq(net_encode, net_decode,\r\n cell_fn=tf.contrib.rnn.BasicLSTMCell,\r\n n_hidden=emb_dim,\r\n initializer=tf.random_uniform_initializer(-0.1, 0.1),\r\n encode_sequence_length=retrieve_seq_length_op2(encode_seqs),\r\n decode_sequence_length=retrieve_seq_length_op2(decode_seqs),\r\n initial_state_encode=None,\r\n dropout=(0.5 if is_train else None),\r\n n_layer=3,\r\n return_seq_2d=True,\r\n name='seq2seq')\r\n\r\n net_out = DenseLayer(net_rnn, n_units=xvocab_size, act=tf.identity, name='output')\r\n return net_out, net_rnn\r\n\r\nwith open(os.path.join(basedir, r'models/metadata_punc.pkl'), 'rb') as f:\r\n metadata = pickle.load(f)\r\n\r\nxvocab_size = metadata[\"xvocab_size\"]\r\nw2idx = metadata[\"w2idx\"]\r\nidx2w = metadata[\"idx2w\"]\r\nemb_dim = metadata[\"emb_dim\"]\r\n\r\nstart_id = w2idx[\"start_id\"]\r\nend_id = w2idx[\"end_id\"]\r\n\r\n# model for training\r\nbatch_size = 16\r\n\r\nencode_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"encode_seqs\")\r\ndecode_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"decode_seqs\")\r\ntarget_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"target_seqs\")\r\ntarget_mask = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"target_mask\") # tl.prepro.sequences_get_mask()\r\nnet_out, _ = model(encode_seqs, decode_seqs, is_train=True, reuse=False)\r\n\r\n# model for inferencing\r\nencode_seqs2 = tf.placeholder(dtype=tf.int64, shape=[1, None], name=\"encode_seqs\")\r\ndecode_seqs2 = tf.placeholder(dtype=tf.int64, shape=[1, None], name=\"decode_seqs\")\r\nnet, net_rnn = model(encode_seqs2, decode_seqs2, is_train=False, reuse=True)\r\ny = tf.nn.softmax(net.outputs)\r\n\r\nos.chdir(os.path.join(basedir, r'models'))\r\n\r\nsess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=False))\r\ntl.layers.initialize_global_variables(sess)\r\ntl.files.load_and_assign_npz(sess=sess, name='n_withPunc.npz', network=net)\r\n\r\n\r\ndef expand_contractions(s, contractions_dict=CONTRACTIONS, contractions_re=CONTRACTIONS_RE):\r\n def replace(match):\r\n return contractions_dict[match.group(0)]\r\n return contractions_re.sub(replace, s)\r\n\r\n\r\ndef clean_text(text, name_list=NAME_LIST):\r\n # get rid of common english names\r\n text = \" \".join([w for w in text.split(\" \") if re.sub(r'[^\\w\\d_\\s]+', '', w) not in name_list])\r\n \r\n # to lower case\r\n text = text.lower()\r\n # remove @ mentions\r\n text = re.sub(r'@\\w+\\b', '', text)\r\n # remove url links\r\n text = re.sub(r'\\bhttp.+\\b', '', text)\r\n # remove line break\r\n text = re.sub(r'\\n', ' ', text)\r\n \r\n # expand contraction\r\n text = expand_contractions(text)\r\n \r\n # replace some common shorthands\r\n text = re.sub(r'&', ' and ', text)\r\n text = re.sub(r'\\bb/c\\b', 'because', text)\r\n text = re.sub(r'\\b<\\b', '<', text)\r\n text = re.sub(r'\\b>\\b', '>', text)\r\n \r\n # remove punctuation\r\n # text = re.sub(r'[^\\w\\d_\\s]+', '', text)\r\n \r\n # get rid of initials at the end\r\n if len(text) > 0:\r\n if re.match(r'(?:\\/|\\^|\\*)[A-z]{2}', text[-1]) is not None:\r\n text.pop()\r\n \r\n if len(text) <= 3:\r\n return \"TO_DELETE\"\r\n else:\r\n return \" \".join(text.split())\r\n\r\n\r\n# landing page\r\n@app.route('/')\r\n@app.route('/index')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n\r\n# get response\r\n@app.route('/get_response', methods=['POST'])\r\ndef get_response():\r\n\r\n seed = str(request.json[\"input\"].replace(u'\\u2019', \"'\").replace('\"', \"\").replace(\"'\", '\"'))\r\n print(\"INPUT: \" + seed)\r\n\r\n seed = clean_text(seed)\r\n print(\"CLEANED INPUT: \" + seed)\r\n\r\n seed_id = [w2idx[w] for w in seed.split(\" \") if w in w2idx.keys()]\r\n\r\n response_list = []\r\n\r\n for _ in range(1): # 1 Query --> 1 Reply\r\n # 1. encode, get state\r\n state = sess.run(net_rnn.final_state_encode, {encode_seqs2: [seed_id]})\r\n # 2. decode, feed start_id, get first word\r\n o, state = sess.run([y, net_rnn.final_state_decode], {net_rnn.initial_state_decode: state, \r\n decode_seqs2: [[start_id]]})\r\n w_id = tl.nlp.sample_top(o[0], top_k=3)\r\n w = idx2w[w_id]\r\n \r\n # sort and save probabilities\r\n probs = []\r\n probabilities = o[0][w_id]\r\n \r\n # this stores the probability of the top word each time\r\n probs = np.append(probs, probabilities)\r\n \r\n # 3. decode, feed state iteratively\r\n if w != \"unk\":\r\n sentence = [w]\r\n else:\r\n sentence = []\r\n\r\n for _ in range(500): # max sentence length\r\n o, state = sess.run([y, net_rnn.final_state_decode], {net_rnn.initial_state_decode: state,\r\n decode_seqs2: [[w_id]]})\r\n w_id = tl.nlp.sample_top(o[0], top_k=2)\r\n w = idx2w[w_id]\r\n\r\n probabilities = o[0][w_id]\r\n \r\n if w_id == end_id:\r\n break\r\n\r\n if w != \"unk\":\r\n sentence = sentence + [w]\r\n\r\n probs = np.append(probs, probabilities)\r\n\r\n print(\"RESPONSE: \" + ' '.join(sentence))\r\n print(probs)\r\n\r\n return ' '.join(sentence)\r\n\r\n\r\n\r\n","sub_path":"chatbot/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"593466131","text":"from __future__ import absolute_import\n\nimport logging\nimport weakref\n\nimport tornado.ioloop\nimport tornado.iostream\n\nfrom ..exceptions import InvalidMessageException\nfrom ..messages import CallRequestMessage\nfrom .connection import TornadoConnection\nfrom .timeout import timeout\nfrom .inbound_server import InboundServer\n\nlog = logging.getLogger('tchannel')\n\n\nclass TChannel(object):\n \"\"\"Manages inbound and outbound connections to various hosts.\"\"\"\n\n def __init__(self, app=None):\n self.peers = {}\n self.inbound_server = InboundServer(app)\n\n @tornado.gen.coroutine\n def add_peer(self, hostport):\n if hostport not in self.peers:\n self.peers[hostport] = TornadoConnection.outgoing(hostport)\n yield self.peers[hostport]\n\n # We only want one connection at a time, someone else is\n # connecting so wait for them without blocking.\n while self.peers[hostport].running():\n yield tornado.gen.sleep(0.0)\n\n raise tornado.gen.Return(self.peers[hostport].result())\n\n def remove_peer(self, hostport):\n # TODO: Connection cleanup\n return self.peers.pop(hostport)\n\n @tornado.gen.coroutine\n def get_peer(self, hostport):\n peer = yield self.add_peer(hostport)\n\n raise tornado.gen.Return(peer)\n\n @tornado.gen.coroutine\n def make_in_connection(self, port):\n self.inbound_server.listen(port)\n\n def request(self, hostport):\n return TChannelClientOperation(hostport, self)\n\n\nclass TChannelClientOperation(object):\n\n def __init__(self, hostport, tchannel):\n self.hostport = hostport\n self.message_id = None\n self.tchannel = weakref.ref(tchannel)\n\n @tornado.gen.coroutine\n def send(self, arg_1, arg_2, arg_3):\n # message = CallRequestMessage.from_context for zipkin shit\n # Make this return a message ID so we can match it up with the\n # response.\n peer_connection = yield self.tchannel().get_peer(self.hostport)\n self.message_id = message_id = peer_connection.next_message_id()\n\n def safebytes(arg):\n if arg is None:\n return None\n if isinstance(arg, bytes):\n return arg\n return bytes(arg.encode('ascii'))\n\n message = CallRequestMessage(\n service='tcurl',\n arg_1=safebytes(arg_1),\n arg_2=arg_2,\n arg_3=arg_3,\n )\n\n log.debug(\"framing and writing message %s\", message_id)\n\n yield peer_connection.frame_and_write(\n message,\n message_id=message_id,\n )\n\n log.debug(\"awaiting response for message %s\", message_id)\n\n # Pull this out into its own loop, look up response message ids\n # and dispatch them to handlers.\n peer_connection.awaiting_responses[message_id] = tornado.gen.Future()\n\n # TODO: use real timeout here\n with timeout(peer_connection):\n response = yield peer_connection.awaiting_responses[message_id]\n\n # TODO: Add a callback to remove ourselves from the ops\n # list.\n\n log.debug(\"got response for message %s\", response.message_id)\n\n if not response:\n raise InvalidMessageException()\n\n raise tornado.gen.Return(response.message)\n","sub_path":"python/tchannel/tornado/tchannel.py","file_name":"tchannel.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"106774691","text":"\"\"\"\nVisualization App to verify that k-means works\n\nThe visualize can view any clustering on a set of 2d points. The visualization is\nlimited to k-values < 20.\n\nAuthor: Walker M. White (wmw2)\nDate: October 20, 2018\n\"\"\"\nimport matplotlib\nimport numpy\nimport math\nimport traceback\nmatplotlib.use('TkAgg')\n\n# Modules to embed matplotlib in a custom Tkinter window\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\n# implement the default mpl key bindings\nfrom matplotlib.backend_bases import key_press_handler\nfrom matplotlib.figure import Figure\nfrom matplotlib.axes import Axes\n\n# File support to load data files\nimport tkinter as tk\nfrom tkinter import font, filedialog, messagebox\nimport sys, os, os.path\n\n# The k-means implementation\nimport a6dataset\nimport a6cluster\nimport a6algorithm\nimport tools\n\n\nclass Visualizer(object):\n \"\"\"\n A class providing a visualization app.\n\n INSTANCE ATTRIBUTES:\n _root: TCL/TK graphics backend [TK object]\n _canvas: MatPlotLib canvas [FigureCanvas object]\n _axes: MatPlotLib axes [Scatter object]\n _dset: Data set [Dataset object]\n _kmean: Clustering of dataset [Algorithm object]\n _count: Number of steps executed [int >= 0]\n _finish: Whether the computation is done [bool]\n\n There are several other attributes for GUI widgets (buttons and labels).\n We do not list all of them here.\n \"\"\"\n # Maximum allowable k-means\n MAX_KVAL = 20\n\n # The cluster colors\n COLORS = ((1,0,0),(0,1,0),(0,0,1),(0,1,1),(1,0,1),(1,1,0),(1,0.5,0),(0.3,0.5,0.3),(1,0.6,0.7),(0,0,0))\n\n @classmethod\n def launch(cls,filename,k):\n \"\"\"\n Launches the visualizer and starts the application loop.\n\n Parameter filename: The name of the initial dataset\n Precondition: filename is a valid file path OR None.\n\n Parameter k: The initial number of clusters\n Precondition: k is an int\n \"\"\"\n cls(filename,k)\n tk.mainloop()\n\n def __init__(self, filename=None, k=3):\n \"\"\"\n Initializes a visualization app.\n\n The initial dataset and k value are optional. By default, it will\n choose the first dataset from the dataset directory.\n\n Parameter filename: The name of the initial dataset\n Precondition: filename is a valid file path OR None.\n\n Parameter k: The initial number of clusters\n Precondition: k is an int\n \"\"\"\n self._root = tk.Tk()\n self._root.wm_title(\"Clustering Visualizer\")\n self._dset = None\n self._kmean = None\n\n # Start the application\n self._config_canvas()\n self._config_control()\n if not k is None:\n self._kval.set(k)\n\n if filename:\n self._select_data(filename,False)\n else:\n self._select_data()\n self._canvas.draw()\n\n def _config_canvas(self):\n \"\"\"\n Loads the MatPlotLib drawing code\n \"\"\"\n # Create the drawing canvas\n figure = Figure(figsize=(6,6), dpi=100)\n self._canvas = FigureCanvasTkAgg(figure, master=self._root)\n self._canvas._tkcanvas.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)\n\n # Initialize the scatter plot\n self._axes = figure.gca()\n self._axes.set_xlim((0.0, 1.0))\n self._axes.set_ylim((0.0, 1.0))\n self._axes.set_xlabel('X')\n label = self._axes.set_ylabel('Y')\n label.set_rotation(0)\n self._axes.set_xticks(numpy.arange(0.0,1.0,0.1))\n self._axes.set_yticks(numpy.arange(0.0,1.0,0.1))\n self._axes.tick_params(labelsize=9)\n\n def _config_control(self):\n \"\"\"\n Creates the control panel on the right hand side\n\n This method is WAY too long, but GUI layout code is typically like this. Plus,\n Tkinter makes this even worse than it should be.\n \"\"\"\n panel = tk.Frame(master=self._root)\n panel.columnconfigure(0,pad=3)\n panel.columnconfigure(1,pad=3,minsize=150)\n panel.rowconfigure(0,pad=3)\n panel.rowconfigure(1,pad=0)\n panel.rowconfigure(2,pad=23)\n panel.rowconfigure(3,pad=3)\n panel.rowconfigure(4,pad=3)\n panel.rowconfigure(5,pad=3)\n panel.rowconfigure(6,pad=3)\n panel.rowconfigure(7,pad=13)\n panel.columnconfigure(2,minsize=20)\n\n title = tk.Label(master=panel,text='K Means Control',height=3)\n wfont = font.Font(font=title['font'])\n wfont.config(weight='bold',size=20)\n title.grid(row=0,columnspan=2, sticky='we')\n title.config(font=wfont)\n\n divider = tk.Frame(master=panel,height=2, bd=1, relief=tk.SUNKEN)\n divider.grid(row=1,columnspan=2, sticky='we')\n\n # Label and button for managing files.\n label = tk.Label(master=panel,text='Data Set: ',height=2)\n wfont = font.Font(font=label['font'])\n wfont.config(weight='bold')\n label.config(font=wfont)\n label.grid(row=2,column=0, sticky='e')\n\n files = tools.list_csv(os.path.join(os.path.split(__file__)[0],'data'),'-2d')\n files.append('', the name\n of a file, or a prefix of a 2d data set in the data directory.\n\n Parameter local: Whether to chose the file from the data directory\n Precondition: local is a boolean\n \"\"\"\n if file is None:\n file = self._kfile.get()\n if file == '