diff --git "a/5878.jsonl" "b/5878.jsonl" new file mode 100644--- /dev/null +++ "b/5878.jsonl" @@ -0,0 +1,653 @@ +{"seq_id":"339996818","text":"\n# -*- coding: utf-8 -*-\n# @Date : 2018-09-16 07:22:42\n# @Author : raj lath (oorja.halt@gmail.com)\n# @Link : link\n# @Version : 1.0.0\n\nimport os\nfrom sys import stdin\n\nmax_val=int(10e12)\nmin_val=int(-10e12)\n\ndef read_int() : return int(stdin.readline())\ndef read_ints() : return [int(x) for x in stdin.readline().split()]\ndef read_str() : return input()\ndef read_strs() : return [x for x in stdin.readline().split()]\ndef read_str_list(): return [x for x in stdin.readline().split().split()]\n\n\ndef is_prime_1(n):\n if n <= 1:return False\n i = 2\n while i * i <= n:\n if not n%i:return False\n i += 1\n return True\n\ndef seive(n):\n primes = [0, 0] + [1] * n\n i = 2\n while i * i <= n:\n if primes[i]:\n j = 2 * i\n while j < n:\n primes[j] = 0\n j += i\n i += 1\n #return [x for x in range(122) if primes[x]]\n #return primes\n\ndef winner(s, maps):\n n1 = s[0]\n n2 = s[0:len(s)-1]\n win = False\n print(n1, n2)\n if not is_prime_1(int(n1)) and not winner(n1, maps):win = True\n if not is_prime_1(int(n2)) and not winner(n2, maps):win = True\n return win\n\n'''\nnb_tests = read_int()\nfor _ in range(nb_tests):\n s = read_int()\n maps = {}\n if win(s//10) or win(s%10):\n print(\"Alice\")\n else:\n print(\"Bob\")\n'''\nimport random\ndef miller_rabin(n, k):\n if n in [2, 3]: return True\n if not n%2 : return False\n left, rite = 0, n-1\n while not rite % 2:\n left += 1\n rite //= 2\n for _ in range(k):\n a = random.randrange(2, n-1)\n x = pow(a, rite, left)\n if x == 1 or x == n-1:continue\n for _ in range(left - 1):\n x = pow(x, 2, n)\n if x == n - 1:\n break\n else:return False\n return True\n\n\n\n","sub_path":"HackerEarth/HOurStorm3_Problem_B_prime_game.py","file_name":"HOurStorm3_Problem_B_prime_game.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"95300494","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport os\nfrom numpy import linalg as LA\nimport math\nimport scipy.stats as stats\n\n\ndef calculateGaussianEquation(x_co, mean, std):\n return (1 / (std * math.sqrt(2 * math.pi))) * np.exp(-np.power(x_co - mean, 2.) / (2 * np.power(std, 2.)))\n\n\ndef calculateProbabilty(x_co, mean, std):\n return (1 / (std * math.sqrt(2 * math.pi))) * (math.exp(-((x_co - mean) ** 2) / (2 * (std) ** 2)))\n\n\ndef em_gmm():\n pixel = []\n g1, g2, g3, g4 = [], [], [], []\n y = []\n \n images=[]\n path = \"/home/varsha/Desktop/ENPM673/Buoy/Orange/\"\n for image in os.listdir(path):\n images.append(image)\n \n #for i in range(1, 37 + 1):\n for image in images:\n image = cv.imread(\"%s%s\"%(path,image))\n image = image[:, :, 2]\n r, c = image.shape\n for j in range(0, r):\n for m in range(0, c):\n im = image[j][m]\n # print(im)\n pixel.append(im)\n print(len(pixel))\n n = 0\n mean1 = 190\n mean2 = 150\n mean3 = 250\n #mean4 = 100\n std1 = 10\n std2 = 10\n std3 = 10\n #std4 = 10\n while (n != 50):\n prob1 = []\n prob2 = []\n prob3 = []\n prob4 = []\n b1 = []\n b2 = []\n b3 = []\n b4 = []\n for im in pixel:\n p1 = calculateProbabilty(im, mean1, std1)\n prob1.append(p1)\n p2 = calculateProbabilty(im, mean2, std2)\n prob2.append(p2)\n p3 = calculateProbabilty(im, mean3, std3)\n prob3.append(p3)\n #p4 = calculateProbabilty(im, mean4, std4)\n #prob4.append(p4)\n #b1.append((p1 * (1 / 4)) / (p1 * (1 / 4) + p2 * (1 / 4) + p3 * (1 / 4) + p4 * (1/4)))\n #b2.append((p2 * (1 / 4)) / (p1 * (1 / 4) + p2 * (1 / 4) + p3 * (1 / 4) + p4 * (1/4)))\n #b3.append((p3 * (1 / 4)) / (p1 * (1 / 4) + p2 * (1 / 4) + p3 * (1 / 4) + p4 * (1/4)))\n #b4.append((p4 * (1 / 4)) / (p1 * (1 / 4) + p2 * (1 / 4) + p3 * (1 / 4) + p4 * (1/4)))\n b1.append((p1 * (1 / 3)) / (p1 * (1 / 3) + p2 * (1 / 3) + p3 * (1 / 3) ))\n b2.append((p2 * (1 / 3)) / (p1 * (1 / 3) + p2 * (1 / 3) + p3 * (1 / 3) ))\n b3.append((p3 * (1 / 3)) / (p1 * (1 / 3) + p2 * (1 / 3) + p3 * (1 / 3) ))\n \n mean1 = np.sum(np.array(b1) * np.array(pixel)) / np.sum(np.array(b1))\n mean2 = np.sum(np.array(b2) * np.array(pixel)) / np.sum(np.array(b2))\n mean3 = np.sum(np.array(b3) * np.array(pixel)) / np.sum(np.array(b3))\n #mean4 = np.sum(np.array(b4) * np.array(pixel)) / np.sum(np.array(b4))\n \n std1 = (np.sum(np.array(b1) * ((np.array(pixel)) - mean1) ** (2)) / np.sum(np.array(b1))) ** (1 / 2)\n std2 = (np.sum(np.array(b2) * ((np.array(pixel)) - mean2) ** (2)) / np.sum(np.array(b2))) ** (1 / 2)\n std3 = (np.sum(np.array(b3) * ((np.array(pixel)) - mean3) ** (2)) / np.sum(np.array(b3))) ** (1 / 2)\n #std4 = (np.sum(np.array(b4) * ((np.array(pixel)) - mean4) ** (2)) / np.sum(np.array(b4))) ** (1 / 2)\n n = n + 1\n print(mean1, mean2, mean3)\n print(std1, std2, std3)\n print('final mean- ',mean1,mean2,mean3)\n print('final strd- ',std1, std2, std3)\n\n\n# In[ ]:\n\n\nem_gmm()\n\n\n# In[ ]:\n\n\n\n\n\n","sub_path":"gmm_red.py","file_name":"gmm_red.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"89554643","text":"import cv2\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable\r\nfrom scipy import ndimage\r\n\r\ndef resize(im,size):\r\n im_resize = cv2.resize(im,size,interpolation=cv2.INTER_CUBIC)\r\n return im_resize\r\n\r\n\r\ndef crop_batch(batch,model,threshold,method,mean):\r\n batch_size = np.shape(batch)[0]\r\n inputs = torch.zeros(1,3,224,224)\r\n for i in range(batch_size):\r\n image = batch[i,:,:,:].view(1,3,224,224).float().cuda().detach()\r\n out = model.features(image).detach()\r\n out = F.relu(out,inplace=True)\r\n \r\n if mean:\r\n heat_map = out.abs().mean(1)[0].view(7,7)\r\n elif not mean:\r\n heat_map = out.abs().max(1)[0].view(7,7)\r\n heat_map = resize(heat_map.cpu().numpy(),(224,224))\r\n heat_map = cv2.normalize(heat_map, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\r\n heat_map[heat_map < threshold] = 0\r\n heat_map[heat_map >= threshold] = 1\r\n \r\n \r\n \r\n if method == 'Simple':\r\n #Return without doing further operations\r\n mask = np.dstack((heat_map,heat_map,heat_map))\r\n image_masked = mask*image.view(3,224,224).permute(1,2,0).cpu().numpy()\r\n \r\n \r\n image_masked = torch.from_numpy(image_masked).permute(2,0,1).view(1,3,224,224)\r\n inputs = torch.cat((inputs,image_masked),0)\r\n elif method == 'Complex':\r\n labeled_image, num_features = ndimage.label(heat_map)\r\n sizes = ndimage.sum(heat_map, labeled_image, range(num_features+1))\r\n largest_blob = sizes.argmax()-1\r\n objs = ndimage.find_objects(labeled_image,max_label=largest_blob)\r\n bb = image.view(3,224,224).permute(1,2,0).cpu().numpy()[objs[0]]\r\n \r\n dim = np.shape(bb)\r\n largest_dim = np.argmax(dim[0:2])\r\n\r\n if largest_dim == 0:\r\n diff = dim[0] - dim[1]\r\n padding_sides = int(np.round(diff/2))\r\n padding_top = int(0)\r\n elif largest_dim == 1:\r\n diff= dim[1] - dim[0]\r\n padding_sides = int(0)\r\n padding_top = int(np.round(diff/2))\r\n \r\n\r\n color = [0, 0, 0]\r\n padded_im = cv2.copyMakeBorder(bb, padding_top, padding_top, \r\n padding_sides, padding_sides, cv2.BORDER_CONSTANT, value=color)\r\n \r\n image_cropped = resize(padded_im,(224,224))\r\n image_cropped = torch.from_numpy(image_cropped).permute(2,0,1).view(1,3,224,224)\r\n inputs = torch.cat((inputs,image_cropped),0)\r\n \r\n \r\n \r\n \r\n \r\n return inputs[1:,:,:,:]\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"cropping.py","file_name":"cropping.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"261419575","text":"# Create your views here.\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom biblioteca.apps.libros.models import *#Prestamo, Autor, Editorial, Categoria, Bibliotecario, Usuario, Ciudad, Tipo_Usuario, Libro, Biblioteca\nfrom datetime import date\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth import login, logout, authenticate\nfrom biblioteca.apps.home.forms import *#libronuevo_form,Login_form\nimport django\n\nfrom biblioteca.apps.libros.models import Espacio\nfrom django.core import serializers\n\nfrom django.utils import simplejson\nfrom django.core.mail import EmailMultiAlternatives\n\nfrom django.http import Http404\n\ndef detail(request, poll_id):\n try:\n poll = Poll.objects.get(pk=poll_id)\n except Poll.DoesNotExist:\n raise Http404\n return render(request, 'home/404.html', {'poll': poll})\n\ndef index_view (request):\n\treturn render_to_response('home/index.html', context_instance = RequestContext(request))\n#administador\ndef administrar_view (request):\n\treturn render_to_response('libros/administrar.html', context_instance = RequestContext(request))\ndef reservas_view (request):\n\treservas = Prestamo.objects.filter(estado_prestamo=\"Reservado\").order_by('-id')\n\tctx = {'reservas' :reservas}\n\treturn render_to_response ('home/reservas.html', ctx, context_instance = RequestContext(request))\n\n#Reservas de los usuarios registrados\ndef mis_reservas_view (request):\n\treservas = Prestamo.objects.filter(usuario__user = request.user).order_by('-id')\n\tctx = {'reservas' :reservas}\n\treturn render_to_response('home/mis_reservas.html', ctx, context_instance = RequestContext(request))\n\n\n\ndef prestamos_view(request):\n\ttipo = Prestamo.objects.filter().order_by('-id')\n\tctx = {'prestamos' :tipo}\n\treturn render_to_response ('home/prestamos.html', ctx, context_instance = RequestContext(request))\n\ndef single_prestamo_view(request, id_editprest):\n\teditprest = Prestamo.objects.get(id = id_editprest)\n\tctx = {'prestamo':editprest}\n\treturn render_to_response('home/single_prestamo.html',ctx,context_instance = RequestContext(request))\n\n\n\n\n#bibliotecario\ndef bibliotecarios_view (request):\n\tif request.method==\"POST\":\n\t\n\t\tif \"product_id\" in request.POST:\n\t\t\ttry:\n\t\t\t\tl = None\n\t\t\t\tid_usuario = request.POST['product_id']\n\t\t\t\tp = Usuario.objects.get(pk=id_usuario)\n\t\t\t\tu = User.objects.get (pk = p.user.id)\n\t\t\t\ttry:\n\t\t\t\t\tl = Prestamo.objects.get(usuario__id = id_usuario, usuario__user__id = u.id)\n\t\t\t\texcept:\n\t\t\t\t\tl = None\n\t\t\t\tif l == None:\n\t\t\t\t\tu.delete()\n\t\t\t\t\t#p.delete()\n\t\t\t\t\tmensaje={\"status\":\"True\",\"product_id\":p.id}\n\t\t\t\treturn HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')\n\t\t\texcept:\n\t\t\t\tmensaje={\"status\":\"False\"}\n\t\t\t\treturn HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')\n\tbiblio = Usuario.objects.filter(tipo_usuario__nombre = 'bibliotecario')\n\tctx = {'bibliotecarios': biblio}\n\treturn render_to_response ('home/bibliotecarios.html', ctx, context_instance = RequestContext(request))\n\ndef single_bibliotecarios_view(request, id_biblio):\n\tusua = Usuario.objects.get(id = id_biblio)\n\tctx = {'usuario':usua}\n\treturn render_to_response('home/single_usuario.html',ctx,context_instance = RequestContext(request))\n\n#usuario\ndef usuarios_view(request):\n\t\n\tif request.method==\"POST\":\n\t\n\t\tif \"product_id\" in request.POST:\n\t\t\ttry:\n\t\t\t\tl = None\n\t\t\t\tid_usuario = request.POST['product_id']\n\t\t\t\tp = Usuario.objects.get(pk=id_usuario)\n\t\t\t\tu = User.objects.get (pk = p.user.id)\n\t\t\t\ttry:\n\t\t\t\t\tl = Prestamo.objects.get(usuario__id = id_usuario, usuario__user__id = u.id)\n\t\t\t\texcept:\n\t\t\t\t\tl = None\n\t\t\t\tif l == None:\n\t\t\t\t\tu.delete()\n\t\t\t\t\t#p.delete()\n\t\t\t\t\tmensaje={\"status\":\"True\",\"product_id\":p.id}\n\t\t\t\treturn HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')\n\t\t\texcept:\n\t\t\t\tmensaje={\"status\":\"False\"}\n\t\t\t\treturn HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')\n\tp = Usuario.objects.all()\n\tctx = {'usuarios':p}\n\treturn render_to_response ('home/usuarios.html', ctx, context_instance = RequestContext(request))\n\ndef single_usuario_view(request, id_usua):\n\tusua = Usuario.objects.get(id = id_usua)\n\tctx = {'usuario':usua}\n\treturn render_to_response('home/single_usuario.html',ctx,context_instance = RequestContext(request))\n\n#tipo_usuario\ndef tipos_usuarios_view(request):\n\n\n\tif request.method==\"POST\":\n\t\n\t\tif \"product_id\" in request.POST:\n\t\t\ttry:\n\t\t\t\tl = None\n\t\t\t\tid_product = request.POST['product_id']\n\t\t\t\tp = Tipo_Usuario.objects.get(pk=id_product)\n\t\t\t\ttry:\n\t\t\t\t\tl = Usuario.objects.get(tipo_usuario__id = id_product)\n\t\t\t\texcept:\n\t\t\t\t\tl = None\n\t\t\t\tif l == None:\n\t\t\t\t\tp.delete()\n\t\t\t\t\t#p.delete()\n\t\t\t\t\tmensaje={\"status\":\"True\",\"product_id\":id_product}\n\t\t\t\treturn HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')\n\t\t\texcept:\n\t\t\t\tmensaje={\"status\":\"False\"}\n\t\t\t\treturn HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')\n\n\n\ttipo = Tipo_Usuario.objects.all()\n\tctx = {'tipos_usuarios' :tipo}\n\treturn render_to_response ('home/tipo_usuario.html', ctx, context_instance = RequestContext(request))\n\ndef single_tipo_usuario_view(request, id_tipo):\n\ttipo = Tipo_Usuario.objects.get(id = id_tipo)\n\tctx = {'tipos_usuarios' :tipo}\n\treturn render_to_response ('home/single_tipo.html', ctx, context_instance = RequestContext(request))\n\n\n\n\n\n\ndef espacios_view (request):\n\tif request.method==\"POST\":\n\t\n\t\tif \"product_id\" in request.POST:\n\t\t\ttry:\n\t\t\t\tl = None\n\t\t\t\tid_product = request.POST['product_id']\n\t\t\t\tp= Espacio.objects.get(pk=id_product)\n\t\t\t\ttry:\n\t\t\t\t\tl = Prestamo.objects.get(espacio__id = id_product)\n\t\t\t\texcept:\n\t\t\t\t\tl = None\n\t\t\t\tif l == None:\n\t\t\t\t\tp.delete()\n\t\t\t\t\t#p.delete()\n\t\t\t\t\tmensaje={\"status\":\"True\",\"product_id\":id_product}\n\t\t\t\treturn HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')\n\t\t\texcept:\n\t\t\t\tmensaje={\"status\":\"False\"}\n\t\t\t\treturn HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')\n\tlista_l = Espacio.objects.all()\n\tctx = {'espacios' :lista_l}\n\treturn render_to_response('home/espacios.html',ctx, context_instance = RequestContext(request))\n\n\t\n\ndef single_espacio_view (request, id_prod): \n\tprod = Espacio.objects.get(id = id_prod)\n\t#cat = prod.categoria.all()\n\tctx = {'espacio':prod}# 'categoria': cat}\n\treturn render_to_response('home/single_espacio.html',ctx, context_instance = RequestContext(request))\n\ndef espacionuevo_view(request):\n\tinfo = \"inicializando\"\n\tfecha_inicio = \"\"\n\tnuevos = []\n\th = date.today()\n\tmensaje = \"\"\n\n\tif request.method == \"POST\":\n\t\tformulario = espacionuevo_form(request.POST)\n\t\tif formulario.is_valid():\n\t\t\t\n\t\t\tinfo = True \n\t\t\tfecha_inicio = formulario.cleaned_data['fecha_inicio']\n\t\t\t\n\t\t\tif fecha_inicio < h:\n\t\t\t\tnuevos = espacio.objects.filter(fecha_publicacion__range =(fecha_inicio, h))#se hace un rango de los ultimos libros comprados\n\t\t\telse:\n\t\t\t\tmensaje = \"no hay espacios\"\n\n\t\t\tformulario = espacionuevo_form()\n\t\tctx = {'form':formulario, 'informacion':info, 'nuevos':nuevos, 'mensaje':mensaje}\n\t\treturn render_to_response ('home/espacionuevo.html', ctx,context_instance =RequestContext(request))\n\n\telse:\n\t\tformulario = espacionuevo_form()\n\tctx = {'form':formulario, 'informacion':info, 'nuevos':nuevos, 'mensaje':mensaje}\n\treturn render_to_response ('home/espacionuevo.html', ctx,context_instance =RequestContext(request))\n\ndef login_view(request):\n\tmensaje = \"\"\n\tif request.user.is_authenticated():\n\t\treturn HttpResponseRedirect('/')\n\telse:\n\t\tif request.method == \"POST\":\n\t\t\tformulario = Login_form(request.POST)\n\t\t\tif formulario.is_valid():\n\t\t\t\tusu = formulario.cleaned_data['usuario']\n\t\t\t\tpas = formulario.cleaned_data['clave']\n\t\t\t\tusuario = authenticate(username = usu, password = pas)\n\t\t\t\tif usuario is not None and usuario.is_active:\n\t\t\t\t\tlogin(request, usuario)\n\t\t\t\t\treturn HttpResponseRedirect('/')\n\t\t\t\telse:\n\t\t\t\t\tmensaje = \"usuario y/o clave incorrecta\"\n\t\tformulario = Login_form()\n\t\tctx = {'form':formulario, 'mensaje':mensaje}\n\t\treturn render_to_response ('home/login.html', ctx, context_instance =RequestContext(request))\n\ndef logout_view(request):\n\tlogout(request)\n\treturn HttpResponseRedirect('/')\n\ndef ws_espacio_view(request):\n\t\tdata = serializers.serialize(\"json\",Espacio.objects.filter())\n\t\treturn HttpResponse(data, mimetype = 'application/json')\n\n","sub_path":"biblioteca/biblioteca/apps/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"434449980","text":"#!/usr/bin/env python3\n#\n# Copyright 2022 Xiaomi Corp. (authors: Yifan Yang,\n# Zengwei Yao,\n# Wei Kang)\n#\n# See ../../../../LICENSE for clarification regarding multiple authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nfrom typing import Optional, Tuple\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ndef make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:\n \"\"\"\n Args:\n lengths:\n A 1-D tensor containing sentence lengths.\n max_len:\n The length of masks.\n Returns:\n Return a 2-D bool tensor, where masked positions\n are filled with `True` and non-masked positions are\n filled with `False`.\n >>> lengths = torch.tensor([1, 3, 2, 5])\n >>> make_pad_mask(lengths)\n tensor([[False, True, True, True, True],\n [False, False, False, True, True],\n [False, False, True, True, True],\n [False, False, False, False, False]])\n \"\"\"\n assert lengths.ndim == 1, lengths.ndim\n max_len = max(max_len, lengths.max())\n n = lengths.size(0)\n seq_range = torch.arange(0, max_len, device=lengths.device)\n expaned_lengths = seq_range.unsqueeze(0).expand(n, max_len)\n\n return expaned_lengths >= lengths.unsqueeze(-1)\n\n\n\nclass FrameReducer(nn.Module):\n \"\"\"The encoder output is first used to calculate\n the CTC posterior probability; then for each output frame,\n if its blank posterior is bigger than some thresholds,\n it will be simply discarded from the encoder output.\n \"\"\"\n\n def __init__(\n self,\n blank_threshlod: float = 0.95,\n ):\n super().__init__()\n self.blank_threshlod = blank_threshlod\n\n def forward(\n self,\n x: torch.Tensor,\n x_lens: torch.Tensor,\n ctc_output: torch.Tensor,\n y_lens: Optional[torch.Tensor] = None,\n blank_id: int = 0,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Args:\n x:\n The shared encoder output with shape [N, T, C].\n x_lens:\n A tensor of shape (batch_size,) containing the number of frames in\n `x` before padding.\n ctc_output:\n The CTC output with shape [N, T, vocab_size].\n y_lens:\n A tensor of shape (batch_size,) containing the number of frames in\n `y` before padding.\n blank_id:\n The blank id of ctc_output.\n Returns:\n out:\n The frame reduced encoder output with shape [N, T', C].\n out_lens:\n A tensor of shape (batch_size,) containing the number of frames in\n `out` before padding.\n \"\"\"\n N, T, C = x.size()\n\n padding_mask = make_pad_mask(x_lens, x.size(1))\n non_blank_mask = (ctc_output[:, :, blank_id] < math.log(self.blank_threshlod)) * (~padding_mask) # noqa\n\n if y_lens is not None:\n # Limit the maximum number of reduced frames\n limit_lens = T - y_lens\n max_limit_len = limit_lens.max().int()\n fake_limit_indexes = torch.topk(\n ctc_output[:, :, blank_id], max_limit_len\n ).indices\n T = (\n torch.arange(max_limit_len)\n .expand_as(\n fake_limit_indexes,\n )\n .to(device=x.device)\n )\n T = torch.remainder(T, limit_lens.unsqueeze(1))\n limit_indexes = torch.gather(fake_limit_indexes, 1, T)\n limit_mask = torch.full_like(\n non_blank_mask,\n False,\n device=x.device,\n ).scatter_(1, limit_indexes, True)\n\n non_blank_mask = non_blank_mask | ~limit_mask\n\n out_lens = non_blank_mask.sum(dim=1)\n max_len = out_lens.max()\n pad_lens_list = (\n torch.full_like(\n out_lens,\n max_len.item(),\n device=x.device,\n )\n - out_lens\n )\n max_pad_len = pad_lens_list.max()\n\n out = F.pad(x, (0, 0, 0, max_pad_len))\n\n valid_pad_mask = ~make_pad_mask(pad_lens_list)\n total_valid_mask = torch.concat([non_blank_mask, valid_pad_mask], dim=1)\n\n out = out[total_valid_mask].reshape(N, -1, C)\n\n return out, out_lens\n\n\nif __name__ == \"__main__\":\n import time\n\n test_times = 10000\n device = \"cuda:0\"\n frame_reducer = FrameReducer()\n\n # non zero case\n x = torch.ones(15, 498, 384, dtype=torch.float32, device=device)\n x_lens = torch.tensor([498] * 15, dtype=torch.int64, device=device)\n y_lens = torch.tensor([150] * 15, dtype=torch.int64, device=device)\n ctc_output = torch.log(\n torch.randn(15, 498, 500, dtype=torch.float32, device=device),\n )\n\n avg_time = 0\n for i in range(test_times):\n torch.cuda.synchronize(device=x.device)\n delta_time = time.time()\n x_fr, x_lens_fr = frame_reducer(x, x_lens, ctc_output, y_lens)\n torch.cuda.synchronize(device=x.device)\n delta_time = time.time() - delta_time\n avg_time += delta_time\n print(x_fr.shape)\n print(x_lens_fr)\n print(avg_time / test_times)\n\n # all zero case\n x = torch.zeros(15, 498, 384, dtype=torch.float32, device=device)\n x_lens = torch.tensor([498] * 15, dtype=torch.int64, device=device)\n y_lens = torch.tensor([150] * 15, dtype=torch.int64, device=device)\n ctc_output = torch.zeros(15, 498, 500, dtype=torch.float32, device=device)\n\n avg_time = 0\n for i in range(test_times):\n torch.cuda.synchronize(device=x.device)\n delta_time = time.time()\n x_fr, x_lens_fr = frame_reducer(x, x_lens, ctc_output, y_lens)\n torch.cuda.synchronize(device=x.device)\n delta_time = time.time() - delta_time\n avg_time += delta_time\n print(x_fr.shape)\n print(x_lens_fr)\n print(avg_time / test_times)\n","sub_path":"PyTorch/built-in/audio/Wenet_Conformer_for_Pytorch/runtime/gpu/cuda_decoders/model_repo_cuda_decoder/scoring/1/frame_reducer.py","file_name":"frame_reducer.py","file_ext":"py","file_size_in_byte":6558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"629314246","text":"from ....tools.decorators import method\nfrom ....tools.utils import check_version\n\nimport scanpy as sc\n\n\n@method(\n method_name=\"Principle Component Analysis (PCA)\",\n paper_name=\"On lines and planes of closest fit to systems of points in space\",\n paper_url=\"https://www.tandfonline.com/doi/abs/10.1080/14786440109462720\",\n paper_year=1901,\n code_url=\"https://scikit-learn.org/stable/modules/generated/\"\n \"sklearn.decomposition.PCA.html\",\n code_version=check_version(\"scikit-learn\"),\n)\ndef pca(adata):\n sc.tl.pca(adata)\n adata.obsm[\"X_emb\"] = adata.obsm[\"X_pca\"][:, :2]\n return adata\n","sub_path":"openproblems/tasks/dimensionality_reduction/methods/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"480956109","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('',views.vista,name='vista'),\n path('cotizador',views.vista2,name='vista2'),\n path('cellphones', views.cellphones, name='cellphones'),\n path('cellphones/add', views.cellphonesAdd, name='cellphonesAdd'),\n path('cellphones/delete', views.cellphoneDelete, name='cellphoneDelete'),\n path('cellphones/get', views.cellphonesGet, name='cellphonesGet'),\n path('cellphones/get/', views.cellphonesGetId, name='cellphonesGetId'),\n path('cellphones/update/', views.cellphonesUpdate, name='cellphonesUpdate'),\n path('companies', views.companies, name='companies')\n]\n","sub_path":"DjangoPython/app/firstapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"276349533","text":"from time import sleep\nfrom modules import read_dht11_dat, LED, destroy, get_logger\n\nGREEN_LED_PIN = 17\nYELLOW_LED_PIN = 5\nRED_LED_PIN = 26\n\nYELLOW_THRESH = 75\nRED_THRESH = 85\n\nlogger = get_logger(__name__)\n\n\ndef main():\n green_led = LED(GREEN_LED_PIN)\n yellow_led = LED(YELLOW_LED_PIN)\n red_led = LED(RED_LED_PIN)\n\n try:\n discomf_idx = 0\n while True:\n result = read_dht11_dat()\n if result:\n humid, temp = result\n\n discomf_idx = 0.81 * temp + 0.01 * humid * (0.99 * temp - 14.3) + 46.3\n\n logger.info('discomfort index: {}'.format(discomf_idx))\n\n if discomf_idx >= RED_THRESH:\n red_led.blick()\n green_led.off()\n yellow_led.off()\n elif discomf_idx >= YELLOW_THRESH:\n yellow_led.blick()\n green_led.off()\n red_led.off()\n else:\n green_led.blick()\n red_led.off()\n yellow_led.off()\n\n sleep(1)\n\n except KeyboardInterrupt:\n green_led.destroy()\n yellow_led.destroy()\n red_led.destroy()\n destory()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"part2/scripts/dim.py","file_name":"dim.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"270355415","text":"from flask import Blueprint, jsonify, request, abort, session, render_template\nfrom app_init import app, client\nfrom utils import logger\nfrom database import db_connect, YmlConfig\n\n\nblueprint = Blueprint('dns_cache', __name__, url_prefix='/dns/cache')\nconf_path = '/dns/cache'\n\n\n@blueprint.route('/v1')\n@app.check_login()\ndef index1():\n return render_template('dns_cache_v1.html')\n\n\n@blueprint.route('/v2/')\n@app.check_login()\ndef index2(role):\n return render_template('dns_cache_v2.html')\n\n\n#===================================================================\n# v1\n@blueprint.route('/v1//cacheClear', methods=['POST'])\n@app.check_login()\ndef cacheClear(provider):\n if session['role'] not in ['admin', 'user_cash']:\n abort(403)\n \n domain_ids = request.json['domain_ids']\n logger.info('cache clear: %s' % str(domain_ids))\n\n try:\n if domain_ids is None:\n raise Exception('bad request')\n\n if provider not in client:\n raise Exception('unknown provider')\n\n results = client[provider].cacheClear(domain_ids)\n return jsonify(results)\n except Exception as e:\n logger.exception(e)\n return str(e), 500\n\n\n#===================================================================\n# v2\n@blueprint.route('/v2//list', methods=['POST'])\n@app.check_login()\ndef cacheTaskList(role):\n if session['role'] not in ['admin', role]:\n abort(403)\n\n path = '%s/%s' % (conf_path, role)\n\n db = db_connect()\n data = db.query(YmlConfig).filter_by(path=path).first()\n if not data:\n db.close()\n return '找不到配置檔: %s' % request.path, 404\n\n result = data.load()\n db.close()\n return jsonify(result)\n\n\n@blueprint.route('/v2//get', methods=['POST'])\n@app.check_login()\ndef cacheTaskEditGet(role):\n if session['role'] not in ['admin', role]:\n abort(403)\n\n path = '%s/%s' % (conf_path, role)\n\n db = db_connect()\n try:\n data = db.query(YmlConfig).filter_by(path=path).first()\n if data:\n result = data.content\n else:\n result = '#空白設定'\n\n db.close()\n return result\n except Exception as e:\n db.close()\n return str(e), 500\n\n\n@blueprint.route('/v2//update', methods=['POST'])\n@app.check_login()\ndef cacheTaskEditUpdate(role):\n if session['role'] not in ['admin', role]:\n abort(403)\n try:\n content = request.json['content']\n except:\n abort(400)\n\n path = '%s/%s' % (conf_path, role)\n\n db = db_connect()\n try:\n data = db.query(YmlConfig).filter_by(path=path).first()\n if data:\n data.save(content)\n else:\n data = YmlConfig(path, content=content)\n db.add(data)\n\n db.commit()\n db.close()\n return 'ok'\n except Exception as e:\n db.rollback()\n db.close()\n return str(e), 500\n\n\n@blueprint.route('/v2//run', methods=['POST'])\n@app.check_login()\ndef cacheTaskRun(role):\n if session['role'] not in ['admin', role]:\n abort(403)\n\n try:\n task = request.json['task']\n except:\n abort(400)\n\n try:\n for provider, domain_ids in task.items():\n logger.info('cache task run request: %s' % request.json)\n results = client[provider.lower()].cacheClear(domain_ids)\n logger.info('cache task run results: %s' % results)\n return str(results)\n except Exception as e:\n logger.exception(e)\n return str(e), 500\n","sub_path":"route/dns_cache.py","file_name":"dns_cache.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"553841453","text":"from flask import Flask, render_template, flash, redirect, url_for, request\n\nfrom model import AppModel\nfrom view_header import Route\nfrom presenter import Presenter\n\napp = Flask(__name__)\napp.secret_key = \"secret\"\nmodel = AppModel(app)\npresenter = Presenter(model)\n\ndef create_template(route):\n \"\"\"\n Takes in a route to redirect to or render a template for\n\n \"\"\"\n route_name = route.get_name()\n\n if route.is_redirect():\n return redirect(url_for(route_name))\n else:\n route_arg = route.get_args()\n if (route_arg == None):\n return render_template(route_name)\n return render_template(route_name, **(route_arg))\n\n\ndef present_flash(msg):\n \"\"\"\n Passes a message at the end of the request if not null\n\n \"\"\"\n if not (msg == None):\n flash(msg)\n\n\ndef render_view(view):\n \"\"\"\n Flashes a message and renders a template for the given view \n\n \"\"\"\n present_flash(view.get_flash())\n return create_template(view.get_route())\n\n\n# ~~~~~~~~~~ Routes ~~~~~~~~~~~~~~~~\n@app.route('/')\ndef index():\n return render_template(presenter.index())\n\n\n@app.route('/analyze', methods=['GET', 'POST'])\ndef analyze():\n if request.method == 'POST':\n return render_view(presenter.analyze(request))\n else:\n return render_template(presenter.index())\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"518497259","text":"\"\"\"Board object\"\"\"\n\nimport os\nimport sys\nimport logging\nimport xml.etree.ElementTree as ET\nimport random\n\nclass Board(object):\n \"\"\"Scrabble board class\"\"\"\n\n def __init__(self, board_matrix=[],board_setup_file='',dims=[]):\n \"\"\"Setup scrabble board\"\"\"\n self.logger = logging.getLogger(type(self).__name__)\n if board_setup_file:\n self.logger.debug('Configuring board from setup file %s'%(board_setup_file))\n self._setup_board(board_setup_file)\n elif dims and board_matrix:\n self.board_matrix = board_matrix\n self.dims = dims\n else:\n self.logger.error('Specify config file or preexisting board setup.')\n\n def _setup_board(self,board_setup_file,default_color='#BBB89E'):\n \"\"\"Configure board\"\"\"\n self.logger.debug('Setting up board')\n tree = ET.parse(board_setup_file)\n root = tree.getroot()\n special_spaces = root.find('special')\n dims = root.find('dimensions')\n nrows,ncols = int(dims.attrib['rows']),int(dims.attrib['cols'])\n self.dims = [nrows,ncols]\n self.board_matrix = []\n self.logger.debug('Setting board dimensions to (%d,%d)'%(self.dims[0],self.dims[1]))\n for j in range(ncols):\n for i in range(nrows):\n self.board_matrix.append({'label':None, 'wmult':1, 'lmult':1, 'letter':None, 'x':j, 'y':i, 'color':default_color, 'points':0})\n for space in special_spaces:\n i_row,i_col = int(space.attrib['row']),int(space.attrib['col'])\n for square in self.board_matrix:\n if square['x'] == i_col and square['y'] == i_row:\n square['label'] = space.attrib['label']\n square['wmult'] = int(space.attrib['wmult'])\n square['lmult'] = int(space.attrib['lmult'])\n square['color'] = space.attrib['color']\n\n def place_tiles(self,tiles,tile_color='#E1BF9A'):\n \"\"\"Put tiles from play on board\"\"\"\n coords = []\n for t in tiles:\n for i in range(len(self.board_matrix)):\n if t['rpos'] == self.board_matrix[i]['y'] and t['cpos'] == self.board_matrix[i]['x']:\n self.board_matrix[i]['letter'] = t['letter']\n self.board_matrix[i]['points'] = t['points']\n self.board_matrix[i]['color'] = tile_color\n coords.append(i)\n break\n\n return coords\n","sub_path":"micro_scrabble/game/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"404867718","text":"from django.core.management.base import BaseCommand\nfrom election.models import ElectionDay, ElectionType\nfrom electionnight.management.commands.methods import BootstrapContentMethods\nfrom geography.models import DivisionLevel\nfrom tqdm import tqdm\n\nfrom government.models import Jurisdiction\n\n\nclass Command(BaseCommand, BootstrapContentMethods):\n help = (\n \"Bootstraps page content items for pages for all elections on an \"\n \"election day. Must be run AFTER bootstrap_election command.\"\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"elections\",\n nargs=\"+\",\n help=\"Election dates to create content for.\",\n )\n\n def route_election(self, election):\n \"\"\"\n Legislative or executive office?\n \"\"\"\n if (\n election.election_type.slug == ElectionType.GENERAL\n or ElectionType.GENERAL_RUNOFF\n ):\n self.bootstrap_general_election(election)\n elif election.race.special:\n self.bootstrap_special_election(election)\n\n if election.race.office.is_executive:\n self.bootstrap_executive_office(election)\n else:\n self.bootstrap_legislative_office(election)\n\n def handle(self, *args, **options):\n self.NATIONAL_LEVEL = DivisionLevel.objects.get(\n name=DivisionLevel.COUNTRY\n )\n self.STATE_LEVEL = DivisionLevel.objects.get(name=DivisionLevel.STATE)\n self.FEDERAL_JURISDICTION = Jurisdiction.objects.get(\n division__level=self.NATIONAL_LEVEL\n )\n print(\"Bootstrapping page content\")\n election_dates = options[\"elections\"]\n\n for election_date in election_dates:\n print(\"> {}\".format(election_date))\n election_day = ElectionDay.objects.get(date=election_date)\n for election in tqdm(election_day.elections.all()):\n self.route_election(election)\n print(\"Done.\")\n","sub_path":"electionnight/management/commands/bootstrap_electionnight_content.py","file_name":"bootstrap_electionnight_content.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"130259663","text":"# -*- coding: utf-8 -*-\n##\n## This file is part of Invenio.\n## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 CERN.\n##\n## Invenio is free software; you can redistribute it and/or\n## modify it under the terms of the GNU General Public License as\n## published by the Free Software Foundation; either version 2 of the\n## License, or (at your option) any later version.\n##\n## Invenio is distributed in the hope that it will be useful, but\n## WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n## General Public License for more details.\n##\n## You should have received a copy of the GNU General Public License\n## along with Invenio; if not, write to the Free Software Foundation, Inc.,\n## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n\"\"\"BibFormat element - Prints INSPIRE jobs affiliation in JOBS search\n\"\"\"\n\nfrom urllib import quote_plus\n\ndef format_element(bfo, style=\"\", separator=' / '):\n \"\"\"\n This is the default format for formatting the contact person\n link in the Jobs format. This link will point to a direct search\n in the HepNames database.\n\n @param style: CSS class of the link\n @type style: str\n\n @param separator: the separator between names.\n @type separator: str\n \"\"\"\n\n contact_list = bfo.fields(\"110__a\")\n if style != \"\":\n style = 'class=\"'+style+'\"'\n\n contacts = ['' + contact +''\n for contact in contact_list]\n\n return separator.join(contacts)\n\ndef escape_values(bfo):\n \"\"\"\n Called by BibFormat in order to check if output of this element\n should be escaped.\n \"\"\"\n return 0\n","sub_path":"bibformat/format_elements/bfe_INSPIRE_jobs_affiliation.py","file_name":"bfe_INSPIRE_jobs_affiliation.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"71533268","text":"\"\"\"Ansible action plugin to decode ignition payloads\"\"\"\n\nimport base64\nimport os\nimport six\nfrom six.moves import urllib\nfrom ansible.plugins.action import ActionBase\n\n\n# pylint: disable=too-many-function-args\ndef get_file_data(encoded_contents):\n \"\"\"Decode data URLs as specified in RFC 2397\"\"\"\n # The following source is adapted from Python3 source\n # License: https://github.com/python/cpython/blob/3.7/LICENSE\n # retrieved from: https://github.com/python/cpython/blob/3.7/Lib/urllib/request.py\n _, data = encoded_contents.split(\":\", 1)\n mediatype, data = data.split(\",\", 1)\n\n # even base64 encoded data URLs might be quoted so unquote in any case:\n data = urllib.parse.unquote(data)\n if mediatype.endswith(\";base64\"):\n data = base64.b64decode(data).decode('utf-8')\n mediatype = mediatype[:-7]\n # End PSF software\n return data\n\n\n# pylint: disable=too-many-function-args\ndef get_files(files_dict, systemd_dict, dir_list, data):\n \"\"\"parse data to populate file_dict\"\"\"\n files = data.get('storage', []).get('files', [])\n for item in files:\n path = item[\"path\"]\n dir_list.add(os.path.dirname(path))\n # remove prefix \"data:,\"\n encoded_contents = item['contents']['source']\n contents = get_file_data(encoded_contents)\n # convert from int to octal, padding at least to 4 places.\n # eg, 420 becomes '0644'\n mode = str(format(int(item[\"mode\"]), '04o'))\n inode = {\"contents\": contents, \"mode\": mode}\n files_dict[path] = inode\n # get the systemd units files we're here\n systemd_units = data.get('systemd', []).get('units', [])\n for item in systemd_units:\n contents = item['contents']\n if six.PY2:\n # pylint: disable=redefined-variable-type\n contents = contents.decode('unicode-escape')\n mode = \"0644\"\n inode = {\"contents\": contents, \"mode\": mode}\n name = item['name']\n path = '/etc/systemd/system/' + name\n dir_list.add(os.path.dirname(path))\n files_dict[path] = inode\n enabled = item.get('enabled') or True\n systemd_dict[name] = enabled\n\n\n# pylint: disable=too-few-public-methods\nclass ActionModule(ActionBase):\n \"\"\"ActionModule for parse_ignition.py\"\"\"\n\n def run(self, tmp=None, task_vars=None):\n \"\"\"Run parse_ignition action plugin\"\"\"\n result = super(ActionModule, self).run(tmp, task_vars)\n result[\"changed\"] = False\n result[\"failed\"] = False\n result[\"msg\"] = \"Parsed successfully\"\n files_dict = {}\n systemd_dict = {}\n dir_list = set()\n result[\"files_dict\"] = files_dict\n result[\"systemd_dict\"] = systemd_dict\n\n # self.task_vars holds all in-scope variables.\n # Ignore settting self.task_vars outside of init.\n # pylint: disable=W0201\n self.task_vars = task_vars or {}\n ign_file_contents = self._task.args.get('ign_file_contents')\n get_files(files_dict, systemd_dict, dir_list, ign_file_contents)\n result[\"dir_list\"] = list(dir_list)\n return result\n","sub_path":"roles/lib_utils/action_plugins/parse_ignition.py","file_name":"parse_ignition.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"319825221","text":"s=str(input())\r\nl1=list(s)\r\nl=list(map(int,l1))\r\nones={1:\"one\",2:\"two\",3:\"three\",4:\"four\",5:\"five\",6:\"six\",7:\"seven\",8:\"eight\",9:\"nine\"}\r\nteens={1:\"eleven\",2:\"twelve\",3:\"thirteen\",4:\"fourteen\",5:\"fifiteen\",6:\"sixteen\",7:\"seventeen\",8:\"eighteen\",9:\"nineteen\"}\r\ntens={1:\"ten\",2:\"twenty\",3:\"thirty\",4:\"fourty\",5:\"fifty\",6:\"sixty\",7:\"seventy\",8:\"eighty\",9:\"ninty\"}\r\na=[]\r\nif(l[-2]==1 and l[-1]!=0):\r\n a.append(teens[l[-1]])\r\nelif(l[-1]==0) :\r\n a.append(tens[l[-2]])\r\nelse:\r\n a.append(tens[l[-2]])\r\n a.append(ones[l[-1]])\r\na.insert(0,ones[l[-3]]+\" hundred\")\r\na.insert(0,ones[l[-4]]+\" thousand\")\r\nprint(\" \".join(a))\r\n\r\n","sub_path":"Numbers2Words.py","file_name":"Numbers2Words.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"145745880","text":"import pytest\n\n\ndef _test_sort_agent(agent_f, env, number_of_problems=1000, max_steps = 1000, verbose=False):\n k = env.k\n for problem in range(1, number_of_problems):\n obs = env.reset()\n for step in range(1, max_steps+1):\n action = agent_f(obs, k)\n obs, reward, is_done, info = env.step(action)\n if is_done:\n if verbose:\n print(f\"Solved problem {problem} of size {len(env.A)} in {step} steps\")\n break\n if step == max_steps:\n pytest.fail(f\"Didn't solve problem {problem} of size {len(env.A)}.\")\n","sub_path":"tests/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"22408249","text":"from bs4 import BeautifulSoup\nimport os\nimport wrapper\nimport util\n\n# archiveディレクトリ内にwebから取得してきたファイルを突っ込む\n\nos.makedirs('archive', exist_ok=True)\n\nfor i in range(1,4054):\n try:\n dic = wrapper.get_site_dict(i)\n except:\n print('{}: ページが存在しません。'.format(i))\n continue\n print('{}: {}'.format(i, dic['title']))\n if dic['title'].find('【教科書に載らない経済と犯罪の危ない話】') != -1:\n util.store_archive(dic)\n print('HIT')\n","sub_path":"nesizumatta/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"59790626","text":"def preguntar():\n num_con = 0\n file_to_send = \"\"\n file_size = \"\"\n print('Bienvenido al servidor TCP')\n\n print('Primero, ingrese el numero de conexiones')\n print('Recuerde que pueden ser entre 1 y 25, o ingrese 0 para apagar')\n num_con = int(input())\n continuar = True\n terminar = False\n if (num_con != 0 and num_con < 26):\n print('Se esperarán ' + str(num_con) + ' conexiones')\n while continuar:\n print(\n 'Escoja el archivo a transmitir (escriba el número correspondiente u oprima 0 para salir):')\n print('1. video1.mkv [104.4 MB]')\n print('2. video2.webm [53.8 MB]')\n print('3. archivo3.pdf [296.3 MB]')\n num_file = int(input())\n if num_file == 1:\n file_to_send = \"video1.mkv\"\n file_size = \"104.4\"\n continuar = False\n elif num_file == 2:\n file_to_send = \"video2.webm\"\n file_size = \"53.8\"\n continuar = False\n elif num_file == 3:\n file_to_send = \"archivo3.pdf\"\n file_size = \"296.3\"\n continuar = False\n elif num_file == 0:\n terminar = True\n continuar = False\n break\n else:\n print('Archivo invaldo, escoja uno nuevamente u oprima 0 para salir')\n if num_file > 0 and num_file < 4:\n print('Esperando ' + str(num_con) +\n ' conexiones para enviar ' + file_to_send + ' ...')\n\n else:\n terminar = True\n return terminar, num_con, file_to_send, file_size\n","sub_path":"TCP/server_view.py","file_name":"server_view.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"464377243","text":"import concurrent.futures as cf\nimport datetime\nimport os\nfrom timeit import default_timer as Timer\nfrom tkinter import filedialog\n\nimport PIL\nfrom PIL import Image\n\n\ndef resizerCore(image):\n\n base_im_width = 1600\n base_im_height = 1000\n ratio = 1.00\n\n im = Image.open(image)\n dirpaths, filename = os.path.split(image)\n im_width, im_height = im.size\n if im_width >= base_im_width and im_height >= im_height:\n if im_width <= im_height:\n ratio = base_im_width / im_width\n else:\n ratio = base_im_height / im_height\n else:\n ratio = 1.00\n new_im_width = int(ratio * im_width)\n new_im_height = int(ratio * im_height)\n resized_image = im.resize((new_im_width, new_im_height), PIL.Image.ANTIALIAS)\n resized_image.save(os.path.join(dirpaths, '_' + filename))\n im.close()\n os.remove(os.path.join(dirpaths, filename))\n\nif __name__ == \"__main__\":\n startTimer = Timer()\n\n list_of_images = []\n source_path = filedialog.askdirectory()\n for dirpaths, _, filenames in os.walk(source_path):\n print(dirpaths)\n for filename in filenames:\n if '.jpg' in filename.lower() or '.png' in filename.lower():\n list_of_images.append(os.path.join(dirpaths, filename))\n else:\n continue\n\n with cf.ProcessPoolExecutor() as executor:\n executor.map(resizerCore, list_of_images)\n\n\n stopTimer = Timer()\n print(str(datetime.timedelta(seconds=(round(stopTimer - startTimer, 2)))))\n print('-' * 20)\n","sub_path":"_resizer_multi_process.py","file_name":"_resizer_multi_process.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"388347510","text":"import json\nimport sys\nimport random\n\n\ndef build_links(nest, root, LINKS, DATA, MAX):\n\t#print(DATA[root]['name'])\n\tprint(root in DATA)\n\tif nest <= MAX:\n\t\ttry: \n\t\t\tfriend_dict = DATA[root]['friends']\n\t\t\t# add source, target for root\n\t\t\tfor friend in friend_dict:\n\t\t\t\tid = friend_dict[friend]\n\t\t\t\tLINKS.append({'source': str(DATA[root]['name']),\n\t\t\t\t\t\t \t 'target': str(friend),\n\t\t\t\t\t\t \t 'value': str(nest)\n\t\t\t\t\t\t \t})\n\t\t\t\tbuild_links(nest + 1, str(id), LINKS, DATA, MAX)\n\t\texcept KeyError:\n\t\t\tpass\n\ndef top_n_max_readers(root, n, BOOKS, USERS):\n\tbook_list_lens = []\n\tfor book_id, book_info in USERS[root].items():\n\t\tbook_list_lens.append((len(BOOKS[book_id]), (book_id, book_info['name'])))\n\n\tbook_list_lens = (sorted(book_list_lens))\n\ttry:\n\t\tlens, ids = zip(*book_list_lens)\n\t\treturn(ids[-n:])\n\texcept ValueError:\n\t\tprint(\"No books for this user!\")\n\t\treturn([])\n\n\ndef build_book_links(root, bLINKS, BOOKS, USERS, FRIENDS):\n\tu_size = 30\n\tb_size = 7\n\tfiltered = top_n_max_readers(root, b_size, BOOKS, USERS)\n\t#Limit to 10 books per root user\n\tfor book_id, book_name in filtered:\n\t\tbLINKS.append({ 'source': FRIENDS[root]['name'],\n\t\t\t\t\t\t'target': book_name,\n\t\t\t\t\t\t'value': 1\n\t\t\t\t\t\t})\n\t\t# \n\t\t# Limit to 30(?) users per book\n\t\tusers_per_book = 0\n\t\tfor user in (BOOKS[book_id]):\n\t\t\tif users_per_book == u_size:\n\t\t\t\tbreak\n\t\t\tif user in FRIENDS[root]['friend']:\n\t\t\t\tval = 2\n\t\t\telse:\n\t\t\t\tval = 3\n\t\t\tbLINKS.append({ 'source': FRIENDS[user]['name'],\n\t\t\t\t\t\t'target': book_name,\n\t\t\t\t\t\t'value': val\n\t\t\t\t\t\t})\n\t\t\tusers_per_book += 1\n\n\ndef data_analyze(root, path):\n\twith open(path + 'reader_basket', 'r') as rd_file:\n\t\treader_basket = json.load(rd_file)\n\n\twith open(path + 'book_basket', 'r') as bk_file:\n\t\tbook_basket = json.load(bk_file)\n\n\twith open(path + 'friends', 'r') as fr_file:\n\t\tfriends = json.load(fr_file)\n\n\n\tif root not in friends:\n\t\tprint(\"not found, randomizing root\")\n\t\trand = random.choice(list(friends.keys()))\n\t\troot = str(rand)\n\tprint(\"Loading data\")\n\n\tprint(root)\n\t#root = str(16506879)\n\t#root = str(65721667)\n\t#print(rand)\n\n\n\n\tprint(\"Found user\")\n\tprint(friends[root]['name'])\n\t#LINKS = []\n\tbLINKS = []\n\tMAX = 10\n\t#tree = build_book_nest(root, book_basket, reader_basket, friends, data)\n\t#print(tree)\n\t# with open('static/book_tree.json', 'w+') as t_file:\n\t# \tjson.dump(tree, t_file)\n\t# build_links(1, root, LINKS, data, MAX)\n\t# print(bLINKS)\n\t# with open('links.json', 'w+') as p_file:\n\t# \tjson.dump(LINKS, p_file)\n\tprint(\"Analyzing\")\n\tbuild_book_links(root, bLINKS, book_basket, reader_basket, friends)\n\t# with open('static/book_links.json', 'w+') as b_file:\n\t# \tjson.dump(bLINKS, b_file)\n\treturn bLINKS\n\ndef main():\n\tdata_analyze('1')\n\nif __name__ == '__main__':\n\tmain()\n\n\n","sub_path":"bookworms/build_links.py","file_name":"build_links.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"549640563","text":"from scene_manager import *\r\n#from AOLMEgame import *\r\n\r\nscene = scene(60,60)\r\n\r\n#Background\r\ngrass = sprite_part(40,20)\r\ngrass.fill_part([0,38],[1,18],\"004d00\")\r\ngrass.fill_part([0,38],[1,1],\"001a00\")\r\ngrass.fill_part([38,38],[1,18],\"001a00\")\r\ngrass.fill_part([0,38],[18,18],\"001a00\")\r\n\r\ngrass.fill_part([0,37],[2,4],\"006600\")\r\ngrass.fill_part([35,37],[2,17],\"006600\")\r\ngrass.fill_part([0,37],[15,17],\"006600\")\r\n#grass.view_part()\r\n\r\narrow = sprite_part(60,60)\r\narrow.fill_part([5,49],[10,10],\"000000\")\r\narrow.fill_part([10,49],[50,50],\"000000\")\r\narrow.fill_part([50,50],[10,50],\"000000\")\r\n\r\narrow.fill_part([9,9],[48,52],\"000000\")\r\narrow.fill_part([8,8],[49,51],\"000000\")\r\narrow.fill_part([7,7],[50,50],\"000000\")\r\n\r\n#Aolme's head\r\nhead = sprite_part(10,12)\r\nhead.fill_part([1,8],[0,0],\"003340\")\r\nhead.fill_part([1,8],[11,11],\"003340\")\r\nhead.fill_part([0,0],[1,10],\"003340\")\r\nhead.fill_part([9,9],[1,10],\"003340\")\r\n\r\nhead.fill_part([1,8],[1,1],\"ff\")\r\nhead.fill_part([1,8],[10,10],\"ff\")\r\nhead.fill_part([1,1],[1,10],\"ff\")\r\nhead.fill_part([8,8],[1,10],\"ff\")\r\n\r\nhead.fill_part([2,7],[2,2],\"80\")\r\nhead.fill_part([2,7],[9,9],\"80\")\r\nhead.fill_part([2,2],[2,9],\"80\")\r\nhead.fill_part([7,7],[2,9],\"80\")\r\n\r\nhead.fill_part([3,3],[3,8],\"d9dcd9\")\r\nhead.fill_part([6,6],[3,8],\"d9dcd9\")\r\nhead.fill_part([4,5],[5,7],\"d9dcd9\")\r\n\r\nhead.part[4,3] = \"d9dcd9\"\r\nhead.part[4,8] = \"d9dcd9\"\r\nhead.part[5,3] = \"ffcbcb\"\r\nhead.part[5,8] = \"ffcbcb\"\r\nhead.part[5,4] = \"d9dcd9\"\r\nhead.part[5,7] = \"d9dcd9\"\r\nhead.part[4,4] = \"00\"\r\nhead.part[4,7] = \"00\"\r\n#head.view_part()\r\n\r\n#Aolme's keyboard\r\nkeyboard = sprite_part(6,14)\r\nkeyboard.fill_part([0,0],[0,13],\"00\")\r\nkeyboard.fill_part([5,5],[0,13],\"00\")\r\nkeyboard.fill_part([0,5],[0,0],\"00\")\r\nkeyboard.fill_part([0,5],[13,13],\"00\")\r\nkeyboard.fill_part([4,4],[1,12],\"d9dcd9\")\r\nkeyboard.fill_part([1,3],[1,12],\"ff\")\r\n\r\nkeyboard.part[1][1] = \"80\"\r\nkeyboard.part[1][3] = \"80\"\r\nkeyboard.part[1][5] = \"80\"\r\nkeyboard.part[1][7] = \"80\"\r\nkeyboard.part[1][9] = \"80\"\r\nkeyboard.part[1][11] = \"80\"\r\nkeyboard.part[3][2] = \"80\"\r\nkeyboard.part[3][4] = \"80\"\r\nkeyboard.part[3][6] = \"80\"\r\nkeyboard.part[3][8] = \"80\"\r\nkeyboard.part[3][10] = \"80\"\r\nkeyboard.part[3][12] = \"80\"\r\n#keyboard.view_part()\r\n\r\n#left arm\r\nleft_arm = sprite_part(6,5)\r\nleft_arm.fill_part([2,4],[0,0],\"07637e\")\r\nleft_arm.part[2][1] = \"07637e\"\r\nleft_arm.part[1][1] = \"07637e\"\r\nleft_arm.part[0][2] = \"07637e\"\r\nleft_arm.part[4][1] = \"07637e\"\r\nleft_arm.part[1][2] = \"07637e\"\r\nleft_arm.part[5][1] = \"07637e\"\r\nleft_arm.part[5][2] = \"07637e\"\r\n\r\nleft_arm.part[2][2] = \"02485b\"\r\nleft_arm.part[3][1] = \"02485b\"\r\nleft_arm.part[4][2] = \"02485b\"\r\n\r\nleft_arm.part[4][3] = \"b4efff\"\r\nleft_arm.part[5][3] = \"b4efff\"\r\nleft_arm.part[5][4] = \"b4efff\"\r\n#left_arm.view_part()\r\n\r\n#Right arm\r\nright_arm = sprite_part(7,3)\r\nright_arm.fill_part([4,5],[0,1],\"07637e\")\r\nright_arm.fill_part([2,5],[1,1],\"07637e\")\r\n\r\nright_arm.fill_part([2,5],[2,2],\"02485b\")\r\nright_arm.fill_part([6,6],[0,1],\"02485b\")\r\n\r\nright_arm.part[1][1] = \"b4efff\"\r\nright_arm.part[1][2] = \"b4efff\"\r\nright_arm.part[0][2] = \"b4efff\"\r\n#right_arm.view_part()\r\n\r\n#legs\r\nlegs = sprite_part(3,8)\r\nlegs.fill_part([0,2],[0,2],\"00\")\r\nlegs.fill_part([0,2],[5,7],\"00\")\r\n#legs.view_part()\r\n\r\naolme = sprite(19,19)\r\naolme.add_part(head,[0,4])\r\naolme.add_part(keyboard,[10,3])\r\naolme.add_part(left_arm,[10,0])\r\naolme.add_part(right_arm,[6,16])\r\naolme.add_part(legs,[16,6])\r\naolme.set_name = 'aolme'\r\n\r\n#aolme.view_sprite()\r\n\r\ngrass_sprite = sprite(40,20)\r\ngrass_sprite.add_part(grass,[0,0])\r\ngrass_sprite.set_name = 'grass'\r\n#grass_sprite.view_sprite()\r\n\r\n#arrow_sprite = sprite(60,60)\r\n#arrow_sprite.add_part(arrow,[0,0])\r\n#arrow_sprite.set_name = 'arrow'\r\n\r\nscene.add_sprite(grass_sprite,[0,20])\r\n#scene.add_sprite(arrow_sprite,[0,0])\r\nscene.add_sprite(aolme,[1,1])\r\n","sub_path":"Session 3/To be implemented/AOLME_game.py","file_name":"AOLME_game.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"109329061","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 15 11:18:46 2017\n\n@author: linhb\n\"\"\"\n\n# pyspark --packages org.mongodb.spark:mongo-spark-connector_2.11:2.0.0\nfrom pyspark.sql import SparkSession\nfrom pyspark.ml.feature import HashingTF, IDF, RegexTokenizer, StopWordsRemover, CountVectorizer\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql.types import StringType, ArrayType, DoubleType, IntegerType\nfrom pyspark.ml.clustering import LDA\n\nmy_spark = SparkSession \\\n .builder \\\n .appName(\"myApp\") \\\n .config(\"spark.mongodb.input.uri\", \"mongodb://127.0.0.1/publications.papers\") \\\n .config(\"spark.mongodb.output.uri\", \"mongodb://127.0.0.1/publications.papers\") \\\n .getOrCreate()\n\ndf = my_spark.read.format(\"com.mongodb.spark.sql.DefaultSource\").load()\n\ndf = df.drop('content')\ndf_IDF.select('features').head()\n\n# clean up text\ndef extract_main_content(text):\n # Main Content are between \"Abstract\" and \"References\"\n text = text.lower()\n abstract_index = text.find(\"abstract\")\n if (abstract_index == -1):\n abstract_index = 0\n reference_index = text.rfind(\"references\")\n if (reference_index == -1):\n reference_index = len(text)\n return text[abstract_index:reference_index]\n \nudf_extract_content = udf(lambda x: extract_main_content(x), StringType())\ndf1 = df.withColumn(\"text_main\", udf_extract_content(df.text))\n\ntokenizer = RegexTokenizer(inputCol=\"text_main\", outputCol=\"words\", pattern=\"\\\\P{Alpha}+\")\ndf2 = tokenizer.transform(df1)\n\nremover = StopWordsRemover(inputCol=\"words\", outputCol=\"words2\")\ndf3 = remover.transform(df2)\n\ndef remove_words(aList):\n stopWords = ['abstract','keyword','introduction','conclusion','acknowledgement']\n return [x for x in aList if (len(x)>1 and x not in stopWords)]\n\nudf_remove_words = udf(lambda x: remove_words(x), ArrayType(StringType()))\ndf4 = df3.withColumn(\"words3\", udf_remove_words(df3.words2))\n\n# text to feature vector - TF_IDF\n# should not use HashingTF because we need word-index dictionary\ncountTF = CountVectorizer(inputCol=\"words3\", outputCol=\"raw_features\", minTF=1.0, minDF=1.0)\ncountTF_model = countTF.fit(df4)\ncountTF.getVocabSize()\ndf_countTF = countTF_model.transform(df4)\nvocab = countTF_model.vocabulary\n\nidf = IDF(inputCol=\"raw_features\", outputCol=\"features\")\nidf_model = idf.fit(df_countTF)\ndf_IDF = idf_model.transform(df_countTF)\ndf_IDF.cache()\n\n# LDA Model\nlda = LDA(k=2, seed=1, optimizer=\"online\", maxIter=100, featuresCol='features')\nlda_model = lda.fit(df_IDF)\n\n# evaluation: high likelihood, low perplexity\nlda_model.logPerplexity(df_IDF)\nlda_model.logLikelihood(df_IDF)\n\n# LDA model description\nlda_model.vocabSize()\ntopics = lda_model.describeTopics(maxTermsPerTopic=10)\n\ndef lookup_words(termIndices, vocab):\n return [vocab[i] for i in termIndices]\n\nudf_lookup_words = udf(lambda x: lookup_words(x, vocab), ArrayType(StringType()))\ntopics_words = topics.withColumn(\"words\", udf_lookup_words(topics.termIndices))\ntopics_words.cache()\ntopics_words.head()\n\nlda_model.topicsMatrix()\nlda_model.estimatedDocConcentration()\n\n# get topicDistribution\n\n\n\n\n\n","sub_path":"Project/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"77363399","text":"# Copyright (c) 2015-2016 Cisco Systems, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\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\n# DEALINGS IN THE SOFTWARE.\n\nimport os\n\nfrom molecule import ansible_playbook\nfrom molecule import util\nfrom molecule.verifier import base\n\n\nclass Goss(base.Base):\n def __init__(self, molecule):\n super(Goss, self).__init__(molecule)\n self._goss_dir = molecule.config.config['molecule']['goss_dir']\n self._goss_playbook = molecule.config.config['molecule'][\n 'goss_playbook']\n self._playbook = self._get_playbook()\n self._ansible = self._get_ansible_instance()\n\n def execute(self):\n \"\"\"\n Executes Goss integration tests and returns None.\n\n :return: None\n \"\"\"\n if self._get_tests():\n status, output = self._goss()\n if status is not None:\n util.sysexit(status)\n\n def _goss(self, out=util.callback_info, err=util.callback_error):\n \"\"\"\n Executes goss against specified playbook and returns a :func:`sh`\n response object.\n\n :param out: An optional function to process STDOUT for underlying\n :func:`sh` call.\n :param err: An optional function to process STDERR for underlying\n :func:`sh` call.\n :return: :func:`sh` response object.\n \"\"\"\n\n msg = 'Executing goss tests found in {}...'.format(self._playbook)\n util.print_info(msg)\n\n self._set_library_path()\n return self._ansible.execute()\n\n def _get_tests(self):\n return os.path.exists(self._playbook)\n\n def _get_playbook(self):\n return os.path.join(self._goss_dir, self._goss_playbook)\n\n def _get_ansible_instance(self):\n ac = self._molecule.config.config['ansible']\n ac['playbook'] = self._playbook\n debug = self._molecule.args.get('debug')\n ansible = ansible_playbook.AnsiblePlaybook(\n ac, self._molecule.driver.ansible_connection_params, debug=debug)\n\n return ansible\n\n def _set_library_path(self):\n library_path = self._ansible.env.get('ANSIBLE_LIBRARY', '')\n goss_path = self._get_library_path()\n if library_path:\n self._ansible.add_env_arg('ANSIBLE_LIBRARY',\n '{}:{}'.format(library_path, goss_path))\n else:\n self._ansible.add_env_arg('ANSIBLE_LIBRARY', goss_path)\n\n def _get_library_path(self):\n return os.path.join(\n os.path.dirname(__file__), os.path.pardir, os.path.pardir,\n 'molecule', 'verifier', 'ansible', 'library')\n","sub_path":"molecule/verifier/goss.py","file_name":"goss.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"527717947","text":"\nimport numpy as np\nimport sys, os, re, math\nfrom numpy import linalg as LA\n\ngamma = 1.4\ngammaMinusOneInv = 1./(gamma-1.)\n\ndef sol(xin,yin,zin, t):\n return 1. + 0.2*np.sin(np.pi*(xin+yin+zin-t*3.))\n\ndef computePressure(rho, u, v, w, E):\n return (gamma - 1.) * (E - rho*(u**2+v**2+w**2)*0.5)\n\ndef extractN(ns):\n reg = re.compile(r''+ns+'.+')\n file1 = open('info.dat', 'r')\n strings = re.search(reg, file1.read())\n file1.close()\n assert(strings)\n return int(strings.group().split()[1])\n\nif __name__== \"__main__\":\n st = int(sys.argv[1])\n nx = extractN('nx')\n ny = extractN('ny')\n nz = extractN('nz')\n numCells = nx*ny*nz\n fomTotDofs = numCells*5\n\n D = np.fromfile(\"solution.bin\")\n nt = int(np.size(D)/fomTotDofs)\n D = np.reshape(D, (nt, fomTotDofs))\n D = D[-1, :]\n D = np.reshape(D, (numCells, 5))\n rho = D[:,0]\n np.savetxt(\"rho_comp.txt\", rho)\n\n coo = np.loadtxt(\"coordinates.dat\", dtype=float)\n x_fom = coo[:,1]\n y_fom = coo[:,2]\n z_fom = coo[:,3]\n\n gold = sol(x_fom, y_fom, z_fom, 2.)\n err = LA.norm(rho-gold, np.inf)\n print(err)\n\n if(st==3):\n assert(math.isclose(err, 0.19999999613178898))\n if(st==5):\n assert(math.isclose(err, 0.19833619929947288))\n","sub_path":"tpls/pressio-demoapps/tests_cpp/eigen_3d_euler_smooth/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"61241048","text":"\"\"\"ShopOnline URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom ShopApp import views as ShopAppViews\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', ShopAppViews.home),\n path('register/', ShopAppViews.register, name=\"register\"),\n path('home/', ShopAppViews.home, name='home'),\n path('all/', ShopAppViews.all_items, name='all'),\n path('category//', ShopAppViews.category, name='category'),\n path('item//', ShopAppViews.item, name='item'),\n path('cart/', ShopAppViews.cart, name='cart'),\n path('order_done', ShopAppViews.order_done, name=\"order_done\"),\n path('profile/', ShopAppViews.profile, name=\"profile\"),\n\n]\n\nurlpatterns += [\n path('accounts/', include('django.contrib.auth.urls')),\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"ShopOnline/ShopOnline/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"512846820","text":"# written by Yuchao on 2020.3.12\n# check and download the latest available radar401300210, parse the datetime\n# backward 1 hour and get download the kakuho data\n# extract the kakuho data and make comparison\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom datetime import datetime,timedelta\nimport urllib.request\nfrom bs4 import BeautifulSoup\nfrom rainymotion import models, metrics, utils\nfrom netCDF4 import Dataset\n\nprint(os.getcwd())\ndt = datetime.utcnow()\nprint(\"UTC now:\",dt.strftime(\"%Y-%m-%d %H:%M\"))\n\nbase_page = \"http://stock1.wni.co.jp/stock/401300210/0000300100200012\"\nbase_URL = \"http://stock1.wni.co.jp/stock/401300210/0000300100200012\"\nbase_goal = \"/Users/jiang/data/jma_radar\"\n\n# 1. get the latest radar file and data\n# 1.1 obtain the radar file name\npage_URL = os.path.join(base_page,dt.strftime(\"%Y/%m/%d\"))\nwith urllib.request.urlopen(page_URL) as response:\n\thtml = response.read()\nsoup = BeautifulSoup(html, 'html.parser')\nfile_list = [a.string for a in soup.find_all('a') if \".000\" in a.string]\nfile_list.sort()\nlatest = file_list[-1]\n\nsource_folder = os.path.join(base_URL,dt.strftime(\"%Y/%m/%d\"))\ngoal_folder = os.path.join(base_goal, dt.strftime(\"%Y/%m/%d\"))\nif not os.path.exists(goal_folder):\n os.makedirs(goal_folder)\n\n# 1.2. download radar data\nfile_string = latest\nsource_path = os.path.join(source_folder, file_string)\ndownload_radar_path = os.path.join(goal_folder, file_string)\ntry: \n urllib.request.urlretrieve(source_path, download_radar_path)\nexcept: \n print(f\"not exist:{source_path}\")\n\n# 1.3 convert wgrib2 file to nc and extract\nnc_file = \"temp1.nc\"\ncmd = f\"wgrib2 {download_radar_path} -s | egrep 'surface'|wgrib2 -i {download_radar_path} -netcdf {nc_file}\"\nfail = os.system(cmd)\nif fail:\n print(\"wgrib2 wrong at \",download_radar_path)\nrain_reduced = Dataset(nc_file, \"r\")['var0_1_203_surface'][0]\nrain_reduced.fill_value = 0.0 \nground_truth = rain_reduced.filled()\nos.system(f\"rm -r {nc_file}\")\njma_mask = rain_reduced.mask\n\n# --------------------------------------------------------------------------------\n# 2. get kakuho prediction data\n# 2.1 get kakuho file name\ndt_12 = datetime.strptime(file_string.split(\".\")[0], '%Y%m%d_%H%M%S')\nprint(\"latest available time:\", dt_12)\ntime_step = 5 * 60 # seconds\ndt_now = dt_12 - timedelta(seconds = time_step * 12)\n\n# 2.2 download kakuho file\nbase_URL = \"http://stock1.wni.co.jp/stock_hdd/411024220/0200600011024220\"\nbase_goal = \"/Users/jiang/data/rain_kakuho\"\nfile_string = dt_now.strftime('%Y%m%d_%H%M00.000')\nsource_folder = os.path.join(base_URL, dt.strftime(\"%Y/%m/%d\"))\ngoal_folder = os.path.join(base_goal, dt.strftime(\"%Y/%m/%d\"))\nif not os.path.exists(goal_folder):\n os.makedirs(goal_folder)\nsource_path = os.path.join(source_folder, file_string)\ngoal_path = os.path.join(goal_folder, file_string)\ntry: \n urllib.request.urlretrieve(source_path,goal_path)\nexcept: \n print(f\"not exist:{source_path}\")\n\n# 2.3 convert wgrib2 to nc file and extract\nvar = \":60 min fcst\"\nnc_file = \"temp2.nc\"\ncmd = f\"wgrib2 {goal_path} -s | egrep '({var})'|wgrib2 -i {goal_path} -netcdf {nc_file}\"\nfail = os.system(cmd)\nif fail:\n print(\"wgrib2 wrong at \",source_path)\nrain_reduced = Dataset(nc_file, \"r\")['APCP_surface'][0]\nrain_reduced.fill_value = 0.0 \nkakuho = rain_reduced.filled() * 6 # mm/10 min to mm/h\nos.system(f\"rm -r {nc_file}\")\n\n\n# 3. compare\ncoverage = np.sum(ground_truth >= 0.1)/ np.sum(~jma_mask)\nthreat = metrics.CSI(ground_truth, kakuho, threshold = 0.1)\nprint(f\"rain coverage = {coverage:.3f}\")\nprint(f\"threat = {threat:.2f}\")","sub_path":"radar_kakuho_evaluation.py","file_name":"radar_kakuho_evaluation.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"381584321","text":"def primeFactors(n):\n #primes = gen_primes()\n #print(primes)\n factors = factorise(n,[])\n print(factors)\n #print(factors)\n\n #print(set(factors))\n\n factor_set = list(set(factors))\n factor_set.sort()\n #print(factor_set)\n _str = \"\"\n\n for factor in factor_set:\n _count = factors.count(factor)\n if _count > 1:\n _s = \"({}**{})\".format(factor,_count) \n else :\n _s = \"({})\".format(factor)\n \n _str = _str + _s\n\n return _str\n \ndef factorise(n, factors):\n #print(n)\n #print(factors)\n if n == 1:\n return factors\n \n #primes = [2,3,5,7,11,13,17]\n #print(primes)\n primes = gen_primes()\n #print(primes)\n while True:\n prime = next(primes)\n #print(prime)\n if n % prime == 0:\n #print(\"{} / {}\".format(n,prime))\n new_n = n / prime\n factors.append(prime)\n return factorise(int(new_n), factors)\n #for prime in next(primes):\n \n\ndef gen_primes():\n \"\"\" Generate an infinite sequence of prime numbers.\n \"\"\"\n # Maps composites to primes witnessing their compositeness.\n # This is memory efficient, as the sieve is not \"run forward\"\n # indefinitely, but only as long as required by the current\n # number being tested.\n #\n D = {}\n \n # The running integer that's checked for primeness\n q = 2\n \n while True:\n if q not in D:\n # q is a new prime.\n # Yield it and mark its first multiple that isn't\n # already marked in previous iterations\n # \n yield q\n D[q * q] = [q]\n q = q + 1\n else:\n # q is composite. D[q] is the list of primes that\n # divide it. Since we've reached q, we no longer\n # need it in the map, but we'll mark the next \n # multiples of its witnesses to prepare for larger\n # numbers\n # \n for p in D[q]:\n D.setdefault(p + q, []).append(p)\n del D[q]\n q = q + 1\n \n ","sub_path":"python solutions/prime_factorization.py","file_name":"prime_factorization.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"384253277","text":"from flask import Flask, request\nfrom graphqlConsumer import *\nfrom flask_graphql import GraphQLView\n\napplication = Flask(__name__)\napplication.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True))\n\n\n@application.route('/')\ndef input_handler():\n query = request.args.get(\"query\")\n if query:\n result = schema.execute(query)\n if result.errors is None:\n return result.data\n else:\n return result.errors\n\n else:\n return \"\"\" Query Example \\n{stations(first:2, latitude:-20, longitude:-10) {\n name\n location\n forecast(initdate:\"2019-09-11\" finaldate:\"2019-09-12\" ){\n periods\n maxTemperature\n precipitation\n }\n }\n }\"\"\"\n\n\nif __name__ == \"__main__\":\n # Setting debug to True enables debug output. This line should be\n # removed before deploying a production app.\n application.debug = True\n application.run()\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"194908776","text":"#-*- coding: utf-8 -*-\n\nimport cyclone.web\nimport cyclone.httpclient\nimport cyclone.jsonrpc\nimport cyclone.xmlrpc\nfrom twisted.python import log\nimport txmongo\n\nfrom twisted.internet import defer\n\n\nclass XmlPingHandler(cyclone.xmlrpc.XmlrpcRequestHandler):\n allowNone = True\n\n def xmlrpc_echo(self, text):\n return text\n\n def xmlrpc_ping(self):\n return 'ping'\n\n @defer.inlineCallbacks\n #@cyclone.web.asynchronous\n def xmlrpc_find(self, spec, limit=10):\n try:\n result = yield self.settings.db.find(spec)\n log.msg(repr(result))\n except:\n log.err()\n result = yield self.settings.db.find(spec)\n defer.returnValue(repr(result))\n\n @defer.inlineCallbacks\n #@cyclone.web.asynchronous\n def xmlrpc_insert(self, doc):\n result = False\n try:\n result = yield self.settings.db.insert(doc)\n except:\n log.err()\n defer.returnValue(repr(result))\n\n @defer.inlineCallbacks\n @cyclone.web.asynchronous\n def xmlrpc_update(self, spec, doc):\n result = yield self.settings.db.update(spec, doc, safe=True)\n defer.returnValue(repr(result))\n\n @defer.inlineCallbacks\n def xmlrpc_geoip_lookup(self, address):\n result = yield cyclone.httpclient.fetch(\n \"http://freegeoip.net/xml/%s\" % address.encode(\"utf-8\"))\n defer.returnValue(result.body)\n","sub_path":"srv_lib/handlers/rpc_handlers/ping_handler.py","file_name":"ping_handler.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"613440947","text":"import factory\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.test import TestCase\n\nfrom river.tests.models import TestModel\nfrom river.tests.models.factories import TestModelObjectFactory\n\n__author__ = 'ahmetdal'\n\n\nclass BaseTestCase(TestCase):\n def setUp(self):\n super(BaseTestCase, self).setUp()\n print('%s is initialized' % self.__class__)\n\n def tearDown(self):\n super(BaseTestCase, self).tearDown()\n print('%s is finished' % self.__class__)\n\n def initialize_normal_scenario(self):\n from river.models.factories import \\\n TransitionObjectFactory, \\\n UserObjectFactory, \\\n PermissionObjectFactory, \\\n ProceedingMetaObjectFactory, \\\n StateObjectFactory\n\n TransitionObjectFactory.reset_sequence(0)\n ProceedingMetaObjectFactory.reset_sequence(0)\n StateObjectFactory.reset_sequence(0)\n TestModel.objects.all().delete()\n\n self.content_type = ContentType.objects.get_for_model(TestModel)\n self.permissions = PermissionObjectFactory.create_batch(4)\n self.user1 = UserObjectFactory(user_permissions=[self.permissions[0]])\n self.user2 = UserObjectFactory(user_permissions=[self.permissions[1]])\n self.user3 = UserObjectFactory(user_permissions=[self.permissions[2]])\n self.user4 = UserObjectFactory(user_permissions=[self.permissions[3]])\n\n self.states = StateObjectFactory.create_batch(\n 9,\n label=factory.Sequence(\n lambda n: \"s%s\" % str(n + 1) if n <= 4 else (\"s4.%s\" % str(n - 4) if n <= 6 else \"s5.%s\" % str(n - 6)))\n )\n self.transitions = TransitionObjectFactory.create_batch(8,\n source_state=factory.Sequence(\n lambda n: self.states[n] if n <= 2 else (\n self.states[n - 1]) if n <= 4 else (\n self.states[n - 2] if n <= 6 else self.states[\n 4])),\n destination_state=factory.Sequence(\n lambda n: self.states[n + 1]))\n\n self.proceeding_metas = ProceedingMetaObjectFactory.create_batch(\n 9,\n content_type=self.content_type,\n transition=factory.Sequence(lambda n: self.transitions[n] if n <= 1 else self.transitions[n - 1]),\n order=factory.Sequence(lambda n: 1 if n == 2 else 0)\n )\n\n for n, proceeding_meta in enumerate(self.proceeding_metas):\n proceeding_meta.permissions.add(self.permissions[n] if n <= 3 else self.permissions[3])\n\n self.objects = TestModelObjectFactory.create_batch(2)\n\n def initialize_circular_scenario(self):\n from river.models.factories import \\\n TransitionObjectFactory, \\\n UserObjectFactory, \\\n PermissionObjectFactory, \\\n ProceedingMetaObjectFactory, \\\n StateObjectFactory\n\n TransitionObjectFactory.reset_sequence(0)\n ProceedingMetaObjectFactory.reset_sequence(0)\n StateObjectFactory.reset_sequence(0)\n TestModel.objects.all().delete()\n\n self.content_type = ContentType.objects.get_for_model(TestModel)\n self.permissions = PermissionObjectFactory.create_batch(4)\n self.user1 = UserObjectFactory(user_permissions=[self.permissions[0]])\n self.user2 = UserObjectFactory(user_permissions=[self.permissions[1]])\n self.user3 = UserObjectFactory(user_permissions=[self.permissions[2]])\n self.user4 = UserObjectFactory(user_permissions=[self.permissions[3]])\n\n\n self.open_state = StateObjectFactory(\n label='open'\n )\n self.in_progress_state = StateObjectFactory(\n label='in-progress'\n )\n\n self.resolved_state = StateObjectFactory(\n label='resolved'\n )\n self.re_opened_state = StateObjectFactory(\n label='re-opened'\n )\n\n self.closed_state = StateObjectFactory(\n label='closed'\n )\n\n self.transitions = [\n TransitionObjectFactory(source_state=self.open_state, destination_state=self.in_progress_state),\n TransitionObjectFactory(source_state=self.in_progress_state,\n destination_state=self.resolved_state),\n TransitionObjectFactory(source_state=self.resolved_state,\n destination_state=self.re_opened_state),\n TransitionObjectFactory(source_state=self.resolved_state, destination_state=self.closed_state),\n TransitionObjectFactory(source_state=self.re_opened_state, destination_state=self.in_progress_state)]\n\n self.proceeding_metas = ProceedingMetaObjectFactory.create_batch(\n 5,\n content_type=self.content_type,\n transition=factory.Sequence(lambda n: self.transitions[n]),\n order=0\n )\n\n for n, proceeding_meta in enumerate(self.proceeding_metas):\n proceeding_meta.permissions.add(self.permissions[n] if n < len(self.permissions) else self.permissions[0])\n\n self.objects = TestModelObjectFactory.create_batch(2)\n","sub_path":"venv/Lib/site-packages/river/tests/base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":5507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"183155896","text":"# -*- coding:utf-8 -*-\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'book_tweet.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^accounts/', include('auth_app.urls', namespace=\"auth_app\")),\n url(r'^accounts/', include('django.contrib.auth.urls')),\n url(r'^accounts/', include('allauth.urls')),\n url(r'^book/', include('book_manager.urls', namespace=\"book_manager\")),\n url(r'^', include('book_manager.urls', namespace=\"book_manager\")),\n)\n","sub_path":"book_tweet/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"38046381","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 20 08:48:39 2017\n\n@author: ssurabhi\n\"\"\"\n\n#import wx\n#\n#app = wx.App()\n#\n#frame = wx.Frame(None, -1, \"sample.py\")\n#frame.Show()\n#\n#app.MainLoop()\nimport wx\n\nclass Example(wx.Frame):\n\n def __init__(self, parent, title): \n super(Example, self).__init__(parent, title=title, \n size=(450, 350))\n\n self.InitUI()\n self.Centre()\n self.Show() \n\n def InitUI(self):\n \n panel = wx.Panel(self)\n \n sizer = wx.GridBagSizer(5, 5)\n\n text1 = wx.StaticText(panel, label=\"Load Combs Generator\")\n sizer.Add(text1, pos=(0, 0), flag=wx.TOP|wx.LEFT|wx.BOTTOM, \n border=15)\n\n line = wx.StaticLine(panel)\n sizer.Add(line, pos=(1, 0), span=(1, 5), \n flag=wx.EXPAND|wx.BOTTOM, border=10)\n\n\n text2 = wx.StaticText(panel, label=\"Load Combs csv file name\")\n sizer.Add(text2, pos=(2, 0), flag=wx.LEFT, border=10)\n \n self.tc1 = wx.TextCtrl(panel)\n sizer.Add(self.tc1, pos=(2, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND)\n self.Bind(wx.EVT_TEXT, self.inputs, self.tc1)\n\n text3 = wx.StaticText(panel, label=\"TCL file name\")\n sizer.Add(text3, pos=(3, 0), flag=wx.LEFT|wx.TOP, border=10)\n\n self.tc2 = wx.TextCtrl(panel)\n sizer.Add(self.tc2, pos=(3, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND, border=5)\n self.Bind(wx.EVT_TEXT, self.inputs, self.tc2)\n\n# button1 = wx.Button(panel, label=\"Browse...\")\n# sizer.Add(button1, pos=(3, 4), flag=wx.TOP|wx.RIGHT, border=5)\n\n text4 = wx.StaticText(panel, label=\"Number of Loads\")\n sizer.Add(text4, pos=(4, 0), flag=wx.TOP|wx.LEFT, border=10)\n\n self.tc3 = wx.TextCtrl(panel)\n sizer.Add(self.tc3, pos=(4, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND, border=5)\n self.Bind(wx.EVT_TEXT, self.inputs, self.tc3)\n\n# button2 = wx.Button(panel, label=\"Browse...\")\n# sizer.Add(button2, pos=(4, 4), flag=wx.TOP|wx.RIGHT, border=5)\n\n text5 = wx.StaticText(panel, label=\"Number of Loadcases\")\n sizer.Add(text5, pos=(5, 0), flag=wx.TOP|wx.LEFT, border=10)\n\n self.tc4 = wx.TextCtrl(panel)\n sizer.Add(self.tc4, pos=(5, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND, border=5)\n self.Bind(wx.EVT_TEXT, self.inputs, self.tc4)\n# sb = wx.StaticBox(panel, label=\"Optional Attributes\")\n#\n# boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)\n# boxsizer.Add(wx.CheckBox(panel, label=\"Public\"), \n# flag=wx.LEFT|wx.TOP, border=5)\n# boxsizer.Add(wx.CheckBox(panel, label=\"Generate Default Constructor\"),\n# flag=wx.LEFT, border=5)\n# boxsizer.Add(wx.CheckBox(panel, label=\"Generate Main Method\"), \n# flag=wx.LEFT|wx.BOTTOM, border=5)\n# sizer.Add(boxsizer, pos=(5, 0), span=(1, 5), \n# flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT , border=10)\n\n# button3 = wx.Button(panel, label='Help')\n# sizer.Add(button3, pos=(7, 2), flag=wx.LEFT, border=10)\n\n button1 = wx.Button(panel, label=\"Generate\")\n sizer.Add(button1, pos=(7, 3))\n button1.Bind(wx.EVT_BUTTON, self.generate_file)\n\n# button5 = wx.Button(panel, label=\"Cancel\")\n# sizer.Add(button5, pos=(7, 4), span=(1, 1), \n# flag=wx.BOTTOM|wx.RIGHT, border=5)\n\n sizer.AddGrowableCol(2)\n \n panel.SetSizer(sizer)\n\n def inputs(self, e):\n self.load_combs_file = self.tc1.GetValue()\n self.tcl_file = self.tc2.GetValue()\n self.number_of_loadcases = self.tc3.GetValue()\n self.number_of_loads = self.tc4.GetValue()\n\n def generate_file(self, e):\n load_combs_file_name = self.load_combs_file + '.csv'\n f = open(load_combs_file_name, 'r')\n file_table = []\n for I in f:\n file_table.append(I.split())\n f.close()\n\n N = int(self.number_of_loads)\n O = int(self.number_of_loadcases)\n #S = 2 #first load ID number\n\n all_combs = []\n for A in range(5,N+6):\n all_combs.append(file_table[A][0].split(\",\"))\n for B in range(1,N+1):\n del all_combs[B][1]\n \n load_IDs = file_table[5][2].split(',')\n load_IDs.remove('IDs')\n \n loadcombs = []\n for X in range(1,O+1):\n lcombs = all_combs[1][X]\n for J in range(2,N+1):\n lcombs += \",\" + all_combs[J][X]\n loadcombs.append(lcombs)\n \n tcl_file_name = self.tcl_file + '.tcl'\n h = open(tcl_file_name, 'w')\n for j in range(O):\n line = 'set lst' + str(j+1) + ' [split \"' + loadcombs[j] + '\" \",\"]\\n'\n h.write(line)\n \n names = []\n for n in range(N+1):\n names.append(all_combs[n][0])\n \n for i in range(1,N+1):\n load_places = []\n for lp in range(1,O+1):\n if all_combs[i][lp] != '0':\n load_places.append(lp)\n M = len(load_places)\n line = 'set name ' + names[i] + '\\n'\n h.write(line)\n line = 'set j [expr ' + str(i) + '+' + str(O) + ']\\n'\n h.write(line)\n line = 'set k ' + str(M) + '\\n'\n h.write(line)\n h.write('*startnotehistorystate {Created loadcollector $name}\\n')\n h.write('*collectorcreate loadcols $name \"\" 11\\n')\n h.write('*createmark loadcols 2 $name\\n')\n h.write('*dictionaryload loadcols 2 \"C:/Program Files/Altair/14.0/templates/feoutput/optistruct/optistruct\" \"LOADADD\"\\n')\n h.write('*startnotehistorystate {Attached attributes to loadcol $name}\\n')\n h.write('*attributeupdateint loadcols $j 3240 1 2 0 1\\n')\n h.write('*attributeupdatedouble loadcols $j 379 1 2 0 1\\n')\n h.write('*attributeupdateint loadcols $j 3236 1 0 0 1\\n')\n h.write('*createdoublearray 1 0\\n')\n h.write('*attributeupdatedoublearray loadcols $j 380 1 2 0 1 1\\n')\n h.write('*createarray 1 0\\n')\n h.write('*attributeupdateentityidarray loadcols $j 383 1 2 0 loadcols 1 1\\n')\n h.write('*endnotehistorystate {Attached attributes to loadcol $name}\\n')\n h.write('*startnotehistorystate {Attached attributes to loadcol $name}\\n')\n h.write('*attributeupdateint loadcols $j 3236 1 0 0 $k\\n')\n line = 'set load1 [lindex $lst' + str(load_places[0]) + ' [expr ' + str(i) + '-1]]\\n'\n h.write(line)\n loads = \"$load1\"\n for K in range(2,M+1):\n line = 'set load' + str(K) + ' [lindex $lst' + str(load_places[K-1]) + ' [expr ' + str(i) + '-1]]\\n'\n h.write(line)\n loads += ' $load' + str(K)\n line = '*createdoublearray $k ' + loads + '\\n'\n h.write(line)\n h.write('*attributeupdatedoublearray loadcols $j 380 1 2 0 1 $k\\n')\n load_p = str(load_IDs[load_places[0]-1])\n for P in range(1,M):\n load_p += ' ' + str(load_IDs[load_places[P]-1])\n line = '*createarray $k ' + load_p + '\\n'\n h.write(line)\n h.write('*attributeupdateentityidarray loadcols $j 383 1 2 0 loadcols 1 $k\\n')\n h.write('*endnotehistorystate {Attached attributes to loadcol $name}\\n')\n h.write('*endnotehistorystate {Created loadcollector $name}\\n')\n line = '#iteration ' + str(i) + ' ends\\n'\n h.write(line)\n h.close()\n\n\nif __name__ == '__main__':\n \n app = wx.App()\n Example(None, title=\"Load Combs TCL file Generator\")\n app.MainLoop()","sub_path":"BTdev/DO NOT TOUCH/Loadcombs TCL Generator/software_1/Loadcombs_Generator.py","file_name":"Loadcombs_Generator.py","file_ext":"py","file_size_in_byte":7648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"412758441","text":"import json\n\nfrom rest_framework import serializers\n\nfrom assessment.serializers import EffectTagsSerializer\n\nfrom bmd.serializers import BMDModelRunSerializer\nfrom study.serializers import StudySerializer\nfrom utils.api import DynamicFieldsMixin\nfrom utils.helper import SerializerHelper\n\nfrom . import models\n\n\nclass ExperimentSerializer(serializers.ModelSerializer):\n study = StudySerializer()\n\n def to_representation(self, instance):\n ret = super(ExperimentSerializer, self).to_representation(instance)\n ret['url'] = instance.get_absolute_url()\n ret['type'] = instance.get_type_display()\n ret['litter_effects'] = instance.get_litter_effects_display()\n ret['is_generational'] = instance.is_generational()\n ret['cas_url'] = instance.cas_url\n return ret\n\n class Meta:\n model = models.Experiment\n\n\nclass DosesSerializer(serializers.ModelSerializer):\n dose_regime = serializers.PrimaryKeyRelatedField(read_only=True)\n\n class Meta:\n model = models.DoseGroup\n depth = 1\n\n\nclass AnimalGroupRelationSerializer(serializers.ModelSerializer):\n\n def to_representation(self, instance):\n ret = super(AnimalGroupRelationSerializer, self).to_representation(instance)\n ret['url'] = instance.get_absolute_url()\n return ret\n\n class Meta:\n model = models.AnimalGroup\n fields = ('id', 'name', )\n\n\nclass DosingRegimeSerializer(serializers.ModelSerializer):\n doses = DosesSerializer(many=True)\n dosed_animals = AnimalGroupRelationSerializer()\n\n def to_representation(self, instance):\n ret = super(DosingRegimeSerializer, self).to_representation(instance)\n ret['route_of_exposure'] = instance.get_route_of_exposure_display()\n ret['positive_control'] = instance.get_positive_control_display()\n ret['negative_control'] = instance.get_negative_control_display()\n return ret\n\n class Meta:\n model = models.DosingRegime\n\n\nclass AnimalGroupSerializer(serializers.ModelSerializer):\n experiment = ExperimentSerializer()\n dosing_regime = DosingRegimeSerializer(allow_null=True)\n species = serializers.StringRelatedField()\n strain = serializers.StringRelatedField()\n parents = AnimalGroupRelationSerializer(many=True)\n siblings = AnimalGroupRelationSerializer()\n children = AnimalGroupRelationSerializer(many=True)\n\n def to_representation(self, instance):\n ret = super(AnimalGroupSerializer, self).to_representation(instance)\n ret['url'] = instance.get_absolute_url()\n ret['sex'] = instance.get_sex_display()\n ret['generation'] = instance.generation_short\n ret['sex_symbol'] = instance.sex_symbol\n return ret\n\n class Meta:\n model = models.AnimalGroup\n\n\nclass EndpointGroupSerializer(serializers.ModelSerializer):\n endpoint = serializers.PrimaryKeyRelatedField(read_only=True)\n\n def to_representation(self, instance):\n ret = super(EndpointGroupSerializer, self).to_representation(instance)\n ret['hasVariance'] = instance.hasVariance\n ret['isReported'] = instance.isReported\n return ret\n\n class Meta:\n model = models.EndpointGroup\n\n\nclass EndpointSerializer(serializers.ModelSerializer):\n assessment = serializers.PrimaryKeyRelatedField(read_only=True)\n effects = EffectTagsSerializer()\n animal_group = AnimalGroupSerializer()\n groups = EndpointGroupSerializer(many=True)\n\n def to_representation(self, instance):\n ret = super(EndpointSerializer, self).to_representation(instance)\n ret['url'] = instance.get_absolute_url()\n ret['dataset_increasing'] = instance.dataset_increasing\n ret['variance_name'] = instance.variance_name\n ret['data_type_label'] = instance.get_data_type_display()\n ret['observation_time_units'] = instance.get_observation_time_units_display()\n ret['expected_adversity_direction_text'] = instance.get_expected_adversity_direction_display()\n ret['monotonicity'] = instance.get_monotonicity_display()\n ret['trend_result'] = instance.get_trend_result_display()\n ret['additional_fields'] = json.loads(instance.additional_fields)\n models.EndpointGroup.getStdevs(ret['variance_type'], ret['groups'])\n models.EndpointGroup.percentControl(ret['data_type'], ret['groups'])\n models.EndpointGroup.getConfidenceIntervals(ret['data_type'], ret['groups'])\n models.Endpoint.setMaximumPercentControlChange(ret)\n\n # get BMD\n ret['BMD'] = None\n try:\n model = instance.BMD_session.latest().selected_model\n if model is not None:\n ret['BMD'] = BMDModelRunSerializer().to_representation(model)\n except instance.BMD_session.model.DoesNotExist:\n pass\n\n return ret\n\n class Meta:\n model = models.Endpoint\n\n\nclass ExperimentCleanupFieldsSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n\n class Meta:\n model = models.Experiment\n cleanup_fields = model.TEXT_CLEANUP_FIELDS\n fields = cleanup_fields + ('id', )\n\n\nclass AnimalGroupCleanupFieldsSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n\n class Meta:\n model = models.AnimalGroup\n cleanup_fields = model.TEXT_CLEANUP_FIELDS\n fields = cleanup_fields + ('id', )\n\n\nclass EndpointCleanupFieldsSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n\n class Meta:\n model = models.Endpoint\n cleanup_fields = model.TEXT_CLEANUP_FIELDS\n fields = cleanup_fields + ('id', )\n\nSerializerHelper.add_serializer(models.Endpoint, EndpointSerializer)\n","sub_path":"project/animal/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"265933505","text":"from django.urls import path\nfrom profiles import views\n\n\napp_name = \"profiles\"\n\n\nurlpatterns = [\n path(\"signup/\", views.SignupView.as_view(), name='signup'),\n path(\"meta/ajax/check_email/\", views.check_email_AJAX, name=\"check_email\"),\n path(\"meta/ajax/register/\", views.register_AJAX, name='register'),\n path(\"login/\", views.LoginView.as_view(), name='login'),\n path(\"logout/\", views.logout_view, name=\"logout\"),\n path(\"\", views.LandingPageView.as_view(), name=\"landing_page\"),\n path(\"ajax/get_profile/\", views.get_profile_AJAX, name='get_profile'),\n path(\"ajax/follow/\", views.follow_AJAX, name='follow'),\n path(\"related_users/\", views.SuggestionsView.as_view(), name='suggestions'),\n path(\"ajax/get_follow_suggestions/\", views.get_follow_suggestions_AJAX, name='who-to-follow'),\n path(\"/\", views.ProfileView.as_view(), name=\"profile\"),\n]\n","sub_path":"twitter_project/profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"141251177","text":"#!/usr/bin/env python\n# -*-coding:utf-8 -*-\n#RobinZ @ chtc.wisc.edu\n#07.18 2017\nimport sys\nsys.path.append('../')\n\nfrom DAGAPI.Dag import *\nfrom DAGAPI.Dag import DAG\n\n\nimport os\n # ------ File name: diamond.dag--------\n # JOB A A.condor\n # JOB B B.condor\n # JOB C C.condor\n # JOB D D.condor\n # SCRIPT PRE B pre.csh $JOB .gz\n # SCRIPT POST C pre.csh $JOB .gz\n # PARENT A CHILD B C\n # PARENT B C CHILD D\n\ndag = DAG('diamond.dag')\n#create jobs\nj1 = Job('job1','a.sh')\nj1.add_commands(should_transfer_files='YES',\n when_to_transfer_output='ON_EXIT',\n Arguments='in1 in2 out1', Queue = 3)\ns1 = Script('a.sh','j1','PRE')\ns2 = Script('a.sh','j1','POST', argu = '$JOB .gz')\n\nj2 = Job('job2','a.sh')\nj2.add_commands(should_transfer_files='No',\n when_to_transfer_output='all_time',\n Arguments='usa', Queue = 0)\ns3 = Script('a.sh','j2','PRE')\n\n\n\nnode1 = Node('A')\nnode1.job = j1\nnode1.scripts = [s1,s2]\nnode2 = Node('B')\nnode2.job = j1\nnode2.scripts = [s2]\n\n\nnode3 = Node('C')\nnode3.job = j2\nnode3.scripts = [s3]\nnode4 = Node('D')\nnode4.job = j2\n\n\ne1 = Edge(['A','D'],['B','C'])\ne2 = Edge(['A'],['B'])\n\nfor _ in [node1,node2,node3,node4]:\n dag.add_node(_)\n\nfor _ in [e1,e2]:\n dag.add_edge(_)\n\ndag.write2file('./')\n\n","sub_path":"BeihangDemo/DAGAPI/testpath/usecase.py","file_name":"usecase.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"24895836","text":"# You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.\n# Merge all the linked-lists into one sorted linked-list and return it.\n\n# Example 1:\n\n# Input: lists = [[1,4,5],[1,3,4],[2,6]]\n# Output: [1,1,2,3,4,4,5,6]\n# Explanation: The linked-lists are:\n# [\n# 1->4->5,\n# 1->3->4,\n# 2->6\n# ]\n# merging them into one sorted list:\n# 1->1->2->3->4->4->5->6\n\n# Example 2:\n# Input: lists = []\n# Output: []\n\n# Example 3:\n# Input: lists = [[]]\n# Output: []\n \n\n# Constraints:\n\n# k == lists.length\n# 0 <= k <= 10^4\n# 0 <= lists[i].length <= 500\n# -10^4 <= lists[i][j] <= 10^4\n# lists[i] is sorted in ascending order.\n# The sum of lists[i].length won't exceed 10^4.\n\n# Definition for singly-linked list.\nimport heapq\n\n\nclass ListNode(object):\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\n# Brute Force: time O(kn) space: O(k)\nclass Solution(object):\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n if not lists:\n return None\n available = set(i for i in range(len(lists)))\n head = ListNode(0,None)\n curr = head\n # Remove all empty lists:\n for i in range(len(lists)):\n if not lists[i]:\n available.remove(i)\n # all lists are empty\n if not available:\n return lists[0]\n while available:\n min_val = float('inf')\n min_node = ListNode(0,None)\n selected = 0\n for i in list(available):\n if lists[i].val < min_val:\n min_node = lists[i]\n min_val = lists[i].val\n selected = i\n if lists[selected].next:\n lists[selected] = lists[selected].next\n else:\n available.remove(selected)\n curr.next = min_node\n curr = curr.next\n return head.next\n# Runtime: 5574 ms.\n\n\n# Optimized by PQ: time O(nlogk) space: O(k)\nclass Solution(object):\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n if not lists:\n return None\n available = set(i for i in range(len(lists)))\n dummy = ListNode(0,None)\n curr = dummy\n # Remove all empty lists:\n for i in range(len(lists)):\n if not lists[i]:\n available.remove(i)\n # all lists are empty\n if not available:\n return lists[0]\n # initialize PQ:\n pq = []\n for i in available:\n heapq.heappush(pq, (lists[i].val, i))\n # pop the mins:\n while pq:\n _, i = heapq.heappop(pq)\n min_node = lists[i]\n if lists[i].next:\n lists[i] = lists[i].next\n heapq.heappush(pq, (lists[i].val, i))\n curr.next = min_node\n curr = min_node\n return dummy.next\n# Runtime: 84 ms, faster than 94.85% of Python online submissions for Merge k Sorted Lists.\n# Memory Usage: 19.6 MB, less than 63.44% of Python online submissions for Merge k Sorted Lists.","sub_path":"23. Merge k Sorted Lists.py","file_name":"23. Merge k Sorted Lists.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"343599961","text":"#!/usr/bin/env python3\n\nfrom sys import exit\n\ndef main( ):\n\n x = 0\n y = 0\n while( True ):\n print( str( x ) + \" x \" + str( y ) + \" = \" + str( int( x ) * int( y ) ) )\n x = x + 1\n y = y + 1\n\n\nif __name__ == \"__main__\":\n exit( main( ) )\n","sub_path":"TimesTables/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"625416363","text":"import numpy as np\n\n# Stoichiometric matrix\nV = np.array([[-1.0, 1.0, 0.0],[-1.0, 1.0, 1.0],[1.0, -1.0, -1.0],[0.0, 0.0, 1.0]])\n\n# Parameters and Initial Conditions\nnA = 6.023e23 # Avagadro's number\nvol = 1e-15 # volume of system\nY = np.zeros((4,))\nc = np.zeros((3,))\nd = np.zeros_like(c)\na = np.zeros_like(c)\nY[0] = round(5e-7 * nA * vol) # molecules of substrate\nY[1] = round(2e-7 * nA * vol) # molecules of enzyme \nc[0] = 1.0e6 / (nA * vol)\nc[1] = 1.0e-4\nc[2] = 0.1\n\ntfinal = 50.0\nL = 250\ntau = tfinal / L # stepsize\n\nfor k in range(L):\n a[0] = c[0] * Y[0] * Y[1]\n a[1] = c[1] * Y[2]\n a[2] = c[2] * Y[2]\n for i in range(3):\n d[i] = tau * a[i] + np.sqrt(abs(tau * a[i])) * np.random.randn()\n Y = Y + d[0] * V[:, 0] + d[1] * V[:, 1] + d[2] * V[:, 2]\n","sub_path":"cle_mm.py","file_name":"cle_mm.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"217432000","text":"from numpy import *\nfrom matplotlib.pyplot import *\nimport time\n\n\ndef ackley(value):\n \"\"\"\n the pattern of value is [x1,x2]\n ackley is the test function for GA.\n \"\"\"\n c1 = 20\n c2 = 0.2\n c3 = 2 * pi\n ex = exp(1)\n x1 = value[0]\n x2 = value[1]\n n = 2\n f_value = -c1*exp(-c2*sqrt(1/n*(x1**2+x2**2)))-exp(1/n*(cos(c3*x1)+cos(c3*x2)))+c1+ex\n return f_value\n\n\ndef randomgroup(fitfunc, experiment_group, pop_size):\n \"\"\"\n create the inital groups.\n fitfunc is the function to calculate the fitness value.\n create a 10*2(numbers in (-5,5)) mat for initial group.\n \"\"\"\n random_mat = 5 * random.rand(pop_size, 2)\n\n # calculate the fitness of the samples in groups\n fitness_value = []\n for value in random_mat:\n fit_value = fitfunc(value)\n fitness_value.append(fit_value)\n\n # put the original values in group\n i = 0\n while i < pop_size:\n sample = list(random_mat[i])\n fit_value = fitness_value[i]\n experiment_group.append([sample,fit_value])\n i += 1\n\n\ndef operate_c(experiment_group, child_group, pop_size, pc):\n \"\"\"\n element = [[x1,x2],]\n v1' = a*v1 + (1-a)*v2\n v2' = a*v2 + (1-a)*v1\n \"\"\"\n work_group = []\n i = 0\n while i pop_size:\n max = -9999\n i = 0\n while i < len(work_group):\n if(work_group[i][1] > max):\n max = work_group[i][1]\n maxsample = work_group[i]\n i += 1\n work_group.remove(maxsample)\n return work_group\n\n\ndef main(*args, **kwargs):\n \"\"\"\n kwargs, pop_size = integer, max_gen = number\n pm = mutate rate, pc = cross rate\n\n store experiment_group child_group,pattern of this list is [[[x1,x2],eval(v)]]\n the pattern of sample(v) is [x1,x2]\n \"\"\"\n experiment_group = []\n child_group = []\n randomgroup(ackley, experiment_group, 10)\n\n i = 0\n while i < 1000:\n print(\"experiment population:\")\n print(experiment_group)\n\n operate_c(experiment_group, child_group, 10, 0.3)\n operate_m(ackley, experiment_group, child_group, 10, i, 1000, 0.1)\n\n print(\"generated offspring:\")\n print(child_group)\n\n experiment_group = select(experiment_group, child_group, 10)\n\n child_group = []\n time.sleep(1)\n i += 1\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"GA.g/ga.py","file_name":"ga.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"384250763","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse\nfrom .models import *\nfrom .forms import *\n\n# app controllers\ndef apps(request):\n try:\n lists = App.objects.all()\n except App.DoesNotExist:\n raise Http404(\"Application does not exist.\")\n return render(request, 'pln/apps.html', {'lists': lists})\n\ndef app(request, item_id):\n item = get_object_or_404(App, id=item_id)\n return render(request, 'pln/app.html', {'item': item})\n\ndef app_new(request):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n if request.method == \"POST\":\n form = AppForm(request.POST)\n if form.is_valid():\n app = form.save(commit=False)\n app.save()\n return redirect('pln.views.app',item_id=app.id)\n else:\n form = AppForm()\n return render(request, 'pln/app_new.html',{'form': form})\n\ndef app_edit(request, item_id):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n app = get_object_or_404(App, id=item_id)\n if request.method == \"POST\":\n form = AppForm(request.POST, instance=app)\n if form.is_valid():\n app = form.save(commit=False)\n app.save()\n return redirect('pln.views.app', item_id=app.id)\n else:\n form = AppForm(instance=app)\n return render(request, 'pln/app_edit.html',{'form': form})\n\ndef app_delete(request, item_id):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n app = get_object_or_404(App, id=item_id)\n app.delete()\n \n return redirect('/pln')\n \n# format controllers\ndef formats(request):\n try:\n lists = Format.objects.all()\n except Format.DoesNotExist:\n raise Http404(\"Format does not exist.\")\n return render(request, 'pln/formats.html', {'lists': lists})\n\ndef format(request, item_id): \n item = get_object_or_404(Format, id=item_id)\n return render(request, 'pln/format.html', {'item': item})\n\ndef format_new(request):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n if request.method == \"POST\":\n form = FormatForm(request.POST)\n if form.is_valid():\n format = form.save(commit=False)\n format.save()\n return redirect('pln.views.format',item_id=format.id)\n else:\n form = FormatForm()\n return render(request, 'pln/format_new.html',{'form': form})\n\ndef format_edit(request, item_id):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n format = get_object_or_404(Format, id=item_id)\n if request.method == \"POST\":\n form = FormatForm(request.POST, instance=format)\n if form.is_valid():\n format = form.save(commit=False)\n format.save()\n return redirect('pln.views.format', item_id=format.id)\n else:\n form = FormatForm(instance=format)\n return render(request, 'pln/format_edit.html',{'form': form})\n\ndef format_delete(request, item_id):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n format = get_object_or_404(Format, id=item_id)\n format.delete()\n \n return redirect('/pln/formats')\n\n# function controllers\ndef functions(request):\n try:\n lists = Function.objects.all()\n except Function.DoesNotExist:\n raise Http404(\"Function does not exist.\")\n return render(request, 'pln/functions.html', {'lists': lists})\n\ndef function(request, item_id):\n item = get_object_or_404(Function, id=item_id)\n return render(request, 'pln/function.html', {'item': item})\n\ndef function_new(request):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n if request.method == \"POST\":\n form = FunctionForm(request.POST)\n if form.is_valid():\n function = form.save(commit=False)\n function.save()\n return redirect('pln.views.function',item_id=function.id)\n else:\n form = FunctionForm()\n return render(request, 'pln/function_new.html',{'form': form})\n\ndef function_edit(request, item_id):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n function = get_object_or_404(Function, id=item_id)\n if request.method == \"POST\":\n form = FunctionForm(request.POST, instance=function)\n if form.is_valid():\n function = form.save(commit=False)\n function.save()\n return redirect('pln.views.function', item_id=function.id)\n else:\n form = FormatForm(instance=function)\n return render(request, 'pln/function_edit.html',{'form': form})\n\ndef function_delete(request, item_id):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n function = get_object_or_404(App, id=item_id)\n function.delete()\n \n return redirect('/pln/functions')\n\n# type controlers\ndef types(request):\n try:\n lists = Type.objects.all()\n except Type.DoesNotExist:\n raise Http404(\"Type dose not exist.\")\n return render(request, 'pln/types.html', {'lists': lists})\n\n\ndef type(request, item_id):\n item = get_object_or_404(Type, id=item_id)\n return render(request, 'pln/type.html', {'item': item})\n\ndef type_new(request):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n if request.method == \"POST\":\n form = TypeForm(request.POST)\n if form.is_valid():\n type = form.save(commit=False)\n type.save()\n return redirect('pln.views.type',item_id=type.id)\n else:\n form = TypeForm()\n return render(request, 'pln/type_new.html',{'form': form})\n\ndef type_edit(request, item_id):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n type = get_object_or_404(Type, id=item_id)\n if request.method == \"POST\":\n form = TypeForm(request.POST, instance=type)\n if form.is_valid():\n type = form.save(commit=False)\n type.save()\n return redirect('pln.views.type', item_id=type.id)\n else:\n form = TypeForm(instance=type)\n return render(request, 'pln/type_edit.html',{'form': form})\n\ndef type_delete(request, item_id):\n if not request.user.is_authenticated():\n return redirect('/admin')\n\n type = get_object_or_404(App, id=item_id)\n type.delete()\n \n return redirect('/pln/types')\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"21113839","text":"class Solution(object):\n # 99%\n def peakIndexInMountainArray(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n ls = len(A)\n if ls == 0: return None\n if ls == 1: return 0\n if ls == 2:\n if A[0] > A[1]: return 0\n else: return 1\n for i in range(1, ls - 1):\n if A[i] > A[i - 1] and A[i] > A[i + 1]:\n return i","sub_path":"Project/Leetcode/Array/852. Peak Index in a Mountain Array.py","file_name":"852. Peak Index in a Mountain Array.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"79842874","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 31 08:23:44 2018\r\n\r\n@author: sriramjee.singh\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nos.chdir('T:\\Ops Control Team\\Sriramjee')\r\ndf1 = pd.read_excel('CWG.RegressionData_UpdatedWithBiodieselEMTSdata.xlsx', 'Weekly Data Original')\r\ndf1.head()\r\ndf1['Wgt Avg Price Two Weeks Ahead'] = df1['Wgt Avg Price Two Weeks Ahead']*100\r\n#df1['Wgt Avg Price Two Weeks Ahead'] = df1['Wgt Avg Price Two Weeks Ahead'].shift(-2)\r\n#df1.rename(columns={'Wgt Avg Price Two Weeks Ahead': 'Wgt Avg Price Four Weeks Ahead'}, inplace=True)\r\ndf1 = df1.iloc[1:,:]\r\ndf1 = df1.drop(['USDA Expected Slaughter', 'Avg percent corn plantation', 'Avg percent corn harvest'], axis=1)\r\n\r\ndf1['Date'] = df1['Date'].astype(str)\r\ndf1['month'] = (df1['Date'].str.partition('-')[2]).str.rpartition('-')[0]\r\ndf1['year'] = df1['Date'].str.partition('-')[0]\r\ndf1['weeks per month'] = df1.groupby(['year', 'month'])['month'].transform('count')\r\n\r\ndf_cwg_mc = pd.read_excel('CWG.RegressionData_UpdatedWithBiodieselEMTSdata.xlsx', 'CWG Monthly Consumption')\r\ndf_cwg_mc.head()\r\ndf_cwg_mc['CWG million pounds'].isnull().sum()\r\ndf_cwg_mc['CWG million pounds'] = df_cwg_mc['CWG million pounds'].fillna(df_cwg_mc['CWG million pounds'].mean())\r\ndf_cwg_mc['Date'] = df_cwg_mc['Date'].astype(str)\r\ndf_cwg_mc['month'] = (df_cwg_mc['Date'].str.partition('-')[2]).str.rpartition('-')[0]\r\ndf_cwg_mc['year'] = df_cwg_mc['Date'].str.partition('-')[0]\r\n\r\ndf = pd.merge(df1, df_cwg_mc, left_on = ['year', 'month'], right_on = ['year', 'month'])\r\ndf.head()\r\n\r\n#df_cwg_me = pd.read_excel('CWG.RegressionData_UpdatedWithBiodieselEMTSdata.xlsx', 'CWG Export GATS Monthly')\r\n#df_cwg_me.head()\r\n#df_cwg_me['CWG export (mil lbs)'].isnull().sum()\r\n#df_cwg_me['CWG export (mil lbs)'] = df_cwg_me['CWG export (mil lbs)'].fillna(df_cwg_me['CWG export (mil lbs)'].mean())\r\n#df_cwg_me['Date'] = df_cwg_me['Date'].astype(str)\r\n#df_cwg_me['month'] = (df_cwg_me['Date'].str.partition('-')[2]).str.rpartition('-')[0]\r\n#df_cwg_me['year'] = df_cwg_me['Date'].str.partition('-')[0]\r\n#\r\n#df = pd.merge(df2, df_cwg_me, left_on = ['year', 'month'], right_on = ['year', 'month'])\r\n#df.head()\r\ndf['CWG consumption'] = df['CWG million pounds']/df['weeks per month']\r\n#df['CWG export'] = df['CWG export (mil lbs)']/df['weeks per month']\r\n#df.dtypes\r\ndf = df.drop(['month', 'year', 'weeks per month', 'Date_y', 'CWG million pounds'], axis=1)\r\ndf = df.rename(columns = {'Date_x' : 'Date'})\r\ndf.head()\r\n\r\ndf['Date'] = df['Date'].astype(str)\r\ndf['month'] = (df['Date'].str.partition('-')[2]).str.rpartition('-')[0]\r\nmonths = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11']\r\nfor m in months:\r\n df['d'+str(m)] = np.where(df['month'] == m, 1, 0)\r\ndf = df.drop(['month'], axis=1)\r\n\r\n#df['Date'] = df['Date'].astype(str)\r\n#df['month'] = (df['Date'].str.partition('-')[2]).str.rpartition('-')[0]\r\n#\r\n#def label_qtr1(row): \r\n# if row['month'] == '01':\r\n# return 1\r\n# if row['month'] == '02':\r\n# return 1\r\n# if row['month'] == '03':\r\n# return 1\r\n# return 0\r\n#df['quarter1'] = df.apply (lambda row: label_qtr1(row), axis=1)\r\n#\r\n#def label_qtr2(row): \r\n# if row['month'] == '04':\r\n# return 1\r\n# if row['month'] == '05':\r\n# return 1\r\n# if row['month'] == '06':\r\n# return 1\r\n# return 0\r\n#df['quarter2'] = df.apply (lambda row: label_qtr2(row), axis=1)\r\n#\r\n#def label_qtr3(row): \r\n# if row['month'] == '07':\r\n# return 1\r\n# if row['month'] == '08':\r\n# return 1\r\n# if row['month'] == '09':\r\n# return 1\r\n# return 0\r\n#df['quarter3'] = df.apply (lambda row: label_qtr3(row), axis=1)\r\n#df = df.drop(['month'], axis=1)\r\n#df['CWGRatioCorn_qtr1'] = df['CWGRatioCorn']*df['quarter1']\r\n#df['CWGRatioCorn_qtr2'] = df['CWGRatioCorn']*df['quarter2']\r\n#df['CWGRatioCorn_qtr3'] = df['CWGRatioCorn']*df['quarter3']\r\n#df = df.drop(['quarter1', 'quarter2', 'quarter3'], axis =1)\r\n\r\n#plt.plot(df['Date'], df['Wgt Avg Price Two Weeks Ahead'])\r\n#plt.plot(df['Date'], df['Wgt Avg Price Three Weeks Ahead'])\r\n\r\ndf.to_excel('CWG-Prediction-4weeks.xlsx', 'data-4weeks', index = False)\r\ndf = df.set_index('Date')\r\ndf.head()\r\n#df_predicted = df.iloc[-2:-1,:]\r\n#df_predicted.head()\r\ndf.isnull().sum()\r\ndf = df.dropna(how = 'any', axis = 0)\r\n\r\nX = df.iloc[:, 1:]\r\ny = df.iloc[:, 0:1]\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)\r\nlm=LinearRegression()\r\nlm.fit(X_train,y_train)\r\nprint(lm.intercept_)\r\nprint(lm.coef_)\r\ny_pred=lm.predict(X_test)\r\nrms=np.sqrt(mean_squared_error(y_test,y_pred))\r\nprint('rmse:',rms)\r\n\r\n#X_predicted = df_predicted.iloc[:, 1:]\r\n#y_predicted = lm.predict(X_predicted)\r\n#y_predicted\r\n\r\nmy_list = map(lambda x: x[0], y_pred)\r\ny_predicted = pd.Series(my_list)\r\ny_test = y_test.reset_index()\r\ndf1 = pd.concat([y_test, y_predicted], axis = 1) \r\ndf1.columns = ['Date', 'Actual Wgt Avg Price Two Weeks Ahead', 'Predicted Wgt Avg Price Two Weeks Ahead']\r\ndf1 = df1.reset_index()\r\ndf1 = df1.set_index('Date')\r\ndf1.head()\r\n\r\nplt.figure()\r\nx = df1['index']\r\ny1 = df1['Actual Wgt Avg Price Two Weeks Ahead']\r\ny2 = df1['Predicted Wgt Avg Price Two Weeks Ahead']\r\nplt.plot(x, y1, 'b-')\r\nplt.plot(x, y2, 'r-')\r\n\r\ny_all_pred=lm.predict(X)\r\nrms=np.sqrt(mean_squared_error(y,y_all_pred))\r\nprint('rmse:',rms)\r\nmy_list = map(lambda x: x[0], y_all_pred)\r\ny_all_predicted = pd.Series(my_list)\r\ny = y.reset_index()\r\ndf1 = pd.concat([y, y_all_predicted], axis = 1) \r\ndf1.columns = ['Date', 'Actual Wgt Avg Price Two Weeks Ahead', 'Predicted Wgt Avg Price Two Weeks Ahead']\r\n#df1 = df1.reset_index()\r\n#df1 = df1.set_index('Date')\r\ndf1.head()\r\n\r\nplt.figure()\r\nx = df1['Date']\r\ny1 = df1['Actual Wgt Avg Price Two Weeks Ahead']\r\ny2 = df1['Predicted Wgt Avg Price Two Weeks Ahead']\r\nplt.plot(x, y1, 'b-')\r\nplt.plot(x, y2, 'r-')\r\n\r\n\r\n\r\n\r\n","sub_path":"REG - codes/reg_cwg.py","file_name":"reg_cwg.py","file_ext":"py","file_size_in_byte":6004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"569869188","text":"# Note that there's a lot of dumb/unidiomatic code here to work around Transcrypt weirdness.\n\n# __pragma__ ('skip')\ndocument = console = ITEMS = __pragma__ = object()\n# __pragma__('noskip')\n\nbaseitem = ('sword', 'bow', 'rod', 'tear', 'armor', 'cloak', 'belt', 'spatula')\n\nitemsj = ITEMS\n\nclass Item(object):\n def __init__(self, itemj):\n self.combine = itemj['comp']\n self.text = itemj['desc']\n self.name = itemj['name']\n self.score = itemj['score']\n\nclass Items(object):\n def __init__(self):\n self.bycombine = {}\n self.byname = {}\n for itemj in itemsj:\n item = Item(itemj)\n self.bycombine[item.combine] = item\n self.byname[item.name] = item\n\n\n# Modified from https://stackoverflow.com/a/21762051\ndef uniquepairs(l):\n result = []\n def rec(l, choice, depth):\n if depth > 10:\n print('MAXDEPTH', depth)\n return\n if len(l) == 0:\n tempresult = []\n for i in choice:\n tempresult.append(tuple(sorted(i)))\n retval = tuple(sorted(tempresult))\n if retval in result:\n return\n result.append(retval)\n else:\n for j in range(1, len(l)):\n choice1 = choice[:]\n choice1.append((l[0],l[j]))\n l1 = []\n for x in range(1, j):\n l1.append(l[x])\n for x in range(j + 1, len(l)):\n l1.append(l[x])\n rec(l1, choice1, depth + 1)\n rec(l, [], 0)\n return result\n\n\ndef sih(k, v):\n document.getElementById(k).innerHTML = v\n\n\nclass TI(object):\n def __init__(self):\n self.items = {}\n self.wanted = set()\n self.ready = False\n\n def setready(self):\n self.ready = True\n\n def clearitems(self):\n if not self.ready:\n return\n self.items = {}\n self.render()\n\n def moditem(self, i, l):\n i = int(i)\n itemcount = self.items.get(i, 0)\n self.items[i] = l(itemcount)\n\n def incitem(self, i):\n if not self.ready or sum(self.items.values()) > 7:\n return\n self.moditem(i, lambda ic: ic + 1)\n self.render()\n\n def decitem(self, i):\n if not self.ready:\n return\n self.moditem(i, lambda ic: max(0, ic - 1))\n self.render()\n\n def decfullitem(self, c):\n if not self.ready:\n return\n decf = lambda ic: max(0, ic - 1)\n self.moditem(c[0], decf)\n self.moditem(c[1], decf)\n self.tipout('b')\n self.render()\n\n def itemstostr(self):\n result = []\n for k in range(8):\n count = self.items.get(k, 0)\n if count > 0:\n for _ in range(count):\n result.append(str(k))\n return ''.join(result)\n\n def render(self):\n self.renderitems()\n self.rendercombinations()\n self.renderwanted()\n\n def renderitems(self):\n result = []\n for iidx in list(self.itemstostr()):\n result.append(''.format(iidx, baseitem[int(iidx)], iidx))\n sih('items', ''.join(result))\n\n # __pragma__('kwargs')\n def rendercombinations(self):\n result = []\n itemstr = self.itemstostr()\n if len(itemstr) < 2:\n sih('combinations', '')\n sih('buildable', '')\n return\n if len(itemstr) & 1:\n itemstr = itemstr + ' '\n up = uniquepairs(tuple(itemstr))\n uniqueitems = {}\n seen = set()\n newup = []\n for p in up:\n newp = []\n spare = None\n for i in p:\n if i[0] == ' ':\n spare = i[1]\n continue\n newp.append(items.bycombine[''.join(i)])\n newup.append((newp, spare))\n for (pi, spare) in sorted(newup, reverse = True, key = lambda ps: sum(i.score for i in ps[0])):\n pi = sorted(pi, reverse = True, key = lambda i: i.score)\n sk = ''.join(sorted(list(i.combine for i in pi)))\n if sk in seen:\n continue\n result.append('
')\n seen.add(sk)\n for thisitem in pi:\n uniqueitems[thisitem.combine] = thisitem\n result.append(self.rendercomponentstr(thisitem.combine[0], thisitem.combine[1], 'c',\n imgclass = 'lowscore' if thisitem.score < 3 else ''))\n if spare is not None:\n result.append(''.format(spare, baseitem[int(spare)]))\n result.append('
')\n self.renderbuildable(uniqueitems.values())\n sih('combinations', ''.join(result))\n\n def renderbuildable(self, uniqueitems):\n result = []\n for item in sorted(uniqueitems, reverse = True, key = lambda i: i.score):\n c = item.combine\n result.append(self.rendercomponentstr(c[0], c[1], 'b', imgextra=\"onclick=\\\"ti.ti.decfullitem('{0}')\\\"\".format(c),\n imgclass = 'lowscore' if item.score < 3 else ''))\n sih('buildable', ''.join(result))\n # __pragma__('nokwargs')\n\n def mkwantedoptions(self):\n sitems = sorted(items.bycombine.values(), key = lambda i: i.name)\n result = ['']\n for item in sitems:\n result.append(''.format(item.combine, item.name))\n sih('wantedselect', ''.join(result))\n\n def tipout(self, typ):\n if typ == 'b':\n did = 'buildabletip'\n elif typ == 'c':\n did = 'combinestip'\n else:\n return\n sih(did, '')\n\n def tip(self, typ, c):\n if typ == 'b':\n did = 'buildabletip'\n elif typ == 'c':\n did = 'combinestip'\n else:\n return\n item = items.bycombine[c]\n itemtitle = '{0}: {1}'.format(item.name, item.text)\n sih(did, itemtitle)\n\n def setwanted(self, thisarg):\n if len(self.wanted) >= 16:\n return\n self.wanted.add(thisarg.value)\n thisarg.value = ''\n self.renderwanted()\n\n def delwanted(self, c):\n self.wanted.remove(c)\n self.renderwanted()\n\n # __pragma__('kwargs')\n def renderwanted(self):\n result = []\n for c in self.wanted:\n if c[0] == c[1]:\n havec = self.items.get(int(c[0]), 0)\n c1buildable = havec > 0\n c2buildable = buildable = havec > 1\n else:\n c1buildable = self.items.get(int(c[0]), 0) > 0\n c2buildable = self.items.get(int(c[1]), 0) > 0\n buildable = c1buildable and c2buildable\n result.append(self.rendercomponentstr(c[0], c[1], 'w',\n minitclass = 'showdel' if not c1buildable else '',\n minibclass = 'showdel' if not c2buildable else '',\n imgclass = 'showdel' if not buildable else '',\n imgextra = \"onclick='ti.ti.delwanted(\\\"{0}\\\")'\".format(c)\n ))\n sih('wanted', ''.join(result))\n\n def rendercomponentstr(self, c1, c2, typ, minitclass = '', minibclass = '', imgclass = '', imgextra = ''):\n c1name = baseitem[int(c1)]\n c2name = baseitem[int(c2)]\n item = items.bycombine[''.join((c1,c2))]\n itemtitle = '{0}: {1}'.format(item.name, item.text)\n return '''\n
\n
\n
\n
\n \n
\n
'''.format(c1 = c1, c2 = c2, c1name = c1name, c2name = c2name,\n itemtitle = itemtitle, typ = typ,\n minibclass = minibclass, minitclass = minitclass,\n imgclass = imgclass, imgextra = imgextra)\n # __pragma__('nokwargs')\n\n def mkbuttons(self):\n result = []\n for iidx in range(8):\n result.append(''.format(iidx, baseitem[iidx], iidx))\n result.append('
')\n sih('baseitems', ''.join(result))\n\nitems = Items()\nti = TI()\nti.mkbuttons()\nti.mkwantedoptions()\n","sub_path":"ti.py","file_name":"ti.py","file_ext":"py","file_size_in_byte":7743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"467678721","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom ..pattern.pattern_generator import out_to_spike_array\nimport matplotlib.animation as animation\nimport cv2\n# from tempfile import NamedTemporaryFile\nfrom IPython.display import HTML, Image\n\n\nSRC, DST, W, DLY = 0, 1, 2, 3\nX, Y, Z = 0, 1, 2\n\ndef my_imshow(ax, img, cmap=\"Greys_r\", interpolation=\"none\", \n vmin=None, vmax=None, no_ticks=True, colorbar=False):\n if no_ticks:\n remove_ticks(ax)\n return plt.imshow(img, cmap=cmap, interpolation=interpolation, vmin=vmin, vmax=vmax)\n\n\ndef remove_ticks(ax):\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.get_xaxis().set_ticks([])\n ax.get_yaxis().set_ticks([])\n\ndef get_bounding_rect(positions):\n min_z = positions[:, Z].min()\n max_z = positions[:, Z].max()\n min_x = positions[:, X].min()\n max_x = positions[:, X].max()\n size_x = np.int32(np.ceil(max_x) - np.floor(min_x))\n size_z = np.int32(np.ceil(max_z) - np.floor(min_z))\n \n return [min_x, 0, min_z], \\\n [max_x, 0, max_z], \\\n [size_x, size_z]\n\n\n\n\ndef get_weights_and_positions(nrn_id, weights, positions, connections):\n src_rows = np.where( connections[:,DST] == nrn_id)[0]\n\n if src_rows.size == 0:\n return None\n\n src_ids = connections[src_rows, SRC].astype(np.int32)\n conn_weights = weights[src_rows]\n poss = positions[src_ids, :]\n min, max, shape = get_bounding_rect(poss)\n\n if shape[0] == 0:\n shape[0] = 1\n if shape[1] == 0:\n shape[1] = 1\n\n kernel = {'weights': conn_weights,\n 'positions': poss,\n 'min': min,\n 'max': max, \n 'shape': shape}\n\n return kernel\n\n\n\n\ndef weights_to_img(nrn_id, weights, src_neuron_pos, connections):\n # conns = np.array(connections)\n\n img_info = get_weights_and_positions(nrn_id, weights, \n src_neuron_pos,\n connections)\n if img_info is None:\n return None\n # print(img_info)\n img = np.zeros(img_info['shape'])\n \n \n xs = np.int32( img_info['positions'][:, X] - \\\n img_info['min'][X] )\n \n # print(xs)\n zs = np.int32( img_info['positions'][:, Z] - \\\n img_info['min'][Z] )\n \n \n # print(zs)\n # print(img[xs, zs].shape)\n # print(img_info['weights'].shape)\n img[xs, zs] = img_info['weights']\n \n return img\n\n\n\n\ndef layer_to_imgs(nrn_ids, weights, src_neuron_pos, connections):\n cs = np.array(connections)\n ws = np.array(weights)\n imgs = []\n for nrn_id in nrn_ids:\n imgs.append(weights_to_img(nrn_id, ws, src_neuron_pos, cs))\n \n return imgs\n\n\n\n\ndef plot_imgs(imgs, figs_per_row, save=False, filename=None, min_v=0., max_v=2.):\n import matplotlib.pyplot as plt\n\n i = 0\n n_imgs = len(imgs)\n fig = plt.figure()\n n_rows = n_imgs/figs_per_row + 1\n for img in imgs:\n i += 1\n if img is None:\n continue\n\n plt.subplot(n_rows, figs_per_row, i)\n plt.imshow(img, interpolation='none', cmap='Greys_r', \\\n vmin=min_v, vmax=max_v)\n plt.axis('off')\n \n if save and filename is not None:\n plt.savefig(filename, dpi=300)\n else:\n plt.show()\n\n\n\n\n\ndef plot_layer(lyr, scale_factor=0.5, exc_color=(0., 0., 1.), \n inh_color=(1., 0., 0.)):\n from mayavi import mlab \n if 'inh' in lyr.keys():\n mlab.points3d(lyr['inh'][:, 0], lyr['inh'][:, 2], lyr['inh'][:, 1], \n scale_factor=scale_factor, color=inh_color,\n mode='sphere')\n\n if 'exc' in lyr.keys():\n mlab.points3d(lyr['exc'][:, 0], lyr['exc'][:, 2], lyr['exc'][:, 1], \n scale_factor=scale_factor, color=exc_color,\n mode='sphere')\n\n\n\ndef plot_connections( conn_list, src_pop, dst_pop, color=(0., 0.4, 0.) ):\n from mayavi import mlab\n u = []; v = []; w = [];\n x = []; y = []; z = [];\n for conn in conn_list:\n src, dst, weight = conn[0], conn[1], conn[2]\n x[:] = []; y[:] = []; z[:] = []\n x.append(src_pop[src, 0])\n x.append(dst_pop[dst, 0])\n y.append(src_pop[src, 2])\n y.append(dst_pop[dst, 2])\n z.append(src_pop[src, 1])\n z.append(dst_pop[dst, 1])\n mlab.plot3d(x, y, z,\n line_width=1., color=color, )\n #~ x.append(src_pop[src, 0])\n #~ y.append(src_pop[src, 2])\n #~ z.append(src_pop[src, 1])\n #~ \n #~ u.append( dst_pop[dst, 0] )\n #~ v.append( dst_pop[dst, 2] )\n #~ w.append( dst_pop[dst, 1] )\n#~ \n #~ mlab.quiver3d(x, y, z, u, v, w, \n #~ line_width=1., color=color, \n #~ # representation=\"wireframe\"\n #~ mode='arrow',\n #~ #scale_factor=0.01,\n #~ \n #~ )\n \n\n\ndef sum_horz_kern(img_width, img_height, kernel_width, \n horz_weights, save_file=None):\n \n min_w = (img_width - (kernel_width - 1))\n min_h = (img_height - (kernel_width - 1))\n new_img = np.zeros((img_height, min_w))\n k_sum = 0\n k_idx = 0\n for r in range(img_height):\n\n for c in range(min_w):\n k_sum = 0\n for k in range(kernel_width):\n k_idx = r*min_w + c + k\n k_sum += horz_weights[k_idx]\n \n new_img[r, c] = k_sum\n \n\n fig = plt.figure(figsize=(5, 5))\n \n ax = plt.subplot(1, 1, 1)\n # ax.set_title(\"k%s\"%(k_idx))\n my_imshow(ax, new_img)\n\n return new_img\n\n\n\ndef sum_sep_kern(img_width, img_height, kernel_width, kernel_images):\n min_w = (img_width - (kernel_width - 1))\n min_h = (img_height - (kernel_width - 1))\n new_img = np.zeros((min_h, min_w))\n\n for r in range(min_h):\n\n for c in range(min_w):\n k_idx = r*min_w + c\n new_img[r, c] = kernel_images[k_idx].sum()\n \n plt.tick_params(axis='x', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n bottom='off', # ticks along the bottom edge are off\n top='off', # ticks along the top edge are off\n labelbottom='off')\n plt.tick_params(axis='y', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n bottom='off', # ticks along the bottom edge are off\n top='off', # ticks along the top edge are off\n labelbottom='off')\n fig = plt.figure(figsize=(5, 5))\n \n ax = plt.subplot(1, 1, 1)\n # ax.set_title(\"k%s\"%(k_idx))\n my_imshow(ax, new_img)\n\n \n return new_img\n\n\n\ndef parse_conns_to_dict(conns):\n conn_dict = {}\n for conn in conns:\n src, tgt, w, d = conn\n if not (tgt in conn_dict.keys()):\n conn_dict[tgt] = {}\n \n conn_dict[tgt][src] = w\n \n return conn_dict\n\n\n\n\ndef plot_sep_kern(img_width, img_height, kernel_width, \n horz_weights, vert_weights, \n num_cols = 4, save_file=None, plt_w = 2.,\n h_col_step=2, h_row_step=2):\n kernel_width = int(kernel_width)\n min_w = (img_width - (kernel_width - 1))\n min_h = (img_height - (kernel_width - 1))\n \n num_vert = len(vert_weights)//kernel_width\n num_rows = num_vert//num_cols + 1\n \n hrz_dict = parse_conns_to_dict(horz_weights)\n \n imgs = [np.zeros((kernel_width, kernel_width)) for i in range(num_vert)]\n \n v_idx = 0; h_idx = 0\n w_v = 0.; w_h = 0.\n r = 0; c = 0\n kv = 0; kh = 0\n subplot_idx = 0\n k_idx = 0\n\n prev_v_idx = 0\n for v_conn in vert_weights:\n v_idx = int(v_conn[1])\n h_idx = int(v_conn[0])\n w_v = float(v_conn[2])\n \n kh = 0\n for src in sorted( hrz_dict[h_idx].keys() ):\n w_h = hrz_dict[h_idx][src]\n imgs[v_idx][kv, kh] = w_v*w_h\n\n kh += 1\n \n kv += 1\n if kv == kernel_width:\n kv = 0\n\n\n subplot_idx = 0\n fig = plt.figure(figsize=(plt_w*num_cols, plt_w*num_rows))\n for k_idx in range(len(imgs)):\n subplot_idx += 1\n ax = plt.subplot(num_rows, num_cols, subplot_idx)\n my_imshow(ax, imgs[k_idx])\n \n prev_v_idx = v_idx\n \n return imgs\n\n \n\ndef plot_1D_conv_conns(conv_conns, img_w, img_h, krnl_w, horiz_conv=True,\n col_step=2, row_step=2, prev_col_step=2, prev_row_step=2):\n src = -1\n conn_str = \"\"\n conn_dic = {}\n for c in conv_conns:\n if not ( c[1] in conn_dic ):\n conn_dic[c[1]] = []\n conn_dic[c[1]].append((c[0], c[2]))\n\n\n max_h = img_h - krnl_w + 1\n max_w = img_w - krnl_w + 1\n if horiz_conv:\n num_kernels = (max_w//col_step)*(img_h//row_step)\n out_w = img_w\n out_h = img_h\n else:\n num_kernels = (max_w//col_step)*(max_h//row_step)\n out_w = max_w//prev_col_step\n out_h = img_h//prev_row_step\n\n \n imgs = [np.zeros(out_h*out_w) for i in range(num_kernels)]\n print(num_kernels)\n n_cols = 6\n n_rows = num_kernels//n_cols + 1\n fig = plt.figure(figsize=(2.8*n_cols, 2.8*n_rows))\n subplot_idx = 1\n sources = []\n i = 0\n w = 1.\n for tgt in conn_dic.keys():\n ax = plt.subplot(n_rows, n_cols, subplot_idx)\n sources[:] = [ i for i, w in conn_dic[tgt] ]\n ax.set_title(\"%s -> %s\"%(sources, tgt))\n subplot_idx += 1\n \n imgs[tgt][:] = 0\n for i, w in conn_dic[tgt]:\n imgs[tgt][i] = w\n \n my_imshow(ax, imgs[tgt].reshape((out_h, out_w)))\n\n\n\ndef plot_spikes(spike_array, max_y=None, pad = 2, title=\"\", marker='.', \n color='blue', markersize=4, base_id=0, plotter=plt):\n neurons = []\n times = []\n n_idx = 0\n min_time = 9999\n max_time = -9999\n for spike_times in spike_array:\n for t in spike_times:\n if t < min_time:\n min_time = t\n if t > max_time:\n max_time = t\n neurons.append(n_idx + base_id)\n times.append(t)\n n_idx += 1\n \n n_idx += base_id\n plotter.plot(times, neurons, linestyle='none',\n marker=marker, markerfacecolor=color, markersize=markersize,\n color=color)\n # plt.xlim(min_time - pad, max_time + pad)\n # print(\"max_y \", max_y)\n if max_y is None:\n \n max_y = n_idx \n \n if plotter != plt:\n plotter.set_ylim(-pad, max_y + pad)\n else:\n plotter.ylim(-pad, max_y + pad)\n\n\n # plt.xlabel(\"Time (ms)\")\n # plt.ylabel(\"Neuron id\")\n # plt.title(title)\n\n\n\n\ndef plot_output_spikes(spikes, pad=0, marker='.', color='blue', markersize=4,\n plotter=plt, max_y=None, pad_y=2, markeredgewidth=0,\n markeredgecolor='none'):\n if len(spikes) == 0:\n return 0\n \n spike_times = [spike_time for (neuron_id, spike_time) in spikes]\n spike_ids = [neuron_id for (neuron_id, spike_time) in spikes]\n # print(np.max(spike_times), np.min(spike_times))\n # print(np.max(spike_ids), np.min(spike_ids))\n max_id = 0 if len(spike_ids) == 0 else np.max(spike_ids)\n\n if max_y is None:\n max_y = max_id\n\n spike_ids[:] = [neuron_id + pad for neuron_id in spike_ids]\n\n plotter.plot(spike_times, spike_ids, marker, markersize=markersize, \n markerfacecolor=color, markeredgecolor=markeredgecolor, \n markeredgewidth=markeredgewidth)\n if plotter != plt:\n plotter.set_ylim(-pad_y, max_y + pad_y)\n else:\n plotter.ylim(-pad_y, max_y + pad_y)\n \n return pad + max_id + 1\n\n\n\ndef spikes_in_time_range(spikes, from_t, to_t, start_idx=0):\n spks = []\n end_idx = start_idx\n for spk in spikes[start_idx:]:\n if from_t <= spk[1] <= to_t:\n spks.append(spk)\n \n end_idx += 1\n \n if spk[1] > to_t:\n break\n \n return spks, end_idx\n\n\n\ndef img_from_spikes(spikes, img_width, height):\n img = np.zeros((img_height*img_width), dtype=np.uint8)\n for spk in spikes:\n img[spk[0]] += 1\n \n return img.reshape((img_height, img_width))\n\ndef default_img_map(i, w, h):\n row = i//w\n col = i%w\n return row, col, 1\n\ndef imgs_in_T_from_spike_array(spike_array, img_width, img_height, \n from_t, to_t, t_step, out_array=False,\n thresh=12, up_down = None,\n map_func = default_img_map):\n num_neurons = img_width*img_height\n if out_array: # should be output spike format\n mult = 2 if up_down is None else 1\n # print(\"imgs_in_T, num neurons: \", mult*num_neurons)\n spike_array = out_to_spike_array(spike_array, mult*num_neurons)\n\n\n \n spikes = [ sorted(spk_ts) for spk_ts in spike_array ]\n \n imgs = [ np.zeros((img_height, img_width, 3)) \\\n for t in range(from_t, to_t, t_step) ]\n \n nrn_start_idx = [ 0 for t in range(len(spikes)) ]\n \n t_idx = 0\n for t in range(from_t, to_t, t_step):\n for nrn_id in range(len(spikes)):\n \n if spikes[nrn_id] is None:\n continue\n \n if len(spikes[nrn_id]) == 0:\n continue\n \n nrn_id = np.uint16(nrn_id)\n row, col, up_dn = map_func(nrn_id, img_width, img_height)\n if up_down is not None:\n up_dn = up_down\n \n for spk_t in spikes[nrn_id][nrn_start_idx[nrn_id]:]:\n if t <= spk_t < t+t_step:\n imgs[t_idx][row, col, up_dn] += thresh\n else:\n break\n nrn_start_idx[nrn_id] += 1\n\n t_idx += 1\n\n # for t_idx in range(len(imgs)):\n # imgs[t_idx] = imgs[t_idx].reshape((img_height, img_width))\n \n return imgs\n\n\n\ndef img_from_spike_array(spike_array, img_width, img_height):\n img = np.zeros((img_height*img_width))\n nrn_idx = 0\n for spike_times in spike_array:\n for t in spike_times:\n img[nrn_idx] += 1\n nrn_idx += 1\n\n return img.reshape((img_height, img_width))\n\n\n\n\ndef plot_class_weights_2D_array(weights, num_classes, img_width, img_height, \n num_cols, num_rows, vmin=None, vmax=None, \n hex_plot=False):\n \n num_prev_neurons = img_width*img_height\n \n for i in range(num_classes):\n ax = plt.subplot(num_rows, num_cols, i+1)\n if hex_plot:\n pass\n # from ....hex_net.hex_pixel import HexImage\n # from ....hex_net.vis.hex_plot import remove_ticks, plot_hex_img\n # plot_hex_img(ax, HexImage( weights[:, i].reshape((img_height, img_width)) ) \\\n # vmin=vvmin, vmax=vmax, markersize=5)\n else:\n my_imshow(ax, weights[:, i].reshape((img_height, img_width)),\n vmin=vmin, vmax=vmax)\n\n\ndef plot_class_weights(weights, num_classes, img_width, img_height, \n num_cols, num_rows, vmin=None, vmax=None):\n num_prev_neurons = img_width*img_height\n imgs = [np.zeros((num_prev_neurons)) for i in range(num_classes)]\n \n\n for j in range(num_classes):\n for i in range(num_prev_neurons):\n # print(i*num_classes + j, i, j)\n imgs[j][i] = weights[i*num_classes + j]\n\n sub_idx = 1\n for img in imgs:\n ax = plt.subplot(num_rows, num_cols, sub_idx)\n sub_idx += 1\n my_imshow(ax, img.reshape((img_height, img_width)),\n vmin=vmin, vmax=vmax)\n \n return imgs\n\n\ndef remove_ticks(ax):\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.get_xaxis().set_ticks([])\n ax.get_yaxis().set_ticks([])\n\n\ndef build_gif(imgs, filename='', show_gif=True, save_gif=True, title='',\n interval=30):\n IMG_TAG = \"\"\"\"some_text\"\"\"\"\n \n if title == '':\n title=filename\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.set_axis_off()\n\n ims = map(lambda x: (ax.imshow(x, interpolation='none'), \\\n ax.set_title(title)), imgs)\n\n im_ani = animation.ArtistAnimation(fig, ims, interval=interval, \\\n repeat_delay=1, \n blit=True, #was False\n #frames=len(imgs)\n )\n\n\n if filename == '':\n filename = 'animation.gif'\n im_ani.save(filename, writer='imagemagick')\n plt.close(im_ani._fig)\n \n if show_gif:\n data = open(filename,\"rb\").read()\n data = data.encode(\"base64\")\n return HTML(IMG_TAG.format(data))\n \n # return HTML(im_ani.to_html5_video())\n \n # Image(filename=filename)\n \n return\n else:\n return\n\n\n\n\n\n# === ------------------------------------------------------------ === #\n\n\n\n","sub_path":"vision/spike_tools/vis/vis_tools.py","file_name":"vis_tools.py","file_ext":"py","file_size_in_byte":17268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"262035579","text":"import logging\nimport unittest\nimport os\n\nimport angr\n\nl = logging.getLogger(\"angr.tests\")\n\ntest_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"binaries\", \"tests\")\n\n\n# pylint: disable=missing-class-docstring\n# pylint: disable=no-self-use\nclass TestBlockCache(unittest.TestCase):\n def test_block_cache(self):\n p = angr.Project(\n os.path.join(test_location, \"x86_64\", \"fauxware\"), translation_cache=True, auto_load_libs=False\n )\n b = p.factory.block(p.entry)\n assert p.factory.block(p.entry).vex is b.vex\n\n p = angr.Project(os.path.join(test_location, \"x86_64\", \"fauxware\"), translation_cache=False)\n b = p.factory.block(p.entry)\n assert p.factory.block(p.entry).vex is not b.vex\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_block_cache.py","file_name":"test_block_cache.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"263041936","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass MaoyanPipeline(object):\n def process_item(self, item, spider):\n\n print(item['name'],item['time'])\n\n return item\n\nimport pymysql\nfrom .settings import *\n\nclass MaoyanMysqlPipeline(object):\n # 爬虫程序开始时只执行1次\n def open_spider(self,spider):\n print('我是open_spider,哈哈')\n # 一般用于创建数据库连接\n self.db = pymysql.connect(\n host=MYSQL_HOST,\n user=MYSQL_USER,\n password=MYSQL_PWD,\n database=MYSQL_DB,\n charset=CHARSET\n )\n self.cursor = self.db.cursor()\n\n def process_item(self,item,spider):\n ins = 'insert into filmtab values(%s,%s,%s)'\n L = [\n item['name'],\n item['star'],\n item['time']\n ]\n self.cursor.execute(ins,L)\n self.db.commit()\n ## create database if not exists maoyandb charset utf8;\n ## create table if note exists filmtab(xx xx);\n\n return item\n\n # 爬虫程序结束时只执行1次\n def close_spider(self,spider):\n # 收尾工作: 一般用于断开数据库\n self.cursor.close()\n self.db.close()\n print('我是close_spider,哈哈')\n\n\nclass MaoyanMongoPipeline(object):\n def process_item(self,item,spider):\n return item\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"爬虫1905/day09/spider_day09_course/day09/Maoyan/Maoyan/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"458354009","text":"from operator import itemgetter\n\ndef run(filename = \"input.txt\"):\n lines = open(filename).readlines()[2:]\n used = []\n avail = []\n #x36-y24\n #x34-y28\n rows = 25\n cols = 37\n data = [[\"%02i\" %i] for i in range(rows+1)]\n print(\" \" + \"\".join([\"%02i\" %i for i in range(cols+1)]))\n for j in range(cols):\n for i in range(rows):\n node = lines[i+j*rows]\n line = filter(None, node.strip().split(\" \"))\n percert = int(line[4][:-1])\n used = int(line[2][:-1])\n if used > 100:\n data[i].append('#')\n elif percert != 0:\n data[i].append('.')\n else:\n data[i].append('_')\n data[0][1] = '+'\n data[0][-1] = '*'\n for line in data:\n print(\" \".join(line))\n \nif __name__ == \"__main__\":\n print(run())\n","sub_path":"day22_Defrag/python/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"204568135","text":"import re\nimport urllib.request\n\nurl = \"https://www.ips.media.osaka-cu.ac.jp/?page_id=180\"\nencoding = \"utf-8\"\nproxy = {\"http\": \"http://prxy.ex.media.osaka-cu.ac.jp:10080\",\n \"https\": \"http://prxy.ex.media.osaka-cu.ac.jp:10080\"}\n\nheader_count = 0\n\nwith urllib.request.FancyURLopener(proxy).open(url) as page:\n for rawline in page:\n line = rawline.decode(encoding).rstrip()\n match = re.search(r\".*\", line)\n if match:\n header_count += 1\n # print(line)\n\nprint(header_count)\n","sub_path":"10/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"650375853","text":"from __future__ import absolute_import\nimport pandas as pd\nimport logging\nfrom .log_with import log_with\nfrom .config import get_setting_value \nfrom . import parameters as _params\nfrom .cache import requests_get\nfrom . import helpers\n\nlogging.basicConfig()\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\n#### ---- utilities for interacting with the GDC api ---- \n\n@log_with()\ndef get_data(endpoint_name, arg=None,\n project_name=None, fields=None, size=get_setting_value('DEFAULT_SIZE'), page=0,\n data_category=None, query_args={}, verify=False, *args, **kwargs):\n \"\"\" Get single result from querying GDC api endpoint\n\n >>> file = get_data(endpoint='files', data_category='Clinical', query_args=dict(file_id=df['case_uuid'][0]))\n \n \"\"\"\n endpoint = get_setting_value('GDC_API_ENDPOINT').format(endpoint=endpoint_name)\n if arg:\n endpoint = endpoint+'/{}'.format(arg)\n else:\n ## prep extra-params, including `from` param, as dict\n extra_params = {}\n if page>0:\n from_param = helpers.compute_start_given_page(page=page, size=size)\n extra_params.update({\n 'from': from_param,\n })\n if fields:\n extra_params.update({'fields': ','.join(helpers.convert_to_list(fields))})\n if dict(**kwargs):\n ## TODO check on whether this handles redundant param spec \n ## correctly\n extra_params.update(dict(**kwargs))\n params = _params.construct_parameters(project_name=project_name,\n size=size,\n data_category=data_category,\n query_args=query_args,\n verify=verify,\n **extra_params\n )\n # requests URL-encodes automatically\n log.info('submitting request for {endpoint} with params {params}'.format(endpoint=endpoint, params=params))\n response = requests_get(endpoint, params=params)\n log.info('url requested was: {}'.format(response.url))\n response.raise_for_status()\n return response\n\n\n@log_with()\ndef _get_case_data(arg=None,\n project_name=None, fields=None, size=get_setting_value('DEFAULT_SIZE'), page=1,\n data_category=None, query_args={}, verify=False, **kwargs):\n \"\"\" Get single case json matching project_name & categories\n\n >>> _get_case_data(project_name='TCGA-BLCA', data_category=['Clinical'], size=5)\n \n \"\"\"\n return get_data(endpoint='cases', arg=arg, project_name=project_name, fields=fields, size=size,\n page=page, data_category=data_category, query_args=query_args,\n verify=verify, **kwargs)\n\n\n@log_with()\ndef _get_sample_data():\n return True\n\n\n@log_with()\ndef get_fileinfo(file_id, fields=get_setting_value('DEFAULT_FILE_FIELDS'), format=None):\n query_args = {'files.file_id': file_id}\n response = get_data(endpoint_name='files', query_args=query_args, fields=fields, format=format)\n if format == 'json':\n return response.json()['data']['hits']\n else:\n return response\n\n\ndef get_fileinfo_data(file_id,\n fields=get_setting_value('DEFAULT_FILE_FIELDS'),\n chunk_size=get_setting_value('DEFAULT_CHUNK_SIZE')\n ):\n file_id = helpers.convert_to_list(file_id)\n file_id = [x for x in file_id if x != '']\n if len(file_id) == 0:\n # logger.warning('No files left to process')\n return pd.DataFrame()\n if len(file_id)>chunk_size:\n chunks = [file_id[x:x+chunk_size] for x in range(0, len(file_id), chunk_size)]\n data = [get_fileinfo_data(chunk, fields=fields) for chunk in chunks]\n return pd.concat(data)\n res = get_fileinfo(file_id=file_id, fields=fields, format='json')\n df = list()\n for hit in res:\n hit_data = dict()\n for (k, v) in hit.items():\n if k == 'cases':\n for (subkey, subval) in hit['cases'][0].items():\n hit_data[subkey] = subval\n elif k == 'analysis':\n for (subkey, subval) in hit['analysis'].items():\n hit_data[subkey] = subval\n else:\n hit_data[k] = v\n df.append(hit_data)\n df = pd.DataFrame(df)\n return df\n\n@log_with()\ndef _describe_samples(case_ids,\n query_args={},\n\n **kwargs):\n \"\"\" Helper function to describe sample files\n \"\"\"\n sample_df = list()\n for case_id in helpers.convert_to_list(case_ids):\n samples = get_data(endpoint_name='cases',\n fields=['files.cases.samples.sample_id',\n 'files.cases.samples.sample_type',\n 'files.cases.samples.sample_type_id',\n 'files.cases.samples.composition',\n 'files.cases.samples.created_datetime',\n'files.cases.samples.current_weight',\n'files.cases.samples.days_to_collection',\n'files.cases.samples.days_to_sample_procurement',\n'files.cases.samples.freezing_method',\n'files.cases.samples.initial_weight',\n'files.cases.samples.intermediate_dimension',\n'files.cases.samples.is_ffpe',\n'files.cases.samples.longest_dimension',\n'files.cases.samples.oct_embedded',\n'files.cases.samples.pathology_report_uuid',\n'files.cases.samples.preservation_method',\n'files.cases.samples.sample_id',\n'files.cases.samples.sample_type',\n'files.cases.samples.sample_type_id',\n'files.cases.samples.shortest_dimension',\n'files.cases.samples.state',\n'files.cases.samples.submitter_id',\n'files.cases.samples.time_between_clamping_and_freezing',\n'files.cases.samples.time_between_excision_and_freezing',\n'files.cases.samples.tissue_type',\n'files.cases.samples.tumor_code',\n'files.cases.samples.tumor_code_id',\n'files.cases.samples.tumor_descriptor',\n'files.cases.samples.updated_datetime'],\n query_args=dict(case_id=case_id, **query_args),\n **kwargs\n )\n sample_data = _convert_sample_result_to_df(samples.json()['data']['hits'])\n sample_df.append(sample_data)\n return pd.concat(sample_df).drop_duplicates()\n\ndef _convert_sample_result_to_df(res):\n sample_df_list = list()\n for hit in res:\n for result_file in hit['files']:\n for result_case in result_file['cases']:\n hit_data = pd.DataFrame(result_case['samples'])\n sample_df_list.append(hit_data)\n return pd.concat(sample_df_list)\n \n","sub_path":"query_tcga/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"328215904","text":"import numpy as np\nfrom PIL import Image, ImageFont, ImageDraw\nimport cv2\n\nfrom keras_centernet.models.networks.hourglass import HourglassNetwork, normalize_image\nfrom keras_centernet.models.decode import CtDetDecode\nfrom keras_centernet.utils.utils import coco_names\nfrom keras_centernet.utils.letterbox import LetterboxTransformer\n\ndef _read_lines(filepath):\n with open(filepath) as fp:\n return [line.strip() for line in fp]\n\ndef pil2cv(image):\n new_image = np.asarray(image)[:, :, ::-1].copy()\n return new_image\n\nclass CENTERNET(object):\n def __init__(self, model, classes_path):\n self.weights = model\n self.classes_name = _read_lines(classes_path)\n if self.classes_name is None:\n self.classes_name = coco_names\n kwargs = {\n 'num_stacks': 2,\n 'cnv_dim': 256,\n 'weights': self.weights,\n }\n heads = {\n 'hm': 80, # 3\n 'reg': 2, # 4\n 'wh': 2 # 5\n }\n model = HourglassNetwork(heads=heads, **kwargs)\n self.model = CtDetDecode(model)\n self.letterbox_transformer = LetterboxTransformer(512, 512)\n\n def detect_image(self, image):\n img = pil2cv(image)\n pimg = self.letterbox_transformer(img)\n pimg = normalize_image(pimg)\n pimg = np.expand_dims(pimg, 0)\n objects = []\n detections = self.model.predict(pimg)[0]\n for d in detections:\n left, top, right, bottom, score, cl = d\n if score < 0.3:\n break\n left, top, right, bottom = self.letterbox_transformer.correct_box(left, top, right, bottom)\n cl = int(cl)\n predicted_class = coco_names[cl]\n objects.append({\n \"bbox\": [left, top, right, bottom],\n \"score\": np.asscalar(score),\n \"class_name\": predicted_class,\n \"class_id\": cl\n })\n\n return {\n \"objects\": objects\n }\n\n def close_session(self):\n pass","sub_path":"centernet.py","file_name":"centernet.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"629570951","text":"# -*- coding: utf-8 -*-\nfrom intelligent_home.components.device_management.models import Device\nfrom intelligent_home.components.category_management.models import Category\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.generic import View\n\n\nclass ShowDevicesPerCategory(View):\n\n def get(self, request, category_id):\n category = get_object_or_404(Category, pk=category_id)\n device_list = category.get_permitted_devices(request.user)\n\n return render(request, 'device_interface/device_view.html', {\n 'category': category,\n 'device_list': device_list\n })\n\n\nclass ShowDeviceWidgets(View):\n\n def get(self, request, category_id, device_id):\n category = get_object_or_404(Category, pk=category_id)\n device_list = category.get_permitted_devices(request.user)\n device = get_object_or_404(Device, pk=device_id)\n\n return render(request, 'device_interface/device_view.html', {\n 'category': category,\n 'device_list': device_list,\n 'device': device if device in device_list else None\n })","sub_path":"Aplikacja webowa/Projekt/intelligent_home/intelligent_home/components/device_interface/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"433780586","text":"import sys\nsys.setrecursionlimit(1000000)\n\n\ndef dump(name, obj, level=0):\n indent = level * ' '#'\\t'\n\n if name is not None:\n prefix = indent + name + \" = \"\n else:\n prefix = indent\n\n if isinstance(obj, (int, float, str)):\n print(prefix + str(obj))\n elif isinstance(obj, list):\n print (prefix + \"[\")\n\n for value in obj:\n dump(None, value, level + 1)\n\n print (indent + \"]\")\n elif isinstance(obj, dict):\n print (prefix + \"{\")\n\n for key, value in obj.items():\n dump(key, value, level + 1)\n\n print (indent + \"}\")\n else:\n # if obj.__class__.__name__ == \"method\":\n # return\n print (prefix + obj.__class__.__name__)\n\n for key in dir(obj):\n if key.startswith(\"__\") or key == \"_accept\" or key.startswith(\"T_\"):\n continue\n\n val = getattr(obj, key)\n if val == None or val == \"\":\n continue\n\n dump(key, val, level + 1)\n","sub_path":"ljd/util/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"199799570","text":"import random\n#import os\n\ndef game_summary(rand,trys) :\n n=1\n for i in trys:\n if i>rand:\n print(\"Your {0} guess was {guess} which is greater than {num}\".format(n,guess=i,num=rand))\n else:\n print(\"Your {0} guess was {guess} which is less than {num}\".format(n, guess=i, num=rand))\n n+=1\n\n\ndef num_input():\n try:\n num = int(input())\n assert 0 < num < 101, \"Invalid input\"\n\n except AssertionError as ae:\n print(\"Invalid input . Enter integers between 1 - 100 : \",end=\"\")\n num_input()\n except ValueError:\n print(\"Invalid input . Enter integers between 1 - 100 : \",end=\"\")\n num_input()\n return num\n\ndef game():\n num = 0\n trys=[]\n rand=random.randint(1, 101)\n print(\"Enter your guess between 1-100 : \",end=\"\")\n num = num_input()\n\n while (num != rand):\n trys.append(num)\n if num= 0.5) or (pair[1] <= -0.5):\n correlation_list.append(pair[0])\n if name in correlation_list:\n correlation_list.remove(name)\n return correlation_list\n\n\ndef main():\n sns.set(font_scale=0.7)\n # Process Data\n url = 'http://lib.stat.cmu.edu/datasets/bodyfat'\n web_data = DataReader(url)\n data, columns = web_data.read()\n # Plotting\n all_correlation = correlation_chart(data, columns)\n graphs(data, all_correlation)\n x = data.loc[:, 'Age (years)':'Wrist circumference (cm)']\n y = data[\"Percent body fat from Siri's (1956) equation\"].to_numpy()\n # Linear Regression\n x_train, x_test, y_train, y_test = \\\n train_test_split(x, y, test_size=0.4, random_state=1)\n model = DecisionTreeRegressor()\n model.fit(x_train, y_train)\n linear_reg_model = linear_regression_fit(x_train, y_train)\n print(\n 'MSE for linear train:',\n mean_squared_error(y_train, linear_reg_model.predict(x_train))\n )\n print(\n 'MSE for linear test:',\n mean_squared_error(y_test, linear_reg_model.predict(x_test))\n )\n print(\n 'MSE for decisiontree train:',\n mean_squared_error(y_train, model.predict(x_train))\n )\n print(\n 'MSE for decisiontree test:',\n mean_squared_error(y_test, model.predict(x_test))\n )\n # High correlation part\n x_high_correlation = data[high_correlation(all_correlation)].copy()\n x_high_train, x_high_test, y_high_train, y_high_test = \\\n train_test_split(x_high_correlation, y, test_size=0.4, random_state=1)\n high_model = DecisionTreeRegressor()\n high_model.fit(x_high_train, y_high_train)\n high_correlation_model = linear_regression_fit(x_high_train, y_high_train)\n print(\n 'MSE for high correlation train:',\n mean_squared_error(\n y_high_train, high_correlation_model.predict(x_high_train)\n )\n )\n print(\n 'MSE for high correlation test:',\n mean_squared_error(\n y_high_test, high_correlation_model.predict(x_high_test)\n )\n )\n print(\n 'MSE for high correlation decisiontree train:',\n mean_squared_error(y_high_train, high_model.predict(x_high_train))\n )\n print(\n 'MSE for high correlation decisiontree test:',\n mean_squared_error(y_high_test, high_model.predict(x_high_test))\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Process.py","file_name":"Process.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"460693967","text":"#!/usr/bin/env python3\n#\n# Written by Ji WenCong \n#\n# The author disclaims copyright to this source code. In place of a legal notice,\n# here is a blessing:\n#\n# 1. May you do good and not evil.\n# 2. May you find forgiveness for yourself and forgive others.\n# 3. May you share freely, never taking more than you give.\n# 4. Give thanks to the Lord if the program helps you.\n#\n\nimport xrpmir.repository.common as _common\nimport xrpmir.repository.exception as _exception\nimport xrpmir.repository.file_info as _fi\nimport xml.etree.ElementTree as _ElementTree\n\n\nclass DeltaInformation:\n \"\"\"Package delta information container.\"\"\"\n\n def __init__(self, file_info, old_version, old_release, old_epoch):\n \"\"\"Initialize the object.\n\n :type file_info: _fi.FileInformation\n :type old_version: str\n :type old_release: str\n :type old_epoch: str\n :param file_info: The file information.\n :param old_version: The old revision.\n :param old_release: The old release.\n :param old_epoch:\n \"\"\"\n\n self.__file_info = file_info\n self.__old_ver = old_version\n self.__old_rel = old_release\n self.__old_epoch = old_epoch\n\n def get_file_information(self):\n \"\"\"Get the file information.\n\n :rtype : _fi.FileInformation\n :return: The file information.\n \"\"\"\n\n return self.__file_info\n\n def get_old_version(self):\n \"\"\"The old version.\n\n :rtype : str\n :return: The old revision.\n \"\"\"\n\n return self.__old_ver\n\n def get_old_release(self):\n \"\"\"Get the old release.\n\n :rtype : str\n :return: The old release.\n \"\"\"\n\n return self.__old_rel\n\n def get_old_epoch(self):\n \"\"\"Get the old epoch.\n\n :rtype : str\n :return: The old epoch.\n \"\"\"\n\n return self.__old_epoch\n\n\nclass NewPackageInformation:\n \"\"\"New package information container.\"\"\"\n\n def __init__(self, name, version, release, epoch, delta_list):\n \"\"\"Initialize the object.\n\n :type name: str\n :type version: str\n :type release: str\n :type epoch: str\n :type delta_list: list[DeltaInformation]\n :param name: The package name.\n :param version: The package version.\n :param release: The package release.\n :param epoch: The package epoch.\n :param delta_list: The delta list.\n \"\"\"\n\n self.__name = name\n self.__ver = version\n self.__rel = release\n self.__epoch = epoch\n self.__delta = delta_list\n\n def get_name(self):\n \"\"\"Get the package name.\n\n :rtype : str\n :return: The name.\n \"\"\"\n\n return self.__name\n\n def get_version(self):\n \"\"\"Get the package version.\n\n :rtype : str\n :return: The version.\n \"\"\"\n\n return self.__ver\n\n def get_release(self):\n \"\"\"Get the package release.\n\n :rtype : str\n :return: The release.\n \"\"\"\n return self.__rel\n\n def get_epoch(self):\n \"\"\"Get the package epoch.\n\n :rtype : str\n :return: The epoch.\n \"\"\"\n\n return self.__epoch\n\n def get_delta_count(self):\n \"\"\"Get the delta count.\n\n :rtype : int\n :return: The count.\n \"\"\"\n\n return len(self.__delta)\n\n def get_delta(self, idx):\n \"\"\"Get specific delta information by its index.\n\n :type idx: int\n :param idx: The index.\n :rtype : DeltaInformation\n :return: The delta information.\n :raise IndexError: Raise when the index is invalid.\n \"\"\"\n\n # Check the index.\n if idx < 0 or idx >= self.get_delta_count():\n raise IndexError(\"Invalid delta index.\")\n\n return self.__delta[idx]\n\n\nclass PrestoDeltaData:\n \"\"\"Presto delta data container.\"\"\"\n\n def __init__(self, dom_root):\n \"\"\"Initialize the object.\n\n :type dom_root: _ElementTree.Element\n :param dom_root: The root node.\n \"\"\"\n\n self.__root = dom_root\n\n def get_root(self):\n \"\"\"Get the root node.\n\n :rtype : _ElementTree.Element\n :return: The root node.\n \"\"\"\n\n return self.__root\n\n def parse_new_packages(self):\n \"\"\"Parse all new packages.\n\n :rtype : list[NewPackageInformation]\n :raise _exception.ParseError: Raise this exception when an error occurred while parsing.\n \"\"\"\n\n # Get the root node.\n root = self.get_root()\n\n # Initialize the package container.\n packages = []\n\n # Scan all nodes.\n for child in root:\n assert isinstance(child, _ElementTree.Element)\n if _common.remove_xml_namespace(child.tag) == \"newpackage\":\n # Check and get the name.\n if \"name\" not in child.attrib:\n raise _exception.ParseError(\"Missing package name.\")\n pkg_name = child.attrib[\"name\"]\n\n # Check and get the epoch.\n if \"epoch\" not in child.attrib:\n raise _exception.ParseError(\"Missing package epoch.\")\n pkg_epoch = child.attrib[\"epoch\"]\n\n # Check and get the version.\n if \"version\" not in child.attrib:\n raise _exception.ParseError(\"Missing package version.\")\n pkg_version = child.attrib[\"version\"]\n\n # Check and get the release string.\n if \"release\" not in child.attrib:\n raise _exception.ParseError(\"Missing package release.\")\n pkg_release = child.attrib[\"release\"]\n\n # Get all delta.\n pkg_delta = []\n for sub_child in child:\n assert isinstance(sub_child, _ElementTree.Element)\n if _common.remove_xml_namespace(sub_child.tag) == \"delta\":\n pkg_delta.append(_parse_delta(sub_child))\n\n # Wrap and write to the container.\n packages.append(NewPackageInformation(\n pkg_name,\n pkg_version,\n pkg_release,\n pkg_epoch,\n pkg_delta\n ))\n\n return packages\n\n\ndef _parse_delta(node):\n \"\"\"Parse a node.\n\n :type node: _ElementTree.Element\n :param node: The node.\n :rtype : DeltaInformation\n :return: The delta information.\n \"\"\"\n\n # Check the tag name.\n if _common.remove_xml_namespace(node.tag) != \"delta\":\n raise _exception.ParseError(\"Corrupted node.\")\n\n # Check and get the old epoch.\n if \"oldepoch\" not in node.attrib:\n raise _exception.ParseError(\"Missing old epoch.\")\n old_epoch = node.attrib[\"oldepoch\"]\n\n # Check and get the old version.\n if \"oldversion\" not in node.attrib:\n raise _exception.ParseError(\"Missing old version.\")\n old_version = node.attrib[\"oldversion\"]\n\n # Check and get the old release.\n if \"oldrelease\" not in node.attrib:\n raise _exception.ParseError(\"Missing old release.\")\n old_release = node.attrib[\"oldrelease\"]\n\n # Get the file location and its checksum.\n file_location = None\n file_checksum = None\n for child in node:\n assert isinstance(child, _ElementTree.Element)\n child_tag = _common.remove_xml_namespace(child.tag)\n if child_tag == \"filename\":\n file_location = child.text.strip()\n continue\n if child_tag == \"checksum\":\n file_checksum = _common.parse_checksum_node(child)\n continue\n\n # Check.\n if file_location is None:\n raise _exception.ParseError(\"Missing file location.\")\n if file_checksum is None:\n raise _exception.ParseError(\"Missing file checksum.\")\n\n # Wrap.\n return DeltaInformation(\n _fi.FileInformation(file_location, file_checksum),\n old_version,\n old_release,\n old_epoch\n )\n\n\ndef load_presto_delta_data(data):\n \"\"\"Load presto delta data from memory.\n\n :type data: str | bytes\n :param data: The source data.\n :rtype : PrestoDeltaData\n :return: The presto delta data instance.\n :raise _exception.ParseError: Raise this exception when an error occurred while parsing.\n \"\"\"\n\n # Parse.\n try:\n dom = _ElementTree.fromstring(data)\n assert isinstance(dom, _ElementTree.Element)\n except:\n raise _exception.ParseError(\"Corrupted XML data.\")\n\n # Wrap.\n return PrestoDeltaData(dom)\n","sub_path":"xrpmir/repository/prestodelta.py","file_name":"prestodelta.py","file_ext":"py","file_size_in_byte":8602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"360067281","text":"\"\"\"\nDifferentiable volumetric implementation used by pi-GAN generator.\n\"\"\"\n\nimport time\nfrom functools import partial\n\nimport math\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nimport random\n\nfrom .math_utils_torch import *\n\n\ndef fancy_integration(rgb_sigma, z_vals, device, noise_std=0.5, last_back=False, white_back=False, clamp_mode=None, fill_mode=None):\n \"\"\"Performs NeRF volumetric rendering.\"\"\"\n\n rgbs = rgb_sigma[..., :3]\n sigmas = rgb_sigma[..., 3:]\n\n deltas = z_vals[:, :, 1:] - z_vals[:, :, :-1]\n delta_inf = 1e10 * torch.ones_like(deltas[:, :, :1])\n deltas = torch.cat([deltas, delta_inf], -2)\n\n noise = torch.randn(sigmas.shape, device=device) * noise_std\n\n if clamp_mode == 'softplus':\n alphas = 1-torch.exp(-deltas * (F.softplus(sigmas + noise)))\n elif clamp_mode == 'relu':\n alphas = 1 - torch.exp(-deltas * (F.relu(sigmas + noise)))\n else:\n raise \"Need to choose clamp mode\"\n\n alphas_shifted = torch.cat([torch.ones_like(alphas[:, :, :1]), 1-alphas + 1e-10], -2)\n weights = alphas * torch.cumprod(alphas_shifted, -2)[:, :, :-1]\n weights_sum = weights.sum(2)\n\n if last_back:\n weights[:, :, -1] += (1 - weights_sum)\n\n rgb_final = torch.sum(weights * rgbs, -2)\n depth_final = torch.sum(weights * z_vals, -2)\n\n if white_back:\n rgb_final = rgb_final + 1-weights_sum\n\n if fill_mode == 'debug':\n rgb_final[weights_sum.squeeze(-1) < 0.9] = torch.tensor([1., 0, 0], device=rgb_final.device)\n elif fill_mode == 'weight':\n rgb_final = weights_sum.expand_as(rgb_final)\n\n return rgb_final, depth_final, weights\n\n\ndef get_initial_rays_trig(n, num_steps, device, fov, resolution, ray_start, ray_end):\n \"\"\"Returns sample points, z_vals, and ray directions in camera space.\"\"\"\n\n W, H = resolution\n # Create full screen NDC (-1 to +1) coords [x, y, 0, 1].\n # Y is flipped to follow image memory layouts.\n x, y = torch.meshgrid(torch.linspace(-1, 1, W, device=device),\n torch.linspace(1, -1, H, device=device))\n x = x.T.flatten()\n y = y.T.flatten()\n z = -torch.ones_like(x, device=device) / np.tan((2 * math.pi * fov / 360)/2)\n\n rays_d_cam = normalize_vecs(torch.stack([x, y, z], -1))\n\n\n z_vals = torch.linspace(ray_start, ray_end, num_steps, device=device).reshape(1, num_steps, 1).repeat(W*H, 1, 1)\n points = rays_d_cam.unsqueeze(1).repeat(1, num_steps, 1) * z_vals\n\n points = torch.stack(n*[points])\n z_vals = torch.stack(n*[z_vals])\n rays_d_cam = torch.stack(n*[rays_d_cam]).to(device)\n\n return points, z_vals, rays_d_cam\n\ndef perturb_points(points, z_vals, ray_directions, device):\n distance_between_points = z_vals[:,:,1:2,:] - z_vals[:,:,0:1,:]\n offset = (torch.rand(z_vals.shape, device=device)-0.5) * distance_between_points\n z_vals = z_vals + offset\n\n points = points + offset * ray_directions.unsqueeze(2)\n return points, z_vals\n\n\ndef transform_sampled_points(points, z_vals, ray_directions, device, h_stddev=1, v_stddev=1, h_mean=math.pi * 0.5, v_mean=math.pi * 0.5, mode='normal'):\n \"\"\"Samples a camera position and maps points in camera space to world space.\"\"\"\n\n n, num_rays, num_steps, channels = points.shape\n\n points, z_vals = perturb_points(points, z_vals, ray_directions, device)\n\n\n camera_origin, pitch, yaw = sample_camera_positions(n=points.shape[0], r=1, horizontal_stddev=h_stddev, vertical_stddev=v_stddev, horizontal_mean=h_mean, vertical_mean=v_mean, device=device, mode=mode)\n forward_vector = normalize_vecs(-camera_origin)\n\n cam2world_matrix = create_cam2world_matrix(forward_vector, camera_origin, device=device)\n\n points_homogeneous = torch.ones((points.shape[0], points.shape[1], points.shape[2], points.shape[3] + 1), device=device)\n points_homogeneous[:, :, :, :3] = points\n\n # should be n x 4 x 4 , n x r^2 x num_steps x 4\n transformed_points = torch.bmm(cam2world_matrix, points_homogeneous.reshape(n, -1, 4).permute(0,2,1)).permute(0, 2, 1).reshape(n, num_rays, num_steps, 4)\n\n\n transformed_ray_directions = torch.bmm(cam2world_matrix[..., :3, :3], ray_directions.reshape(n, -1, 3).permute(0,2,1)).permute(0, 2, 1).reshape(n, num_rays, 3)\n\n homogeneous_origins = torch.zeros((n, 4, num_rays), device=device)\n homogeneous_origins[:, 3, :] = 1\n transformed_ray_origins = torch.bmm(cam2world_matrix, homogeneous_origins).permute(0, 2, 1).reshape(n, num_rays, 4)[..., :3]\n\n return transformed_points[..., :3], z_vals, transformed_ray_directions, transformed_ray_origins, pitch, yaw\n\ndef truncated_normal_(tensor, mean=0, std=1):\n size = tensor.shape\n tmp = tensor.new_empty(size + (4,)).normal_()\n valid = (tmp < 2) & (tmp > -2)\n ind = valid.max(-1, keepdim=True)[1]\n tensor.data.copy_(tmp.gather(-1, ind).squeeze(-1))\n tensor.data.mul_(std).add_(mean)\n return tensor\n\ndef sample_camera_positions(device, n=1, r=1, horizontal_stddev=1, vertical_stddev=1, horizontal_mean=math.pi*0.5, vertical_mean=math.pi*0.5, mode='normal'):\n \"\"\"\n Samples n random locations along a sphere of radius r. Uses the specified distribution.\n Theta is yaw in radians (-pi, pi)\n Phi is pitch in radians (0, pi)\n \"\"\"\n\n if mode == 'uniform':\n theta = (torch.rand((n, 1), device=device) - 0.5) * 2 * horizontal_stddev + horizontal_mean\n phi = (torch.rand((n, 1), device=device) - 0.5) * 2 * vertical_stddev + vertical_mean\n\n elif mode == 'normal' or mode == 'gaussian':\n theta = torch.randn((n, 1), device=device) * horizontal_stddev + horizontal_mean\n phi = torch.randn((n, 1), device=device) * vertical_stddev + vertical_mean\n\n elif mode == 'hybrid':\n if random.random() < 0.5:\n theta = (torch.rand((n, 1), device=device) - 0.5) * 2 * horizontal_stddev * 2 + horizontal_mean\n phi = (torch.rand((n, 1), device=device) - 0.5) * 2 * vertical_stddev * 2 + vertical_mean\n else:\n theta = torch.randn((n, 1), device=device) * horizontal_stddev + horizontal_mean\n phi = torch.randn((n, 1), device=device) * vertical_stddev + vertical_mean\n\n elif mode == 'truncated_gaussian':\n theta = truncated_normal_(torch.zeros((n, 1), device=device)) * horizontal_stddev + horizontal_mean\n phi = truncated_normal_(torch.zeros((n, 1), device=device)) * vertical_stddev + vertical_mean\n\n elif mode == 'spherical_uniform':\n theta = (torch.rand((n, 1), device=device) - .5) * 2 * horizontal_stddev + horizontal_mean\n v_stddev, v_mean = vertical_stddev / math.pi, vertical_mean / math.pi\n v = ((torch.rand((n,1), device=device) - .5) * 2 * v_stddev + v_mean)\n v = torch.clamp(v, 1e-5, 1 - 1e-5)\n phi = torch.arccos(1 - 2 * v)\n\n else:\n # Just use the mean.\n theta = torch.ones((n, 1), device=device, dtype=torch.float) * horizontal_mean\n phi = torch.ones((n, 1), device=device, dtype=torch.float) * vertical_mean\n\n phi = torch.clamp(phi, 1e-5, math.pi - 1e-5)\n\n output_points = torch.zeros((n, 3), device=device)\n output_points[:, 0:1] = r*torch.sin(phi) * torch.cos(theta)\n output_points[:, 2:3] = r*torch.sin(phi) * torch.sin(theta)\n output_points[:, 1:2] = r*torch.cos(phi)\n\n return output_points, phi, theta\n\ndef create_cam2world_matrix(forward_vector, origin, device=None):\n \"\"\"Takes in the direction the camera is pointing and the camera origin and returns a cam2world matrix.\"\"\"\n\n forward_vector = normalize_vecs(forward_vector)\n up_vector = torch.tensor([0, 1, 0], dtype=torch.float, device=device).expand_as(forward_vector)\n\n left_vector = normalize_vecs(torch.cross(up_vector, forward_vector, dim=-1))\n\n up_vector = normalize_vecs(torch.cross(forward_vector, left_vector, dim=-1))\n\n rotation_matrix = torch.eye(4, device=device).unsqueeze(0).repeat(forward_vector.shape[0], 1, 1)\n rotation_matrix[:, :3, :3] = torch.stack((-left_vector, up_vector, -forward_vector), axis=-1)\n\n translation_matrix = torch.eye(4, device=device).unsqueeze(0).repeat(forward_vector.shape[0], 1, 1)\n translation_matrix[:, :3, 3] = origin\n\n cam2world = translation_matrix @ rotation_matrix\n\n return cam2world\n\n\n\ndef create_world2cam_matrix(forward_vector, origin):\n \"\"\"Takes in the direction the camera is pointing and the camera origin and returns a world2cam matrix.\"\"\"\n cam2world = create_cam2world_matrix(forward_vector, origin, device=device)\n world2cam = torch.inverse(cam2world)\n return world2cam\n\n\ndef sample_pdf(bins, weights, N_importance, det=False, eps=1e-5):\n \"\"\"\n Sample @N_importance samples from @bins with distribution defined by @weights.\n Inputs:\n bins: (N_rays, N_samples_+1) where N_samples_ is \"the number of coarse samples per ray - 2\"\n weights: (N_rays, N_samples_)\n N_importance: the number of samples to draw from the distribution\n det: deterministic or not\n eps: a small number to prevent division by zero\n Outputs:\n samples: the sampled samples\n Source: https://github.com/kwea123/nerf_pl/blob/master/models/rendering.py\n \"\"\"\n N_rays, N_samples_ = weights.shape\n weights = weights + eps # prevent division by zero (don't do inplace op!)\n pdf = weights / torch.sum(weights, -1, keepdim=True) # (N_rays, N_samples_)\n cdf = torch.cumsum(pdf, -1) # (N_rays, N_samples), cumulative distribution function\n cdf = torch.cat([torch.zeros_like(cdf[: ,:1]), cdf], -1) # (N_rays, N_samples_+1)\n # padded to 0~1 inclusive\n\n if det:\n u = torch.linspace(0, 1, N_importance, device=bins.device)\n u = u.expand(N_rays, N_importance)\n else:\n u = torch.rand(N_rays, N_importance, device=bins.device)\n u = u.contiguous()\n\n inds = torch.searchsorted(cdf, u)\n below = torch.clamp_min(inds-1, 0)\n above = torch.clamp_max(inds, N_samples_)\n\n inds_sampled = torch.stack([below, above], -1).view(N_rays, 2*N_importance)\n cdf_g = torch.gather(cdf, 1, inds_sampled)\n cdf_g = cdf_g.view(N_rays, N_importance, 2)\n bins_g = torch.gather(bins, 1, inds_sampled).view(N_rays, N_importance, 2)\n\n denom = cdf_g[...,1]-cdf_g[...,0]\n denom[denom\n#\n# Distributed under terms of the MIT license.\nimport logging\nimport collections\n\nfrom src.address import Address\n\n\nclass Store:\n def __init__(self, store_dict=None):\n self.csv_address = None\n self.csv_phone = None\n self.csv_name = None\n\n # value from google place api\n self.name = None\n self.formatted_address = None\n self.location = None\n self.place_id = None\n self.formatted_phone_number = None\n self.adr_address = None\n self.url = None\n self.website = None\n self.city = None\n\n if type(store_dict) is collections.OrderedDict:\n self._dict_to_store(store_dict)\n elif store_dict is None:\n self.csv_address = Address()\n else:\n logging.error('client_dict not of type OrderedDict' + str(store_dict))\n raise TypeError\n\n def _dict_to_store(self, store_dict):\n self.csv_name = store_dict['store_name']\n self.csv_phone = store_dict['phone']\n self.csv_address = Address(store_dict)\n\n def to_dict(self):\n return {\n 'name': self.name,\n 'formatted_address': self.formatted_address,\n 'adr_address': self.adr_address,\n 'location': self.location,\n 'url': self.url,\n 'website': self.website,\n 'formatted_phone_number': self.formatted_phone_number,\n 'city': self.city,\n # 'place_id': self.place_id\n }\n\n def __lt__(self, other):\n if type(other) is not Store:\n logging.error('comparison not possible b/c other not of type Store')\n raise TypeError\n\n return self.place_id < other.google_placeid\n\n def __eq__(self, other):\n if type(other) is not Store:\n logging.error('comparison not possible b/c other not of type Store')\n raise TypeError\n\n return self.place_id == other.google_placeid\n","sub_path":"src/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"7912056","text":"# Question 7\n\n# Ek function define karo jo ki input me 2 strings lega aur dono strings me se jiski\n# length jyaada hogi use print karega aur agar dono strings ki length equal hui to \n# dono ko line by line print karega\n\ndef check(m,n):\n if len(m)>len(n):\n print(m)\n elif len(n)>len(m):\n print(n)\n elif len(m)==len(n):\n print(m,n)\n\nstring1=input(\"enter any string : \")\nstring2=input(\"enter any string : \")\ncheck(string1,string2)","sub_path":"meraki functions ques/inner function ques/q7.py","file_name":"q7.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"272626773","text":"class Solution(object):\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n ans=\"\"\n no=n\n while(no):\n ans=ans+chr((no-1)%26+ord(\"A\"))\n no=(no-1)//26\n return ans[::-1]\n \n \n \n","sub_path":"Excel Sheet Column Title.py","file_name":"Excel Sheet Column Title.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"334284283","text":"from django.db import models\nfrom django.db.models.signals import post_save\nfrom django.conf import settings\nfrom django.dispatch import receiver\nfrom django.utils import timezone\n\nfrom django.contrib.auth.models import User\n\nfrom account.models import SignupCode, SignupCodeResult, EmailConfirmation\nfrom account.signals import signup_code_used, email_confirmed\nfrom kaleo.signals import invite_sent, invite_accepted\n\n\nDEFAULT_INVITE_EXPIRATION = getattr(settings, \"KALEO_DEFAULT_EXPIRATION\", 168) # 168 Hours = 7 Days\nDEFAULT_INVITE_ALLOCATION = getattr(settings, \"KALEO_DEFAULT_INVITE_ALLOCATION\", 0)\n\n\nclass NotEnoughInvitationsError(Exception):\n pass\n\n\nclass JoinInvitation(models.Model):\n \n STATUS_SENT = 1\n STATUS_ACCEPTED = 2\n STATUS_JOINED_INDEPENDENTLY = 3\n \n INVITE_STATUS_CHOICES = [\n (STATUS_SENT, \"Sent\"),\n (STATUS_ACCEPTED, \"Accepted\"),\n (STATUS_JOINED_INDEPENDENTLY, \"Joined Independently\")\n ]\n \n from_user = models.ForeignKey(User, related_name=\"invites_sent\")\n to_user = models.ForeignKey(User, null=True, related_name=\"invites_received\")\n message = models.TextField(null=True)\n sent = models.DateTimeField(default=timezone.now)\n status = models.IntegerField(choices=INVITE_STATUS_CHOICES)\n signup_code = models.OneToOneField(SignupCode)\n \n def to_user_email(self):\n return self.signup_code.email\n \n @classmethod\n def invite(cls, from_user, to_email, message=None):\n if not from_user.invitationstat.can_send():\n raise NotEnoughInvitationsError()\n \n signup_code = SignupCode.create(\n email=to_email,\n inviter=from_user,\n expiry=DEFAULT_INVITE_EXPIRATION,\n check_exists=False # before we are called caller must check for existence\n )\n signup_code.save()\n join = cls.objects.create(\n from_user=from_user,\n message=message,\n status=JoinInvitation.STATUS_SENT,\n signup_code=signup_code\n )\n signup_code.send()\n stat = from_user.invitationstat\n stat.invites_sent += 1\n stat.save()\n invite_sent.send(sender=cls, invitation=join)\n return join\n\n\nclass InvitationStat(models.Model):\n \n user = models.OneToOneField(User)\n invites_sent = models.IntegerField(default=0)\n invites_allocated = models.IntegerField(default=DEFAULT_INVITE_ALLOCATION)\n invites_accepted = models.IntegerField(default=0)\n \n def invites_remaining(self):\n if self.invites_allocated == -1:\n return -1\n return self.invites_allocated - self.invites_sent\n \n def can_send(self):\n if self.invites_allocated == -1:\n return True\n return self.invites_allocated > self.invites_sent\n can_send.boolean = True\n\n\n@receiver(signup_code_used, sender=SignupCodeResult)\ndef handle_signup_code_used(sender, **kwargs):\n result = kwargs.get(\"signup_code_result\")\n try:\n invite = result.signup_code.joininvitation\n invite.to_user = result.user\n invite.status = JoinInvitation.STATUS_ACCEPTED\n invite.save()\n stat = invite.from_user.invitationstat\n stat.invites_accepted += 1\n stat.save()\n invite_accepted.send(sender=JoinInvitation, invitation=invite)\n except JoinInvitation.DoesNotExist:\n pass\n\n\n@receiver(email_confirmed, sender=EmailConfirmation)\ndef handle_email_confirmed(sender, **kwargs):\n email_address = kwargs.get(\"email_address\")\n invites = JoinInvitation.objects.filter(\n to_user__isnull=True,\n signup_code__email=email_address.email\n )\n for invite in invites:\n invite.to_user = email_address.user\n invite.status = JoinInvitation.STATUS_JOINED_INDEPENDENTLY\n invite.save()\n\n\n@receiver(post_save, sender=User)\ndef create_stat(sender, instance=None, **kwargs):\n if instance is None:\n return\n InvitationStat.objects.get_or_create(user=instance)\n","sub_path":"kaleo/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"610004424","text":"from __future__ import print_function\nimport numpy as np\nimport tensorflow as tf\nfrom six.moves import cPickle as pickle\n\nimport scipy.io as sio\nimport sys, os, os.path, inspect\n\n# Need to ensure that the training data will be used from directionDNN.py \n# package location. Saved classifier is stored in same location.\nfiledir = inspect.getframeinfo(inspect.currentframe())[0]\nfiledir = os.path.dirname(os.path.abspath(filedir))\n\n# Loads .mat file in to np.arrays\nmat_contents = sio.loadmat( filedir + '/sampleData_wNetChangeLabels.mat')\ntrain_dataset = np.array(mat_contents['train_data']).astype(np.float32)\ntrain_labels = np.array(mat_contents['train_label']).astype(np.float32)\nvalid_dataset = np.array(mat_contents['test_data']).astype(np.float32)\nvalid_labels = np.array(mat_contents['test_label']).astype(np.float32)\nprint('Training set - ', train_dataset.shape, train_labels.shape)\nprint('Test set - ', valid_dataset.shape, ' ',valid_labels.shape)\n\nsample_size = train_dataset.shape[1]\nnum_labels = train_labels.shape[1]\n\ndef accuracy(predictions, labels):\n return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n / predictions.shape[0])\n\nbatch_size = 128\nhidden_size = 512\nhidden_1_size = hidden_size\nhidden_2_size = hidden_size\nhidden_3_size = hidden_size\nbeta = .01\nSEED = None\ndropoutPercent = 0.5\n\ngraph = tf.Graph()\nwith graph.as_default():\n # Graph -----------------------------------------------------------------------------\n # Input data. For the training data, we use a placeholder that will be fed.\n tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, sample_size))\n tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n tf_valid_dataset = tf.constant(valid_dataset)\n # tf_predict_label is used to single predictions during call from server\n tf_predict_label = tf.placeholder(tf.float32, shape=(1,sample_size))\n\n # Variables\n weights_1 = tf.Variable(tf.truncated_normal([sample_size, hidden_1_size], stddev=0.1), name=\"weights_1\")\n biases_1 = tf.Variable(tf.zeros([hidden_1_size]), name=\"biases_1\")\n weights_2 = tf.Variable(tf.truncated_normal([hidden_1_size, hidden_2_size]), name=\"weights_2\")\n biases_2 = tf.Variable(tf.zeros([hidden_2_size]), name=\"biases_2d\")\n weights_3 = tf.Variable(tf.truncated_normal([hidden_2_size, hidden_3_size]), name=\"weights_3\")\n biases_3 = tf.Variable(tf.zeros([hidden_3_size]), name=\"biases_3\")\n # Output\n weights_o = tf.Variable(tf.truncated_normal([hidden_3_size, num_labels], stddev=0.1), name=\"weights_o\")\n biases_o = tf.Variable(tf.zeros([num_labels]), name=\"biases_o\")\n\n def model(data, train=False):\n hidden = tf.nn.relu(tf.matmul(data, weights_1) + biases_1)\n # While training we use dropout to reduce overfitting. Dropout removes\n # a specified precentange of outputs to reduce individual weight dependencies.\n if train:\n hidden = tf.nn.dropout(hidden, dropoutPercent, seed= SEED)\n hidden = tf.nn.relu(tf.matmul(hidden, weights_2) + biases_2)\n if train:\n hidden = tf.nn.dropout(hidden, dropoutPercent, seed= SEED)\n hidden = tf.nn.relu(tf.matmul(hidden, weights_3) + biases_3)\n if train:\n hidden = tf.nn.dropout(hidden, dropoutPercent, seed= SEED)\n return tf.matmul(hidden, weights_o) + biases_o\n\n logits = model(tf_train_dataset, True)\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n # Regularization is used to penalize large weights to help prevent over fitting\n regularized_loss = loss + beta*( tf.nn.l2_loss(weights_1) + tf.nn.l2_loss(weights_2)\n + tf.nn.l2_loss(weights_3) + tf.nn.l2_loss(weights_o))\n\n # Optimizer.\n global_step = tf.Variable(0) # count the number of steps taken.\n learning_rate = tf.train.exponential_decay(0.001, global_step, 250, 0.96)\n optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(regularized_loss, global_step=global_step)\n\n # Predictions for the training, validation, and test data.\n train_prediction = tf.nn.softmax(model(tf_train_dataset))\n valid_prediction = tf.nn.softmax(model(tf_valid_dataset))\n data_prediction = tf.nn.softmax(model(tf_predict_label))\n init_op = tf.initialize_all_variables()\n saver = tf.train.Saver()\n # ----------------------------------------------------------------------------------\n\nsession = tf.Session(graph = graph)\n\ndef train(num_steps = 501, save = True, filename = 'model_directionDNN.ckpt'):\n with session.as_default():\n session.run(init_op)\n print(\"Initialized\")\n\n for step in range(num_steps):\n # Offset is used for stochastic gradient descent\n offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n # Generate a minibatch.\n batch_data = train_dataset[offset:(offset + batch_size), :]\n batch_labels = train_labels[offset:(offset + batch_size), :]\n # Prepare a dictionary telling the session where to feed the minibatch.\n # The key of the dictionary is the placeholder node of the graph to be fed,\n # and the value is the numpy array to feed to it.\n feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)\n if (step % 500 == 0):\n print(\"Minibatch loss at step %d: %f Learning_rate: %f\" % (step, l, learning_rate.eval()))\n print(\"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels))\n print(\"Validation accuracy: %.1f%%\" % accuracy(valid_prediction.eval(), valid_labels))\n save_path = saver.save(session, filedir + '/' + filename, global_step=step)\n if save:\n save_path = saver.save(session, filedir + '/' + filename)\n\ndef init():\n with session.as_default():\n saver.restore(session, filedir + \"/model_directionDNN.ckpt\") \n\ndef predict(input_data):\n with session.as_default(): \n feed_dict = {tf_predict_label : input_data}\n predictionArray = session.run([data_prediction], feed_dict=feed_dict)\n prediction = np.argmax(predictionArray)\n print('Direction-predictions: {}, np.argmax: {}'.format(predictionArray, prediction))\n return prediction\n\ndef close():\n session.close()\n\nif __name__ == \"__main__\":\n train(save=True)\n close\n\n\n\n\n","sub_path":"dnnClassifier/directionDNN.py","file_name":"directionDNN.py","file_ext":"py","file_size_in_byte":6265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"581570603","text":"#APR 2015 Stefano Bosisio\n#Script to extract DG values from analysis_gro once everything has been done\n#Output:AVERAGE.dat: DG +-/ err\nfrom numpy import *\n\ngromacs=open(\"analysis_gro/results.txt\",\"r\")\nreader = gromacs.readlines()\nlen_read = len(reader) - 1\n\nDG = float(reader[len_read].split()[1])\nerr = float(reader[len_read].split()[3])\n\n\n\noutput_mean = open(\"AVERAGE_gro.dat\",\"w\")\n\noutput_mean.write(\"DG = %.3f\t+/- %.3f kcal/mol\" % (DG,err))\n\n\nTI=open(\"freenrg-TI.dat\",\"r\")\nreader = TI.readlines()\n\ncounter = 0 \nfor f in reader:\n splitter=f.split()\n if \"TI\" in splitter:\n if counter==2:\n DG=float(f.split()[3])*0.593\n err=float(f.split()[5])*0.593\n else:\n counter+=1\n\n\noutput_mean = open(\"AVERAGE_TI.dat\",\"w\")\n\noutput_mean.write(\"DG = %.3f\t+/- %.3f kcal/mol\" % (DG,err))\n","sub_path":"chebyshev/chebyshev_test/protocol/extract_results.py","file_name":"extract_results.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"40575694","text":"#!/usr/bin/env python\nimport pandas as pd\nfrom pprint import pformat\nfrom functools import reduce\n\n\nclass SearchResult(object):\n \"\"\"\n An object containing the matching results of a search on the database.\n \"\"\"\n\n def __init__(self, results):\n \"\"\"\n Create a SearchResult.\n \"\"\"\n self.results = pd.DataFrame(results)\n if self.results.size == 0:\n return\n self.results.sort_values(list(self.results.columns), inplace=True)\n self.results.reset_index(drop=True, inplace=True)\n\n def __repr__(self):\n return pformat(self.results.T.to_dict())\n\n def __str__(self):\n return pformat(self.results.T.to_dict())\n\n def __eq__(self, other):\n if type(other) is type(self):\n return self.results.equals(other.results)\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def filter(self, indices):\n \"\"\"\n Filter the search results.\n Returns new SearchResult with only the filtered results.\n \"\"\"\n df = self.results.filter(items=indices, axis=0)\n return SearchResult(df.reset_index(drop=True))\n\n def download(self, filename):\n \"\"\"\n Download the search results as a spreadsheet.\n \"\"\"\n frames = []\n for name in self.results:\n f = self.results[name].rename(name.replace('_', ' ').title())\n f = f.to_frame()\n frames.append(f)\n df = reduce(lambda x, y: x.join(y), frames)\n\n writer = pd.ExcelWriter(filename, engine='xlsxwriter')\n df.to_excel(writer, index=False)\n sheet = writer.sheets['Sheet1']\n for i, name in enumerate(df):\n width = max(len(str(val)) for val in df[name])\n width = max(width, len(name)) + 1\n sheet.set_column(i, i, width)\n writer.save()\n","sub_path":"sampledb/searchresult.py","file_name":"searchresult.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"96251800","text":"\"\"\"add simple admin to user\n\nRevision ID: cdbd433a9d78\nRevises: c4cd6daf947e\nCreate Date: 2017-01-20 18:32:38.761785\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'cdbd433a9d78'\ndown_revision = 'c4cd6daf947e'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n with op.batch_alter_table(\"users\") as batch_op:\n batch_op.add_column(sa.Column('admin', sa.Boolean))\n\ndef downgrade():\n with op.batch_alter_table(\"users\") as batch_op:\n batch_op.drop_column('admin')\n\n","sub_path":"alembic/versions/cdbd433a9d78_add_simple_admin_to_user.py","file_name":"cdbd433a9d78_add_simple_admin_to_user.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"525781848","text":"# 10 x 10 격자에 색을 칠한다.\n# 예를 들어 2개의 색칠 영역을 갖는 위 그림에 대한 색칠 정보이다.\n# 2\n# 2 2 4 4 1 ( [2,2] 부터 [4,4] 까지 color 1 (빨강) 으로 칠한다 )\n# 3 3 6 6 2 ( [3,3] 부터 [6,6] 까지 color 2 (파랑) 으로 칠한다 )\n\n\nT = int(input())\nfor test_case in range(1, T + 1):\n # 데이터 입력 받기\n N = int(input())\n rectangle = [list(map(int, input().split())) for _ in range(N)]\n\n # 10 x 10이 고정이므로, 초기세팅\n canvas = [[0]*10 for _ in range(10)]\n count = 0\n\n # 입력받은 rectangle의 좌표를 가져와서\n for color in rectangle:\n # row, column 에다가 color의 값을 입력\n for row in range(color[0], color[2]+1):\n for column in range(color[1], color[3]+1):\n if canvas[row][column] == 0:\n canvas[row][column] = color[-1]\n elif canvas[row][column] != 3 and canvas[row][column] != color[-1]:\n canvas[row][column] = 3\n count += 1\n\n print(\"#{} {}\".format(test_case, count))","sub_path":"SWEA/intermediate/List(2)/색칠하기.py","file_name":"색칠하기.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"592470265","text":"try:\n import urllib2 as http\nexcept ImportError:\n # Python 3\n from urllib import request as http\n\nfrom flask import request, current_app\nfrom wtforms import ValidationError\nfrom werkzeug import url_encode\nfrom .._compat import to_bytes\n\nRECAPTCHA_VERIFY_SERVER = 'https://www.google.com/recaptcha/api/verify'\n\n__all__ = [\"Recaptcha\"]\n\n\nclass Recaptcha(object):\n \"\"\"Validates a ReCaptcha.\"\"\"\n\n _error_codes = {\n 'invalid-site-public-key': 'The public key for reCAPTCHA is invalid',\n 'invalid-site-private-key': 'The private key for reCAPTCHA is invalid',\n 'invalid-referrer': (\n 'The public key for reCAPTCHA is not valid for '\n 'this domainin'\n ),\n 'verify-params-incorrect': (\n 'The parameters passed to reCAPTCHA '\n 'verification are incorrect'\n )\n }\n\n def __init__(self, message=u'Invalid word. Please try again.'):\n self.message = message\n\n def __call__(self, form, field):\n if current_app.testing:\n return True\n\n if request.json:\n challenge = request.json.get('recaptcha_challenge_field', '')\n response = request.json.get('recaptcha_response_field', '')\n else:\n challenge = request.form.get('recaptcha_challenge_field', '')\n response = request.form.get('recaptcha_response_field', '')\n remote_ip = request.remote_addr\n\n if not challenge or not response:\n raise ValidationError(field.gettext(self.message))\n\n if not self._validate_recaptcha(challenge, response, remote_ip):\n field.recaptcha_error = 'incorrect-captcha-sol'\n raise ValidationError(field.gettext(self.message))\n\n def _validate_recaptcha(self, challenge, response, remote_addr):\n \"\"\"Performs the actual validation.\"\"\"\n try:\n private_key = current_app.config['RECAPTCHA_PRIVATE_KEY']\n except KeyError:\n raise RuntimeError(\"No RECAPTCHA_PRIVATE_KEY config set\")\n\n data = url_encode({\n 'privatekey': private_key,\n 'remoteip': remote_addr,\n 'challenge': challenge,\n 'response': response\n })\n\n response = http.urlopen(RECAPTCHA_VERIFY_SERVER, to_bytes(data))\n\n if response.code != 200:\n return False\n\n rv = [l.strip() for l in response.readlines()]\n\n if rv and rv[0] == to_bytes('true'):\n return True\n\n if len(rv) > 1:\n error = rv[1]\n if error in self._error_codes:\n raise RuntimeError(self._error_codes[error])\n\n return False\n","sub_path":"flask/Lib/site-packages/flask_wtf/recaptcha/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"365539640","text":"\nimport time\nimport threading\n\nSTEP_SPEED = 0.05\nSCREEN_WIDTH = 200\n\n# Overdamped\nTICK_TIME = 30\nP_VALUE = 0.5\nD_VALUE = 0.1\n\n\n# # Overdamped\n# TICK_TIME = 30\n# P_VALUE = 0.5\n# D_VALUE = 0.5\n\n# # Overdamped\n# TICK_TIME = 5\n# P_VALUE = 0.1\n# D_VALUE = 0.25\n#\n#\n#\n# # Overdamped\n# TICK_TIME = 5\n# P_VALUE = 0.5\n# D_VALUE = 0.25\n\n# Underdamped long settling time\n# TICK_TIME = 5\n# P_VALUE = 0.001\n# D_VALUE = 0.01 # Change this to 0.05 to fix\n\n# Overshoot with long settling time\n# TICK_TIME = 2\n# P_VALUE = 0.005 # Default 0.005 extra fast 0.05\n# D_VALUE = 0.25\n\ndef main():\n ball = Ball()\n timer = 0\n trigger_time = 0\n ticks = 0\n while True:\n time.sleep(STEP_SPEED)\n timer += STEP_SPEED\n if timer > trigger_time:\n trigger_time += TICK_TIME\n ticks += 1\n if ticks %2 == 0:\n ball.position_target = SCREEN_WIDTH / 6 * 2\n else:\n ball.position_target = SCREEN_WIDTH / 6 * 4\n ball.timetick(STEP_SPEED)\n print_spaces(ball.position_target, ball.position_actual)\n\nclass Ball:\n def __init__(self):\n self.position_actual = SCREEN_WIDTH/2\n self.position_target = 0\n self.velocity = 0\n self.last_error = 0\n\n def timetick(self, tick_time):\n if self.position_actual != self.position_target:\n error = self.position_target - self.position_actual\n self.velocity += P_VALUE * error * tick_time + (self.last_error - error) * D_VALUE * -1\n self.position_actual += self.velocity * tick_time\n self.last_error = error\n\n\n def set_target(self, setpoint):\n self.target = setpoint\n\n\n#\n# def update_values(self, interval, overrun):\n# if math.fabs(self.velocity_command) > MAX_VELOCITY:\n# self.velocity_command = 0\n# error = self.velocity_command - self.velocity_feedback\n#\n#\n# self.errors.insert(0, error)\n# self.errors.pop()\n#\n# error_diffs = [i-j for i, j in zip(self.errors[:-1], self.errors[1:])]\n# average_error_diffs = 0\n# for e in error_diffs:\n# average_error_diffs += e\n# average_error_diffs /= len(error_diffs)\n#\n# #print(\"Velocity Command %r, velocity_feedback %r, error %r\" % (self.velocity_command, self.velocity_feedback, average_error_diffs))\n# #print(self.errors)\n#\n#\n# d_comp = interval/(interval+overrun)\n#\n# current_command = error * P_SCALAR + D_SCALAR * average_error_diffs * d_comp\n#\n# self.last_error = error\n#\n# if (current_command * np.sign(self.velocity_command)) > 0:\n# brake = False\n# if current_command > MAX_CURRENT:\n# current_command = MAX_CURRENT\n# elif current_command < -MAX_CURRENT:\n# current_command = -MAX_CURRENT\n# else:\n# brake = True\n# if current_command > MAX_BRAKE_CURRENT:\n# current_command = MAX_BRAKE_CURRENT\n# elif current_command < -MAX_BRAKE_CURRENT:\n# current_command = -MAX_BRAKE_CURRENT\n#\n# self.set_current(current_command, brake)\n#\n# def set_current(self, current_command, brake=True):\n# self.vesc.set_motor_current(current_command, self.canId, brake)\n#\n# def tick_velocity(self, tick_length):\n# if self.velocity_command != self.velocity_goal:\n# # Increment by acceleration * tick_length with the appropriate sign\n# increment = self.acceleration * tick_length * np.sign(self.velocity_goal-self.velocity_command) # * np.sign(self.velocity_goal)\n# #print(\"velocity %d, velocity setpoint %f, increment %f, position %g\" % (int(self.velocity*1000), self.velocity_setpoint, increment, self.position))\n# self.velocity_command += increment\n# self.tick_position(tick_length)\n#\n# def tick_position(self, tick_length):\n# self.position += self.velocity_command * tick_length\n\n\ndef print_spaces(dot_position, ball_position):\n dot_position = int(dot_position)\n ball_position = int(ball_position)\n if dot_position < ball_position:\n print(' ' * int(dot_position) + '.' + ' ' * int(ball_position-dot_position-1) + 'O')\n elif dot_position > ball_position:\n print(' ' * int(ball_position) + 'O' + ' ' * int(dot_position - ball_position-1) + '.')\n else:\n print(' ' * int(ball_position) + 'O')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"control_system_example.py","file_name":"control_system_example.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"212047339","text":"# <>\n# Copyright 2022, Lawrence Livermore National Security, LLC.\n# See the top-level COPYRIGHT file for details.\n# \n# SPDX-License-Identifier: BSD-3-Clause\n# <>\n\nimport os\nfrom fudge.core.utilities import fudgeFileMisc\nfrom brownies.legacy.endl import bdfls, endl2, endl_Z\n\n\ndef processTDF_Reaction( target, C, S = None, X1 = None, X2 = None, X3 = None, X4 = None, Q = None, outputFile = 'tdfgen.out', workDir = None,\n bdflsFile = None ) :\n\n if( bdflsFile is None ) : bdflsFile = bdfls.getDefaultBdfls()\n AMUToMeV = bdflsFile.constant( 4 )\n xsec = target.findData( C = C, I = 0, S = S, X1 = X1, X2 = X2, X3 = X3, X4 = X4, Q = Q )\n\n residualZA, yos, Q = endl2.residualZA_yos_Q(target.yi, target.ZA, C, bdflsFile = bdflsFile)\n projectileMass = bdflsFile.mass( target.yi )\n targetMass = bdflsFile.mass( target.ZA )\n\n yi = endl2.ZAToYo(target.yi)\n yiZA = endl2.yoToZA(yi)\n yiZ, yiA = endl2.ZandAFromZA(yiZA)\n\n ZA = target.ZA\n# ZAZA = endl2.yoToZA( ZA )\n ZAZA = ZA\n ZAZ, ZAA = endl2.ZandAFromZA(ZAZA)\n\n if( projectileMass > targetMass ) :\n reaction = '%s%d__%s%d_' % (endl_Z.endl_ZSymbol(yiZ), yiA, endl_Z.endl_ZSymbol(ZAZ), ZAA)\n else :\n reaction = '%s%d__%s%d_' % (endl_Z.endl_ZSymbol(ZAZ), ZAA, endl_Z.endl_ZSymbol(yiZ), yiA)\n\n outGoing = []\n print( yos )\n for yo in yos : \n if( yo < 1000 ) :\n outGoing.append([endl2.yoToZA(yo)])\n else :\n outGoing.append( [ yo ] )\n outGoing.append( [ residualZA ] )\n\n for i in outGoing :\n iZA = i[0]\n i.insert( 0, bdflsFile.mass( iZA ) )\n Z, A = endl2.ZandAFromZA(iZA)\n i.append( Z )\n i.append( A )\n outGoing.sort( )\n s = ''\n for mass, iZA, Z, A in outGoing :\n reaction += '%s%s%d' % (s, endl_Z.endl_ZSymbol(Z), A)\n s = '__'\n\n outputStr = [ '## Fudge generated data for tdfgen version:0.9.9' ]\n outputStr.append( '## Data generated from:fudge' )\n outputStr.append( '' )\n outputStr.append( '## Reaction:%s' % reaction )\n outputStr.append( '' )\n outputStr.append( '# Masses of particles in MeV.' )\n outputStr.append( '## Mass of projectile:%.12e' % ( projectileMass * AMUToMeV ) )\n outputStr.append( '## Mass of target:%.12e' % ( targetMass * AMUToMeV ) )\n\n outputStr.append( '' )\n outputStr.append( '## Number of final particles:%d' % len( outGoing ) )\n for mass, iZA, Z, A in outGoing : outputStr.append( '## %.12e' % ( mass * AMUToMeV ) )\n\n outputStr.append( '' )\n outputStr.append( '## Lab of CM frame:Lab' )\n outputStr.append( '## Number of data points:%d' % len( xsec ) )\n outputStr.append( '# E(MeV) Sigma( barn )' )\n outputStr.append( '#------------------------' )\n outputStr.append( xsec.toString( ) )\n\n outputStr = '\\n'.join( outputStr )\n\n inputFile = fudgeFileMisc.FudgeTempFile( dir = workDir )\n inputFile.write( outputStr )\n\n inputName = inputFile.getName( )\n print( inputName )\n os.system( './tdfgen -i %s -o %s' % ( inputFile.getName( ), outputFile ) )\n","sub_path":"brownies/legacy/endl/endltdf.py","file_name":"endltdf.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"35673522","text":"from django.template import Context\nfrom django.template.loader import get_template\n\nfrom accountifie.toolkit.utils import get_bstrap_table\n\n\ndef daily_activity(dt):\n data_url = \"/reporting/reports/AccountActivity/?col_tag=daily_%s&format=json\" % dt.isoformat()\n row_defs = [{'data_field': 'label', 'value': 'Account', 'formatter': 'nameFormatter'},\n {'data_field': 'Yesterday', 'value': 'Yesterday', 'formatter': 'drillFormatter'},\n {'data_field': 'Change', 'value': 'Change', 'formatter': 'drillFormatter'},\n {'data_field': 'Today', 'value': 'Today', 'formatter': 'drillFormatter'},\n ]\n return get_bstrap_table(data_url, row_defs)\n\n\ndef balance_trends(dt, acct_list=None, accts_path=None, company_id='EFIE'):\n if acct_list:\n data_url = \"/reporting/api/balance_trends/?date=%s&acct_list=%s&company_id=%s\" %( dt, '.'.join(acct_list), company_id)\n elif accts_path:\n data_url = \"/reporting/api/balance_trends/?date=%s&accts_path=%s&company_id=%s\" %( dt, accts_path, company_id)\n\n row_defs = [{'data_field': 'label', 'value': 'Date', 'formatter': 'nameFormatter'},\n {'data_field': 'M_2', 'value': '2 Months Ago', 'formatter': 'drillFormatter'},\n {'data_field': 'M_1', 'value': '1 Month Ago', 'formatter': 'drillFormatter'},\n {'data_field': 'M_0', 'value': 'This Month', 'formatter': 'drillFormatter'},\n ]\n return get_bstrap_table(data_url, row_defs)\n\n\ndef check_external_bals(dt, company_id='EFIE'):\n data_url = \"/api/gl/check_external_bals/?date=%s&company_id=%s\" % (dt.isoformat(), company_id)\n row_defs = [{'data_field': 'Account', 'value': 'Account', 'formatter': 'nameFormatter'},\n {'data_field': 'Internal', 'value': 'Internal', 'formatter': 'valueFormatter'},\n {'data_field': 'External', 'value': 'External', 'formatter': 'valueFormatter'},\n {'data_field': 'Diff', 'value': 'Diff', 'formatter': 'valueFormatter'},\n ]\n return get_bstrap_table(data_url, row_defs)\n\ndef external_bals_history(dt, company_id='EFIE', acct=''):\n data_url = \"/api/gl/external_bals_history/?date=%s&company_id=%s&acct=%s\" % (dt.isoformat(), company_id, acct)\n row_defs = [{'data_field': 'Date', 'value': 'Date', 'formatter': 'nameFormatter'},\n {'data_field': 'Internal', 'value': 'Internal', 'formatter': 'valueFormatter'},\n {'data_field': 'External', 'value': 'External', 'formatter': 'valueFormatter'},\n {'data_field': 'Diff', 'value': 'Diff', 'formatter': 'valueFormatter'},\n ]\n return get_bstrap_table(data_url, row_defs)\n\n\ndef snapshots():\n data_url = 'api/snapshot/glsnapshot/'\n row_defs = [{'data_field': 'id', 'value': 'ID', 'formatter': 'nameFormatter'},\n {'data_field': 'short_desc', 'value': 'Description', 'formatter': 'nameFormatter'},\n {'data_field': 'closing_date', 'value': 'Closing Date', 'formatter': 'nameFormatter'},\n {'data_field': 'snapped_at', 'value': 'Snapped At', 'formatter': 'nameFormatter'},\n {'data_field': 'reconciliation', 'value': 'Reconciliation', 'formatter': 'nameFormatter'},\n ]\n return get_bstrap_table(data_url, row_defs)\n\n\ndef forecasts():\n data_url = \"/api/forecasts/forecast/\"\n row_defs = [{'data_field': 'id_link', 'value': 'Label', 'formatter': 'nameFormatter'},\n {'data_field': 'start_date', 'value': 'Start Date', 'formatter': 'nameFormatter'},\n {'data_field': 'comment', 'value': 'Comment', 'formatter': 'nameFormatter'}\n ]\n return get_bstrap_table(data_url, row_defs)","sub_path":"accountifie/reporting/bstrap_tables/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"238550411","text":"import parselmouth\nimport numpy as np\nimport seaborn as sep\nimport matplotlib.pyplot as plt\nimport mplcursors\nimport os\nfrom msvcrt import getch\nimport datetime\nimport time\nimport msvcrt\nimport subprocess\n\nprint(\"/*Displays recorded data for selected files.*/\\n\")\n\ndef countdown(t):\n aborted=False\n while t>-1 and aborted==False:\n mins, secs = divmod(t, 60)\n timefmt = '{:02d}:{:02d}'.format(mins, secs)\n print(timefmt+\" secs. Press 'esc' to exit and show only data plots. Press 'Enter' to open now.\", end='\\r')\n time.sleep(1)\n if msvcrt.kbhit():\n keypress=msvcrt.getch()\n if keypress == chr(27).encode():\n aborted=True\n return True\n elif keypress == chr(13).encode():\n aborted=True\n return False\n t -= 1\n\ndef getListOfFiles(dirName):\n listOfFile = os.listdir(dirName)\n allFiles = list()\n for entry in listOfFile:\n fullPath = os.path.join(dirName, entry)\n if os.path.isdir(fullPath):\n allFiles = allFiles + getListOfFiles(fullPath)\n else:\n allFiles.append(fullPath)\n \n return allFiles \n\npath = os.path.dirname(os.path.abspath(__file__))+\"\\\\output\\\\\"\n\nif not os.path.exists(path):\n os.makedirs(path)\n\nbasepath = path\n\nlistOfFiles = getListOfFiles(basepath)\n# tnames=[]\n# for i in listOfFiles:\n# temp=i.split('\\\\')\n# tnames.append(str(temp[len(temp)-1]))\n# for i in tnames:\n# if i[len(i)-3:len(i)] == \"wav\":\n# print(i)\n\ncount=1\nfor i in listOfFiles:\n temp=i.split('\\\\')\n tempFn=str(temp[len(temp)-1])\n if tempFn[len(tempFn)-3:len(tempFn)] == \"wav\":\n print(\"\\n------------------------------------------------------------------------------------------------------------------------------------\\n\") \n print(str(count)+\") Filename: \"+tempFn+\" :--\\n\")\n count+=1\n print(\"Copy this:- \"+i+\"\\n\")\n\nprint(\"\\n\\nEnter .wav files to display. 🛈 Copy filenames from above and paste them below.\")\nsearch=input()\nfilenamelist=search.split(\"\\\\\")\nfilenamenew=filenamelist[len(filenamelist)-1]\npathnew=\"\"\nfor i in range(len(filenamelist)-1):\n pathnew=pathnew+filenamelist[i]+\"\\\\\"\n\nsfn=\"soundData\"+\"_for_\"+filenamenew[0:-4]+\".log\"\nops=os.path.join(pathnew, sfn)\n\nmfccfn=\"MFCC_features_for_\"+filenamenew[0:-4]+\".DATA\"\nmfccdata=os.path.join(pathnew, mfccfn)\n\nformantfn=\"Formant_features_for_\"+filenamenew[0:-4]+\".DATA\"\nformantmatrixSave=os.path.join(pathnew,formantfn)\n\ntry:\n snd = parselmouth.Sound(search)\nexcept:\n print(\"\\nFile not found/Not a .wav file\")\n print(\"Press any key to exit\")\n getch()\n quit()\n\nsep.set()\n\ndef draw_spectrogram(spectrogram, dynamic_range=70):\n X, Y = spectrogram.x_grid(), spectrogram.y_grid()\n sg_db = 10 * np.log10(spectrogram.values)\n plt.pcolormesh(X, Y, sg_db, vmin=sg_db.max() - dynamic_range, cmap='afmhot')\n plt.ylim([spectrogram.ymin, spectrogram.ymax])\n plt.xlabel(\"time [s]\")\n plt.ylabel(\"frequency [Hz]\")\n\ndef draw_pitch(pitch):\n pitch_values = pitch.selected_array['frequency']\n pitch_values[pitch_values==0] = np.nan\n plt.plot(pitch.xs(), pitch_values, 'o', markersize=5, color='w')\n plt.plot(pitch.xs(), pitch_values, 'o', markersize=2)\n plt.grid(False)\n plt.ylim(0, pitch.ceiling)\n plt.ylabel(\"F0 [Hz]\")\n\npitch = snd.to_pitch()\npre_emphasized_snd = snd.copy()\npre_emphasized_snd.pre_emphasize()\nspectrogram = pre_emphasized_snd.to_spectrogram(window_length=0.03, maximum_frequency=8000)\n\n\n\n# sfn=\"soundData\"+\"_for_\"+fn+\".log\"\n# ops=os.path.join(path, sfn)\n# with open(ops, 'w') as f:\n# f.write('-----------------------------------------------------------------------------------------\\n')\n# print('About:', pitch, file=f)\nprint(\"Launching 2 .DATA and 1 .log files, along with generated data plots in : \\n\")\nif countdown(20)!=True:\n try:\n subprocess.Popen([\"notepad.exe\", formantmatrixSave])\n except:\n pass\n try:\n subprocess.Popen([\"notepad.exe\", mfccdata])\n except:\n pass\n try:\n subprocess.Popen([\"notepad.exe\", ops])\n except:\n pass\n \n \n \nelse:\n print(\"Exiting...\")\n\nplt.subplot(1,2,1)\nplt.title('Speech Signal Representation')\nplt.plot(snd.xs(), snd.values.T)\nplt.xlim([snd.xmin, snd.xmax])\nplt.xlabel(\"Time [s]\")\nplt.ylabel(\"Amplitude\")\nmplcursors.cursor(hover=True)\n\nplt.subplot(1,2,2)\nplt.title('Fundamental Frequency F0')\ndraw_spectrogram(spectrogram)\nplt.twinx()\ndraw_pitch(pitch)\nplt.xlim([snd.xmin, snd.xmax])\nmplcursors.cursor(hover=True)\n\n\nmng=plt.get_current_fig_manager()\nmng.window.state(\"zoomed\")\nplt.show()\n\n\n\n","sub_path":"Wacom_FE/Release/Sound/showDiag.py","file_name":"showDiag.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"298029213","text":"from __future__ import print_function\nfrom __future__ import division\n\nimport tensorflow as tf\nfrom lib.model_utils import init_loss, init_optimizers\nfrom nets.lenet.lenet5 import LeNet5, TrongNet\nfrom tensorflow.python import keras\nfrom tensorflow.python.keras.applications.inception_resnet_v2 import InceptionResNetV2\nimport os\nimport glob\nimport numpy as np\nimport tqdm\ntf.random.set_random_seed(101)\nnp.random.seed(101)\n\n# Directory PATH\ntf.app.flags.DEFINE_string('dataset_dir', '', 'Directory where store tf_record files.')\ntf.app.flags.DEFINE_string('output_dir', '', 'Directory where srote checkpoints.')\n# Data input and output\ntf.app.flags.DEFINE_integer('image_size', 100, 'Size of image.')\ntf.app.flags.DEFINE_string('split_train_name', 'train-*.tfrecord', 'Name for split dataset.')\ntf.app.flags.DEFINE_string('split_validation_name', 'validation-*.tfrecord', 'Name for split dataset.')\ntf.app.flags.DEFINE_string('output_file_name', 'final_models.hdf5', 'Name of output file.')\ntf.app.flags.DEFINE_string('checkpoint_pattern', 'weights-{epoch:02d}-{acc:.2f}-{val_acc:.2f}.hdf5',\n 'Checkpoint pattern for saving')\n# Training configurations\ntf.app.flags.DEFINE_float('validation_split', None, 'Ratio of validation data.')\ntf.app.flags.DEFINE_string('pretrained_weights', None, 'Path to pretrained weights file (hdf5)')\ntf.app.flags.DEFINE_integer('batch_size', 10, 'Batch size.')\ntf.app.flags.DEFINE_integer('num_classes', 3581, 'Number of classes.')\ntf.app.flags.DEFINE_integer('epochs', 10, 'Number of epochs.')\ntf.app.flags.DEFINE_bool('using_augmentation', False, 'Using Image Generator from Keras')\n# Optimizer\ntf.app.flags.DEFINE_string('optimizer', 'adadelta', 'Optimizer algorithm')\ntf.app.flags.DEFINE_float('lr', 0.001, 'Amount of Learning rate')\ntf.app.flags.DEFINE_string('loss', 'categorical_crossentropy', 'Loss function')\n# Tensor board\ntf.app.flags.DEFINE_string('monitor_checkpoint', 'acc', 'Value that have been checked for save weights')\ntf.app.flags.DEFINE_string('monitor_mode', 'max', 'Mode for compare old state')\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef create_dataset(file_path):\n images = []\n labels = []\n features = {'image/encoded': tf.FixedLenFeature([], tf.string),\n 'image/class/label': tf.FixedLenFeature([], tf.int64),\n 'image/height': tf.FixedLenFeature([], tf.int64),\n 'image/width': tf.FixedLenFeature([], tf.int64)\n }\n for s_example in tf.python_io.tf_record_iterator(file_path):\n example = tf.parse_single_example(s_example, features=features)\n image = tf.image.decode_png(example['image/encoded'])\n images.append(image)\n labels.append(tf.one_hot(example['image/class/label'], FLAGS.num_classes))\n return images, labels\n\n\ndef load_data(dataset_dir, pattern):\n dir_pattern = os.path.join(dataset_dir, pattern)\n list_files = glob.glob(dir_pattern, recursive=True)\n list_files.sort()\n if len(list_files) == 0:\n raise ValueError('There is not any tf record file in {} folder'.format(os.path.basename(dataset_dir)))\n images = []\n labels = []\n with tqdm.tqdm(total=len(list_files)) as pbar:\n for file in list_files:\n image, label = create_dataset(os.path.join(dataset_dir, file))\n images.extend(image)\n labels.extend(label)\n pbar.update(1)\n return images, labels\n\n\ndef get_data_augment():\n data_augment = keras.preprocessing.image.ImageDataGenerator(\n width_shift_range=0.2,\n zoom_range=0.2\n )\n return data_augment\n\n\ndef main(_):\n # Log configurations of FLAGS\n model = TrongNet((50, 50, 1), FLAGS.num_classes, FLAGS.pretrained_weights)\n # model.load_weights('/media/trongpq/HDD/callbacks/lotery/201909271141_lenet5/final_models.hdf5')\n log_file = os.path.join(FLAGS.output_dir, 'config.txt')\n if not os.path.isdir(FLAGS.dataset_dir):\n raise FileExistsError('Directory {} is not exits'.format(FLAGS.dataset_dir))\n with open(log_file, 'w') as log:\n for key, value in FLAGS.flag_values_dict().items():\n log.writelines(\"{} : {}\\n\".format(key, value))\n with tf.Session() as sess:\n # print('Load data training:')\n # training_data = load_data(FLAGS.dataset_dir, FLAGS.split_train_name)\n # images_train, labels_train = sess.run(training_data)\n # images_train = np.array(images_train)\n # labels_train = np.array(labels_train)\n # print('Total records for training: {}'.format(images_train.shape[0]))\n # log.writelines('Training data: {}\\n'.format(images_train.shape[0]))\n # print('Loading data validating...')\n # validating_data = load_data(FLAGS.dataset_dir, FLAGS.split_validation_name)\n # images_val, labels_val = sess.run(validating_data)\n # labels_val = np.array(labels_val)\n # images_val = np.array(images_val)\n # print('Total records for validating: {}'.format(images_val.shape[0]))\n # log.writelines('Validating data: {}\\n'.format(images_val.shape[0]))\n model.summary(print_fn=lambda x: log.write(x + '\\n'))\n optimizer = None\n loss = None\n \n try:\n # Get optimizer\n optimizer = init_optimizers(FLAGS.optimizer, FLAGS.lr)\n loss = init_loss(FLAGS.loss)\n except ValueError:\n pass\n\n model.summary()\n\n checkpoint = keras.callbacks.ModelCheckpoint(os.path.join(FLAGS.output_dir, FLAGS.checkpoint_pattern),\n monitor=FLAGS.monitor_checkpoint, verbose=1,\n save_best_only=True, mode=FLAGS.monitor_mode)\n tensor_board = keras.callbacks.TensorBoard(log_dir=os.path.join(FLAGS.output_dir, 'tensor_board'), write_graph=True,\n write_images=True)\n callbacks_list = [checkpoint, tensor_board]\n model.compile(loss=loss,\n optimizer=optimizer, metrics=['accuracy'])\n\n if FLAGS.using_augmentation:\n data_augment = get_data_augment()\n train_generator = data_augment.flow_from_directory(\n '/media/trongpq/HDD/dataset/lotery/images/digits/train',\n target_size=(50, 50),\n color_mode='grayscale',\n batch_size=FLAGS.batch_size,\n class_mode='categorical'\n )\n validation_generator = data_augment.flow_from_directory(\n '/media/trongpq/HDD/dataset/lotery/images/digits/validation',\n target_size=(50, 50),\n color_mode='grayscale',\n batch_size=FLAGS.batch_size,\n class_mode='categorical'\n )\n # data_augment.fit(images_train)\n # model.fit_generator(data_augment.flow(images_train, labels_train, batch_size=FLAGS.batch_size),\n # steps_per_epoch=len(images_train) // FLAGS.batch_size, epochs=FLAGS.epochs,\n # verbose=1, callbacks=callbacks_list, validation_data=(images_val, labels_val),\n # validation_steps=len(images_val) // FLAGS.batch_size)\n model.fit_generator(\n train_generator,\n steps_per_epoch=560,\n epochs=FLAGS.epochs,\n validation_data=validation_generator,\n validation_steps=16,\n callbacks=callbacks_list,\n verbose=1\n )\n # else:\n # model.fit(images_train, labels_train, batch_size=FLAGS.batch_size, epochs=FLAGS.epochs,\n # callbacks=callbacks_list, validation_split=FLAGS.validation_split,\n # validating_data=(images_val, labels_val), verbose=1)\n\n model.save(os.path.join(FLAGS.output_dir, FLAGS.output_file_name))\n print('Model is saved!')\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"cnn_train_classifier.py","file_name":"cnn_train_classifier.py","file_ext":"py","file_size_in_byte":7847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"463733592","text":"import os\nimport re\n\ndef rename_files():\n # 1) get file names\n file_location = r\"/home/dzshu49/python-foundations/secret-message/prank/prank\"\n file_list = os.listdir(file_location)\n print(file_list)\n initial_path = os.getcwd()\n os.chdir(file_location)\n \n # 2) for each file, rename\n for file_name in file_list:\n new_name = re.sub(\"\\d\", \"\", file_name)\n print(\"Old Name: \"+file_name)\n print(\"New Name: \"+new_name)\n os.rename(file_name, new_name)\n os.chdir(initial_path)\n\nrename_files()\n","sub_path":"secret-message.py","file_name":"secret-message.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"232885509","text":"from __future__ import print_function\n\nimport logging\nimport numpy\nimport operator\nimport os\nimport re\nimport signal\nimport time\nimport theano\n\nfrom blocks.extensions import SimpleExtension\nfrom blocks.search import BeamSearch\n\nfrom subprocess import Popen, PIPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SamplingBase(object):\n \"\"\"Utility class for BleuValidator and Sampler.\"\"\"\n\n def _get_attr_rec(self, obj, attr):\n return self._get_attr_rec(getattr(obj, attr), attr) \\\n if hasattr(obj, attr) else obj\n\n def _get_true_length(self, seq, vocab):\n try:\n return seq.tolist().index(vocab['']) + 1\n except ValueError:\n return len(seq)\n\n def _oov_to_unk(self, seq, vocab_size, unk_idx):\n return [x if x < vocab_size else unk_idx for x in seq]\n\n def _idx_to_word(self, seq, ivocab):\n return \" \".join([ivocab.get(idx, \"\") for idx in seq])\n\n def _word_to_idx(self, seq, vocab, unk_idx):\n ans = []\n for word in seq:\n ans.append(vocab.get(word, unk_idx) )\n return ans\n\n\n\nclass Sampler(SimpleExtension, SamplingBase):\n \"\"\"Random Sampling from model.\"\"\"\n\n def __init__(self, config, model0, model1, model2, data_stream, hook_samples=1,\n src_vocab=None, trg_vocab=None, src_ivocab=None,\n trg_ivocab=None, src_vocab_size=None, **kwargs):\n super(Sampler, self).__init__(**kwargs)\n self.hook_samples = hook_samples\n self.data_stream = data_stream\n self.src_vocab = src_vocab\n self.trg_vocab = trg_vocab\n self.src_ivocab = src_ivocab\n self.trg_ivocab = trg_ivocab\n self.src_vocab_size = src_vocab_size\n self.is_synced = False\n self.config = config\n\n self.src_eos_idx = self.config['src_vocab_size']-1\n self.trg_eos_idx = self.config['trg_vocab_size']-1\n\n self.sampling_fn0 = model0.get_theano_function()\n self.sampling_fn1 = model1.get_theano_function()\n self.sampling_fn2 = model2.get_theano_function()\n\n def _changeIdx(self, trg_seq):\n # change\n trg_words = self._idx_to_word(trg_seq, self.trg_ivocab)\n words = trg_words.split(\" \")\n src_idx = self._word_to_idx(words, self.src_vocab, self.config['unk_id'])\n return numpy.array(src_idx)\n \n\n def do(self, which_callback, *args):\n\n # Get dictionaries, this may not be the practical way\n sources = self._get_attr_rec(self.main_loop, 'data_stream')\n\n # Load vocabularies and invert if necessary\n # WARNING: Source and target indices from data stream\n # can be different\n if not self.src_vocab:\n self.src_vocab = sources.data_streams[0].dataset.dictionary\n if not self.trg_vocab:\n self.trg_vocab = sources.data_streams[1].dataset.dictionary\n if not self.src_ivocab:\n self.src_ivocab = {v: k for k, v in self.src_vocab.items()}\n if not self.trg_ivocab:\n self.trg_ivocab = {v: k for k, v in self.trg_vocab.items()}\n if not self.src_vocab_size:\n self.src_vocab_size = len(self.src_vocab)\n\n # Randomly select source samples from the current batch\n # WARNING: Source and target indices from data stream\n # can be different\n batch = args[0]\n batch_size = batch['source0'].shape[0]\n hook_samples = min(batch_size, self.hook_samples)\n\n # TODO: this is problematic for boundary conditions, eg. last batch\n sample_idx = numpy.random.choice(\n batch_size, hook_samples, replace=False)\n \n src_batch0 = batch[self.main_loop.data_stream.mask_sources[0]]\n trg_batch0 = batch[self.main_loop.data_stream.mask_sources[1]]\n\n src_batch1 = batch[self.main_loop.data_stream.mask_sources[2]]\n trg_batch1 = batch[self.main_loop.data_stream.mask_sources[3]]\n\n src_batch2 = batch[self.main_loop.data_stream.mask_sources[4]]\n trg_batch2 = batch[self.main_loop.data_stream.mask_sources[5]]\n\n input0_ = src_batch0[sample_idx, :]\n target0_ = trg_batch0[sample_idx, :]\n\n input1_ = src_batch1[sample_idx, :]\n target1_ = trg_batch1[sample_idx, :]\n\n input2_ = src_batch2[sample_idx, :]\n target2_ = trg_batch2[sample_idx, :]\n\n # Sample\n print()\n for i in range(hook_samples):\n input_length = self._get_true_length(input0_[i], self.src_vocab) # same length\n target_length = self._get_true_length(target0_[i], self.trg_vocab)\n\n OriSensArray = []\n OriSensArray.append(self._idx_to_word(input0_[i][:input_length], self.src_ivocab))\n OriSensArray.append(self._idx_to_word(target0_[i][:target_length], self.trg_ivocab))\n OriSensArray.append(self._idx_to_word(target1_[i][:target_length], self.trg_ivocab))\n OriSensArray.append(self._idx_to_word(target2_[i][:target_length], self.trg_ivocab))\n\n\n\n genSensArray = []\n genSensArray.append(self._idx_to_word(input0_[i][:input_length], self.src_ivocab))\n\n totalcosts = 0.0\n inp = input0_[i, :input_length]\n inp = inp[None, :]\n #print(inp)\n #print(inp.shape)\n\n totalcosts = 0.0\n \n # generate the first sentence\n states = numpy.zeros((1,self.config['enc_nhids']), dtype=theano.config.floatX)\n states0, outputs0, _2_0, _3_0, costs0, lastrep0 = (self.sampling_fn0(input0 = inp, hstates0 = states))\n lastrep0 = lastrep0[:input_length]\n #print(lastrep0.shape)\n\n outputs0 = outputs0.flatten()\n sample_length0 = self._get_true_length(outputs0, self.trg_vocab)\n\n costs0 = costs0.T\n totalcosts += costs0[:sample_length0].sum()\n\n outputs0 = outputs0[:sample_length0]\n genSensArray.append(self._idx_to_word(outputs0, self.trg_ivocab))\n states0 = states0[sample_length0-1]\n\n # generate the second sentence\n #print(outputs0)\n inp1 = self._changeIdx(outputs0)\n #print(inp1)\n inp1 = inp1[None, :]\n states1, outputs1, _2_1, _3_1, costs1, lastrep1 = (self.sampling_fn1(input1 = inp1, hstates1 = states0, lastrep0 = lastrep0))\n lastrep1 = lastrep1[:input_length]\n #print(lastrep1.shape)\n\n outputs1 = outputs1.flatten()\n sample_length1 = self._get_true_length(outputs1, self.trg_vocab)\n\n costs1 = costs1.T\n totalcosts += costs1[:sample_length1].sum()\n\n outputs1 = outputs1[:sample_length1]\n genSensArray.append(self._idx_to_word(outputs1, self.trg_ivocab))\n states1 = states1[sample_length1-1]\n\n # generate the third sentence\n inp2 = self._changeIdx(outputs1)\n inp2 = inp2[None, :]\n states2, outputs2, _2_2, _3_2, costs2, lastrep2 = (self.sampling_fn2(input2 = inp2, hstates2 = states1, lastrep0 = lastrep0, lastrep1 = lastrep1))\n lastrep2 = lastrep2[:input_length]\n\n outputs2 = outputs2.flatten()\n sample_length2 = self._get_true_length(outputs2, self.trg_vocab)\n\n costs2 = costs2.T\n totalcosts += costs2[:sample_length2].sum()\n\n outputs2 = outputs2[:sample_length2]\n genSensArray.append(self._idx_to_word(outputs2, self.trg_ivocab))\n states2 = states2[sample_length2-1]\n\n\n\n\n \n #print(states0.shape)\n #print(outputs0.shape)\n #print(_2_0.shape)\n #print(_3_0.shape)\n #print(costs0.shape)\n\n print(\"origin poem: \")\n for j in range(0, len(OriSensArray)):\n print(OriSensArray[j])\n\n print(\"generated poem:\")\n for j in range(0, len(genSensArray )):\n print(genSensArray[j] + \"\")\n\n print(\"generate cost: %f\" % (totalcosts))\n\n print()\n","sub_path":"sampling.py","file_name":"sampling.py","file_ext":"py","file_size_in_byte":8038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"146025472","text":"import datetime\nimport calendar\n\ndef meetup_day(year, month, weekday, meetup):\n dic_meetup = {'teenth': 1, '1st': 1, '2nd': 2, '3rd': 3, '4th': 4, '5th': 5, 'last': -1}\n weekdays = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')\n\n c = 0\n if meetup == 'teenth':\n d = datetime.date(year, month, 10)\n elif meetup == 'last':\n d = datetime.date(year, month, calendar.monthrange(year, month)[1])\n while True:\n if weekdays[d.weekday()] is weekday:\n return d\n d -= datetime.timedelta(days=1)\n else:\n d = datetime.date(year, month, 1)\n\n while c != dic_meetup[meetup]:\n if weekdays[d.weekday()] is weekday:\n c += 1\n d += datetime.timedelta(days=1)\n\n if month != d.month:\n raise Exception()\n\n return d - datetime.timedelta(days=1)\n","sub_path":"exercism.io/meetup/meetup.py","file_name":"meetup.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"646793467","text":"# names.py>\nimport sys\nimport os\n# import csv\n# import re\n# from removals import remove\n# import petl as etl\nfrom nameparser import HumanName as hn\nimport pandas as pd\nimport click\n\n# -- print(\"dumb fuck\")\n# -- etl.transform.regex.capture() <-- WILL be useful, learn REGEX!!!\n# -- https://petl.readthedocs.io/en/stable/transform.html\n\n# Prints a note about acceptable file types/format and prompts user for input file\n# print('NOTE: Accepts .xlsx files with a single column (Name) of names to be fixed\n# \\n and split into separate parts.')\n@click.command()\n@click.argument('file')#, help='Enter the filename to process (.xlsx)')\n@click.argument('cols')#, help='Enter the names of the column(s) you would like to parse.')\n\n# file = input('Enter filename to process: ')\n\n# cols = input('Enter the name of the column(s) that contain' +\n# '\\n' + 'names you would like to parse: ')\n\n\ndef SplitNames(file, cols):\n \"\"\"NOTE: Accepts .xlsx files with a single column (Name) of names to be fixed\n \\n and split into separate parts.\"\"\"\n # -- Define variables for the output file we'll create at the end\n fn = 'FixedNames'\n ext = '.csv'\n n = ''\n\n # -- Read in the file entered at prompt\n df = pd.read_excel(file)\n avail_head = list(df.columns)\n #split_col = list(avail_head)\n try:\n if cols in avail_head:\n print('All columns entered are valid. Please Wait...')\n\n names = []\n\n for row in df[cols]:\n # -- Removes current known portions of unformatted names -- Need to\n # -- figure out how to pass this as a list\n # -- ['Rev.','Sr.','Sr',' sr','Jr.','Jr','jr','III','II','-DEL']\n a = row.replace('Rev.', '').replace(\n 'Sr.,', '').replace('Sr.', '').replace('Sr', '').replace(' sr', '') \\\n .replace('Jr.', '').replace('Jr', '').replace('jr', '') \\\n .replace('III', '').replace('II', '').replace('-DEL', '')\n # .replace(' , ','')\n a2 = a.replace('(', '').replace(')', '')\n # -- Apply the HumanName parser\n b = hn(a2)\n # -- Pull out and name the appropriate columns\n w = [b.first, b.middle, b.last, b.nickname]\n names.append(w)\n fixed = pd.DataFrame(names, columns=['deathcertificate.about.firstName',\n 'deathcertificate.about.middleName',\n 'deathcertificate.about.lastName',\n 'deathcertificate.about.aka'])\n\n # -- Check if pre-formatted output file exists, if it does, this will\n # -- make a sequential filename like \"filename#\" where # is the sequence\n while os.path.exists('%s%s%s' % (fn, n, ext)):\n if isinstance(n, str):\n n = -1\n n += 1\n xx = '%s%s%s' % (fn, n, ext)\n except KeyError:\n print('Invalid column name, check file and try again.')\n sys.exit()\n\n # -- Write output of function to newly created filename\n\n return fixed.to_csv(xx)\n\n\n# if __name__ == '__main__':\n# SplitNames(file, cols)\n","sub_path":"dataload/lib/python3.8/site-packages/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"535469087","text":"from odoo import models, fields, api, exceptions\n\nclass Parkpersonal(models.Model):\n _name = 'naturalparks.parkpersonal'\n\n name = fields.Char(string=\"name of the employee\", required=True)\n dni = fields.Char(string=\"dni of the employee\", required=True)\n ss_number = fields.Char(string=\"social security number of the employee\", required=True)\n natural_park_id = fields.Many2one('naturalparks.natural_park', ondelete='cascade', string=\"Natural Park\", required=True)\n address = fields.Char(string=\"address of the employee\")\n mobile_phone = fields.Char(string=\"mobile phone of the employee\")\n home_phone = fields.Char(string=\"home phone of the employee\")\n salary = fields.Integer(string=\"salary of the employee\")\n\n @api.constrains('salary')\n def _check_park_has_extension(self):\n for r in self:\n if r.salary <= 0:\n raise exceptions.ValidationError(\"error\")\n\nclass Managementper(models.Model):\n _name = 'naturalparks.managementper'\n _order = 'name'\n _inherit = 'naturalparks.parkpersonal'\n\n number_of_entry = fields.Integer()\n\nclass Surveillanceper(models.Model):\n _name = 'naturalparks.surveillanceper'\n _order = 'name'\n _inherit = 'naturalparks.parkpersonal'\n\n area_id = fields.Many2one('naturalparks.area', string=\"area\", required=True)\n personalcar_id = fields.Many2one('naturalparks.personalcar', string=\"personalcar\", required=True)\n\nclass Personalcar(models.Model):\n _name = 'naturalparks.personalcar'\n _order = 'name'\n\n name = fields.Char(string=\"car model\", required=True)\n\nclass Researchper(models.Model):\n _name = 'naturalparks.researchper'\n _order = 'name'\n _inherit = 'naturalparks.parkpersonal'\n\n title = fields.Char(string=\"tittle of the employee\", required=True)\n\nclass Conservationper(models.Model):\n _name = 'naturalparks.conservationper'\n _order = 'name'\n _inherit = 'naturalparks.parkpersonal'\n\n area_id = fields.Many2one('naturalparks.area', string=\"Area\", required=True)\n specialty = fields.Selection([('cleaning', 'Cleaning'), ('roads', 'Roads'), ('others', 'Others')]) \n\n ","sub_path":"models/Parkpersonal.py","file_name":"Parkpersonal.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"350895916","text":"\"\"\"\nWrite Operations for Vi that involves inserting documents, editing or deleting documents.\n\"\"\"\nimport io\nimport gc\nimport types\nimport json\nimport base64\nimport warnings\nimport requests\nimport pandas as pd\nimport numpy as np\nimport copy\nfrom tqdm.notebook import tqdm\nfrom typing import List, Dict, Union, Any, Callable\nfrom functools import partial\nfrom multiprocessing import Pool\nfrom .utils import UtilsMixin\nfrom .errors import APIError, MissingFieldError, MissingFieldWarning, CollectionNameError\nfrom .api import ViAPIClient\n\n\nclass ViWriteClient(ViAPIClient, UtilsMixin):\n \"\"\"Class to write to database.\"\"\"\n\n def __init__(self, username, api_key, url=\"https://api.vctr.ai\" ):\n self.username = username\n self.api_key = api_key\n self.url = url\n\n @staticmethod\n def _raise_error(response):\n \"\"\"\n Internal Error check if there is a 'status' key.\n\n Args:\n response:\n A python dictionary/JSON response that contains the response function\n\n Example:\n\n >>> from vectorai.client import ViClient\n >>> response = requests.get(...)\n >>> ViClient._raise_error(response)\n \"\"\"\n if 'status' in response.keys():\n if response[\"status\"].lower() == \"error\":\n raise APIError(response[\"message\"])\n\n @classmethod\n def _chunks(self, lst: List, n: int):\n \"\"\"\n Chunk an iterable object in Python but not a pandas DataFrame.\n\n Args:\n lst:\n Python List\n n:\n The chunk size of an object.\n\n Example:\n >>> documents = [{...}]\n >>> ViClient.chunk(documents)\n \"\"\"\n for i in range(0, len(lst), n):\n yield lst[i : i + n]\n\n @staticmethod\n def chunk(documents: Union[pd.DataFrame, List], chunk_size: int = 20):\n \"\"\"\n Chunk an iterable object in Python.\n\n Args:\n documents:\n List of dictionaries/Pandas dataframe\n chunk_size:\n The chunk size of an object.\n\n Example:\n >>> documents = [{...}]\n >>> ViClient.chunk(documents)\n \"\"\"\n if isinstance(documents, pd.DataFrame):\n for i in range(0, len(documents), chunk_size):\n yield documents.iloc[i : i + chunk_size]\n else:\n for i in range(0, len(documents), chunk_size):\n yield documents[i : i + chunk_size]\n\n @staticmethod\n def dummy_vector(vector_length):\n \"\"\"\n Dummy vector for missing vector fields.\n\n Args:\n collection_name:\n Name of collection\n\n edits:\n What edits to make in a collection.\n\n document_id:\n Id of the document\n\n Example:\n >>> from vectorai.client import ViClient\n >>> dummy_vector = ViClient.dummy_vector(20)\n \"\"\"\n return [1e-7] * vector_length\n\n @staticmethod\n def set_field(\n field: str, doc: Dict, value: Any, handle_if_missing=True\n ):\n \"\"\"\n For nested dictionaries, tries to write to the respective field.\n If you toggle off handle_if_misisng, then it will output errors if the field is\n not found.\n e.g.\n field = kfc.item\n value = \"fried wings\"\n This should then create the following entries if they dont exist:\n {\n \"kfc\": {\n \"item\": \"fried wings\"\n }\n }\n\n Args:\n field:\n Field of the document to write.\n doc:\n Python dictionary\n value:\n Value to write\n\n Example:\n\n >>> from vectorai.client import ViClient\n >>> vi_client = ViClient(username, api_key, vectorai_url)\n >>> sample_document = {'kfc': {'item': ''}}\n >>> vi_client.set_field('kfc.item', sample_document, 'chickens')\n \"\"\"\n fields = field.split(\".\")\n # Assign a pointer.\n d = doc\n for i, f in enumerate(fields):\n # Assign the value if this is the last entry e.g. stores.fastfood.kfc.item will be item\n if i == len(fields) - 1:\n d[f] = value\n else:\n if f in d.keys():\n d = d[f]\n else:\n d.update({f: {}})\n d = d[f]\n\n def create_collection(self, collection_name: str, collection_schema: Dict = {}, **kwargs):\n \"\"\"\n Create a collection\n\n A collection can store documents to be searched, retrieved, filtered and aggregated (similar to Collections in MongoDB, Tables in SQL, Indexes in ElasticSearch).\n\n If you are inserting your own vector use the suffix (ends with) \"_vector_\" for the field name. and specify the length of the vector in colletion_schema like below example::\n\n {\n \"collection_schema\": {\n \"celebrity_image_vector_\": 1024,\n \"celebrity_audio_vector\" : 512,\n \"product_description_vector\" : 128\n }\n }\n\n Args:\n collection_name:\n Name of a collection\n collection_schema:\n A collection schema. This is necessary if the first document is not representative of the overall schema collection. This should be specified if the items need to be edited. The schema needs to look like this : { vector_field_name: vector_length }\n\n Example:\n >>> collection_schema = {'image_vector_':2048}\n >>> ViClient.create_collection(collection_name, collection_schema)\n \"\"\"\n collection_name_lower_case = collection_name.lower()\n if collection_name_lower_case != collection_name:\n warnings.warn(\"Your collection name is not in lower case. We are automatically converting to lower case for compatibility.\")\n\n response = self._create_collection(\n collection_name_lower_case, collection_schema=collection_schema, **kwargs\n )\n self._raise_error(response)\n print(f\"Collection {collection_name} created successfully.\")\n\n def delete_collection(self, collection_name: str, **kwargs):\n \"\"\"\n Delete the collection via the colleciton name.\n\n Args:\n collection_name:\n Name of collection to delete.\n\n Example:\n >>> from vectorai.client import ViClient\n >>> vi_client = ViClient(username, api_key, vectorai_url)\n >>> vi_client.delete_collection(collection_name)\n \"\"\"\n return self._delete_collection(collection_name, **kwargs)\n\n def _get_vector_name_for_encoding(self, f: str, model: Callable, model_list: List[Callable]):\n \"\"\"\n Returns the vector names for encoding.\n\n Args:\n f:\n Field to encode\n model:\n The model used for encoding\n models:\n A dictionary of fields and models to determine the type of encoding for each field.\n\n \"\"\"\n if len(model_list) == 1 and self.get_name(model) is None:\n vector_name = f\"{f}_vector_\"\n elif isinstance(model, (types.FunctionType, types.MethodType)):\n vector_name = f\"{f}_vector_\"\n else:\n vector_name = f\"{f}_{self.get_name(model)}_vector_\"\n return vector_name\n\n def _check_if_multiple_models_have_same_name(self, models: Dict):\n \"\"\"\n For a model dictionary, ensure that the name of a function is good.\n\n Args:\n models:\n A dictionary where a key links to a dictionary.\n\n \"\"\"\n for f, model_list in models.items():\n if not isinstance(model_list, list):\n model_list = [model_list]\n name_list = []\n for model in model_list:\n name = self.get_name(model)\n if name is None and len(model_list) > 1:\n assert self.get_name(m) is not None, f\"Your models are missing names. Please set name using set_name(model) function.\"\n name_list.append(name)\n if len(set(name_list)) != len(name_list):\n raise ValueError(\"Models have the set name. Check each model name is unique.\")\n\n def encode_documents_with_models_using_encode(self, documents: List[Dict], models: Dict):\n \"\"\"\n Encode documents with appropriate models without a bulk_encode function.\n Args:\n documents:\n List of documents/JSONs/dictionaries.\n models:\n A dictionary of fields and models to determine the type of encoding for each field.\n\n \"\"\"\n for d in documents:\n for f, model_list in models.items():\n # Typecast callable to a list to easily pass through for-loop.\n if not isinstance(model_list, list):\n model_list = [model_list]\n\n for model in model_list:\n vector_field = self._get_vector_name_for_encoding(f, model, model_list)\n\n if not self.is_field(f, d):\n warnings.warn(f\"\"\"Missing {f} in a document. Filling the missing with empty vectors.\"\"\")\n self.set_field(vector_field, d, self.dummy_vector(self._get_vector_length_from_model(model)))\n\n if isinstance(model, (types.FunctionType, types.MethodType, partial)):\n vector = model(self.get_field(f, d))\n self._set_vector_length_from_model(model, vector)\n self.set_field(vector_field, d, vector)\n else:\n self.set_field(vector_field, d, model.encode(self.get_field(f, d)))\n\n return documents\n\n def _get_vector_length_from_model(self, model):\n if isinstance(model, (types.FunctionType, types.MethodType, partial)):\n self.vector_length = len(vector)\n return\n\n if hasattr(model, 'vector_length'):\n return model.vector_length\n\n if hasattr(model, 'urls') and hasattr(model, 'url'):\n return model.urls[model.url]['vector_length']\n\n if hasattr(model, 'urls') and hasattr(model, 'model_url'):\n return model.urls[model.model_url]\n\n raise APIError(\"Please set the vector length of the model as an attribute.\")\n\n def _set_vector_length_from_model(self, model, vector):\n \"\"\"\n Set the vector length for the model\n \"\"\"\n if isinstance(model, (types.FunctionType, types.MethodType, partial)):\n self.vector_length = len(vector)\n return\n if not hasattr(model, 'vector_length'):\n setattr(model, 'vector_length', len(vector))\n return\n\n def encode_documents_with_models(\n self, documents: List[Dict], models: Union[Dict[str, Callable], List[Dict]] = {}, use_bulk_encode=False\n ):\n \"\"\"\n Encode documents with appropriate models.\n\n Args:\n documents:\n List of documents/jsons/dictionaries.\n models:\n A dictionary of fields and models to determine the type of encoding for each field.\n\n Example:\n >>> from vectorai.client import ViClient\n >>> vi_client = ViClient(username, api_key, vectorai_url)\n >>> from vectorai.models.deployed import ViText2Vec\n >>> text_encoder = ViText2Vec(username, api_key, vectorai_url)\n >>> documents = [{'chicken': 'Big chicken'}, {'chicken': 'small_chicken'}, {'chicken': 'cow'}]\n >>> vi_client.encode_documents_with_models(documents=documents, models={'chicken': text_encoder.encode})\n \"\"\"\n # TODO: refactor & test if changing black length\n self._check_if_multiple_models_have_same_name(models)\n if use_bulk_encode:\n return self.encode_documents_with_models_in_bulk(documents=documents, models=models)\n return self.encode_documents_with_models_using_encode(documents=documents, models=models)\n\n def encode_documents_with_models_in_bulk(self, documents: List[Dict], models: Dict):\n \"\"\"\n Encode documents with models to allow for bulk_encode.\n\n Args:\n documents:\n List of documents/jsons/dictionaries.\n models:\n A dictionary of fields and models to determine the type of encoding for each field.\n \"\"\"\n # Ensure all models have a bulk_encode method.\n for f, model_list in models.items():\n if not isinstance(model_list, list):\n models[f] = [model_list]\n for model in models[f]:\n if model.__name__ is not None:\n assert hasattr(model, 'bulk_encode'), f\"Model {model.__name__} cannot be encoded in bulk. Missing bulk_encode method.\"\n else:\n assert hasattr(model, 'bulk_encode'), \"Model cannot be encoded in bulk. Missing bulk_encode method.\"\n # Now bulk-encode and then set the field for each dictionary\n for f, model_list in models.items():\n for model in model_list:\n vector_field = self._get_vector_name_for_encoding(f, model, model_list)\n values = self.get_field_across_documents(f, documents, )\n vectors = model.bulk_encode(values)\n self.set_field_across_documents(vector_field, vectors, documents)\n return documents\n\n def _insert_and_encode(\n self, documents: list, collection_name: str, models: dict, verbose=False,\n use_bulk_encode: bool=False, overwrite: bool=False, quick: bool=False, **kwargs\n ):\n \"\"\"\n Insert and encode documents\n \"\"\"\n self._convert_ids_to_string(documents)\n\n return self.bulk_insert(\n collection_name=collection_name,\n documents=self.encode_documents_with_models(documents, models=models,\n use_bulk_encode=use_bulk_encode),\n overwrite=overwrite,\n quick=quick,\n **kwargs\n )\n\n def insert_document(self, collection_name: str, document: Dict, verbose=False):\n \"\"\"\n Insert a document into a collection\n\n Args:\n collection_name:\n Name of collection\n\n documents:\n List of documents/jsons/dictionaries.\n\n Example:\n >>> from vectorai import ViClient\n >>> from vectorai.models.deployed import ViText2Vec\n >>> vi_client = ViClient()\n >>> collection_name = 'test_collection'\n >>> document = {'chicken': 'Big chicken'}\n >>> vi_client.insert_document(collection_name, document)\n \"\"\"\n response = self.insert(collection_name=collection_name, document=document)\n if response != \"inserted\":\n raise APIError(f\"Document failed to insert into {collection_name}\")\n\n if verbose:\n print(f\"Document inserted succesfully into {collection_name}\")\n\n\n def insert_single_document(self, collection_name: str, document: Dict):\n \"\"\"\n Encode documents with models.\n\n\n Args:\n documents:\n List of documents/jsons/dictionaries.\n\n Example:\n >>> from vectorai import ViClient\n >>> from vectorai.models.deployed import ViText2Vec\n >>> vi_client = ViClient()\n >>> collection_name = 'test_collection'\n >>> document = {'chicken': 'Big chicken'}\n >>> vi_client.insert_single_document(collection_name, document)\n \"\"\"\n return self.insert_document(collection_name=collection_name, document=document)\n\n def _convert_ids_to_string(self, documents: List[Dict]):\n \"\"\"\n Convert IDs in a document to strings if the first document has a field.\n \"\"\"\n try:\n id_values = self.get_field_across_documents('_id', documents)\n # Typecast to string\n id_values = [str(x) for x in id_values]\n self.set_field_across_documents('_id', id_values, documents)\n except MissingFieldError:\n pass\n\n @property\n def NO_ID_WARNING_MESSAGE(self):\n return \"\"\"If inserting documents breaks, you will not be\n able to resume inserting. We recommending adding IDs to your documents.\n You can do this by using set_field_across_documents function with a list of\n IDs.\"\"\"\n\n def _raise_warning_if_no_id(self, documents: List[Dict]):\n \"\"\"\n If no documents have no IDs, raise warnings\n \"\"\"\n try:\n self.get_field_across_documents('_id', documents)\n except MissingFieldError:\n warnings.warn(self.NO_ID_WARNING_MESSAGE, MissingFieldWarning)\n\n def insert_documents(\n self,\n collection_name: str,\n documents: List,\n models: Dict[str, Callable] = {},\n chunksize: int = 15,\n workers: int = 1,\n verbose: bool=False,\n use_bulk_encode: bool=False,\n overwrite: bool=False,\n show_progress_bar: bool=True,\n quick: bool=False,\n preprocess_hook: Callable=None,\n **kwargs\n ):\n \"\"\"\n Insert documents into a collection with an option to encode with models.\n\n Args:\n collection_name:\n Name of collection\n documents:\n All documents.\n models:\n Models with an encode method\n use_bulk_encode:\n Use the bulk_encode method in models\n verbose:\n Whether to print document ids that have failed when inserting.\n overwrite:\n If True, overwrites document based on _id field.\n quick:\n If True, skip the collection schema checks. Not advised if this is\n your first time using the API until you are used to using Vector AI.\n preprocess_hook:\n Document-level function taht updates\n\n Example:\n >>> from vectorai.models.deployed import ViText2Vec\n >>> text_encoder = ViText2Vec(username, api_key, vectorai_url)\n >>> documents = [{'chicken': 'Big chicken'}, {'chicken': 'small_chicken'}, {'chicken': 'cow'}]\n >>> vi_client.insert_documents(documents, models={'chicken': text_encoder.encode})\n \"\"\"\n if collection_name not in self.list_collections():\n if len(models) == 0:\n self._check_schema(documents[0])\n self.create_collection_from_document(\n collection_name,\n self.encode_documents_with_models([documents[0]], models)[0],\n )\n self._raise_warning_if_no_id(documents)\n failed = []\n iter_len = int(len(documents) / chunksize) + (len(documents) % chunksize > 0)\n iter_docs = self._chunks(documents, chunksize)\n\n if workers == 1:\n for c in self.progress_bar(iter_docs, total=iter_len, show_progress_bar=show_progress_bar):\n if preprocess_hook: {preprocess_hook(d) for d in c}\n result = self._insert_and_encode(\n documents=c, collection_name=collection_name, models=models, use_bulk_encode=use_bulk_encode,\n overwrite=overwrite, quick=quick, **kwargs\n )\n self._raise_error(result)\n if verbose and len(result['failed_document_ids']) > 0: print(f\"Failed: {result['failed_document_ids']}\")\n failed.append(result[\"failed_document_ids\"])\n else:\n if preprocess_hook:\n raise NotImplementedError(\"Preprocess hooks are not supported with multi-processing.\")\n pool = Pool(processes=workers)\n # Using partial insert for compatibility with ViCollectionClient\n partial_insert = partial(self._insert_and_encode, models=models,collection_name=collection_name,\n overwrite=overwrite, quick=quick, **kwargs)\n for result in self.progress_bar(\n pool.imap_unordered(func=partial_insert, iterable=iter_docs), total=iter_len):\n self._raise_error(result)\n if verbose and len(result['failed_document_ids']) > 0:\n warnings.warn(\"\"\"There are failed documents. Try re-inserting these IDs\n and test by choosing the most important fields first!\"\"\")\n print(f\"Failed: {result['failed_document_ids']}\")\n failed.append(result[\"failed_document_ids\"])\n pool.close()\n pool.join()\n failed = self.flatten_list(failed)\n return {\n \"inserted_successfully\": len(documents) - len(failed),\n \"failed\": len(failed),\n \"failed_document_ids\": failed,\n }\n\n def resume_insert_documents(\n self,\n collection_name: str,\n documents: List,\n models: Dict[str, Callable] = {},\n chunksize: int = 15,\n workers: int = 1,\n verbose: bool=False,\n use_bulk_encode: bool=False,\n show_progress_bar: bool=True\n ):\n \"\"\"\n Resume inserting documents\n \"\"\"\n document_ids = self.get_field_across_documents(documents)\n missing_ids = set(self.bulk_missing_id(collection_name, document_ids))\n self.insert_documents(collection_name=collection_name,\n documents=[doc for doc in documents if doc['_id'] in missing_ids],\n models=models,\n chunksize=chunksize,\n workers=workers,\n verbose=verbose,\n use_bulk_encode=use_bulk_encode,\n overwrite=False,\n show_progress_bar=show_progress_bar)\n\n\n def insert_df(\n self,\n collection_name: str,\n df: pd.DataFrame,\n models: Dict[str, Callable] = {},\n chunksize: int = 15,\n workers: int = 1,\n verbose: bool = True,\n use_bulk_encode: bool = False,\n **kwargs\n ):\n \"\"\"\n Insert dataframe into a collection\n\n Args:\n collection_name:\n Name of collection\n df:\n Pandas DataFrame\n models:\n Models with an encode method\n verbose:\n Whether to print document ids that have failed when inserting.\n\n Example:\n >>> from vectorai.models.deployed import ViText2Vec\n >>> text_encoder = ViText2Vec(username, api_key, vectorai_url)\n >>> documents_df = pd.DataFrame.from_records([{'chicken': 'Big chicken'}, {'chicken': 'small_chicken'}, {'chicken': 'cow'}])\n >>> vi_client.insert_df(documents=documents_df, models={'chicken': text_encoder.encode})\n \"\"\"\n return self.insert_documents(\n collection_name,\n [ {k:v for k,v in m.items() if not isinstance(v, float) or pd.notnull(v)} for m in df.to_dict(orient='records')],\n models=models,\n chunksize=chunksize,\n workers=workers,\n verbose=verbose,\n use_bulk_encode=use_bulk_encode,\n **kwargs\n )\n\n def _edit_document_return_id(\n self, edits: Dict[str, str], collection_name: str\n ):\n \"\"\"\n Edit documents when ID is returned.\n\n\n Args:\n collection_name:\n Name of collection\n\n edits:\n What edits to make in a collection. Ensure that _id is stored in the document.\n\n \"\"\"\n copy_doc = edits.copy()\n if '_id' not in edits.keys():\n warnings.warn(\"One of the documents is missing an _id field.\")\n copy_doc.pop('_id')\n response = self._edit_document(\n collection_name=collection_name, edits=copy_doc, document_id=edits[\"_id\"]\n )\n if response == \"failed\":\n return edits[\"_id\"]\n return\n\n def edit_documents(self, collection_name: str, edits: Dict, chunk_size: int=15, verbose: bool=False, **kwargs):\n \"\"\"\n Edit documents in a collection\n\n\n Args:\n collection_name:\n Name of collection\n\n edits:\n What edits to make in a collection. Ensure that _id is stored in the document.\n\n workers:\n Number of parallel processes to run.\n\n Example:\n >>> from vectorai.client import ViClient\n >>> vi_client = ViClient(username, api_key, vectorai_url)\n >>> vi_client.edit_documents(collection_name, edits=documents, workers=10)\n \"\"\"\n failed = []\n for c in self.progress_bar(self.chunk(edits, chunk_size=chunk_size),\n total=int(len(edits)/chunk_size)):\n response = self.bulk_edit_document(collection_name, c, **kwargs)\n if verbose: print(response)\n failed += response['failed_document_ids']\n return {\n \"edited_successfully\": len(edits) - len(failed),\n \"failed\": len(failed),\n \"failed_document_ids\": failed,\n }\n\n def retrieve_and_encode(\n self,\n collection_name: str,\n models: Dict[str, Callable] = {},\n chunksize: int = 15,\n use_bulk_encode: bool=False,\n filters: list = [],\n refresh: bool=False):\n \"\"\"\n Retrieve all documents and re-encode with new models.\n Args:\n collection_name: Name of collection\n models: Models as a dictionary\n chunksize: the number of results to\n retrieve and then encode and then edit in one go\n use_bulk_encode: Whether to use bulk_encode on the models.\n filter_query: Filtering\n refresh: If True, retrieves and encodes from scratch, otherwise, only\n encodes for fields that are not there. Only the filter for the first\n model is applied\n \"\"\"\n docs = self.retrieve_documents(collection_name, page_size=chunksize)\n docs['cursor'] = None\n failed_all = {\n \"failed_document_ids\": []\n }\n num_of_docs = self.collection_stats(collection_name)['number_of_documents']\n if refresh:\n filter_query = []\n else:\n filter_query = filters\n # Filter for documents that are missing the first document\n for f, model in models.items():\n vector_field_name = self._get_vector_name_for_encoding(f, model, list(models.keys()))\n filter_query.append(\n {'field' : vector_field_name, 'filter_type' : 'exists', \"condition\":\"!=\", \"condition_value\":\" \"}\n )\n break\n\n with self.progress_bar(list(range(int(num_of_docs/ chunksize)))) as pbar:\n while len(docs['documents']) > 0:\n docs = self.retrieve_documents_with_filters(\n collection_name, cursor=docs['cursor'],\n include_fields=list(models.keys()),\n filters=filter_query,\n page_size=chunksize)\n failed = self.bulk_edit_document(\n collection_name=collection_name,\n documents=self.encode_documents_with_models(docs['documents'],\n models=models,\n use_bulk_encode=use_bulk_encode))\n for k in failed_all.keys():\n failed_all[k] += failed[k]\n pbar.update(1)\n return failed_all\n\n def retrieve_and_edit(\n self,\n collection_name: str,\n edit_fn: Callable,\n refresh: bool=False,\n edited_fields: list= [],\n include_fields: list=[],\n chunksize: int = 15):\n \"\"\"\n Retrieve all documents and re-encode with new models.\n Args:\n collection_name: Name of collection\n edit_fn: Function for editing an entire document\n include_fields: The number of fields to retrieve to speed up the document\n retrieval step\n chunksize: the number of results to\n retrieve and then encode and then edit in one go\n edited_fields: These are the edited fields used to change\n \"\"\"\n docs = self.retrieve_documents(collection_name, page_size=1,\n include_fields=['_id'])\n docs['cursor'] = None\n failed_all = {\n \"failed_document_ids\": []\n }\n num_of_docs = self.collection_stats(collection_name)['number_of_documents']\n if refresh:\n filter_query = []\n else:\n filter_query = []\n for f in edited_fields:\n filter_query.append({'field' : f, 'filter_type' : 'exists', \"condition\":\"!=\", \"condition_value\":\" \"})\n with self.progress_bar(list(range(int(num_of_docs/ chunksize)))) as pbar:\n while len(docs['documents']) > 0:\n docs = self.retrieve_documents_with_filters(\n collection_name, cursor=docs['cursor'],\n page_size=chunksize, include_fields=include_fields,\n filters=filter_query)\n {edit_fn(d) for d in docs['documents']}\n failed = self.bulk_edit_document(\n collection_name=collection_name,\n documents=docs['documents'])\n for k in failed_all.keys():\n failed_all[k] += failed[k]\n pbar.update(1)\n return failed_all\n\n def _typecheck_collection_name(self, collection_name: str):\n \"\"\"\n Typecheck collection name\n \"\"\"\n ACCEPTABLE_LETTERS = 'abcdefghijklmnopqrstuvwxyz_-.1234567890'\n for letter in collection_name:\n if letter not in ACCEPTABLE_LETTERS:\n raise CollectionNameError()\n if len(collection_name) > 240:\n raise CollectionNameError()\n\n def create_collection_from_document(self, collection_name: str, document: dict, **kwargs):\n \"\"\"\nCreates a collection by infering the schema from a document\n\nIf you are inserting your own vector use the suffix (ends with) **\"\\_vector\\_\"** for the field name. e.g. \"product\\_description\\_vector\\_\"\n\nArgs:\n\tcollection_name:\n\t\tName of Collection\n\tdocument:\n\t\tA Document is a JSON-like data that we store our metadata and vectors with. For specifying id of the document use the field '\\_id', for specifying vector field use the suffix of '\\_vector\\_'\n\"\"\"\n self._typecheck_collection_name(collection_name)\n return self._create_collection_from_document(\n collection_name=collection_name, document=document)\n","sub_path":"vectorai/write.py","file_name":"write.py","file_ext":"py","file_size_in_byte":30826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"182246556","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.3-fat/egg/tgmochikit/base.py\n# Compiled at: 2008-10-26 13:30:23\nimport pkg_resources, os, glob, logging\nlogger = logging.getLogger(('.').join(__name__.split('.')[:-1]))\nVERSION = '1.3.1'\nINITIALIZED = False\nPACKED = False\nXHTML = False\nSUBMODULES = []\nPATHS = []\nDRAGANDDROP = False\n\ndef init(register_static_directory, config={}, version=None, packed=None, xhtml=None, draganddrop=None):\n \"\"\"Initializes the MochiKit resources.\n\n The parameter register_static_directory is somewhat hackish: because this\n init is called during initialization of turbogears.widgets itself,\n register_static_directory isn't importable. So we need to pass it as\n argument.\n\n \"\"\"\n global DRAGANDDROP\n global INITIALIZED\n global PACKED\n global PATHS\n global VERSION\n global XHTML\n if not INITIALIZED:\n if version is not None:\n VERSION = version\n if packed is not None:\n PACKED = packed\n if xhtml is not None:\n XHTML = xhtml\n if draganddrop is not None:\n DRAGANDDROP = draganddrop\n INITIALIZED = True\n PACKED = config.get('tg_mochikit.packed', PACKED)\n VERSION = config.get('tg_mochikit.version', VERSION)\n XHTML = config.get('tg_mochikit.xhtml', XHTML)\n DRAGANDDROP = config.get('tg_mochikit.draganddrop', DRAGANDDROP)\n is_131 = '1.3.1' in VERSION\n js_base_dir = pkg_resources.resource_filename('tgmochikit', 'static/javascript/')\n if os.path.exists(os.path.join(js_base_dir, VERSION)):\n js_dir = os.path.join(js_base_dir, VERSION)\n else:\n candidates = glob.glob(os.path.join(js_base_dir, '%s*' % VERSION))\n candidates.sort()\n js_dir = candidates[(-1)]\n logger.info('MochiKit version chosen: %s', os.path.basename(js_dir))\n path = os.path.join(js_dir, 'unpacked', '*.js')\n for name in glob.glob(path):\n module = os.path.basename(name)\n if '__' not in name and 'MochiKit' not in module:\n SUBMODULES.append(module)\n\n register_static_directory('tgmochikit', js_dir)\n if PACKED:\n PATHS = [\n 'packed/MochiKit/MochiKit.js']\n else:\n res = [\n 'unpacked/MochiKit.js']\n if XHTML:\n for submodule in SUBMODULES:\n res.append('unpacked/%s' % submodule)\n\n PATHS = res\n if DRAGANDDROP and not is_131:\n PATHS.append('unpacked/DragAndDrop.js')\n return\n\n\ndef get_paths():\n return PATHS\n\n\ndef get_shipped_versions():\n js_base_dir = pkg_resources.resource_filename('tgmochikit', 'static/javascript/')\n return [ os.path.basename(p) for p in glob.glob(os.path.join(js_base_dir, '*')) ]","sub_path":"pycfiles/tgMochiKit-1.4.2-py2.4/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"55877289","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\n\nadmin.autodiscover()\n\n\nurlpatterns = patterns('',\n url('^$', TemplateView.as_view(template_name='home.html'), name='home'),\n url(r'^accounts/', include('allauth.urls')),\n # Examples:\n # url(r'^$', 'innovation.views.home', name='home'),\n # url(r'^innovation/', include('innovation.foo.urls')),\n\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n\nimport settings\nif not settings.DEBUG:\n urlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),\n )\n\nurlpatterns += staticfiles_urlpatterns()\n","sub_path":"innovation/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"230904142","text":"class Employee():\n def __init__(self, name, salary, age, gender):\n self.name = name\n self.salary = salary\n self.age = age\n self.gender = gender\n\n def show_employee_details(self):\n print(\"Employee name is \", self.name)\n print(\"Employee salary is \", self.salary)\n print(\"Employee age is \", self.age)\n print(\"Employee gender is \", self.gender)\n\n\np1 = Employee(\"Jose\", 25000, 25, \"Male\")\n\np1.show_employee_details()\n","sub_path":"constructor.py","file_name":"constructor.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"479485459","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#############################################################################\n# Copyright Kitware 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\n\n# Constants representing the setting keys for this plugin\nclass PluginSettings(object):\n LARGE_IMAGE_SHOW_THUMBNAILS = 'large_image.show_thumbnails'\n LARGE_IMAGE_SHOW_EXTRA_PUBLIC = 'large_image.show_extra_public'\n LARGE_IMAGE_SHOW_EXTRA = 'large_image.show_extra'\n LARGE_IMAGE_SHOW_EXTRA_ADMIN = 'large_image.show_extra_admin'\n LARGE_IMAGE_SHOW_VIEWER = 'large_image.show_viewer'\n LARGE_IMAGE_DEFAULT_VIEWER = 'large_image.default_viewer'\n LARGE_IMAGE_AUTO_SET = 'large_image.auto_set'\n LARGE_IMAGE_MAX_THUMBNAIL_FILES = 'large_image.max_thumbnail_files'\n LARGE_IMAGE_MAX_SMALL_IMAGE_SIZE = 'large_image.max_small_image_size'\n LARGE_IMAGE_ANNOTATION_HISTORY = 'large_image.annotation_history'\n\n\nclass SourcePriority(object):\n NAMED = 0 # Explicitly requested\n PREFERRED = 1\n HIGH = 2\n MEDIUM = 3\n LOW = 4\n FALLBACK = 5\n MANUAL = 6 # Will never be selected automatically\n","sub_path":"server/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"193893879","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2015 Pexego All Rights Reserved\n# $Jesús Ventosinos Mayor $\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom openerp import models, fields, api, exceptions, _\nfrom datetime import datetime\n\n\nclass StockLocation(models.Model):\n\n _inherit = 'stock.location'\n\n location_flush_dest = fields.Many2one('stock.location', 'Flush location')\n\n @api.one\n def flush_location(self):\n if not self.location_flush_dest:\n raise exceptions.Warning(\n _('Location error'),\n _('Location %s not have flush destination') %\n self.complete_name)\n\n quants = self.env['stock.quant'].read_group(\n [('location_id', '=', self.id)],\n ['product_id', 'lot_id', 'qty'], ['product_id', 'lot_id'],\n lazy=False)\n if not quants:\n return\n\n wh = self.env['stock.location'].get_warehouse(self)\n type_search_dict = [('code', '=', 'internal')]\n if wh:\n type_search_dict.append(('warehouse_id', '=', wh))\n picking_type = self.env['stock.picking.type'].search(\n type_search_dict)\n picking_vals = {\n 'picking_type_id': picking_type.id,\n 'date': datetime.now(),\n 'origin': 'flush ' + self.complete_name + '->' +\n self.location_flush_dest.complete_name\n }\n picking_id = self.env['stock.picking'].create(picking_vals)\n for quant in quants:\n product = self.env['product.product'].browse(\n quant['product_id'] and quant['product_id'][0] or False)\n move_dict = {\n 'name': product.name or '',\n 'product_id': product.id,\n 'product_uom': product.uom_id.id,\n 'product_uos': product.uom_id.id,\n 'product_uom_qty': quant['qty'],\n 'date': datetime.now(),\n 'date_expected': datetime.now(),\n 'location_id': self.id,\n 'location_dest_id': self.location_flush_dest.id,\n 'move_dest_id': False,\n 'state': 'draft',\n 'company_id': self.env.user.company_id.id,\n 'picking_type_id': picking_type.id,\n 'procurement_id': False,\n 'origin': picking_id.origin,\n 'invoice_state': 'none',\n 'picking_id': picking_id.id\n }\n if quant['lot_id']:\n move_dict['restrict_lot_id'] = quant['lot_id'][0]\n self.env['stock.move'].create(move_dict).action_confirm()\n picking_id.action_assign()\n picking_id.do_transfer()\n\n @api.model\n def flush_location_cron(self):\n self.search([('location_flush_dest', '!=', False)]).flush_location()\n","sub_path":"project-addons/stock_location_flush/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"512499614","text":"import xlrd\n\n\nclass ExcelOperation:\n def __init__(self,path=None,sheet_name=None):\n if path == None:\n path = '../../config/Autocase.xlsx'\n else:\n path = path\n if sheet_name == None:\n sheet_name = '用例参数'\n else:\n sheet_name = sheet_name\n #获取工作簿\n self.workbook = xlrd.open_workbook(path)\n # 获取sheet页面\n self.sheet = self.workbook.sheet_by_name(sheet_name)\n\n def get_row(self):\n return self.sheet.nrows\n\n def get_col(self):\n return self.sheet.ncols\n\n def get_cell_value(self,nrow,ncol):\n if self.sheet.cell(nrow,ncol).ctype == 2:\n cell = str(self.sheet.cell_value(nrow,ncol))\n else:\n cell = self.sheet.cell_value(nrow,ncol)\n return cell\n\n# exl = ExcelOperation()\n# print(exl.get_cell_value(1,3))","sub_path":"quote/util/excel_aperation.py","file_name":"excel_aperation.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"464541415","text":"\nfrom django.contrib import admin\n\nfrom mezzanine.blog.models import BlogPost, Comment\nfrom mezzanine.core.admin import DisplayableAdmin, OwnableAdmin\nfrom mezzanine.settings import COMMENTS_DISQUS_SHORTNAME\n\n\nclass BlogPostAdmin(DisplayableAdmin, OwnableAdmin):\n\n list_display = (\"title\", \"user\", \"status\", \"admin_link\")\n\n def save_form(self, request, form, change):\n \"\"\"\n Super class ordering is important here - user must get saved first.\n \"\"\"\n OwnableAdmin.save_form(self, request, form, change)\n return DisplayableAdmin.save_form(self, request, form, change)\n\n\nclass CommentAdmin(admin.ModelAdmin):\n\n list_display = (\"avatar_link\", \"intro\", \"time_created\", \"approved\",\n \"blog_post\", \"admin_link\")\n list_display_links = (\"intro\", \"time_created\")\n list_editable = (\"approved\",)\n list_filter = (\"blog_post\", \"approved\", \"name\")\n search_fields = (\"name\", \"email\", \"body\")\n date_hierarchy = \"time_created\"\n ordering = (\"-time_created\",)\n fieldsets = (\n (None, {\"fields\": ((\"name\", \"email\", \"website\"), \"body\",\n (\"ip_address\", \"approved\"), (\"blog_post\", \"replied_to\"))}),\n )\n\nadmin.site.register(BlogPost, BlogPostAdmin)\nif not COMMENTS_DISQUS_SHORTNAME:\n admin.site.register(Comment, CommentAdmin)\n","sub_path":"mezzanine/blog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"173950035","text":"from database.DatabaseResult import DatabaseResult\n\n\nclass Dummy:\n pass\n\n\ndef override_get_organization_uuid_from_hrpartner(hr_partner: int) -> (DatabaseResult, str):\n hrpartners_count = 1 if hr_partner == 5 else 0\n if hrpartners_count == 0:\n return DatabaseResult.FAILURE, \"\"\n else:\n return DatabaseResult.SUCCESS, \"9ff2faff-dc3f-40b0-8c02-53a67750281e\"\n\n\ndef override_get_interview_uuid_from_application_id(application_id: int, which: int) -> (DatabaseResult, str):\n interviews_count = 2 if application_id == 1 else 0\n if interviews_count == 0:\n return DatabaseResult.FAILURE, \"\"\n elif interviews_count <= which:\n return DatabaseResult.DONT_EXIST, \"\"\n else:\n return DatabaseResult.SUCCESS, \"e1177e54-d903-4e91-a299-ddc56606785b\" if which == 0 else \"cbb6b884-888a-4ec4-9446-0a25ba2f2e9e\"\n\n\ndef override_get_user_from_interview_uuid(interview_uuid: str) -> (DatabaseResult, str):\n if interview_uuid != \"e1177e54-d903-4e91-a299-ddc56606785b\":\n return DatabaseResult.DONT_EXIST, f\"Interview with id: {interview_uuid} doesn't exist\"\n user = Dummy()\n user.firstName = \"John\"\n user.lastName = \"Adams\"\n return DatabaseResult.SUCCESS, user\n","sub_path":"tests/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"60119898","text":"from datetime import datetime, time\n\nfrom scheme import current_timestamp\nfrom spire.core import Component, Dependency\nfrom spire.support.daemon import Daemon\nfrom spire.support.logs import LogHelper\nfrom spire.schema import SchemaDependency\nfrom spire.support.threadpool import ThreadPool\n\nfrom platoon.idler import Idler\n\nlog = LogHelper('platoon')\n\nclass ThreadPackage(object):\n def __init__(self, session, model, method, **params):\n self.method = method\n self.model = model\n self.params = params\n self.session = session\n\n def __call__(self):\n session = self.session\n model = session.merge(self.model, load=False)\n\n method = getattr(model, self.method)\n try:\n method(session, **self.params)\n except Exception:\n session.rollback()\n log('exception', '%s raised uncaught exception', repr(model))\n else:\n session.commit()\n\nclass TaskQueue(Component, Daemon):\n \"\"\"An asynchronous task queue.\"\"\"\n\n idler = Dependency(Idler)\n schema = SchemaDependency('platoon')\n threads = Dependency(ThreadPool)\n\n def enqueue(self, model, method, **params):\n session = self.schema.get_session(True)\n self.threads.enqueue(ThreadPackage(session, model, method, **params))\n\n def run(self):\n from platoon.models import Event, Process, ScheduledTask\n\n idler = self.idler\n schema = self.schema\n session = schema.session\n threads = self.threads\n\n ScheduledTask.retry_executing_tasks(session)\n try:\n while True:\n idler.idle()\n try:\n Event.process_events(session)\n Process.process_processes(self, session)\n ScheduledTask.process_tasks(self, session)\n finally:\n session.close()\n except Exception:\n log('exception', 'exception raised by task queue')\n","sub_path":"platoon/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"452186852","text":"from Messages.Systems import messageReceiveSystem\nimport ev3dev2\nfrom ev3dev2 import motor\nfrom ev3dev2 import port\nfrom .FakeMotor import FakeMotor\n\nfrom enum import Enum\n\n\nclass MotorType(Enum):\n NotConnected = 1\n Large = 2\n Medium = 3\n\n\nclass MotorSystem():\n def __init__(self, type1=MotorType.Medium, type2=MotorType.Large, type3=MotorType.Large, type4=MotorType.NotConnected):\n messageReceiveSystem.AddChannelListener(32, self.OnMessage)\n self.percentScalar = 100\n self.InitMotor1(type1)\n self.InitMotor2(type2)\n self.InitMotor3(type3)\n self.InitMotor4(type4)\n self.commandLookup = {\n 0: lambda floats: self.SetMotor(self.motor1, floats[0]),\n 1: lambda floats: self.SetMotor(self.motor2, floats[0]),\n 2: lambda floats: self.SetMotor(self.motor3, floats[0]),\n 3: lambda floats: self.SetMotor(self.motor4, floats[0]),\n 4: lambda floats: self.SetMotors([self.motor1, self.motor2], floats),\n 5: lambda floats: self.SetMotors([self.motor1, self.motor3], floats),\n 6: lambda floats: self.SetMotors([self.motor1, self.motor4], floats),\n 7: lambda floats: self.SetMotors([self.motor2, self.motor3], floats),\n 8: lambda floats: self.SetMotors([self.motor2, self.motor4], floats),\n 9: lambda floats: self.SetMotors([self.motor3, self.motor4], floats),\n 10: lambda floats: self.SetMotors([self.motor1, self.motor2, self.motor3], floats),\n 11: lambda floats: self.SetMotors([self.motor1, self.motor2, self.motor4], floats),\n 12: lambda floats: self.SetMotors([self.motor2, self.motor3, self.motor4], floats),\n 13: lambda floats: self.SetMotors([self.motor1, self.motor2, self.motor3, self.motor4], floats)\n }\n\n def InitMotor1(self, motorType):\n self.motor1 = self.InitMotor(motorType, motor.OUTPUT_A)\n\n def InitMotor2(self, motorType):\n self.motor2 = self.InitMotor(motorType, motor.OUTPUT_B)\n\n def InitMotor3(self, motorType):\n self.motor3 = self.InitMotor(motorType, motor.OUTPUT_C)\n\n def InitMotor4(self, motorType):\n self.motor4 = self.InitMotor(motorType, motor.OUTPUT_D)\n\n def InitMotor(self, motorType, port):\n if(motorType == MotorType.Medium):\n return motor.MediumMotor(port)\n elif(motorType == MotorType.Large):\n return motor.LargeMotor(port)\n else:\n return FakeMotor()\n\n def InvertDirection(self):\n self.percentScalar = self.percentScalar * -1\n\n def OnMessage(self, args):\n command = self.commandLookup.get(args.message.command)\n if(command == None):\n print(\"Ev3 - invalid command: {}\".format(command))\n else:\n command(args.message.data)\n\n def SetMotor(self, motor, normalVal):\n speed = normalVal * self.percentScalar\n print(\"setting motor {} to {}\".format(motor, speed))\n motor.on(speed)\n\n def SetMotors(self, motors, normalSpeeds):\n for i in range(len(motors)):\n speed = normalSpeeds[i] * self.percentScalar\n motors[i].on(speed)\n\n\n# if __name__ == \"__main__\":\n# print()\n # try:\n # except:\n # pass\n # print(ev3dev2.port.LegoPort())\n","sub_path":"River.Body/Ahoy/Ev3/MotorSystem.py","file_name":"MotorSystem.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"186524067","text":"import json\nimport pika\nimport logging\nfrom src.configuration import configuration as config\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.DEBUG)\nconf = config.get('service')\n\n\nclass Queue:\n def __init__(self, coin, method):\n logger.debug('Starting Queue object.')\n self.queue = conf.get('service').get(method).get('queue').get(coin)\n self.host = conf.get('service').get('host_queue')\n self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host))\n self.channel = self.connection.channel()\n\n def prepare(self):\n self.channel.queue_declare(queue=self.queue, durable='true')\n\n def send(self, message) -> None:\n\n self.channel.basic_publish(exchange='',\n routing_key=self.queue,\n body=json.dumps(message),\n properties=pika.BasicProperties(delivery_mode=2))\n\n print(\"message sended\")\n","sub_path":"src/service/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"458306457","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 16 20:26:24 2020\r\n\r\n@author: shrey\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport time\r\n\r\nfilePath = input(\"Please provide the path of the file: \")\r\n\r\nstart_time = time.time()\r\n\r\ntransactions = pd.read_csv(filePath, header=None, delimiter=',', engine='python', names=range(100))\r\ntransactions = transactions.where((pd.notnull(transactions)), None)\r\n\r\ntransactionItemMatrix = \\\r\n pd.get_dummies(transactions.unstack().dropna()).groupby(level=1).sum()\r\ntransactionCnt, itemCnt = transactionItemMatrix.shape\r\nprint('The number of transactions in the dataset are: ',transactionCnt)\r\nprint('The number of different items in the dataset are: ',itemCnt,'\\n')\r\n\r\nlargeItemsets = []\r\nfor items in range(1, itemCnt+1):\r\n from itertools import combinations\r\n for itemset in combinations(transactionItemMatrix, items):\r\n itemsetSupport = transactionItemMatrix[list(itemset)].all(axis=1).sum()\r\n s = [str(x) for x in itemset]\r\n if (len(s) >= 1):\r\n largeItemsets.append([\",\".join(s), itemsetSupport])\r\nfreqItemset = pd.DataFrame(largeItemsets, columns=[\"Itemset\", \"Support\"])\r\nresults = freqItemset[freqItemset.Support >= 2]\r\nprint(results)\r\n\r\n\r\ndataFile = open('output.txt', 'w')\r\n\r\nfor eachitem in largeItemsets:\r\n dataFile.write(str(eachitem)+'\\n')\r\ndataFile.close()\r\n\r\nprint(\"--- %s seconds ---\" % (time.time() - start_time))","sub_path":"BruteForce.py","file_name":"BruteForce.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"117866919","text":"#!/usr/bin/env python\n# coding: utf-8\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport gc\nimport datetime\nfrom PIL import Image\nfrom SSIM_PIL import compare_ssim\n\n# Helper functions for the network\ndef conv_layer(tensor_in, name_layer, is_training):\n x = tf.layers.conv2d(\n inputs = tensor_in,\n filters = 64,\n kernel_size = [3, 3],\n padding = \"same\",\n kernel_initializer=tf.truncated_normal_initializer(stddev=(2 / (9.0 * 64)) ** 0.5),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-6),\n activation= None,\n name = name_layer,\n use_bias=False)\n \n x = tf.layers.batch_normalization(x, name = name_layer + \"_bn\",\n center=True, \n scale=True, \n training=is_training)\n \n return tf.nn.relu(x, name = name_layer + \"_relu\")\n# Definition of the NN\ndef AutoEncoder_model(features, labels, mode):\n # Input Layer\n input_layer = features['x']\n \n # Convolutional layer #1 \n conv1 = tf.layers.conv2d(\n inputs = input_layer,\n filters = 64,\n kernel_size = 3,\n padding = \"same\",\n activation= tf.nn.relu,\n name = \"Conv_1\")\n is_training_mode = (mode == tf.estimator.ModeKeys.TRAIN)\n \n # 18 of the middle layers with Convolution, batch normalization and afterwards ReLu\n conv2 = conv_layer(conv1, \"conv2\", is_training = is_training_mode)\n conv3 = conv_layer(conv2, \"conv3\", is_training = is_training_mode)\n conv4 = conv_layer(conv3, \"conv4\", is_training = is_training_mode)\n conv5 = conv_layer(conv4, \"conv5\", is_training = is_training_mode)\n conv6 = conv_layer(conv5, \"conv6\", is_training = is_training_mode)\n conv7 = conv_layer(conv6, \"conv7\", is_training = is_training_mode)\n conv8 = conv_layer(conv7, \"conv8\", is_training = is_training_mode)\n conv9 = conv_layer(conv8, \"conv9\", is_training = is_training_mode)\n conv10 = conv_layer(conv9, \"conv10\", is_training = is_training_mode)\n conv11 = conv_layer(conv10, \"conv11\", is_training = is_training_mode)\n conv12 = conv_layer(conv11, \"conv12\", is_training = is_training_mode)\n conv13 = conv_layer(conv12, \"conv13\", is_training = is_training_mode)\n conv14 = conv_layer(conv13, \"conv14\", is_training = is_training_mode)\n conv15 = conv_layer(conv14, \"conv15\", is_training = is_training_mode)\n conv16 = conv_layer(conv15, \"conv16\", is_training = is_training_mode)\n conv17 = conv_layer(conv16, \"conv17\", is_training = is_training_mode)\n conv18 = conv_layer(conv17, \"conv18\", is_training = is_training_mode)\n conv19 = conv_layer(conv18, \"conv19\", is_training = is_training_mode)\n\n # final \n final_layer = tf.layers.conv2d(\n inputs = conv19,\n filters = 1,\n kernel_size = [1, 1],\n padding = \"same\",\n activation = None,\n name = \"final_layer\") + input_layer\n \n \n if not (mode == tf.estimator.ModeKeys.PREDICT):\n # Output all learnable variables for tensorboard\n for var in tf.trainable_variables():\n name = var.name\n name = name.replace(':', '_')\n tf.summary.histogram(name, var)\n merged_summary = tf.summary.merge_all()\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n tf.summary.image(\"Input_Image\", input_layer, max_outputs = 1)\n tf.summary.image(\"Output_Image\", final_layer, max_outputs = 1)\n tf.summary.image(\"True_Image\", labels, max_outputs = 1)\n tf.summary.histogram(\"Summary_final_layer\", final_layer)\n tf.summary.histogram(\"Summary_labels\", labels)\n \n # Give output in prediction mode\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode = mode, predictions=final_layer)\n \n\n # Calculate Loss (for both Train and EVAL modes)\n # See that the residual learning is implemented here.\n loss = tf.losses.mean_squared_error(labels = labels , predictions = final_layer)\n tf.summary.scalar(\"Value_Loss_Function\", loss)\n \n # Configure Learning when training.\n if mode == tf.estimator.ModeKeys.TRAIN:\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n original_optimizer = tf.train.AdamOptimizer(learning_rate = 0.003)\n optimizer = tf.contrib.estimator.clip_gradients_by_norm(original_optimizer, clip_norm=5.0)\n train_op = optimizer.minimize(loss = loss, global_step=tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n \n# Running Specification\nrunconf = tf.estimator.RunConfig(save_summary_steps=5, log_step_count_steps = 10)\n\nAutoEncoder = tf.estimator.Estimator(config=runconf,\n model_fn=AutoEncoder_model, model_dir=\"/scratch2/ttoebro/models/DnCNN_V5_V2\")\n\n# Evalutation\n# Evaluate on rad_41\n# Load Data\nX = np.load('/scratch2/ttoebro/data/X_test_rad41.npy')\nY = np.load('/scratch2/ttoebro/data/Y_test_rad41.npy')\n\n# Evaluate the model and print results\npredict_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": X[:,:,:,:]},\n y=Y[:,:,:,:],\n batch_size = 1,\n shuffle=False)\npredict_results = AutoEncoder.predict(input_fn=predict_input_fn)\n\nsum_mae_rad41 = 0\nsum_mse_rad41 = 0\nsum_ssim_rad41 = 0\n\nfor im_num in range(0, Y.shape[0]):\n prediction = next(predict_results)\n true_image = Y[im_num,:,:,:]\n sum_mae_rad41 += np.mean(np.abs(prediction - true_image))\n sum_mse_rad41 += np.mean(np.power((prediction - true_image), 2))\n sum_ssim_rad41 += compare_ssim(Image.fromarray((prediction[:,:,0] * 255).astype('uint8'), 'L'),\n Image.fromarray((true_image[:,:,0] * 255).astype('uint8'), 'L'))\n if(im_num % 10000 == 0):\n print(\"Current mae is \" + str(sum_mae_rad41) + \" and mse is \" + str(sum_mse_rad41) + \" and ssim is \" + str(sum_ssim_rad41) + \" at picture \" + str(im_num))\n\nsum_mae_rad41 /= X.shape[0]\nsum_mse_rad41 /= X.shape[0]\nsum_ssim_rad41 /= X.shape[0]\n\n# Evaluate on rad_15\nX = np.load('/scratch2/ttoebro/data/X_test_rad_15.npy')\nY = np.load('/scratch2/ttoebro/data/Y_test_rad_15.npy')\n\n# Evaluate the model and print results\npredict_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": X[:,:,:,:]},\n y=Y[:,:,:,:],\n batch_size = 1,\n shuffle=False)\npredict_results = AutoEncoder.predict(input_fn=predict_input_fn)\n\nsum_mae_rad15 = 0\nsum_mse_rad15 = 0\nsum_ssim_rad15 = 0\n\nfor im_num in range(0, Y.shape[0]):\n prediction = next(predict_results)\n true_image = Y[im_num,:,:,:]\n sum_mae_rad15 += np.mean(np.abs(prediction - true_image))\n sum_mse_rad15 += np.mean(np.power((prediction - true_image), 2))\n sum_ssim_rad15 += compare_ssim(Image.fromarray((prediction[:,:,0] * 255).astype('uint8'), 'L'),\n Image.fromarray((true_image[:,:,0] * 255).astype('uint8'), 'L'))\n if(im_num % 10000 == 0):\n print(\"Current mae is \" + str(sum_mae_rad15) + \" and mse is \" + str(sum_mse_rad15) + \" and ssim is \" + str(sum_ssim_rad15) + \" at picture \" + str(im_num))\n\nsum_mae_rad15 /= X.shape[0]\nsum_mse_rad15 /= X.shape[0]\nsum_ssim_rad15 /= X.shape[0]\n\n# Evaluate on Pois\nX = np.load('/scratch2/ttoebro/data/X_test_pois_1_9.npy')\nY = np.load('/scratch2/ttoebro/data/Y_test_pois_1_9.npy')\n\n# Evaluate the model and print results\npredict_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": X[:,:,:,:]},\n y=Y[:,:,:,:],\n batch_size = 1,\n shuffle=False)\npredict_results = AutoEncoder.predict(input_fn=predict_input_fn)\n\nsum_mae_pois_1_9 = 0\nsum_mse_pois_1_9 = 0\nsum_ssim_pois_1_9= 0\n\nfor im_num in range(0, Y.shape[0]):\n prediction = next(predict_results)\n true_image = Y[im_num,:,:,:]\n sum_mae_pois_1_9 += np.mean(np.abs(prediction - true_image))\n sum_mse_pois_1_9 += np.mean(np.power((prediction - true_image), 2))\n sum_ssim_pois_1_9 += compare_ssim(Image.fromarray((prediction[:,:,0] * 255).astype('uint8'), 'L'),\n Image.fromarray((true_image[:,:,0] * 255).astype('uint8'), 'L'))\n if(im_num % 10000 == 0):\n print(\"Current mae is \" + str(sum_mae_pois_1_9) + \" and mse is \" + str(sum_mse_pois_1_9) + \" and ssim is \" + str(sum_ssim_pois_1_9) + \" at picture \" + str(im_num))\n\nsum_mae_pois_1_9 /= X.shape[0]\nsum_mse_pois_1_9 /= X.shape[0]\nsum_ssim_pois_1_9 /= X.shape[0]\n\ndic_data_frame = {'MAE' : [sum_mae_rad41, sum_mae_rad15, sum_mae_pois_1_9],\n 'MSE' : [sum_mse_rad41, sum_mse_rad15, sum_mse_pois_1_9],\n 'SSIM' : [sum_ssim_rad41, sum_ssim_rad15, sum_ssim_pois_1_9]}\n\nresult = pd.DataFrame(dic_data_frame, index=['Rad_41', 'Rad_15', 'pois_1_9'])\n\nresult.to_csv('/scratch2/ttoebro/results/DnCNN_V5_V2')","sub_path":"Evaluation/DnCNN_V5_V2_evaluation.py","file_name":"DnCNN_V5_V2_evaluation.py","file_ext":"py","file_size_in_byte":8803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"552448230","text":"# Copyright 2015 Google Inc. 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\"\"\"Test data for rfmt tool (c.f. rfmt_test.py).\"\"\"\n\nUNFORMATTED_SRC = ('samples <- MCMC2({\\n'\n ' mu.mu.beta.01 <- coef(mle.01) # Hyperparameter'\n 's\\n'\n ' sigma.mu.beta.01 <- 5 * abs(coef(mle.01))\\n'\n ' mu.mu.beta.11 <- coef(mle.11)\\n'\n ' sigma.mu.beta.11 <- 5 * abs(coef(mle.11))\\n'\n '\\n'\n ' # Parent-level parameters\\n'\n ' beta.01 <- matrix(runif(length(i.p.01) * m), l'\n 'ength(i.p.01), m, dimnames = list(names(i.p.01), N'\n 'ULL))\\n'\n ' beta.11 <- matrix(runif(length(i.p.11) * m), l'\n 'ength(i.p.11), m, dimnames = list(names(i.p.11), N'\n 'ULL))\\n'\n ' }, {\\n'\n ' # Sample parent-level variates\\n'\n ' for (p in ps) {\\n'\n ' i.01 <- i.p.01[[p]]\\n'\n ' if (length(i.01)) {\\n'\n ' x.tn.01.p <- x.tn.01[i.01, , drop = FALSE]'\n '\\n'\n ' mu.01 <- drop(x.tn.01.p %*% beta.01[p, ])\\n'\n ' pbt.01 <- rtnorm(length(i.01), mu.01, 1, l'\n 'o = pbt.01.lo[i.01], hi = pbt.01.hi[i.01])\\n'\n ' beta.01[p, ] <- SampleLRPosteriorCoefficie'\n 'nts(pbt.01, x.tn.01.p, 1, mu.beta.01, sigma.beta.0'\n '1)\\n'\n ' }\\n'\n ' i.11 <- i.p.11[[p]]\\n'\n ' if (length(i.11)) {\\n'\n ' x.tn.11.p <- x.tn.11[i.11, , drop = FALSE]'\n '\\n'\n ' mu.11 <- drop(x.tn.11.p %*% beta.11[p, ])\\n'\n ' pbt.11 <- rtnorm(length(i.11), mu.11, 1, l'\n 'o = pbt.11.lo[i.11], hi = pbt.11.hi[i.11])\\n'\n ' beta.11[p, ] <- SampleLRPosteriorCoefficie'\n 'nts(pbt.11, x.tn.11.p, 1, mu.beta.11, sigma.beta.1'\n '1)\\n'\n ' }\\n'\n ' }\\n'\n '\\n'\n ' # Sample population hyperparameters; no correl'\n 'ations at present\\n'\n ' for (i in 1:m) {\\n'\n ' mu.beta.01[i] <- SampleNormalPosteriorMean(b'\n 'eta.01[, i], sigma.beta.01[i], mu.mu.beta.01, sigm'\n 'a.mu.beta.01)\\n'\n ' sigma.beta.01[i] <- SampleNormalPosteriorSD('\n 'beta.01[, i], mu.beta.01[i], .1, 5 * max(sigma.mu.'\n 'beta.01))\\n'\n ' mu.beta.11[i] <- SampleNormalPosteriorMean(b'\n 'eta.11[, i], sigma.beta.11[i], mu.mu.beta.11, sigm'\n 'a.mu.beta.11)\\n'\n ' sigma.beta.11[i] <- SampleNormalPosteriorSD('\n 'beta.11[, i], mu.beta.11[i], .1, 5 * max(sigma.mu.'\n 'beta.11))\\n'\n ' }\\n'\n '\\n'\n ' list(beta.01 = beta.01, beta.11 = beta.11,\\n'\n ' mu.beta.01 = mu.beta.01, sigma.beta.01 = sig'\n 'ma.beta.01,\\n'\n ' mu.beta.11 = mu.beta.11, sigma.beta.11 = sig'\n 'ma.beta.11)\\n'\n ' },\\n'\n ' n.samples = 7000,\\n'\n ' thin = 3\\n'\n ')\\n'\n '\\n')\n\nFORMATTED_SRC = ('samples <- MCMC2(\\n'\n ' {\\n'\n ' mu.mu.beta.01 <- coef(mle.01) # Hyperparame'\n 'ters\\n'\n ' sigma.mu.beta.01 <- 5 * abs(coef(mle.01))\\n'\n ' mu.mu.beta.11 <- coef(mle.11)\\n'\n ' sigma.mu.beta.11 <- 5 * abs(coef(mle.11))\\n'\n '\\n'\n ' # Parent-level parameters\\n'\n ' beta.01 <- matrix(runif(length(i.p.01) * m),'\n ' length(i.p.01), m,\\n'\n ' dimnames = list(names(i.p.'\n '01), NULL))\\n'\n ' beta.11 <- matrix(runif(length(i.p.11) * m),'\n ' length(i.p.11), m,\\n'\n ' dimnames = list(names(i.p.'\n '11), NULL))\\n'\n ' },\\n'\n ' {\\n'\n ' # Sample parent-level variates\\n'\n ' for (p in ps) {\\n'\n ' i.01 <- i.p.01[[p]]\\n'\n ' if (length(i.01)) {\\n'\n ' x.tn.01.p <- x.tn.01[i.01, , drop = FALS'\n 'E]\\n'\n ' mu.01 <- drop(x.tn.01.p %*% beta.01[p, ]'\n ')\\n'\n ' pbt.01 <- rtnorm(length(i.01), mu.01, 1,'\n ' lo = pbt.01.lo[i.01],\\n'\n ' hi = pbt.01.hi[i.01])\\n'\n ' beta.01[p, ] <- SampleLRPosteriorCoeffic'\n 'ients(\\n'\n ' pbt.01, x.tn.01.p, 1, mu.beta.01, si'\n 'gma.beta.01)\\n'\n ' }\\n'\n ' i.11 <- i.p.11[[p]]\\n'\n ' if (length(i.11)) {\\n'\n ' x.tn.11.p <- x.tn.11[i.11, , drop = FALS'\n 'E]\\n'\n ' mu.11 <- drop(x.tn.11.p %*% beta.11[p, ]'\n ')\\n'\n ' pbt.11 <- rtnorm(length(i.11), mu.11, 1,'\n ' lo = pbt.11.lo[i.11],\\n'\n ' hi = pbt.11.hi[i.11])\\n'\n ' beta.11[p, ] <- SampleLRPosteriorCoeffic'\n 'ients(\\n'\n ' pbt.11, x.tn.11.p, 1, mu.beta.11, si'\n 'gma.beta.11)\\n'\n ' }\\n'\n ' }\\n'\n '\\n'\n ' # Sample population hyperparameters; no corr'\n 'elations at present\\n'\n ' for (i in 1:m) {\\n'\n ' mu.beta.01[i] <- SampleNormalPosteriorMean'\n '(\\n'\n ' beta.01[, i], sigma.beta.01[i], mu.mu.'\n 'beta.01, sigma.mu.beta.01)\\n'\n ' sigma.beta.01[i] <- SampleNormalPosteriorS'\n 'D(\\n'\n ' beta.01[, i], mu.beta.01[i], .1, 5 * m'\n 'ax(sigma.mu.beta.01))\\n'\n ' mu.beta.11[i] <- SampleNormalPosteriorMean'\n '(\\n'\n ' beta.11[, i], sigma.beta.11[i], mu.mu.'\n 'beta.11, sigma.mu.beta.11)\\n'\n ' sigma.beta.11[i] <- SampleNormalPosteriorS'\n 'D(\\n'\n ' beta.11[, i], mu.beta.11[i], .1, 5 * m'\n 'ax(sigma.mu.beta.11))\\n'\n ' }\\n'\n '\\n'\n ' list(beta.01 = beta.01, beta.11 = beta.11, m'\n 'u.beta.01 = mu.beta.01,\\n'\n ' sigma.beta.01 = sigma.beta.01, mu.beta.'\n '11 = mu.beta.11,\\n'\n ' sigma.beta.11 = sigma.beta.11)\\n'\n ' },\\n'\n ' n.samples = 7000,\\n'\n ' thin = 3)\\n')\n","sub_path":"rfmt_test_data.py","file_name":"rfmt_test_data.py","file_ext":"py","file_size_in_byte":8084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"163716189","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 12 13:47:07 2019\n\n@author: clhu\n\"\"\"\nfrom flask import Flask\nfrom flask import request, abort, jsonify\nimport requests\nimport yaml\nimport json\n\nimport io\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\napp = Flask(__name__)\n\n\ndef handler(event, context):\n \"\"\"\n @event: dict\n @context: dict\n return: string\n \"\"\"\n print(\"entering handler....\", event, context)\n rules = yaml.load(io.open('rule.yaml', encoding='utf8'))\n\n event_id = event.get('event_id')\n channel_id = 0\n for recipe in rules.get('events'):\n if recipe.get('event_id') == event_id:\n channel_id = recipe.get(\"channel_id\")\n break\n if not channel_id:\n return \"error event id\"\n\n find, host, port, url = False, None, None, None\n for channel in rules.get(\"channels\"):\n if channel.get(\"uuid\") == channel_id:\n find, host, port, url = True, channel.get(\"host\"), channel.get(\"port\"), channel.get(\"url\")\n if not find:\n return \"error channel id...not register\"\n\n headers = {'Content-Type': \"application/json\"}\n data = {\"event\":event, \"context\": context}\n ret = requests.post(\"http://{}:{}{}\".format(host, port, url), data=json.dumps(data), headers=headers)\n\n print(\"exit handler....\", ret.content)\n return ret.content\n\n@app.route(\"/ping\", methods=[\"GET\", \"POST\"])\ndef ifttt_test():\n print(\"enter test...\")\n print(request)\n print(\"exit test...\")\n return json.dumps(request.json if request.json else {\"status\":\"200\"}, ensure_ascii=False)\n\n@app.route('/', methods=[\"POST\", \"GET\"])\ndef ifttt_simulator():\n print(\"enter ifttt...\", request.json)\n\n if \"event\" not in request.json or \"context\" not in request.json:\n abort(400)\n ret = handler(request.json.get(\"event\"), request.json.get(\"context\"))\n\n print(\"exit ifttt...\", ret)\n if type(ret)==str:\n return ret\n ret = {\"return_message\": json.loads(ret)} if ret else {\"return_message\": \"\"}\n return json.dumps(ret,ensure_ascii=False)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=3000, debug=True)\n","sub_path":"IFTTT/ifttt_simulator.py","file_name":"ifttt_simulator.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"16488528","text":"# coding=\"utf-8\"\n#\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport random\n#\n# plt.figure(figsize=(20, 6), dpi=90)\n# x = range(2, 26, 2)\n# y = [15, 13, 14.5, 17, 20, 25, 26, 26, 24, 22, 18, 15]\n# plt.plot(x, y)\n# xtick_label=[i/2 for i in range(4,49)]\n# plt.xticks(xtick_label)\n# plt.yticks(range(min(y),max(y)+1))\n# # plt.\n# plt.savefig(\"./pic1.png\")\n# plt.show()\n#\n# # --------------------------------------------------------------------------------------------\n# import matplotlib\n# from matplotlib import pyplot as plt\n# import random\n# ##########################改变字体为中文\nfrom matplotlib import rc\n\nfont = {'family': 'MicroSoft YaHei',\n 'weight': 'bold',\n 'size': 15}\nmatplotlib.rc(\"font\", **font)\n#######################################\n# x = range(0, 120)\n# y = [random.randint(20, 35) for i in range(120)]\n# y2=[random.randint(20, 30) for i in range(60)]\n# y2+=[random.randint(30, 35) for i in range(60)]\n#\n# plt.figure(figsize=(20, 4), dpi=90)\n#\n# plt.plot(x, y,label=\"南阳\",color=\"r\",linestyle=\"--\")\n# plt.plot(x,y2,label=\"郑州\")\n#\n# _xtick_labels = [\"10点{}分\".format(i) for i in range(60)]\n# _xtick_labels += [\"11点{}分\".format(i) for i in range(60)]\n# plt.xticks(list(x)[::10], _xtick_labels[::10], rotation=270)\n#\n# plt.xlabel(\"时间\")\n# plt.ylabel(\"温度\")\n# plt.title(\"10-12点温度变化\")\n#\n# plt.grid()\n# plt.legend()#显示图例\n# plt.show()\n\n#\n# # 散点图\n# y_3 = [random.randint(10, 20) for i in range(31)]\n# y_10 = [random.randint(15, 25) for i in range(31)]\n# x = range(1, 32)\n# x1 = range(50, 81)\n# plt.scatter(x, y_3)\n# plt.scatter(x1, y_10)\n# plt.show()\n#\n# # 条形图\n# plt.figure(figsize=(20,8),dpi=90)\n# x = [\"战狼\", \"速度与激情8\", \"西游伏魔\", \"变形金刚5\", \"摔跤吧爸爸\", \"加勒比海盗\", \"盗梦空间\", \"荒野猎人\", \"泰囧\"]\n# y = [51.7, 27.6, 20.3, 18.3, 24.5, 15.8, 29.3, 10.9, 7.8]\n# plt.bar(x,y,width=0.3)\n# plt.xticks(range(len(x)),x,rotation=45)\n# plt.xlabel(\"电影名\")\n# plt.ylabel('票房')\n# plt.title(\"内地票房前九\")\n# plt.show()\n\n\n# # 垂直多条形图\n# plt.figure(figsize=(20, 8), dpi=90)\n# x = [\"战狼\", \"速度与激情8\", \"西游伏魔\", \"变形金刚5\", \"摔跤吧爸爸\", \"加勒比海盗\", \"盗梦空间\", \"荒野猎人\", \"泰囧\"]\n# y_14 = [21.7, 17.6, 10.3, 8.3, 14.5, 15.8, 19.3, 10.9, 7.8]\n# y_15 = [12, 13, 3, 4, 13, 3, 7, 8, 3]\n# y_16 = [9, 3, 4, 2.3, 3.4, 5, 3, 1, 2.3]\n#\n# format=0.3\n# x_14=list(range(len(x)))\n# x_15=[i+format for i in range(len(x))]\n# x_16=[i+2*format for i in range(len(x))]\n#\n# plt.barh(x, y_14, height=0.3,label=\"九月14日\")\n# plt.barh(x_15, y_15, height=0.3,label=\"九月15日\")\n# plt.barh(x_16, y_16, height=0.3,label=\"九月16日\")\n#\n# plt.legend()\n# plt.ylabel(\"电影名\")\n# plt.xlabel('票房')\n# plt.yticks(x_15,x)\n# plt.title(\"内地票房前九\")\n# plt.show()\n\n# #直方图\n# plt.figure(figsize=(20,8),dpi=90)\n# x=[random.randint(78,150) for i in range(250)]\n# d=3#组距\n# bar_width=((max(x)-min(x))//d)\n# print(bar_width)\n# plt.hist(x,bar_width)\n#\n# plt.xticks(range(min(x),max(x)+d,d))\n# plt.grid()\n# plt.show()\n\n\nplt.figure(figsize=(20, 8), dpi=90)\ninterval = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 60, 90]\nwidth=[5,5,5,5,5,5,5,5,5,15,30,60]\nquantity=[836,2737,3723,3926,3596,1438,3723,642,824,613,215,57]\n\nplt.bar(range(12),quantity,width=1)\n\n_x=[i-0.5 for i in range(13)]\ninterval+=[150]\nplt.xticks(_x,interval)\nplt.show()\n\n\n\n","sub_path":"pythonfiles/matplotlib_demo.py","file_name":"matplotlib_demo.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"94687513","text":"from django.urls import path\nfrom .views import (\n post_list_and_create,\n load_post_data_view,\n hello_world_view,\n like_unlike_post,\n)\n\napp_name = 'posts'\n\nurlpatterns = [\n path('',post_list_and_create, name='main-board'),\n path('like-unlike/', like_unlike_post, name='like-unlike'),\n path('data//', load_post_data_view, name='posts-data'),\n path('hello-world/',hello_world_view, name='hello-world'),\n]","sub_path":"src/posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"9677118","text":"import sys\nimport Tkinter as GUI\nimport tkMessageBox\nimport pickle\nimport AI\nimport file\n\ndef startGame(settings, restart, code, load, loadData):\n\tdef drawInterface():\n\t\tguesses = settings[\"guesses\"]\n\t\tcolourNo = settings[\"colours\"]\n\t\tpegNo = settings[\"pegs\"]\n\t\tcolourList = settings[\"colourList\"]\n\t\t\n\t\t# Draw interface frame layout\n\t\t#================================================\n\t\tframe = GUI.Frame(gameScr, relief=GUI.RAISED, borderwidth=1, bg=\"white\")\n\t\tframe.pack(fill=GUI.BOTH, expand=1)\n\t\t\n\t\t# Draw game board\n\t\t#================================================\n\t\thintWidth = 8 + int((pegNo + 1) / 2) * 12\n\t\tgridWidth = 50 * pegNo + hintWidth\n\t\tcvsGrid = GUI.Canvas(frame, width=gridWidth, height=((guesses + 1) * 50 + guesses), bg=\"white\")\n\t\tcvsGrid.pack(side=GUI.RIGHT)\n\t\tgridPegs = []\n\t\thintPegs = []\n\t\trow = 0\n\t\twhile row < guesses + 1:\n\t\t\tgridPegs.append([])\n\t\t\thintPegs.append([])\n\t\t\tcol = 0\n\t\t\twhile col < pegNo:\n\t\t\t\n\t\t\t\t# Draw rows of pegs\n\t\t\t\t#================================================\n\t\t\t\txPos = 50 * col + 3\n\t\t\t\tyPos = 50 * row + row + 3\n\t\t\t\tgridPegs[row].append(cvsGrid.create_oval(xPos, yPos, xPos + 44, yPos + 44, fill=\"black\"))\n\t\t\t\t\n\t\t\t\t# Draw hint pegs\n\t\t\t\t#================================================\n\t\t\t\tif row < guesses:\n\t\t\t\t\thintX = 50 * pegNo + 6 + int(col / 2) * 12\n\t\t\t\t\tif col % 2 == 0:\n\t\t\t\t\t\thintY = 50 * row + 15 + row\n\t\t\t\t\telse:\n\t\t\t\t\t\thintY = 50 * row + 27 + row\n\t\t\t\t\thintPegs[row].append(cvsGrid.create_oval(hintX, hintY, hintX + 8, hintY + 8, fill=\"black\"))\n\t\t\t\t\t\n\t\t\t\t# Separate rows with lines\n\t\t\t\t#================================================\n\t\t\t\tif row != 0:\n\t\t\t\t\tcvsGrid.create_line(0, yPos - 3, gridWidth, yPos - 3)\n\t\t\t\tcol += 1\n\t\t\trow += 1\n\t\t\n\t\t# Draw common interface buttons\n\t\t#================================================\n\t\tbtnQuit = GUI.Button(gameScr, text=\"Quit Game\", fg=\"red\", command=quitGame)\n\t\tbtnQuit.pack(side=GUI.RIGHT)\n\t\tbtnMenu = GUI.Button(gameScr, text=\"Back to Menu\", command=openMenu)\n\t\tbtnMenu.pack(side=GUI.RIGHT)\n\t\tbtnRestart = GUI.Button(gameScr, text=\"Restart Game\", command=restartGame)\n\t\tbtnRestart.pack(side=GUI.RIGHT)\n\t\tbtnNew = GUI.Button(gameScr, text=\"New Game\", command=newGame)\n\t\tbtnNew.pack(side=GUI.RIGHT)\n\t\t\n\t\t# Draw human codebreaker buttons\n\t\t#================================================\n\t\tif settings[\"mode\"] == 1:\n\t\t\tfor i in range(0, colourNo):\n\t\t\t\tbtnColour = GUI.Button(frame, text=colourList[i], bg=colourList[i], width=12, height=5, command=lambda a=colourList[i]: selectPeg(a))\n\t\t\t\tbtnColour.pack(anchor=GUI.W)\n\t\t\tbtnDel = GUI.Button(frame, text=\"Undo\", width=12, command=undo)\n\t\t\tbtnDel.pack(anchor=GUI.W)\n\t\t\tbtnSave = GUI.Button(gameScr, text=\"Save Game\", command=lambda a=settings, b=gameEnded: file.saveGame(a, b))\n\t\t\tbtnSave.pack(side=GUI.RIGHT)\n\t\t\n\t\t# Draw CPU codebreaker buttons\n\t\t#================================================\n\t\tif settings[\"mode\"] == 2:\n\t\t\tbtnAI = GUI.Button(gameScr, text=\"Start AI\", fg=\"blue\", command=lambda a=settings, b=GUI, c=gameScr, d=gameEnded, e=selectPeg: AI.startAI(a, b, c, d, e))\n\t\t\tbtnAI.pack(side=GUI.RIGHT)\n\t\t\n\t\t# Set up canvas objects for manipulation\n\t\t#================================================\n\t\tsettings[\"grid\"] = gridPegs\n\t\tsettings[\"hints\"] = hintPegs\n\t\tsettings[\"canvas\"] = cvsGrid\n\t\t\n\t\t# Resume a loaded game\n\t\t#================================================\n\t\tif load == True:\n\t\t\tloadGrid = loadData[0]\n\t\t\tloadHints = loadData[1]\n\t\t\tfor row in range(0, settings[\"guesses\"]):\n\t\t\t\tfor col in range(0, settings[\"pegs\"]):\n\t\t\t\t\tsettings[\"canvas\"].itemconfig(settings[\"grid\"][row][col], fill=loadGrid[row][col])\n\t\t\t\t\tsettings[\"canvas\"].itemconfig(settings[\"hints\"][row][col], fill=loadHints[row][col])\n\t\t\n\tdef quitGame():\n\t\tif tkMessageBox.askyesno(\"Quit\", \"Are you sure you want to quit this game?\"):\n\t\t\tsys.exit()\n\t\t\t\n\tdef restartGame():\n\t\tif not settings[\"AIstarted\"]:\n\t\t\tif tkMessageBox.askyesno(\"Restart\", \"Are you sure you want to restart this game?\"):\n\t\t\t\tsettings[\"restart\"] = True\n\t\t\t\tgameScr.destroy()\n\t\telse:\n\t\t\ttkMessageBox.showinfo(\"Start AI\", \"Please wait for the AI to finish guessing.\")\n\t\t\t\n\tdef newGame():\n\t\tif not settings[\"AIstarted\"]:\n\t\t\tif tkMessageBox.askyesno(\"New\", \"Are you sure you want to start a new game?\"):\n\t\t\t\tgameScr.destroy()\n\t\telse:\n\t\t\ttkMessageBox.showinfo(\"Start AI\", \"Please wait for the AI to finish guessing.\")\t\n\tdef undo():\n\t\tif not gameEnded() and not settings[\"col\"] == 0:\n\t\t\tcanvas = settings[\"canvas\"]\n\t\t\trow = settings[\"row\"]\n\t\t\tcol = settings[\"col\"] - 1\n\t\t\tif col >= 0:\n\t\t\t\tcanvas.itemconfig(settings[\"grid\"][row][col], fill=\"black\")\n\t\t\t\tsettings[\"col\"] -= 1\n\t\telif gameEnded():\n\t\t\ttkMessageBox.showinfo(\"Undo\", \"You can't undo once the game has ended.\")\n\t\telif settings[\"col\"] == 0 and settings[\"row\"] == 0:\n\t\t\ttkMessageBox.showinfo(\"Undo\", \"There is nothing to undo!\")\n\t\telse:\n\t\t\ttkMessageBox.showinfo(\"Undo\", \"You can't undo a finished guess, that's cheating!\")\n\t\t\t\n\tdef selectPeg(pegColour):\n\t\tcanvas = settings[\"canvas\"]\n\t\tif not gameEnded():\n\t\t\trow = settings[\"row\"]\n\t\t\tcol = settings[\"col\"]\n\t\t\tcanvas.itemconfig(settings[\"grid\"][row][col], fill=pegColour)\n\t\t\tsettings[\"col\"] += 1\n\t\t\tif settings[\"col\"] == settings[\"pegs\"]: # If the row has been filled\n\t\t\t\tcorrect = checkRow()\n\t\t\t\tif correct == False:\n\t\t\t\t\tsettings[\"row\"] += 1\n\t\t\t\t\tsettings[\"col\"] = 0\n\t\t\t\telse:\n\t\t\t\t\tendGame(True)\n\t\telse:\n\t\t\ttkMessageBox.showinfo(\"Game Over\", \"You have already guessed the code.\")\n\t\tif settings[\"row\"] == settings[\"guesses\"]:\n\t\t\tendGame(False)\n\t\t\treturn\n\t\t\n\tdef gameEnded():\n\t\tcanvas = settings[\"canvas\"]\n\t\tif canvas.itemcget(settings[\"grid\"][settings[\"guesses\"]][0], \"fill\") == \"black\" and settings[\"row\"] != settings[\"guesses\"]: # If the game is still going\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\t\t\n\tdef checkRow():\n\t\trowNo = settings[\"row\"]\n\t\tcanvas = settings[\"canvas\"]\n\t\tcorrect = True\n\t\thints = []\n\t\tcode = settings[\"code\"][:]\n\t\t\n\t\t# First, check correct positions\n\t\t#================================================\n\t\tp = 0\n\t\twhile p < settings[\"pegs\"]:\n\t\t\tpegColour = canvas.itemcget(settings[\"grid\"][rowNo][p], \"fill\")\n\t\t\tif pegColour == settings[\"code\"][p]:\n\t\t\t\thints.append(0) # 0 means colour is in correct position\n\t\t\t\tcode[p] = \"used\" # Set the colour to used so we don't use it for hints again\n\t\t\telse:\n\t\t\t\tcorrect = False\n\t\t\tp += 1\n\t\t\t\n\t\t# Next, check correct colours in wrong positions\n\t\t#================================================\n\t\tp = 0\n\t\twhile p < settings[\"pegs\"]:\n\t\t\tpegColour = canvas.itemcget(settings[\"grid\"][rowNo][p], \"fill\")\n\t\t\tif pegColour in code and pegColour != settings[\"code\"][p]:\n\t\t\t\thints.append(1) # 1 means colour exists but is not in correct position\n\t\t\t\ti = 0\n\t\t\t\twhile i < settings[\"pegs\"]:\n\t\t\t\t\tif code[i] == pegColour:\n\t\t\t\t\t\tcode[i] = \"used\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\ti += 1\n\t\t\tp += 1\n\t\thints.sort()\n\t\t\n\t\t# Fill in the hint pegs\n\t\t#================================================\n\t\th = 0\n\t\twhile h < len(hints):\n\t\t\tif hints[h] == 0:\n\t\t\t\tcanvas.itemconfig(settings[\"hints\"][rowNo][h], fill=\"red\")\n\t\t\telif hints[h] == 1:\n\t\t\t\tcanvas.itemconfig(settings[\"hints\"][rowNo][h], fill=\"white\")\n\t\t\th += 1\n\t\treturn correct\n\t\t\n\tdef endGame(win):\n\t\tcanvas = settings[\"canvas\"]\n\t\tcode = settings[\"code\"]\n\t\tp = 0\n\t\twhile p < settings[\"pegs\"]:\n\t\t\tcanvas.itemconfig(settings[\"grid\"][settings[\"guesses\"]][p], fill=code[p])\n\t\t\tp += 1\n\t\tif win == True:\n\t\t\ttkMessageBox.showinfo(\"Win\", \"Congratulations, you found the code in \" + str(settings[\"row\"] + 1) + \" guesses!\")\n\t\telse:\n\t\t\ttkMessageBox.showinfo(\"Lose\", \"Sorry, you've used all of your \" + str(settings[\"guesses\"]) + \" guesses!\")\n\t\n\tdef openMenu():\n\t\tif not settings[\"AIstarted\"]:\n\t\t\tif tkMessageBox.askyesno(\"Menu\", \"Are you sure you want to leave this game and return to the menu?\"):\n\t\t\t\tsettings[\"menu\"] = True\n\t\t\t\tgameScr.destroy()\n\t\telse:\n\t\t\ttkMessageBox.showinfo(\"Start AI\", \"Please wait for the AI to finish guessing.\")\n\t\n\t# Set up variables\n\t#====================================================\n\tsettings[\"colourList\"] = [\"red\", \"green\", \"blue\", \"yellow\", \"purple\", \"orange\", \"pink\", \"white\"]\n\tsettings[\"guesses\"] = 12\n\tsettings[\"restart\"] = False\n\tsettings[\"menu\"] = False\n\tsettings[\"AIstarted\"] = False\n\tif load == False:\n\t\tsettings[\"row\"] = 0\n\t\tsettings[\"col\"] = 0\n\t\n\t# Draw interface\n\t#====================================================\n\tgameScr = GUI.Tk()\n\tdrawInterface()\n\t\n\t# Generate/reload the answer\n\t#====================================================\n\tif restart == True:\n\t\tsettings[\"code\"] = code\n\telif load == False:\n\t\tsettings[\"code\"] = AI.codeMaker(settings[\"pegs\"], settings[\"colours\"], settings[\"colourList\"])\n\t\n\tgameScr.mainloop()\n\t\n\t# Return instructions for menu when game is stopped\n\t#================================================\n\treturn (settings[\"restart\"], settings[\"code\"], settings[\"menu\"])","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":8727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"135652998","text":"# coding: utf-8\n\"\"\"\ntrainings app helpers\n\"\"\"\nfrom django.utils.translation import gettext as _\nfrom core.helpers import BaseEnum\n\n\nclass TrainingMoodsEnum(BaseEnum):\n \"\"\"\n training moods enumeration\n \"\"\"\n AWESOME, GOOD, BAD, INJURY = range(0, 4)\n values = {\n AWESOME: _(u'awesome').title(),\n GOOD: _(u'good').title(),\n BAD: _(u'bad').title(),\n INJURY: _(u'injury').title()\n }","sub_path":"fitness/domain/trainings/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"188246784","text":"# Create a method that find the 5 most common lottery numbers otos.csv\nimport csv\n\ncsv_file = open('otos.csv', 'r')\ncontent = csv.reader(csv_file, delimiter=';')\nnum_list = []\nlast_five_slice = slice(-5, None)\n\n\ndef all_lottery_numbers():\n for row in content:\n for num in row[last_five_slice]:\n num_list.append(num)\n return num_list\n\n\ndef five_most_frequented_numbers():\n all_lottery_numbers()\n counted = {}\n for num in num_list:\n if num in counted:\n counted[num] += 1\n else:\n counted[num] = 0\n result = [(key, counted[key]) for key in sorted(counted, key=counted.get, reverse=True)][:5]\n return result\n\n\nprint(five_most_frequented_numbers())\n","sub_path":"week-03/day-01/lottery.py","file_name":"lottery.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"388735768","text":"# To use this context manager, we just need to assign objects in a normal way, but when we have to deal with more than one locks, we should use acquire().\n\nimport threading\nfrom deadlock import acquire\n\nx_lock = threading.Lock()\ny_lock = threading.Lock()\n\ndef thread_1():\n\twhile True:\n\t\twith acquire(x_lock, y_lock):\n\t\t\tprint ('Thread-1')\n\ndef thread_2():\n\twhile True:\n\t\twith acquire(y_lock, x_lock):\n\t\t\tprint ('Thread-2')\n\ninput('This program runs forever. Press [return] to start, [ctrl-C] to exit.')\n\nt1 = threading.Thread(target=thread_1)\nt1.daemon = True\nt1.start()\n\nt2 = threading.Thread(target=thread_2)\nt2.daemon = True\nt2.start()\n\nimport time\nwhile True:\n\ttime.sleep(1)\n","sub_path":"12_cocurrency/5_avoid_deadlock/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"639935570","text":"import torch\nfrom torch import Tensor\nfrom collections import deque, defaultdict\nfrom tqdm import tqdm\nfrom .patches import Patches\nfrom .utils import *\nfrom .bound_ops import *\nimport warnings\n\n\ndef batched_backward(\n self, node, C, unstable_idx, batch_size, bound_lower=True,\n bound_upper=True):\n crown_batch_size = self.bound_opts['crown_batch_size']\n unstable_size = get_unstable_size(unstable_idx)\n print(f'Batched CROWN: unstable size {unstable_size}')\n num_batches = (unstable_size + crown_batch_size - 1) // crown_batch_size\n output_shape = node.output_shape[1:]\n dim = int(prod(output_shape))\n ret = []\n for i in tqdm(range(num_batches)):\n if isinstance(unstable_idx, tuple):\n unstable_idx_batch = tuple(\n u[i*crown_batch_size:(i+1)*crown_batch_size]\n for u in unstable_idx\n )\n unstable_size_batch = len(unstable_idx_batch[0])\n else:\n unstable_idx_batch = unstable_idx[i*crown_batch_size:(i+1)*crown_batch_size]\n unstable_size_batch = len(unstable_idx_batch)\n if node.patches_start and node.mode == \"patches\":\n assert C in ['Patches', None]\n C_batch = Patches(shape=[\n unstable_size_batch, batch_size, *node.output_shape[1:-2], 1, 1],\n identity=1, unstable_idx=unstable_idx_batch,\n output_shape=[batch_size, *node.output_shape[1:]])\n elif isinstance(node, BoundLinear) or isinstance(node, BoundMatMul):\n assert C in ['OneHot', None]\n C_batch = OneHotC(\n [batch_size, unstable_size_batch, *node.output_shape[1:]],\n self.device, unstable_idx_batch, None)\n else:\n assert C in ['eye', None]\n C_batch = torch.zeros([1, unstable_size_batch, dim], device=self.device)\n C_batch[0, torch.arange(unstable_size_batch), unstable_idx_batch] = 1.0\n C_batch = C_batch.expand(batch_size, -1, -1).view(\n batch_size, unstable_size_batch, *output_shape)\n ret.append(self.backward_general(\n C=C_batch, node=node,\n bound_lower=bound_lower, bound_upper=bound_upper,\n average_A=False, need_A_only=False, unstable_idx=unstable_idx_batch,\n verbose=False))\n if bound_lower:\n lb = torch.cat([item[0].view(batch_size, -1) for item in ret], dim=1)\n else:\n lb = None\n if bound_upper:\n ub = torch.cat([item[1].view(batch_size, -1) for item in ret], dim=1)\n else:\n ub = None\n return lb, ub\n\n\ndef backward_general(\n self, C, node=None, bound_lower=True, bound_upper=True, average_A=False,\n need_A_only=False, unstable_idx=None, unstable_size=0, update_mask=None, verbose=True):\n if verbose:\n logger.debug(f'Bound backward from {node.__class__.__name__}({node.name})')\n if isinstance(C, str):\n logger.debug(f' C: {C}')\n elif C is not None:\n logger.debug(f' C: shape {C.shape}, type {type(C)}')\n _print_time = False\n\n if isinstance(C, str):\n # If C is a str, use batched CROWN. If batched CROWN is not intended to\n # be enabled, C must be a explicitly provided non-str object for this function.\n if need_A_only or self.return_A or average_A:\n raise ValueError(\n 'Batched CROWN is not compatible with '\n f'need_A_only={need_A_only}, return_A={self.return_A}, '\n f'average_A={average_A}')\n node.lower, node.upper = self.batched_backward(\n node, C, unstable_idx,\n batch_size=self.root[0].value.shape[0],\n bound_lower=bound_lower, bound_upper=bound_upper,\n )\n return node.lower, node.upper\n\n for l in self._modules.values():\n l.lA = l.uA = None\n l.bounded = True\n\n degree_out = get_degrees(node, self.backward_from)\n all_nodes_before = list(degree_out.keys())\n\n C, batch_size, output_dim, output_shape = preprocess_C(C, node)\n\n node.lA = C if bound_lower else None\n node.uA = C if bound_upper else None\n lb = ub = torch.tensor(0., device=self.device)\n\n\n # Save intermediate layer A matrices when required.\n A_record = {}\n\n queue = deque([node])\n while len(queue) > 0:\n l = queue.popleft() # backward from l\n l.bounded = True\n\n if l.name in self.root_name: continue\n\n # if all the succeeds are done, then we can turn to this node in the\n # next iteration.\n for l_pre in l.inputs:\n degree_out[l_pre.name] -= 1\n if degree_out[l_pre.name] == 0:\n queue.append(l_pre)\n\n # Initially, l.lA or l.uA will be set to C for this node.\n if l.lA is not None or l.uA is not None:\n if verbose:\n logger.debug(f' Bound backward to {l}'\n f' (lA shape {l.lA.shape if l.lA is not None else None},'\n f' uA shape {l.uA.shape if l.uA is not None else None},'\n f' out shape {l.output_shape})')\n\n if _print_time:\n start_time = time.time()\n\n if not l.perturbed:\n if not hasattr(l, 'forward_value'):\n self.get_forward_value(l)\n lb, ub = add_constant_node(lb, ub, l)\n continue\n\n if l.zero_uA_mtx and l.zero_lA_mtx:\n # A matrices are all zero, no need to propagate.\n continue\n\n if isinstance(l, BoundRelu):\n # TODO: unify this interface.\n A, lower_b, upper_b = l.bound_backward(\n l.lA, l.uA, *l.inputs, start_node=node, unstable_idx=unstable_idx,\n beta_for_intermediate_layers=self.intermediate_constr is not None)\n elif isinstance(l, BoundOptimizableActivation):\n # For other optimizable activation functions (TODO: unify with ReLU).\n if node.name != self.final_node_name:\n start_shape = node.output_shape[1:]\n else:\n start_shape = C.shape[0]\n A, lower_b, upper_b = l.bound_backward(\n l.lA, l.uA, *l.inputs, start_shape=start_shape, start_node=node)\n else:\n A, lower_b, upper_b = l.bound_backward(l.lA, l.uA, *l.inputs)\n # After propagation through this node, we delete its lA, uA variables.\n if not self.return_A and node.name != self.final_name:\n del l.lA, l.uA\n if _print_time:\n time_elapsed = time.time() - start_time\n if time_elapsed > 1e-3:\n print(l, time_elapsed)\n if lb.ndim > 0 and type(lower_b) == Tensor and self.conv_mode == 'patches':\n lb, ub, lower_b, upper_b = check_patch_biases(lb, ub, lower_b, upper_b)\n lb = lb + lower_b\n ub = ub + upper_b\n if self.return_A and self.needed_A_dict and node.name in self.needed_A_dict:\n # FIXME remove [0][0] and [0][1]?\n if len(self.needed_A_dict[node.name]) == 0 or l.name in self.needed_A_dict[node.name]:\n A_record.update({l.name: {\n \"lA\": A[0][0].transpose(0, 1).detach() if A[0][0] is not None else None,\n \"uA\": A[0][1].transpose(0, 1).detach() if A[0][1] is not None else None,\n # When not used, lb or ub is tensor(0).\n \"lbias\": lb.transpose(0, 1).detach() if lb.ndim > 1 else None,\n \"ubias\": ub.transpose(0, 1).detach() if ub.ndim > 1 else None,\n \"unstable_idx\": unstable_idx\n }})\n # FIXME: solve conflict with the following case\n self.A_dict.update({node.name: A_record})\n if need_A_only and set(self.needed_A_dict[node.name]) == set(A_record.keys()):\n # We have collected all A matrices we need. We can return now!\n self.A_dict.update({node.name: A_record})\n # Do not concretize to save time. We just need the A matrices.\n # return A matrix as a dict: {node.name: [A_lower, A_upper]}\n return None, None, self.A_dict\n\n\n for i, l_pre in enumerate(l.inputs):\n add_bound(l, l_pre, lA=A[i][0], uA=A[i][1])\n\n if lb.ndim >= 2:\n lb = lb.transpose(0, 1)\n if ub.ndim >= 2:\n ub = ub.transpose(0, 1)\n\n if self.return_A and self.needed_A_dict and node.name in self.needed_A_dict:\n save_A_record(\n node, A_record, self.A_dict, self.root, self.needed_A_dict[node.name],\n lb=lb, ub=ub, unstable_idx=unstable_idx)\n\n # TODO merge into `concretize`\n if self.cut_used and getattr(self, 'cut_module', None) is not None and self.cut_module.x_coeffs is not None:\n # propagate input neuron in cut constraints\n self.root[0].lA, self.root[0].uA = self.cut_module.input_cut(\n node, self.root[0].lA, self.root[0].uA, self.root[0].lower.size()[1:], unstable_idx,\n batch_mask=update_mask)\n\n lb, ub = concretize(\n lb, ub, node, self.root, batch_size, output_dim,\n bound_lower, bound_upper, average_A=average_A)\n\n # TODO merge into `concretize`\n if self.cut_used and getattr(self, \"cut_module\", None) is not None and self.cut_module.cut_bias is not None:\n # propagate cut bias in cut constraints\n lb, ub = self.cut_module.bias_cut(node, lb, ub, unstable_idx, batch_mask=update_mask)\n if lb is not None and ub is not None and ((lb-ub)>0).sum().item() > 0:\n # make sure there is no bug for cut constraints propagation\n print(f\"Warning: lb is larger than ub with diff: {(lb-ub)[(lb-ub)>0].max().item()}\")\n\n lb = lb.view(batch_size, *output_shape) if bound_lower else None\n ub = ub.view(batch_size, *output_shape) if bound_upper else None\n\n if verbose:\n logger.debug('')\n\n if self.return_A:\n return lb, ub, self.A_dict\n else:\n return lb, ub\n\n\ndef get_unstable_size(unstable_idx):\n if isinstance(unstable_idx, tuple):\n return unstable_idx[0].numel()\n else:\n return unstable_idx.numel()\n\n\ndef check_optimized_variable_sparsity(self, node):\n alpha_sparsity = None # unknown.\n for relu in self.relus:\n if hasattr(relu, 'alpha_lookup_idx') and node.name in relu.alpha_lookup_idx:\n if relu.alpha_lookup_idx[node.name] is not None:\n # This node was created with sparse alpha\n alpha_sparsity = True\n else:\n alpha_sparsity = False\n break\n # print(f'node {node.name} alpha sparsity {alpha_sparsity}')\n return alpha_sparsity\n\n\ndef get_sparse_C(\n self, node, sparse_intermediate_bounds=True, ref_intermediate_lb=None,\n ref_intermediate_ub=None):\n sparse_conv_intermediate_bounds = self.bound_opts.get('sparse_conv_intermediate_bounds', False)\n minimum_sparsity = self.bound_opts.get('minimum_sparsity', 0.9)\n crown_batch_size = self.bound_opts.get('crown_batch_size', 1e9)\n dim = int(prod(node.output_shape[1:]))\n batch_size = self.batch_size\n\n reduced_dim = False # Only partial neurons (unstable neurons) are bounded.\n unstable_idx = None\n unstable_size = np.inf\n newC = None\n\n alpha_is_sparse = self.check_optimized_variable_sparsity(node)\n\n # NOTE: batched CROWN is so far only supported for some of the cases below\n\n # FIXME: C matrix shape incorrect for BoundParams.\n if (isinstance(node, BoundLinear) or isinstance(node, BoundMatMul)) and int(\n os.environ.get('AUTOLIRPA_USE_FULL_C', 0)) == 0:\n if sparse_intermediate_bounds:\n # If we are doing bound refinement and reference bounds are given, we only refine unstable neurons.\n # Also, if we are checking against LP solver we will refine all neurons and do not use this optimization.\n # For each batch element, we find the unstable neurons.\n unstable_idx, unstable_size = self.get_unstable_locations(\n ref_intermediate_lb, ref_intermediate_ub)\n if unstable_size == 0:\n # Do nothing, no bounds will be computed.\n reduced_dim = True\n unstable_idx = []\n elif unstable_size > crown_batch_size:\n # Create C in batched CROWN\n newC = 'OneHot'\n reduced_dim = True\n elif (unstable_size <= minimum_sparsity * dim and unstable_size > 0 and alpha_is_sparse is None) or alpha_is_sparse:\n # When we already have sparse alpha for this layer, we always use sparse C. Otherwise we determine it by sparsity.\n # Create an abstract C matrix, the unstable_idx are the non-zero elements in specifications for all batches.\n newC = OneHotC(\n [batch_size, unstable_size, *node.output_shape[1:]],\n self.device, unstable_idx, None)\n reduced_dim = True\n else:\n unstable_idx = None\n del ref_intermediate_lb, ref_intermediate_ub\n if not reduced_dim:\n newC = eyeC([batch_size, dim, *node.output_shape[1:]], self.device)\n elif node.patches_start and node.mode == \"patches\":\n if sparse_intermediate_bounds:\n unstable_idx, unstable_size = self.get_unstable_locations(\n ref_intermediate_lb, ref_intermediate_ub, conv=True)\n if unstable_size == 0:\n # Do nothing, no bounds will be computed.\n reduced_dim = True\n unstable_idx = []\n elif unstable_size > crown_batch_size:\n # Create C in batched CROWN\n newC = 'Patches'\n reduced_dim = True\n # We sum over the channel direction, so need to multiply that.\n elif (sparse_conv_intermediate_bounds and unstable_size <= minimum_sparsity * dim and alpha_is_sparse is None) or alpha_is_sparse:\n # When we already have sparse alpha for this layer, we always use sparse C. Otherwise we determine it by sparsity.\n # Create an abstract C matrix, the unstable_idx are the non-zero elements in specifications for all batches.\n # The shape of patches is [unstable_size, batch, C, H, W].\n newC = Patches(\n shape=[unstable_size, batch_size, *node.output_shape[1:-2], 1, 1],\n identity=1, unstable_idx=unstable_idx,\n output_shape=[batch_size, *node.output_shape[1:]])\n reduced_dim = True\n else:\n unstable_idx = None\n del ref_intermediate_lb, ref_intermediate_ub\n # Here we create an Identity Patches object\n if not reduced_dim:\n newC = Patches(\n None, 1, 0, [node.output_shape[1], batch_size, *node.output_shape[2:],\n *node.output_shape[1:-2], 1, 1], 1,\n output_shape=[batch_size, *node.output_shape[1:]])\n elif isinstance(node, (BoundAdd, BoundSub)) and node.mode == \"patches\":\n # FIXME: BoundAdd does not always have patches. Need to use a better way to determine patches mode.\n # FIXME: We should not hardcode BoundAdd here!\n if sparse_intermediate_bounds:\n if crown_batch_size < 1e9:\n warnings.warn('Batched CROWN is not supported in this case')\n unstable_idx, unstable_size = self.get_unstable_locations(\n ref_intermediate_lb, ref_intermediate_ub, conv=True)\n if unstable_size == 0:\n # Do nothing, no bounds will be computed.\n reduced_dim = True\n unstable_idx = []\n elif (sparse_conv_intermediate_bounds and unstable_size <= minimum_sparsity * dim and alpha_is_sparse is None) or alpha_is_sparse:\n # When we already have sparse alpha for this layer, we always use sparse C. Otherwise we determine it by sparsity.\n num_channel = node.output_shape[-3]\n # Identity patch size: (ouc_c, 1, 1, 1, out_c, 1, 1).\n patches = (\n torch.eye(num_channel, device=self.device,\n dtype=list(self.parameters())[0].dtype)).view(\n num_channel, 1, 1, 1, num_channel, 1, 1)\n # Expand to (out_c, 1, unstable_size, out_c, 1, 1).\n patches = patches.expand(-1, 1, node.output_shape[-2], node.output_shape[-1], -1, 1, 1)\n patches = patches[unstable_idx[0], :, unstable_idx[1], unstable_idx[2]]\n # Expand with the batch dimension. Final shape (unstable_size, batch_size, out_c, 1, 1).\n patches = patches.expand(-1, batch_size, -1, -1, -1)\n newC = Patches(\n patches, 1, 0, patches.shape, unstable_idx=unstable_idx,\n output_shape=[batch_size, *node.output_shape[1:]])\n reduced_dim = True\n else:\n unstable_idx = None\n del ref_intermediate_lb, ref_intermediate_ub\n if not reduced_dim:\n num_channel = node.output_shape[-3]\n # Identity patch size: (ouc_c, 1, 1, 1, out_c, 1, 1).\n patches = (\n torch.eye(num_channel, device=self.device,\n dtype=list(self.parameters())[0].dtype)).view(\n num_channel, 1, 1, 1, num_channel, 1, 1)\n # Expand to (out_c, batch, out_h, out_w, out_c, 1, 1).\n patches = patches.expand(-1, batch_size, node.output_shape[-2], node.output_shape[-1], -1, 1, 1)\n newC = Patches(patches, 1, 0, patches.shape, output_shape=[batch_size, *node.output_shape[1:]])\n else:\n if sparse_intermediate_bounds:\n unstable_idx, unstable_size = self.get_unstable_locations(\n ref_intermediate_lb, ref_intermediate_ub)\n if unstable_size == 0:\n # Do nothing, no bounds will be computed.\n reduced_dim = True\n unstable_idx = []\n elif unstable_size > crown_batch_size:\n # Create in C in batched CROWN\n newC = 'eye'\n reduced_dim = True\n elif (unstable_size <= minimum_sparsity * dim and alpha_is_sparse is None) or alpha_is_sparse:\n newC = torch.zeros([1, unstable_size, dim], device=self.device)\n # Fill the corresponding elements to 1.0\n newC[0, torch.arange(unstable_size), unstable_idx] = 1.0\n newC = newC.expand(batch_size, -1, -1).view(batch_size, unstable_size, *node.output_shape[1:])\n reduced_dim = True\n else:\n unstable_idx = None\n del ref_intermediate_lb, ref_intermediate_ub\n if not reduced_dim:\n if dim > 1000:\n warnings.warn(f\"Creating an identity matrix with size {dim}x{dim} for node {node}. This may indicate poor performance for bound computation. If you see this message on a small network please submit a bug report.\", stacklevel=2)\n newC = torch.eye(dim, device=self.device, dtype=list(self.parameters())[0].dtype) \\\n .unsqueeze(0).expand(batch_size, -1, -1) \\\n .view(batch_size, dim, *node.output_shape[1:])\n\n return newC, reduced_dim, unstable_idx, unstable_size\n\n\ndef restore_sparse_bounds(\n self, node, unstable_idx, unstable_size, ref_intermediate_lb, ref_intermediate_ub,\n new_lower=None, new_upper=None):\n batch_size = self.batch_size\n if unstable_size == 0:\n # No unstable neurons. Skip the update.\n node.lower = ref_intermediate_lb.detach().clone()\n node.upper = ref_intermediate_ub.detach().clone()\n else:\n if new_lower is None:\n new_lower = node.lower\n if new_upper is None:\n new_upper = node.upper\n # If we only calculated unstable neurons, we need to scatter the results back based on reference bounds.\n if isinstance(unstable_idx, tuple):\n lower = ref_intermediate_lb.detach().clone()\n upper = ref_intermediate_ub.detach().clone()\n # Conv layer with patches, the unstable_idx is a 3-element tuple for 3 indices (C, H,W) of unstable neurons.\n if len(unstable_idx) == 3:\n lower[:, unstable_idx[0], unstable_idx[1], unstable_idx[2]] = new_lower\n upper[:, unstable_idx[0], unstable_idx[1], unstable_idx[2]] = new_upper\n elif len(unstable_idx) == 4:\n lower[:, unstable_idx[0], unstable_idx[1], unstable_idx[2], unstable_idx[3]] = new_lower\n upper[:, unstable_idx[0], unstable_idx[1], unstable_idx[2], unstable_idx[3]] = new_upper\n else:\n # Other layers.\n lower = ref_intermediate_lb.detach().clone().view(batch_size, -1)\n upper = ref_intermediate_ub.detach().clone().view(batch_size, -1)\n lower[:, unstable_idx] = new_lower.view(batch_size, -1)\n upper[:, unstable_idx] = new_upper.view(batch_size, -1)\n node.lower = lower.view(batch_size, *node.output_shape[1:])\n node.upper = upper.view(batch_size, *node.output_shape[1:])\n\n\ndef get_degrees(node_start, backward_from):\n degrees = {}\n queue = deque([node_start])\n node_start.bounded = False\n while len(queue) > 0:\n l = queue.popleft()\n backward_from[l.name].append(node_start)\n for l_pre in l.inputs:\n degrees[l_pre.name] = degrees.get(l_pre.name, 0) + 1\n if l_pre.bounded:\n l_pre.bounded = False\n queue.append(l_pre)\n return degrees\n\n\ndef preprocess_C(C, node):\n if isinstance(C, Patches):\n if C.unstable_idx is None:\n # Patches have size (out_c, batch, out_h, out_w, c, h, w).\n if len(C.shape) == 7:\n out_c, batch_size, out_h, out_w = C.shape[:4]\n output_dim = out_c * out_h * out_w\n else:\n out_dim, batch_size, out_c, out_h, out_w = C.shape[:5]\n output_dim = out_dim * out_c * out_h * out_w\n else:\n # Patches have size (unstable_size, batch, c, h, w).\n output_dim, batch_size = C.shape[:2]\n else:\n batch_size, output_dim = C.shape[:2]\n\n # The C matrix specified by the user has shape (batch, spec) but internally we have (spec, batch) format.\n if not isinstance(C, (eyeC, Patches, OneHotC)):\n C = C.transpose(0, 1)\n elif isinstance(C, eyeC):\n C = C._replace(shape=(C.shape[1], C.shape[0], *C.shape[2:]))\n elif isinstance(C, OneHotC):\n C = C._replace(\n shape=(C.shape[1], C.shape[0], *C.shape[2:]),\n index=C.index.transpose(0,-1),\n coeffs=None if C.coeffs is None else C.coeffs.transpose(0,-1))\n\n if isinstance(C, Patches) and C.unstable_idx is not None:\n # Sparse patches; the output shape is (unstable_size, ).\n output_shape = [C.shape[0]]\n elif prod(node.output_shape[1:]) != output_dim and not isinstance(C, Patches):\n # For the output node, the shape of the bound follows C\n # instead of the original output shape\n #\n # TODO Maybe don't set node.lower and node.upper in this case?\n # Currently some codes still depend on node.lower and node.upper\n output_shape = [-1]\n else:\n # Generally, the shape of the bounds match the output shape of the node\n output_shape = node.output_shape[1:]\n\n return C, batch_size, output_dim, output_shape\n\n\ndef concretize(lb, ub, node, root, batch_size, output_dim, bound_lower=True, bound_upper=True, average_A=False):\n\n for i in range(len(root)):\n if root[i].lA is None and root[i].uA is None: continue\n if average_A and isinstance(root[i], BoundParams):\n lA = root[i].lA.mean(node.batch_dim + 1, keepdim=True).expand(root[i].lA.shape) if bound_lower else None\n uA = root[i].uA.mean(node.batch_dim + 1, keepdim=True).expand(root[i].uA.shape) if bound_upper else None\n else:\n lA, uA = root[i].lA, root[i].uA\n if not isinstance(root[i].lA, eyeC) and not isinstance(root[i].lA, Patches):\n lA = root[i].lA.reshape(output_dim, batch_size, -1).transpose(0, 1) if bound_lower else None\n if not isinstance(root[i].uA, eyeC) and not isinstance(root[i].uA, Patches):\n uA = root[i].uA.reshape(output_dim, batch_size, -1).transpose(0, 1) if bound_upper else None\n if hasattr(root[i], 'perturbation') and root[i].perturbation is not None:\n if isinstance(root[i], BoundParams):\n # add batch_size dim for weights node\n lb = lb + root[i].perturbation.concretize(\n root[i].center.unsqueeze(0), lA,\n sign=-1, aux=root[i].aux) if bound_lower else None\n ub = ub + root[i].perturbation.concretize(\n root[i].center.unsqueeze(0), uA,\n sign=+1, aux=root[i].aux) if bound_upper else None\n else:\n lb = lb + root[i].perturbation.concretize(\n root[i].center, lA, sign=-1, aux=root[i].aux) if bound_lower else None\n ub = ub + root[i].perturbation.concretize(\n root[i].center, uA, sign=+1, aux=root[i].aux) if bound_upper else None\n else:\n fv = root[i].forward_value\n if type(root[i]) == BoundInput:\n # Input node with a batch dimension\n batch_size_ = batch_size\n else:\n # Parameter node without a batch dimension\n batch_size_ = 1\n\n if bound_lower:\n if isinstance(lA, eyeC):\n lb = lb + fv.view(batch_size_, -1)\n elif isinstance(lA, Patches):\n lb = lb + lA.matmul(fv, input_shape=root[0].center.shape)\n elif type(root[i]) == BoundInput:\n lb = lb + lA.matmul(fv.view(batch_size_, -1, 1)).squeeze(-1)\n else:\n lb = lb + lA.matmul(fv.view(-1, 1)).squeeze(-1)\n else:\n lb = None\n\n if bound_upper:\n if isinstance(uA, eyeC):\n ub = ub + fv.view(batch_size_, -1)\n elif isinstance(uA, Patches):\n ub = ub + uA.matmul(fv, input_shape=root[0].center.shape)\n elif type(root[i]) == BoundInput:\n ub = ub + uA.matmul(fv.view(batch_size_, -1, 1)).squeeze(-1)\n else:\n ub = ub + uA.matmul(fv.view(-1, 1)).squeeze(-1)\n else:\n ub = None\n\n return lb, ub\n\n\ndef addA(A1, A2):\n \"\"\" Add two A (each of them is either Tensor or Patches) \"\"\"\n if type(A1) == type(A2):\n return A1 + A2\n elif type(A1) == Patches:\n return A1 + A2\n elif type(A2) == Patches:\n return A2 + A1\n else:\n raise NotImplementedError(f'Unsupported types for A1 ({type(A1)}) and A2 ({type(A2)}')\n\n\ndef add_bound(node, node_pre, lA, uA):\n \"\"\"Propagate lA and uA to a preceding node.\"\"\"\n if lA is not None:\n if node_pre.lA is None:\n # First A added to this node.\n node_pre.zero_lA_mtx = node.zero_backward_coeffs_l\n node_pre.lA = lA\n else:\n node_pre.zero_lA_mtx = node_pre.zero_lA_mtx and node.zero_backward_coeffs_l\n new_node_lA = addA(node_pre.lA, lA)\n node_pre.lA = new_node_lA\n if uA is not None:\n if node_pre.uA is None:\n # First A added to this node.\n node_pre.zero_uA_mtx = node_pre.zero_backward_coeffs_u\n node_pre.uA = uA\n else:\n node_pre.zero_uA_mtx = node_pre.zero_uA_mtx and node.zero_backward_coeffs_u\n node_pre.uA = addA(node_pre.uA, uA)\n\n\ndef get_beta_watch_list(intermediate_constr, all_nodes_before):\n beta_watch_list = defaultdict(dict)\n if intermediate_constr is not None:\n # Intermediate layer betas are handled in two cases.\n # First, if the beta split is before this node, we don't need to do anything special;\n # it will done in BoundRelu.\n # Second, if the beta split after this node, we need to modify the A matrix\n # during bound propagation to reflect beta after this layer.\n for k in intermediate_constr:\n if k not in all_nodes_before:\n # The second case needs special care: we add all such splits in a watch list.\n # However, after first occurance of a layer in the watchlist,\n # beta_watch_list will be deleted and the A matrix from split constraints\n # has been added and will be propagated to later layers.\n for kk, vv in intermediate_constr[k].items():\n beta_watch_list[kk][k] = vv\n return beta_watch_list\n\n\ndef add_constant_node(lb, ub, node):\n new_lb = node.get_bias(node.lA, node.forward_value)\n new_ub = node.get_bias(node.uA, node.forward_value)\n if isinstance(lb, Tensor) and isinstance(new_lb, Tensor) and lb.ndim > 0 and lb.ndim != new_lb.ndim:\n new_lb = new_lb.reshape(lb.shape)\n if isinstance(ub, Tensor) and isinstance(new_ub, Tensor) and ub.ndim > 0 and ub.ndim != new_ub.ndim:\n new_ub = new_ub.reshape(ub.shape)\n lb = lb + new_lb # FIXME (09/16): shape for the bias of BoundConstant.\n ub = ub + new_ub\n return lb, ub\n\n\ndef save_A_record(node, A_record, A_dict, root, needed_A_dict, lb, ub, unstable_idx):\n root_A_record = {}\n for i in range(len(root)):\n if root[i].lA is None and root[i].uA is None: continue\n if root[i].name in needed_A_dict:\n if root[i].lA is not None:\n if isinstance(root[i].lA, Patches):\n _lA = root[i].lA\n else:\n _lA = root[i].lA.transpose(0, 1).detach()\n else:\n _lA = None\n\n if root[i].uA is not None:\n if isinstance(root[i].uA, Patches):\n _uA = root[i].uA\n else:\n _uA = root[i].uA.transpose(0, 1).detach()\n else:\n _uA = None\n root_A_record.update({root[i].name: {\n \"lA\": _lA,\n \"uA\": _uA,\n # When not used, lb or ub is tensor(0). They have been transposed above.\n \"lbias\": lb.detach() if lb.ndim > 1 else None,\n \"ubias\": ub.detach() if ub.ndim > 1 else None,\n \"unstable_idx\": unstable_idx\n }})\n root_A_record.update(A_record) # merge to existing A_record\n A_dict.update({node.name: root_A_record})\n\n\ndef select_unstable_idx(ref_intermediate_lb, ref_intermediate_ub, unstable_locs, max_crown_size):\n \"\"\"When there are too many unstable neurons, only bound those\n with the loosest reference bounds.\"\"\"\n gap = (\n ref_intermediate_ub[:, unstable_locs]\n - ref_intermediate_lb[:, unstable_locs]).sum(dim=0)\n indices = torch.argsort(gap, descending=True)\n indices_selected = indices[:max_crown_size]\n indices_selected, _ = torch.sort(indices_selected)\n print(f'{len(indices_selected)}/{len(indices)} unstable neurons selected for CROWN')\n return indices_selected\n\n\ndef get_unstable_locations(\n self, ref_intermediate_lb, ref_intermediate_ub, conv=False, channel_only=False):\n max_crown_size = self.bound_opts.get('max_crown_size', int(1e9))\n # For conv layer we only check the case where all neurons are active/inactive.\n unstable_masks = torch.logical_and(ref_intermediate_lb < 0, ref_intermediate_ub > 0)\n # For simplicity, merge unstable locations for all elements in this batch. TODO: use individual unstable mask.\n # It has shape (H, W) indicating if a neuron is unstable/stable.\n # TODO: so far we merge over the batch dimension to allow easier implementation.\n if channel_only:\n # Only keep channels with unstable neurons. Used for initializing alpha.\n unstable_locs = unstable_masks.sum(dim=(0,2,3)).bool()\n # Shape is consistent with linear layers: a list of unstable neuron channels (no batch dim).\n unstable_idx = unstable_locs.nonzero().squeeze(1)\n else:\n if not conv and unstable_masks.ndim > 2:\n # Flatten the conv layer shape.\n unstable_masks = unstable_masks.view(unstable_masks.size(0), -1)\n ref_intermediate_lb = ref_intermediate_lb.view(ref_intermediate_lb.size(0), -1)\n ref_intermediate_ub = ref_intermediate_ub.view(ref_intermediate_ub.size(0), -1)\n unstable_locs = unstable_masks.sum(dim=0).bool()\n if conv:\n # Now converting it to indices for these unstable nuerons.\n # These are locations (i,j) of unstable neurons.\n unstable_idx = unstable_locs.nonzero(as_tuple=True)\n else:\n unstable_idx = unstable_locs.nonzero().squeeze(1)\n\n unstable_size = get_unstable_size(unstable_idx)\n if unstable_size > max_crown_size:\n indices_seleted = select_unstable_idx(\n ref_intermediate_lb, ref_intermediate_ub, unstable_locs, max_crown_size)\n if isinstance(unstable_idx, tuple):\n unstable_idx = tuple(u[indices_seleted] for u in unstable_idx)\n else:\n unstable_idx = unstable_idx[indices_seleted]\n unstable_size = get_unstable_size(unstable_idx)\n\n return unstable_idx, unstable_size\n\n\ndef get_alpha_crown_start_nodes(\n self, node, c=None, share_slopes=False, final_node_name=None):\n # When use_full_conv_alpha is True, conv layers do not share alpha.\n sparse_intermediate_bounds = self.bound_opts.get('sparse_intermediate_bounds', False)\n use_full_conv_alpha_thresh = self.bound_opts.get('use_full_conv_alpha_thresh', 512)\n\n start_nodes = []\n for nj in self.backward_from[node.name]: # Pre-activation layers.\n unstable_idx = None\n use_sparse_conv = None\n use_full_conv_alpha = self.bound_opts.get('use_full_conv_alpha', False)\n if (sparse_intermediate_bounds and isinstance(node, BoundRelu)\n and nj.name != final_node_name and not share_slopes):\n # Create sparse optimization variables for intermediate neurons.\n if ((isinstance(nj, BoundLinear) or isinstance(nj, BoundMatMul))\n and int(os.environ.get('AUTOLIRPA_USE_FULL_C', 0)) == 0):\n # unstable_idx has shape [neuron_size_of_nj]. Batch dimension is reduced.\n unstable_idx, _ = self.get_unstable_locations(nj.lower, nj.upper)\n elif isinstance(nj, (BoundConv, BoundAdd, BoundSub, BoundBatchNormalization)) and nj.mode == 'patches':\n if nj.name in node.patch_size:\n # unstable_idx has shape [channel_size_of_nj]. Batch and spatial dimensions are reduced.\n unstable_idx, _ = self.get_unstable_locations(\n nj.lower, nj.upper, channel_only=not use_full_conv_alpha, conv=True)\n use_sparse_conv = False # alpha is shared among channels. Sparse-spec alpha in hw dimension not used.\n if use_full_conv_alpha and unstable_idx[0].size(0) > use_full_conv_alpha_thresh:\n # Too many unstable neurons. Using shared alpha per channel.\n unstable_idx, _ = self.get_unstable_locations(\n nj.lower, nj.upper, channel_only=True, conv=True)\n use_full_conv_alpha = False\n else:\n # matrix mode for conv layers.\n # unstable_idx has shape [c_out * h_out * w_out]. Batch dimension is reduced.\n unstable_idx, _ = self.get_unstable_locations(nj.lower, nj.upper)\n use_sparse_conv = True # alpha is not shared among channels, and is sparse in spec dimension.\n if nj.name == final_node_name:\n size_final = self[final_node_name].output_shape[-1] if c is None else c.size(1)\n start_nodes.append((final_node_name, size_final, None))\n continue\n if share_slopes:\n # all intermediate neurons from the same layer share the same set of slopes.\n output_shape = 1\n elif isinstance(node, BoundOptimizableActivation) and node.patch_size and nj.name in node.patch_size:\n # Patches mode. Use output channel size as the spec size. This still shares some alpha, but better than no sharing.\n if use_full_conv_alpha:\n # alphas not shared among channels, so the spec dim shape is c,h,w\n # The patch size is [out_ch, batch, out_h, out_w, in_ch, H, W]. We use out_ch as the output shape.\n output_shape = node.patch_size[nj.name][0], node.patch_size[nj.name][2], node.patch_size[nj.name][3]\n else:\n # The spec dim is c only, and is shared among h, w.\n output_shape = node.patch_size[nj.name][0]\n assert not sparse_intermediate_bounds or use_sparse_conv is False # Double check our assumption holds. If this fails, then we created wrong shapes for alpha.\n else:\n # Output is linear layer, or patch converted to matrix.\n assert not sparse_intermediate_bounds or use_sparse_conv is not False # Double check our assumption holds. If this fails, then we created wrong shapes for alpha.\n output_shape = nj.lower.shape[1:] # FIXME: for non-relu activations it's still expecting a prod.\n start_nodes.append((nj.name, output_shape, unstable_idx))\n return start_nodes\n","sub_path":"auto_LiRPA/backward_bound.py","file_name":"backward_bound.py","file_ext":"py","file_size_in_byte":37902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"241709885","text":"import pandas as pd\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport sklearn\n\nfrom utils import *\nfrom bovw import BoVW\n\nif __name__ == '__main__':\n # Prepare Data\n train_df = pd.read_csv(\"train.csv\")\n test_df = pd.read_csv(\"test.csv\")\n\n bovw = BoVW(n_words=300, img_size=(512,512))\n\n imgs_train, labels_train = get_data(train_df)\n bovw.KM_cluster(imgs_train)\n X_train = bovw.build_histograms(imgs_train)\n y_train = np.array(labels_train)\n\n # Test Data\n imgs_test, labels_test = get_data(test_df)\n X_test = bovw.build_histograms(imgs_test)\n y_test = np.array(labels_test)\n\n print(\"--Data Shape\")\n print(X_train.shape)\n print(y_train.shape)\n print(X_test.shape)\n print(y_test.shape)\n\n \n print(\"{:^3} | {:^10} | {:^10}\".format(\"K\", \"Train Acc\", \"Test Acc\"))\n print('-'*27)\n for k in range(1, 30+1):\n\n # ---- Change Here ---- #\n from sklearn.neighbors import KNeighborsClassifier\n model = KNeighborsClassifier(n_neighbors=k, algorithm='brute', p=1)\n model.fit(X_train, y_train) \n\n y_pred = model.predict(X_train)\n train_acc = compute_accuracy(y_pred, y_train)\n \n y_pred = model.predict(X_test)\n test_acc = compute_accuracy(y_pred, y_test)\n # ---- Change Here ---- #\n\n print(\"{:^3} | {:^10} | {:^10}\".format(k, \"%.4f\"%train_acc, \"%.4f\"%test_acc))\n plot_confusion_matrix(y_pred, y_test, labels= [i for i in range(num_classes)])","sub_path":"5. Scene Classification/codes/BoVW_kNN.py","file_name":"BoVW_kNN.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"549108861","text":"# -*- coding: UTF-8 -*-\n\n\"\"\"\nFunctions that list the *recently used files* and / or remove *blacklisted\nentries* from it.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport os\n\nfrom time import sleep\n\nfrom .blacklist import BlacklistChecker\n\n\ndef show_recent(recent_documents, blacklist):\n \"\"\"\n Prints all URIs from the *recent_documents*.\n\n Documents matching the *blacklist* are marked.\n\n :param recent_documents: a :class:`RecentlyUsedFiles` instance.\n\n :param blacklist: a :class:`ZGBlacklist` instance.\n\n \"\"\"\n for document in recent_documents:\n on_blacklist = BlacklistChecker.is_blacklisted(document, blacklist)\n status = 'x' if on_blacklist else ' '\n uri = document.attrib['href']\n print(\"[{status}] {uri}\".format(status=status, uri=uri))\n\n\ndef show_blacklisted(recent_documents, blacklist):\n \"\"\"\n Prints the URIs of the *recent_documents* matching the *blacklist*.\n\n :param recent_documents: a :class:`RecentlyUsedFiles` instance.\n\n :param blacklist: a :class:`ZGBlacklist` instance.\n\n \"\"\"\n bc = BlacklistChecker(recent_documents, blacklist)\n for uri in bc.blacklisted_uris:\n print(uri)\n\n\ndef remove_blacklisted(recent_documents, blacklist, save=True):\n \"\"\"\n Removes all entries matching the *blacklist* from the *recent_documents*.\n\n :param recent_documents: a :class:`RecentlyUsedFiles` instance.\n\n :param blacklist: a :class:`ZGBlacklist` instance.\n\n If *save* is not `True`, no changes where saved to the file.\n\n \"\"\"\n bc = BlacklistChecker(recent_documents, blacklist, autosave=save)\n bc.remove_blacklisted()\n\n\ndef watch(recent_documents, blacklist, interval=60):\n \"\"\"\n Watches *recent_documents* and removes the ones on the *blacklist*.\n\n Read (and reread on change) the list of *recent_documents* and keep\n removing the entries on the *blacklist*.\n\n Use ``CTRL+C`` to return.\n\n :param recent_documents: a :class:`RecentlyUsedFiles` instance.\n\n :param blacklist: a :class:`ZGBlacklist` instance.\n\n :param interval: is the number of seconds between checks for change.\n\n \"\"\"\n # setup\n bc = BlacklistChecker(\n recent_documents, blacklist, autoload=True, autosave=True\n )\n # initial cleanup\n bc.remove_blacklisted()\n filename = recent_documents.filename\n old_time = os.stat(filename).st_mtime\n # watch...\n try:\n while True:\n new_time = os.stat(filename).st_mtime\n if new_time != old_time:\n bc.remove_blacklisted()\n old_time = os.stat(filename).st_mtime\n else:\n sleep(int(interval))\n except KeyboardInterrupt:\n pass\n","sub_path":"nautilus-blacklist/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"473422412","text":"import pytest\n\nfrom django.contrib.auth.models import User\nfrom django.contrib.gis.geos import Point\n\nfrom erp.models import Accessibilite, Activite, Commune, Erp\n\n\n@pytest.fixture\ndef activite_administration_publique():\n return Activite.objects.create(nom=\"Administration Publique\")\n\n\n@pytest.fixture\ndef activite_mairie():\n return Activite.objects.create(nom=\"Mairie\")\n\n\n@pytest.fixture\ndef commune_castelnau():\n return Commune.objects.create(\n nom=\"Castelnau-le-Lez\",\n code_postaux=[\"34170\"],\n code_insee=\"34057\",\n departement=\"93\",\n geom=Point(0, 0),\n )\n\n\n@pytest.fixture\ndef commune_montpellier():\n return Commune.objects.create(\n nom=\"Montpellier\",\n code_postaux=[\"34000\"],\n code_insee=\"34172\",\n departement=\"34\",\n geom=Point(0, 0),\n )\n\n\n@pytest.fixture\ndef commune_montreuil():\n return Commune.objects.create(\n nom=\"Montreuil\",\n code_postaux=[\"93100\"],\n code_insee=\"93048\",\n departement=\"93\",\n geom=Point(0, 0),\n )\n\n\n@pytest.fixture\ndef data(db):\n obj_admin = User.objects.create_user(\n username=\"admin\",\n password=\"Abc12345!\",\n email=\"admin@admin.tld\",\n is_staff=True,\n is_superuser=True,\n is_active=True,\n )\n obj_niko = User.objects.create_user(\n username=\"niko\",\n password=\"Abc12345!\",\n email=\"niko@niko.tld\",\n is_staff=True,\n is_active=True,\n )\n obj_sophie = User.objects.create_user(\n username=\"sophie\",\n password=\"Abc12345!\",\n email=\"sophie@sophie.tld\",\n is_staff=True,\n is_active=True,\n )\n obj_jacou = Commune.objects.create(\n nom=\"Jacou\",\n code_postaux=[\"34830\"],\n code_insee=\"34120\",\n departement=\"34\",\n geom=Point((3.9047933, 43.6648217)),\n )\n obj_boulangerie = Activite.objects.create(nom=\"Boulangerie\")\n obj_erp = Erp.objects.create(\n nom=\"Aux bons croissants\",\n siret=\"52128577500016\",\n numero=\"4\",\n voie=\"grand rue\",\n code_postal=\"34830\",\n commune=\"Jacou\",\n commune_ext=obj_jacou,\n geom=Point((3.9047933, 43.6648217)),\n activite=obj_boulangerie,\n published=True,\n user=obj_niko,\n )\n obj_accessibilite = Accessibilite.objects.create(\n erp=obj_erp, sanitaires_presence=True, sanitaires_adaptes=0\n )\n\n class Data:\n admin = obj_admin\n niko = obj_niko\n sophie = obj_sophie\n jacou = obj_jacou\n boulangerie = obj_boulangerie\n accessibilite = obj_accessibilite\n erp = obj_erp\n\n return Data()\n","sub_path":"tests/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"18190359","text":"import numpy as np\n\nfrom pyoperators import (\n flags, Operator, AdditionOperator, BlockColumnOperator,\n BlockDiagonalOperator, BlockRowOperator, CompositionOperator,\n DiagonalOperator, HomothetyOperator, IdentityOperator,\n MultiplicationOperator, I, asoperator)\nfrom pyoperators.core import BlockOperator\nfrom pyoperators.utils import merge_none\nfrom pyoperators.utils.testing import (\n assert_eq, assert_is_instance, assert_raises, assert_is_type)\nfrom .common import Stretch\n\n\ndef test_partition1():\n o1 = HomothetyOperator(1, shapein=1)\n o2 = HomothetyOperator(2, shapein=2)\n o3 = HomothetyOperator(3, shapein=3)\n r = DiagonalOperator([1, 2, 2, 3, 3, 3]).todense()\n\n def func(ops, p):\n op = BlockDiagonalOperator(ops, partitionin=p, axisin=0)\n assert_eq(op.todense(6), r, str(op))\n for ops, p in zip(\n ((o1, o2, o3), (I, o2, o3), (o1, 2*I, o3), (o1, o2, 3*I)),\n (None, (1, 2, 3), (1, 2, 3), (1, 2, 3))):\n yield func, ops, p\n\n\ndef test_partition2():\n # in some cases in this test, partitionout cannot be inferred from\n # partitionin, because the former depends on the input rank\n i = np.arange(3*4*5*6).reshape(3, 4, 5, 6)\n\n def func(axisp, p, axiss):\n op = BlockDiagonalOperator(3*[Stretch(axiss)], partitionin=p,\n axisin=axisp)\n assert_eq(op(i), Stretch(axiss)(i))\n for axisp, p in zip(\n (0, 1, 2, 3, -1, -2, -3),\n ((1, 1, 1), (1, 2, 1), (2, 2, 1), (2, 3, 1), (2, 3, 1), (2, 2, 1),\n (1, 2, 1), (1, 1, 1))):\n for axiss in (0, 1, 2, 3):\n yield func, axisp, p, axiss\n\n\ndef test_partition3():\n # test axisin != axisout...\n pass\n\n\ndef test_partition4():\n o1 = HomothetyOperator(1, shapein=1)\n o2 = HomothetyOperator(2, shapein=2)\n o3 = HomothetyOperator(3, shapein=3)\n\n @flags.separable\n class Op(Operator):\n pass\n op = Op()\n p = BlockDiagonalOperator([o1, o2, o3], axisin=0)\n r = (op + p + op) * p\n assert isinstance(r, BlockDiagonalOperator)\n\n\ndef test_block1():\n ops = [HomothetyOperator(i, shapein=(2, 2)) for i in range(1, 4)]\n\n def func(axis, s):\n op = BlockDiagonalOperator(ops, new_axisin=axis)\n assert_eq(op.shapein, s)\n assert_eq(op.shapeout, s)\n for axis, s in zip(\n range(-3, 3),\n ((3, 2, 2), (2, 3, 2), (2, 2, 3), (3, 2, 2), (2, 3, 2),\n (2, 2, 3))):\n yield func, axis, s\n\n\ndef test_block2():\n shape = (3, 4, 5, 6)\n i = np.arange(np.product(shape)).reshape(shape)\n\n def func(axisp, axiss):\n op = BlockDiagonalOperator(shape[axisp]*[Stretch(axiss)],\n new_axisin=axisp)\n axisp_ = axisp if axisp >= 0 else axisp + 4\n axiss_ = axiss if axisp_ > axiss else axiss + 1\n assert_eq(op(i), Stretch(axiss_)(i))\n for axisp in (0, 1, 2, 3, -1, -2, -3):\n for axiss in (0, 1, 2):\n yield func, axisp, axiss\n\n\ndef test_block3():\n # test new_axisin != new_axisout...\n pass\n\n\ndef test_block4():\n o1 = HomothetyOperator(1, shapein=2)\n o2 = HomothetyOperator(2, shapein=2)\n o3 = HomothetyOperator(3, shapein=2)\n\n @flags.separable\n class Op(Operator):\n pass\n op = Op()\n p = BlockDiagonalOperator([o1, o2, o3], new_axisin=0)\n r = (op + p + op) * p\n assert isinstance(r, BlockDiagonalOperator)\n\n\ndef test_block_column1():\n I2 = IdentityOperator(2)\n I3 = IdentityOperator(3)\n assert_raises(ValueError, BlockColumnOperator, [I2, 2*I3], axisout=0)\n assert_raises(ValueError, BlockColumnOperator, [I2, 2*I3], new_axisout=0)\n\n\ndef test_block_column2():\n p = np.matrix([[1, 0], [0, 2], [1, 0]])\n o = asoperator(np.matrix(p))\n e = BlockColumnOperator([o, 2*o], axisout=0)\n assert_eq(e.todense(), np.vstack([p, 2*p]))\n assert_eq(e.T.todense(), e.todense().T)\n e = BlockColumnOperator([o, 2*o], new_axisout=0)\n assert_eq(e.todense(), np.vstack([p, 2*p]))\n assert_eq(e.T.todense(), e.todense().T)\n\n\ndef test_block_row1():\n I2 = IdentityOperator(2)\n I3 = IdentityOperator(3)\n assert_raises(ValueError, BlockRowOperator, [I2, 2*I3], axisin=0)\n assert_raises(ValueError, BlockRowOperator, [I2, 2*I3], new_axisin=0)\n\n\ndef test_block_row2():\n p = np.matrix([[1, 0], [0, 2], [1, 0]])\n o = asoperator(np.matrix(p))\n r = BlockRowOperator([o, 2*o], axisin=0)\n assert_eq(r.todense(), np.hstack([p, 2*p]))\n assert_eq(r.T.todense(), r.todense().T)\n r = BlockRowOperator([o, 2*o], new_axisin=0)\n assert_eq(r.todense(), np.hstack([p, 2*p]))\n assert_eq(r.T.todense(), r.todense().T)\n\n\ndef test_partition_implicit_commutative():\n partitions = (None, None), (2, None), (None, 3), (2, 3)\n ops = [I, 2*I]\n\n def func(op1, op2, p1, p2, cls):\n op = operation([op1, op2])\n assert type(op) is cls\n if op.partitionin is None:\n assert op1.partitionin is op2.partitionin is None\n else:\n assert op.partitionin == merge_none(p1, p2)\n if op.partitionout is None:\n assert op1.partitionout is op2.partitionout is None\n else:\n assert op.partitionout == merge_none(p1, p2)\n for operation in (AdditionOperator, MultiplicationOperator):\n for p1 in partitions:\n for p2 in partitions:\n for cls, aout, ain, pout1, pin1, pout2, pin2 in zip(\n (BlockRowOperator, BlockDiagonalOperator,\n BlockColumnOperator),\n (None, 0, 0), (0, 0, None), (None, p1, p1),\n (p1, p1, None), (None, p2, p2), (p2, p2, None)):\n op1 = BlockOperator(\n ops, partitionout=pout1, partitionin=pin1, axisin=ain,\n axisout=aout)\n op2 = BlockOperator(\n ops, partitionout=pout2, partitionin=pin2, axisin=ain,\n axisout=aout)\n yield func, op1, op2, p1, p2, cls\n\n\ndef test_partition_implicit_composition():\n partitions = (None, None), (2, None), (None, 3), (2, 3)\n ops = [I, 2*I]\n\n def func(op1, op2, pin1, pout2, cls):\n op = op1 * op2\n assert_is_instance(op, cls)\n if not isinstance(op, BlockOperator):\n return\n pout = None if isinstance(op, BlockRowOperator) else \\\n merge_none(pin1, pout2)\n pin = None if isinstance(op, BlockColumnOperator) else \\\n merge_none(pin1, pout2)\n assert pout == op.partitionout\n assert pin == op.partitionin\n for pin1 in partitions:\n for pout2 in partitions:\n for cls1, cls2, cls, aout1, ain1, aout2, ain2, pout1, pin2, in zip(\n (BlockRowOperator, BlockRowOperator, BlockDiagonalOperator,\n BlockDiagonalOperator),\n (BlockDiagonalOperator, BlockColumnOperator,\n BlockDiagonalOperator, BlockColumnOperator),\n (BlockRowOperator, HomothetyOperator,\n BlockDiagonalOperator, BlockColumnOperator),\n (None, None, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0),\n (0, None, 0, None), (None, None, pin1, pin1),\n (pout2, None, pout2, None)):\n op1 = BlockOperator(ops, partitionin=pin1, partitionout=pout1,\n axisout=aout1, axisin=ain1)\n op2 = BlockOperator(ops, partitionout=pout2, partitionin=pin2,\n axisout=aout2, axisin=ain2)\n yield func, op1, op2, pin1, pout2, cls\n\n\ndef test_mul():\n opnl = Operator(shapein=10, flags='square')\n oplin = Operator(flags='linear,square', shapein=10)\n clss = ((BlockRowOperator, BlockDiagonalOperator, BlockRowOperator),\n 3 * (BlockDiagonalOperator,),\n (BlockDiagonalOperator, BlockColumnOperator, BlockColumnOperator),\n (BlockRowOperator, BlockColumnOperator, AdditionOperator))\n\n def func(op, cls1, cls2, cls3):\n operation = CompositionOperator \\\n if op.flags.linear else MultiplicationOperator\n op1 = cls1(3*[op], axisin=0)\n op2 = cls2(3*[op], axisout=0)\n result = op1 * op2\n assert_is_type(result, cls3)\n assert_is_type(result.operands[0], operation)\n for op in opnl, oplin:\n for cls1, cls2, cls3 in clss:\n yield func, op, cls1, cls2, cls3\n","sub_path":"test/test_partition.py","file_name":"test_partition.py","file_ext":"py","file_size_in_byte":8493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"140231471","text":"from flask import jsonify, request, Flask\nfrom sklearn.preprocessing import normalize\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom app.const import TOPIC_SHOPPING_VECTORIZER, TOPIC_SHOPPING_CLASSIFIER, \\\n TOPIC_SHOPPING_W2P_BIGRAM, TOPIC_SHOPPING_W2P_TRIGRAM, \\\n TOPIC_TRAVEL_VECTORIZER, TOPIC_TRAVEL_CLASSIFIER, \\\n TOPIC_TRAVEL_W2P_BIGRAM, TOPIC_TRAVEL_W2P_TRIGRAM\nfrom scipy.sparse import *\nimport ast\n\ndef identify_topics(request):\n text = request.GET.get('text')\n domain_name = request.GET.get('domain_name')\n if domain_name == \"shopping\":\n X = TOPIC_SHOPPING_VECTORIZER.transform([text])\n X = normalize(X)\n lst = list(TOPIC_SHOPPING_CLASSIFIER.predict_proba(X)[0])\n ans = str(sorted(zip(lst,TOPIC_SHOPPING_CLASSIFIER.classes_),reverse=True))\n return HttpResponse(ans)\n elif domain_name == \"travel\":\n X = TOPIC_TRAVEL_VECTORIZER.transform([text])\n X = normalize(X)\n lst = list(TOPIC_TRAVEL_CLASSIFIER.predict_proba(X)[0])\n ans = str(sorted(zip(lst,TOPIC_TRAVEL_CLASSIFIER.classes_),reverse=True))\n return HttpResponse(ans)\ndef w2p_process(request):\n text = request.GET.get('text')\n domain_name = request.GET.get('domain_name')\n if domain_name == \"shopping\":\n spl = text.split()\n ret = TOPIC_SHOPPING_W2P_BIGRAM[spl]\n ret = TOPIC_SHOPPING_W2P_TRIGRAM[ret]\n return HttpResponse(\" \".join(ret))\n elif domain_name == \"travel\":\n spl = text.split()\n ret = TOPIC_TRAVEL_W2P_BIGRAM[spl]\n ret = TOPIC_TRAVEL_W2P_TRIGRAM[ret]\n return HttpResponse(\" \".join(ret))\n","sub_path":"app/topic_identification.py","file_name":"topic_identification.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"57165924","text":"from django.db import models\n\nfrom telegram import bot\n\n\nclass States():\n states = (\n 'main',\n ('get_fns_number', 'Введите номер телефона'),\n ('get_fns_password', 'Введите пароль из смс'),\n )\n\n def __init__(self, user=None):\n self.messages = {}\n for state in self.states:\n message = None\n if type(state) != str:\n message = state[1]\n state = state[0]\n setattr(self, state.upper(), state.lower())\n self.messages[state.lower()] = message\n self.user = user\n\n def __call__(self):\n django_states = []\n for state in self.states:\n state = state[0] if type(state) != str else state\n django_states.append((state.upper(), state.lower()))\n return django_states\n\nstates = States()\n\n\nclass TelegramUser(models.Model):\n user_id = models.IntegerField(unique=True)\n login = models.CharField(max_length=128, unique=True, null=True, blank=True)\n state = models.CharField(choices=states(), max_length=128, default=states.MAIN)\n\n def send_message(self, **data):\n return bot.send_message(chat_id=self.user_id, **data)\n\n def edit_message(self, **data):\n return bot.edit_message_text(chat_id=self.user_id, **data)\n\n def change_state(self, state):\n if states.messages[state]:\n self.send_message(text=states.messages[state])\n self.state = state\n self.save()\n","sub_path":"vinniejonesbot/telegram/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"294684378","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Odoo, an open source suite of business apps\n# This module copyright (C) 2015 bloopark systems ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom openerp import api, fields, models\nfrom openerp.addons import decimal_precision\n\n\nclass SaleOrder(models.Model):\n\n \"\"\"Overwrites and add Definitions to module: sale.\"\"\"\n\n _inherit = 'sale.order'\n\n amount_subtotal = fields.Float(\n compute='_compute_amount_subtotal',\n digits=decimal_precision.get_precision('Account'),\n string='Subtotal Amount',\n store=True,\n help=\"The amount without anything.\",\n track_visibility='always'\n )\n\n @api.depends('order_line', 'order_line.price_subtotal')\n def _compute_amount_subtotal(self):\n \"\"\"compute Function for amount_subtotal.\"\"\"\n for rec in self:\n line_amount = sum([line.price_subtotal for line in rec.order_line if\n not line.is_delivery])\n currency = rec.pricelist_id.currency_id\n rec.amount_subtotal = currency.round(line_amount)\n","sub_path":"models/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"243926765","text":"from tkinter import*\nfrom tkinter import ttk\nimport smtplib\nfrom email.mime.text import MIMEText\nimport xml.etree.ElementTree as ET\nimport webbrowser\n\nimport data\n\nclass main:\n def __init__(self):\n self.myData = data.GetDataReservation()\n\n self.tree = ET.parse(\"dataReservation.xml\")\n self.root = self.tree.getroot()\n\n self.window = Tk()\n self.window.title(\"Reservation\")\n self.window.geometry(\"500x600\")\n\n self.listTitle = []\n\n self.rValue = IntVar()\n Radiobutton(self.window, text=\"문화 행사 전체 출력하기\", variable=self.rValue, value=1).place(x=10, y=10)\n Radiobutton(self.window, text=\"문화 행사 검색해서 출력하기\", variable=self.rValue, value=2).place(x=10, y=45)\n\n self.cValue = StringVar()\n combo = ttk.Combobox(self.window, width=5, textvariable=self.cValue, state=\"readonly\")\n combo['values'] = ('Select', '장르', '제목')\n combo.place(x=35, y=80)\n combo.current(0)\n\n self.tValue = StringVar()\n textbox = ttk.Entry(self.window, width=20, textvariable=self.tValue)\n textbox.place(x=105, y=80)\n\n sButton = Button(self.window, text=\"검색\", width=4, command=self.select)\n sButton.place(x=410, y=78)\n\n self.mValue = StringVar()\n self.mTextbox = ttk.Entry(self.window, width=20, textvariable=self.mValue)\n self.mTextbox.place(x=250, y=542)\n\n eButton = Button(self.window, text=\"메일\", width=4, command=self.mail)\n eButton.place(x=410, y=540)\n\n scrollbarX = Scrollbar(self.window)\n scrollbarX.pack(side=RIGHT, fill=Y)\n scrollbarY = Scrollbar(self.window, orient='horizontal')\n scrollbarY.pack(side=BOTTOM, fill=X)\n self.listbox = Listbox(self.window, width=65, height=25,\n yscrollcommand=scrollbarX.set, xscrollcommand=scrollbarY.set)\n self.listbox.bind(\"\", self.site)\n self.listbox.place(x=5, y=120)\n scrollbarX.config(command=self.listbox.yview)\n scrollbarY.config(command=self.listbox.xview)\n\n self.window.mainloop()\n\n def select(self):\n self.listbox.delete(0, self.listbox.size())\n self.listTitle.clear()\n if self.rValue.get() == 1:\n self.printAll()\n elif self.rValue.get() == 2:\n if self.cValue.get() == '장르':\n self.selectSub()\n elif self.cValue.get() == '제목':\n self.selectTitle()\n\n def printAll(self):\n cnt = 0\n for i in self.root.iter(\"row\"):\n self.listTitle.append(i.findtext(\"SVCNM\"))\n self.listbox.insert(cnt, \"장르: \"+i.findtext(\"MINCLASSNM\")+\" 제목: \"+i.findtext(\"SVCNM\")+\n \" 장소: \"+i.findtext(\"PLACENM\")+\"비용: \"+i.findtext(\"PAYATNM\")+\n \" 접수 시작일\"+i.findtext(\"RCPTBGNDT\")+\" 접수 종료일\"+i.findtext(\"RCPTENDDT\")+\n \" 예약 상태: : \"+i.findtext(\"SVCSTATNM\"))\n cnt += 1\n\n def selectSub(self):\n cnt = 0\n for i in self.root.iter(\"row\"):\n if self.tValue.get() == i.findtext(\"MINCLASSNM\"):\n self.listTitle.append(i.findtext(\"SVCNM\"))\n self.listbox.insert(cnt, \"장르: \"+i.findtext(\"MINCLASSNM\")+\" 제목: \"+i.findtext(\"SVCNM\")+\n \" 장소: \"+i.findtext(\"PLACENM\")+\"비용: \"+i.findtext(\"PAYATNM\")+\n \" 접수 시작일\"+i.findtext(\"RCPTBGNDT\")+\" 접수 종료일\"+i.findtext(\"RCPTENDDT\")+\n \" 예약 상태: : \"+i.findtext(\"SVCSTATNM\"))\n cnt += 1\n\n def selectTitle(self):\n cnt = 0\n for i in self.root.iter(\"row\"):\n if self.tValue.get() == i.findtext(\"SVCNM\"):\n self.listTitle.append(i.findtext(\"SVCNM\"))\n self.listbox.insert(cnt, \"장르: \"+i.findtext(\"MINCLASSNM\")+\" 제목: \"+i.findtext(\"SVCNM\")+\n \" 장소: \"+i.findtext(\"PLACENM\")+\"비용: \"+i.findtext(\"PAYATNM\")+\n \" 접수 시작일\"+i.findtext(\"RCPTBGNDT\")+\" 접수 종료일\"+i.findtext(\"RCPTENDDT\")+\n \" 예약 상태: : \"+i.findtext(\"SVCSTATNM\"))\n cnt += 1\n\n def site(self, event):\n idx = self.listbox.curselection()\n for i in self.root.iter(\"row\"):\n if self.listTitle[idx[0]] == i.findtext(\"SVCNM\"):\n webbrowser.open_new(i.findtext(\"SVCURL\"))\n break\n\n def mail(self):\n idx = self.listbox.curselection()\n\n if len(idx) > 0 and self.mValue.get() != \"\":\n msg = MIMEText(self.listbox.get(idx[0]), \"html\", _charset=\"utf-8\")\n\n msg['Subject'] = '문화행사 정보'\n msg['From'] = \"ta722blo@gmail.com\"\n msg['To'] = self.mValue.get()\n\n s = smtplib.SMTP('smtp.gmail.com', 587)\n s.ehlo()\n s.starttls()\n s.ehlo()\n\n s.login(\"ta722blo@gmail.com\", \"12345qwert!\")\n s.sendmail(\"ta722blo@gmail.com\", self.mValue.get(), msg.as_string())\n s.quit()\n\n self.mTextbox.delete(0, END)","sub_path":"최종발표/reserve.py","file_name":"reserve.py","file_ext":"py","file_size_in_byte":5312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"651259384","text":"import cv2\nimport numpy as np\n\nimg1 = cv2.imread(\"../image1.png\", 0)\nimg2 = cv2.imread(\"../image2.png\", 0)\n\nrow, col = img1.shape\nkx, ky = 10, 10\nA = np.mat([[kx, 0], [0, ky]])\n\nimg1_new = np.zeros((kx * row, ky * col))\nimg2_new = np.zeros((kx * row, ky * col))\n\nfor r in range(kx * row):\n for l in range(ky * col):\n v = np.dot(A.I, np.array([r, l]).T)\n img1_new[r, l] = img1[int(v[0, 0]), int(v[0, 1])]\n img2_new[r, l] = img2[int(v[0, 0]), int(v[0, 1])]\n\ncv2.imwrite(\"../scaled1.png\", img1_new)\ncv2.imwrite(\"../scaled2.png\", img2_new)\n","sub_path":"image_processing/scaling.py","file_name":"scaling.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"617460864","text":"load(\"@bazel_tools//tools/build_defs/repo:git.bzl\", \"git_repository\")\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\ndef maybe(repo_rule, name, **kwargs):\n \"\"\"Defines a repository if it does not already exist.\n \"\"\"\n if name not in native.existing_rules():\n repo_rule(name = name, **kwargs)\n\ndef kythe_rule_repositories():\n \"\"\"Defines external repositories for Kythe Bazel rules.\n\n These repositories must be loaded before calling external.bzl%kythe_dependencies.\n \"\"\"\n maybe(\n http_archive,\n name = \"io_bazel_rules_go\",\n url = \"https://github.com/bazelbuild/rules_go/releases/download/0.16.1/rules_go-0.16.1.tar.gz\",\n sha256 = \"f5127a8f911468cd0b2d7a141f17253db81177523e4429796e14d429f5444f5f\",\n )\n\n maybe(\n http_archive,\n name = \"bazel_gazelle\",\n strip_prefix = \"bazel-gazelle-253128b77088080a348f54d79a28dcd47d99caf9\",\n sha256 = \"6e48a5f804ee1f0df84b546aa5c2eb15b3b2e2bcfc75f2bf305323343c2e8b94\",\n urls = [\"https://github.com/bazelbuild/bazel-gazelle/archive/253128b77088080a348f54d79a28dcd47d99caf9.zip\"],\n )\n\n maybe(\n git_repository,\n name = \"build_bazel_rules_nodejs\",\n remote = \"https://github.com/bazelbuild/rules_nodejs.git\",\n tag = \"0.16.0\",\n )\n","sub_path":"setup.bzl","file_name":"setup.bzl","file_ext":"bzl","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"115513171","text":"'''# Copyright 2020 QuantumBlack Visual Analytics Limited\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# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS\n# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# The QuantumBlack Visual Analytics Limited (\"QuantumBlack\") name and logo\n# (either separately or in combination, \"QuantumBlack Trademarks\") are\n# trademarks of QuantumBlack. The License does not grant you any right or\n# license to the QuantumBlack Trademarks. You may not use the QuantumBlack\n# Trademarks or any confusingly similar mark as a trademark for your product,\n# or use the QuantumBlack Trademarks in any other manner that might cause\n# confusion in the marketplace, including but not limited to in advertising,\n# on websites, or on software.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Example code for the nodes in the example pipeline. This code is meant\njust for illustrating basic Kedro features.\n\nPLEASE DELETE THIS FILE ONCE YOU START WORKING ON YOUR OWN PROJECT!\n\"\"\"\n\nfrom typing import Any, Dict\n\nimport pandas as pd\n\n\ndef split_data(data: pd.DataFrame, example_test_data_ratio: float) -> Dict[str, Any]:\n \"\"\"Node for splitting the classical Iris data set into training and test\n sets, each split into features and labels.\n The split ratio parameter is taken from conf/project/parameters.yml.\n The data and the parameters will be loaded and provided to your function\n automatically when the pipeline is executed and it is time to run this node.\n \"\"\"\n data.columns = [\n \"sepal_length\",\n \"sepal_width\",\n \"petal_length\",\n \"petal_width\",\n \"target\",\n ]\n classes = sorted(data[\"target\"].unique())\n # One-hot encoding for the target variable\n data = pd.get_dummies(data, columns=[\"target\"], prefix=\"\", prefix_sep=\"\")\n\n # Shuffle all the data\n data = data.sample(frac=1).reset_index(drop=True)\n\n # Split to training and testing data\n n = data.shape[0]\n n_test = int(n * example_test_data_ratio)\n training_data = data.iloc[n_test:, :].reset_index(drop=True)\n test_data = data.iloc[:n_test, :].reset_index(drop=True)\n\n # Split the data to features and labels\n train_data_x = training_data.loc[:, \"sepal_length\":\"petal_width\"]\n train_data_y = training_data[classes]\n test_data_x = test_data.loc[:, \"sepal_length\":\"petal_width\"]\n test_data_y = test_data[classes]\n\n # When returning many variables, it is a good practice to give them names:\n return dict(\n train_x=train_data_x,\n train_y=train_data_y,\n test_x=test_data_x,\n test_y=test_data_y,\n )\n'''\n\n'''Data Abstraction'''\nimport spacy\nimport numpy as np\nimport pandas as pd\n\nclass Error(Exception):\n \"\"\"Base class for exceptions in this module.\"\"\"\n pass\n\n\nclass PipelineError(Error):\n \"\"\"Exception raised for errors in the input.\n\n Attributes:\n expression -- input expression in which the error occurred\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, expression, message):\n self.expression = expression\n self.message = message\n\n\nclass SpacyBulk():\n def __init__(self, ner=1, parser=1, tagger=1):\n self.disable = []\n self.ner = ner\n self.parser = parser\n self.tagger = tagger\n\n if self.ner == 0:\n self.disable.append('ner')\n if self.parser == 0:\n self.disable.append('parser')\n if self.tagger == 0:\n self.disable.append('tagger')\n if self.disable:\n self.nlp = spacy.load(\"en_core_web_sm\", disable=self.disable)\n else:\n self.nlp = spacy.load('en_core_web_sm')\n self.pos_tag = []\n self.tokens = []\n self.tokenCnt_lst = []\n self.poss = []\n self.dep = []\n self.nerl = []\n self.text_corpus = []\n\n def get_DF(self, text_corpus,preprocess_out):\n self.text_corpus = text_corpus\n if len(self.text_corpus) == 0:\n raise PipelineError('Input text cannot be None',\n 'This object extract sentences, parts of speech, named entity recognition, dependencies')\n sentences = []\n tokens = []\n dep = []\n tag = []\n ID = []\n for i, text in enumerate(self.text_corpus):\n #print(i)\n self.dep = []\n self.pos_tag = []\n self.doc = self.nlp(str(text))\n sents = self.get_sentences_lst()\n ID.extend([i] * len(sents))\n sentences.extend(sents)\n tokens.extend(self.get_tokens())\n if self.parser:\n dep_vecs = self.get_dependencies()\n dep_lst = []\n # print(dep_vecs)\n for i in dep_vecs:\n dep_lst.append(' '.join(i))\n dep.extend(dep_lst)\n else:\n dep.extend(['disabled'] * len(sents))\n if self.tagger:\n tag_vecs = self.get_pos_tag()\n tag_lst = []\n for i in tag_vecs:\n tag_lst.append(' '.join(i))\n tag.extend(tag_lst)\n else:\n tag.extend(['disabled'] * len(sents))\n del self.doc\n\n # print(len(ID),len(sentences),len(dep),len(tag))\n self.df = pd.DataFrame(\n {'textID': ID, 'sentences': sentences, 'Dependency': dep, 'POS Tags': tag, 'tokens': tokens})\n self.df.to_csv(preprocess_out)\n return self.df\n\n def get_sentences_lst(self):\n return [i.text for i in self.doc.sents]\n\n def get_sentences(self):\n return list(self.doc.sents)\n\n def get_tokens(self):\n self.sentences = self.get_sentences()\n tokens = []\n for i in self.sentences:\n token = []\n for tokenz in i:\n if tokenz.is_alpha:\n token.append(tokenz.text)\n tokens.append(token)\n return tokens\n\n def get_pos_tag(self):\n if self.tagger:\n self.sentences = self.get_sentences()\n\n for i in self.sentences:\n token = []\n for tokenz in i:\n token.append((tokenz.tag_))\n self.pos_tag.append(token)\n return list(self.pos_tag)\n else:\n raise PipelineError('\"tagger\" disabled', 'enable to use this feature')\n\n def get_pos(self):\n if self.tagger:\n self.sentences = self.get_sentences()\n\n for i in self.sentences:\n token = []\n for tokenz in i:\n token.append((tokenz.pos_))\n self.poss.append(token)\n return list(self.poss)\n else:\n raise PipelineError('\"tagger\" disabled', 'enable to use this feature')\n\n def get_dependencies(self):\n if self.parser:\n self.sentences = self.get_sentences()\n\n for i in self.sentences:\n token = []\n for tokenz in i:\n token.append(tokenz.dep_)\n self.dep.append(token)\n return list(self.dep)\n else:\n raise PipelineError('\"dep\" disabled', 'enable to use this feature')\n\n def get_ner(self):\n if self.ner:\n # self.sentences.ents\n for ent in self.doc.ents:\n token = (ent.text, ent.label_)\n self.nerl.append(token)\n return list(self.nerl)\n else:\n raise PipelineError('\"ner\" disabled', 'enable to use this feature')\n\n\nclass Spacyize:\n def __init__(self, ner=1, parser=1, tagger=1, text=None):\n self.disable = []\n self.ner = ner\n self.parser = parser\n self.tagger = tagger\n self.text = text\n if self.text == None:\n raise PipelineError('Input text cannot be None',\n 'This object extract sentences, parts of speech, named entity recognition, dependencies')\n if self.ner == 0:\n self.disable.append('ner')\n if self.parser == 0:\n self.disable.append('parser')\n if self.tagger == 0:\n self.disable.append('tagger')\n if self.disable:\n self.nlp = spacy.load(\"en_core_web_sm\", disable=self.disable)\n else:\n self.nlp = spacy.load('en_core_web_sm')\n self.doc = self.nlp(text)\n self.pos_tag = []\n self.tokens = []\n self.tokenCnt_lst = []\n self.poss = []\n self.dep = []\n self.nerl = []\n\n def get_sentences_lst(self):\n return [i.text for i in self.doc.sents]\n\n def get_sentences(self):\n return list(self.doc.sents)\n\n def count_sentences(self):\n return len(list(self.doc.sents))\n\n def get_tokens(self):\n self.sentences = self.get_sentences()\n # self.tokens = []\n for i in self.sentences:\n token = []\n for tokenz in i:\n if tokenz.is_alpha:\n token.append(tokenz)\n self.tokens.append(token)\n return list(self.tokens)\n\n def average_tokens(self):\n if not self.tokens:\n self.get_tokens()\n\n for i in self.tokens:\n self.tokenCnt_lst.append(len(i))\n return np.mean(self.tokenCnt_lst)\n\n def get_pos_tag(self):\n if self.tagger:\n self.sentences = self.get_sentences()\n\n for i in self.sentences:\n token = []\n for tokenz in i:\n token.append((tokenz.tag_))\n self.pos_tag.append(token)\n return list(self.pos_tag)\n else:\n raise PipelineError('\"tagger\" disabled', 'enable to use this feature')\n\n def get_pos(self):\n if self.tagger:\n self.sentences = self.get_sentences()\n\n for i in self.sentences:\n token = []\n for tokenz in i:\n token.append((tokenz.pos_))\n self.poss.append(token)\n return list(self.poss)\n else:\n raise PipelineError('\"tagger\" disabled', 'enable to use this feature')\n\n def get_dependencies(self):\n if self.parser:\n self.sentences = self.get_sentences()\n\n for i in self.sentences:\n token = []\n for tokenz in i:\n token.append(tokenz.dep_)\n self.dep.append(token)\n return list(self.dep)\n else:\n raise PipelineError('\"dep\" disabled', 'enable to use this feature')\n\n def get_ner(self):\n if self.ner:\n # self.sentences.ents\n for ent in self.doc.ents:\n token = (ent.text, ent.label_)\n self.nerl.append(token)\n return list(self.nerl)\n else:\n raise PipelineError('\"ner\" disabled', 'enable to use this feature')\n\n\nclass CustomTokenParser(Spacyize):\n def __init__(self, ner, parser, tagger, text, split):\n super().__init__(ner, parser, tagger, text)\n self.split = split\n self.nlp.add_pipe(self.set_custom_boundaries, before='parser')\n self.doc = self.nlp(text)\n\n def set_custom_boundaries(self, doc1):\n for token in doc1[:-1]:\n if token.text == self.split:\n doc1[token.i + 1].is_sent_start = True\n return doc1\n\ndef read_preprocessed(preprocess_out=''):\n df = pd.read_csv(preprocess_out)\n return df","sub_path":"src/nlpipe/pipelines/Preprocess/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":12065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"209537837","text":"from django.shortcuts import render, redirect\nfrom .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\n\n'''\nWhat would happen if we would create a website from scratch without a framework?\n\nWe would have to put in different kinds of validation checks to make sure\nuser was putting the correct information correctly. Make sure that their hash passwords match.\nWrite regex to check if e-mail is ok...\n\nDjango takes care of that providing uses with forms that already give us that. These forms will\nbe classes that will be converted to html!\n'''\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST) # Instantiates an user created form\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'Your account has been created. Your are now able to log in!')\n return redirect('login')\n else:\n form = UserRegisterForm()\n\n return render(request, 'users/register.html', {'form': form})\n\n\n@login_required\ndef profile(request):\n\n if request.method == 'POST':\n u_form = UserUpdateForm(request.POST, instance=request.user)\n p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)\n if u_form.is_valid() and p_form.is_valid():\n u_form.save()\n p_form.save()\n messages.success(request, f'Your account has been updated!')\n return redirect('profile') # Causes the browser to send a get request instead of sending another post request once we reload the page\n else:\n u_form = UserUpdateForm(instance=request.user)\n p_form = ProfileUpdateForm(instance=request.user.profile)\n\n context = {\n 'u_form': u_form,\n 'p_form': p_form\n }\n\n return render(request, 'users/profile.html', context)\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"546494466","text":"import wx\r\n\r\nfrom LaserRender import swizzlecolor\r\nfrom icons import icons8_bold_50, icons8_underline_50, icons8_italic_50\r\nfrom svgelements import *\r\n\r\n_ = wx.GetTranslation\r\n\r\n\r\nclass TextProperty(wx.Frame):\r\n def __init__(self, *args, **kwds):\r\n # begin wxGlade: TextProperty.__init__\r\n kwds[\"style\"] = kwds.get(\"style\", 0) | wx.DEFAULT_FRAME_STYLE | wx.FRAME_TOOL_WINDOW | wx.STAY_ON_TOP\r\n wx.Frame.__init__(self, *args, **kwds)\r\n self.SetSize((317, 426))\r\n self.text_text = wx.TextCtrl(self, wx.ID_ANY, \"\")\r\n self.combo_font_size = wx.ComboBox(self, wx.ID_ANY, choices=[], style=wx.CB_DROPDOWN)\r\n self.combo_font = wx.ComboBox(self, wx.ID_ANY, choices=[], style=wx.CB_DROPDOWN)\r\n self.button_bold = wx.ToggleButton(self, wx.ID_ANY, \"\")\r\n self.button_italic = wx.ToggleButton(self, wx.ID_ANY, \"\")\r\n self.button_underline = wx.ToggleButton(self, wx.ID_ANY, \"\")\r\n self.button_stroke_none = wx.Button(self, wx.ID_ANY, \"None\")\r\n self.button_stroke_none.name = \"stroke none\"\r\n self.button_stroke_F00 = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_stroke_F00.name = \"stroke #F00\"\r\n self.button_stroke_0F0 = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_stroke_0F0.name = \"stroke #0F0\"\r\n self.button_stroke_00F = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_stroke_00F.name = \"stroke #00F\"\r\n self.button_stroke_F0F = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_stroke_F0F.name = \"stroke #F0F\"\r\n self.button_stroke_0FF = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_stroke_0FF.name = \"stroke #0FF\"\r\n self.button_stroke_FF0 = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_stroke_FF0.name = \"stroke #FF0\"\r\n self.button_stroke_000 = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_stroke_000.name = \"stroke #000\"\r\n\r\n self.button_fill_none = wx.Button(self, wx.ID_ANY, \"None\")\r\n self.button_fill_none.name = \"fill none\"\r\n self.button_fill_F00 = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_fill_F00.name = \"fill #F00\"\r\n self.button_fill_0F0 = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_fill_0F0.name = \"fill #0F0\"\r\n self.button_fill_00F = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_fill_00F.name = \"fill #00F\"\r\n self.button_fill_F0F = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_fill_F0F.name = \"fill #F0F\"\r\n self.button_fill_0FF = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_fill_0FF.name = \"fill #0FF\"\r\n self.button_fill_FF0 = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_fill_FF0.name = \"fill #FF0\"\r\n self.button_fill_000 = wx.Button(self, wx.ID_ANY, \"\")\r\n self.button_fill_000.name = \"fill #000\"\r\n\r\n self.__set_properties()\r\n self.__do_layout()\r\n\r\n self.Bind(wx.EVT_TEXT, self.on_text_name_change, self.text_text)\r\n self.Bind(wx.EVT_TEXT_ENTER, self.on_text_name_change, self.text_text)\r\n self.Bind(wx.EVT_COMBOBOX, self.on_combo_font_size, self.combo_font_size)\r\n self.Bind(wx.EVT_COMBOBOX, self.on_combo_font, self.combo_font)\r\n self.Bind(wx.EVT_TOGGLEBUTTON, self.on_button_bold, self.button_bold)\r\n self.Bind(wx.EVT_TOGGLEBUTTON, self.on_button_italic, self.button_italic)\r\n self.Bind(wx.EVT_TOGGLEBUTTON, self.on_button_underline, self.button_underline)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_stroke_none)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_stroke_F00)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_stroke_0F0)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_stroke_00F)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_stroke_F0F)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_stroke_0FF)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_stroke_FF0)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_stroke_000)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_fill_none)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_fill_F00)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_fill_0F0)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_fill_00F)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_fill_F0F)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_fill_0FF)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_fill_FF0)\r\n self.Bind(wx.EVT_BUTTON, self.on_button_color, self.button_fill_000)\r\n # end wxGlade\r\n self.kernel = None\r\n self.text_element = None\r\n self.Bind(wx.EVT_CLOSE, self.on_close, self)\r\n\r\n def on_close(self, event):\r\n self.kernel.mark_window_closed(\"TextProperty\")\r\n event.Skip() # Call destroy.\r\n\r\n def set_element(self, element):\r\n self.text_element = element\r\n try:\r\n if element.stroke is not None and element.stroke != \"none\":\r\n color = wx.Colour(swizzlecolor(element.stroke))\r\n self.text_text.SetBackgroundColour(color)\r\n except AttributeError:\r\n pass\r\n\r\n def set_kernel(self, kernel):\r\n self.kernel = kernel\r\n\r\n def __set_properties(self):\r\n # begin wxGlade: TextProperty.__set_properties\r\n self.SetTitle(_(\"Text Properties\"))\r\n self.button_bold.SetMinSize((52, 52))\r\n self.button_bold.SetBitmap(icons8_bold_50.GetBitmap())\r\n self.button_italic.SetMinSize((52, 52))\r\n self.button_italic.SetBitmap(icons8_italic_50.GetBitmap())\r\n self.button_underline.SetMinSize((52, 52))\r\n self.button_underline.SetBitmap(icons8_underline_50.GetBitmap())\r\n self.button_stroke_none.SetToolTip(_(\"\\\"none\\\" defined value\"))\r\n self.button_stroke_F00.SetBackgroundColour(wx.Colour(255, 0, 0))\r\n self.button_stroke_F00.SetToolTip(_(\"#FF0000 defined values.\"))\r\n self.button_stroke_0F0.SetBackgroundColour(wx.Colour(0, 255, 0))\r\n self.button_stroke_0F0.SetToolTip(_(\"#00FF00 defined values.\"))\r\n self.button_stroke_00F.SetBackgroundColour(wx.Colour(0, 0, 255))\r\n self.button_stroke_00F.SetToolTip(_(\"#00FF00 defined values.\"))\r\n self.button_stroke_F0F.SetBackgroundColour(wx.Colour(255, 0, 255))\r\n self.button_stroke_F0F.SetToolTip(_(\"#FF00FF defined values.\"))\r\n self.button_stroke_0FF.SetBackgroundColour(wx.Colour(0, 255, 255))\r\n self.button_stroke_0FF.SetToolTip(_(\"#00FFFF defined values.\"))\r\n self.button_stroke_FF0.SetBackgroundColour(wx.Colour(255, 255, 0))\r\n self.button_stroke_FF0.SetToolTip(_(\"#FFFF00 defined values.\"))\r\n self.button_stroke_000.SetBackgroundColour(wx.Colour(0, 0, 0))\r\n self.button_stroke_000.SetToolTip(_(\"#000000 defined values.\"))\r\n self.button_fill_none.SetToolTip(_(\"\\\"none\\\" defined value\"))\r\n self.button_fill_F00.SetBackgroundColour(wx.Colour(255, 0, 0))\r\n self.button_fill_F00.SetToolTip(_(\"#FF0000 defined values.\"))\r\n self.button_fill_0F0.SetBackgroundColour(wx.Colour(0, 255, 0))\r\n self.button_fill_0F0.SetToolTip(_(\"#00FF00 defined values.\"))\r\n self.button_fill_00F.SetBackgroundColour(wx.Colour(0, 0, 255))\r\n self.button_fill_00F.SetToolTip(_(\"#00FF00 defined values.\"))\r\n self.button_fill_F0F.SetBackgroundColour(wx.Colour(255, 0, 255))\r\n self.button_fill_F0F.SetToolTip(_(\"#FF00FF defined values.\"))\r\n self.button_fill_0FF.SetBackgroundColour(wx.Colour(0, 255, 255))\r\n self.button_fill_0FF.SetToolTip(_(\"#00FFFF defined values.\"))\r\n self.button_fill_FF0.SetBackgroundColour(wx.Colour(255, 255, 0))\r\n self.button_fill_FF0.SetToolTip(_(\"#FFFF00 defined values.\"))\r\n self.button_fill_000.SetBackgroundColour(wx.Colour(0, 0, 0))\r\n self.button_fill_000.SetToolTip(_(\"#000000 defined values.\"))\r\n # end wxGlade\r\n\r\n def __do_layout(self):\r\n # begin wxGlade: TextProperty.__do_layout\r\n sizer_8 = wx.BoxSizer(wx.VERTICAL)\r\n sizer_6 = wx.BoxSizer(wx.HORIZONTAL)\r\n sizer_9 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, _(\"Fill Color\")), wx.VERTICAL)\r\n sizer_7 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, _(\"Stroke Color\")), wx.VERTICAL)\r\n sizer_3 = wx.BoxSizer(wx.HORIZONTAL)\r\n sizer_2 = wx.BoxSizer(wx.HORIZONTAL)\r\n sizer_1 = wx.BoxSizer(wx.HORIZONTAL)\r\n sizer_8.Add(self.text_text, 0, wx.EXPAND, 0)\r\n label_1 = wx.StaticText(self, wx.ID_ANY, _(\"Font Size:\"))\r\n sizer_1.Add(label_1, 1, 0, 0)\r\n sizer_1.Add(self.combo_font_size, 2, 0, 0)\r\n sizer_8.Add(sizer_1, 1, wx.EXPAND, 0)\r\n label_2 = wx.StaticText(self, wx.ID_ANY, _(\"Font:\"))\r\n sizer_2.Add(label_2, 1, 0, 0)\r\n sizer_2.Add(self.combo_font, 2, 0, 0)\r\n sizer_8.Add(sizer_2, 1, wx.EXPAND, 0)\r\n sizer_3.Add(self.button_bold, 0, 0, 0)\r\n sizer_3.Add(self.button_italic, 0, 0, 0)\r\n sizer_3.Add(self.button_underline, 0, 0, 0)\r\n sizer_8.Add(sizer_3, 0, wx.EXPAND, 0)\r\n sizer_7.Add(self.button_stroke_none, 0, wx.EXPAND, 0)\r\n sizer_7.Add(self.button_stroke_F00, 0, wx.EXPAND, 0)\r\n sizer_7.Add(self.button_stroke_0F0, 0, wx.EXPAND, 0)\r\n sizer_7.Add(self.button_stroke_00F, 0, wx.EXPAND, 0)\r\n sizer_7.Add(self.button_stroke_F0F, 0, wx.EXPAND, 0)\r\n sizer_7.Add(self.button_stroke_0FF, 0, wx.EXPAND, 0)\r\n sizer_7.Add(self.button_stroke_FF0, 0, wx.EXPAND, 0)\r\n sizer_7.Add(self.button_stroke_000, 0, wx.EXPAND, 0)\r\n sizer_6.Add(sizer_7, 1, wx.EXPAND, 0)\r\n sizer_9.Add(self.button_fill_none, 0, wx.EXPAND, 0)\r\n sizer_9.Add(self.button_fill_F00, 0, wx.EXPAND, 0)\r\n sizer_9.Add(self.button_fill_0F0, 0, wx.EXPAND, 0)\r\n sizer_9.Add(self.button_fill_00F, 0, wx.EXPAND, 0)\r\n sizer_9.Add(self.button_fill_F0F, 0, wx.EXPAND, 0)\r\n sizer_9.Add(self.button_fill_0FF, 0, wx.EXPAND, 0)\r\n sizer_9.Add(self.button_fill_FF0, 0, wx.EXPAND, 0)\r\n sizer_9.Add(self.button_fill_000, 0, wx.EXPAND, 0)\r\n sizer_6.Add(sizer_9, 1, wx.EXPAND, 0)\r\n sizer_8.Add(sizer_6, 1, wx.EXPAND, 0)\r\n self.SetSizer(sizer_8)\r\n self.Layout()\r\n self.Centre()\r\n # end wxGlade\r\n\r\n def on_combo_font_size(self, event): # wxGlade: TextProperty.\r\n pass\r\n\r\n def on_combo_font(self, event): # wxGlade: TextProperty.\r\n event.Skip()\r\n\r\n def on_button_bold(self, event): # wxGlade: TextProperty.\r\n dialog = wx.FontDialog(None, wx.FontData())\r\n if dialog.ShowModal() == wx.ID_OK:\r\n data = dialog.GetFontData()\r\n font = data.GetChosenFont()\r\n color = data.GetColour()\r\n print(color)\r\n print('\"%s\", %d pt\\n' % (font.GetFaceName(), font.GetPointSize()))\r\n dialog.Destroy()\r\n\r\n def on_button_italic(self, event): # wxGlade: TextProperty.\r\n font_picker = wx.FontDialog()\r\n font_picker.Show()\r\n\r\n def on_button_underline(self, event): # wxGlade: TextProperty.\r\n font_picker = wx.FontDialog()\r\n font_picker.Show()\r\n\r\n def on_text_name_change(self, event): # wxGlade: ElementProperty.\r\n try:\r\n self.text_element.text = self.text_text.GetValue()\r\n if self.kernel is not None:\r\n self.kernel.signal(\"element_property_update\", self.text_element)\r\n except AttributeError:\r\n pass\r\n\r\n def on_button_color(self, event): # wxGlade: ElementProperty.\r\n button = event.EventObject\r\n color = None\r\n if 'none' not in button.name:\r\n color = button.GetBackgroundColour()\r\n rgb = color.GetRGB()\r\n color = swizzlecolor(rgb)\r\n color = Color(color, 1.0)\r\n if 'stroke' in button.name:\r\n if color is not None:\r\n self.text_element.stroke = color\r\n self.text_element.values[SVG_ATTR_STROKE] = color.hex\r\n else:\r\n self.text_element.stroke = Color('none')\r\n self.text_element.values[SVG_ATTR_STROKE] = 'none'\r\n elif 'fill' in button.name:\r\n if color is not None:\r\n self.text_element.fill = color\r\n self.text_element.values[SVG_ATTR_FILL] = color.hex\r\n else:\r\n self.text_element.fill = Color('none')\r\n self.text_element.values[SVG_ATTR_FILL] = 'none'\r\n if self.kernel is not None:\r\n self.kernel.signal(\"element_property_update\", self.text_element)\r\n self.kernel.signal(\"refresh_scene\", 0)\r\n","sub_path":"TextProperty.py","file_name":"TextProperty.py","file_ext":"py","file_size_in_byte":12883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"354353697","text":"from django.contrib import admin\nfrom MyBook.base_admin import BaseOwnerAdmin\nfrom MyBook.custom_site import custom_site\nfrom .models import Chapter\n# Register your models here.\n\n\n@admin.register(Chapter,site=custom_site)\nclass ChapterAdmin(BaseOwnerAdmin):\n\n list_display = (\n 'book',\n 'chapters',\n 'content',\n 'status',\n 'update_time',\n )\n\n list_filter = (\n 'book',\n 'chapters',\n 'content',\n )\n\n","sub_path":"chapter/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"406191981","text":"\"\"\"rename scripted corpus code groups\n\nRevision ID: 98b45ec95d60\nRevises: e5edc71852ad\nCreate Date: 2016-10-26 09:44:35.783968\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '98b45ec95d60'\ndown_revision = 'e5edc71852ad'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade():\n\n\t# drop references to scripted groups\n\top.drop_index('corpus_codes_by_scripted_corpus_code_group_id', table_name='corpus_codes')\n\top.drop_column(u'corpus_codes', 'scripted_corpus_code_group_id')\n\n\t# drop scripted groups\n\top.drop_table('scripted_corpus_code_groups')\n\n\t# add checking groups\n\top.create_table('audio_checking_groups',\n\tsa.Column('audio_checking_group_id', sa.INTEGER(), nullable=False),\n\tsa.Column('recording_platform_id', sa.INTEGER(), nullable=False),\n\tsa.Column('name', sa.TEXT(), nullable=False),\n\tsa.Column('selection_size', sa.INTEGER(), nullable=False),\n\tsa.CheckConstraint(u'selection_size > 0'),\n\tsa.ForeignKeyConstraint(['recording_platform_id'], ['recording_platforms.recording_platform_id'], ),\n\tsa.PrimaryKeyConstraint('audio_checking_group_id')\n\t)\n\top.create_index('audio_checking_groups_by_recording_platform_id', 'audio_checking_groups', ['recording_platform_id'], unique=False)\n\n\t# add references to checking groups\t\n\top.add_column(u'corpus_codes', sa.Column('audio_checking_group_id', sa.INTEGER(), nullable=True))\n\top.create_index('corpus_codes_by_audio_checking_group_id', 'corpus_codes', ['audio_checking_group_id'], unique=False)\n\top.create_foreign_key(None, 'corpus_codes', 'audio_checking_groups', ['audio_checking_group_id'], ['audio_checking_group_id'])\n\n\ndef downgrade():\n\n\t# drop references to checking groups\n\top.drop_index('corpus_codes_by_audio_checking_group_id', table_name='corpus_codes')\n\top.drop_column(u'corpus_codes', 'audio_checking_group_id')\n\n\t# drop checking groups\n\top.drop_table('audio_checking_groups')\n\n\t# add scripted groups\n\top.create_table('scripted_corpus_code_groups',\n\tsa.Column('scripted_corpus_code_group_id', sa.INTEGER(), nullable=False),\n\tsa.Column('recording_platform_id', sa.INTEGER(), autoincrement=False, nullable=False),\n\tsa.Column('name', sa.TEXT(), autoincrement=False, nullable=False),\n\tsa.Column('selection_size', sa.INTEGER(), autoincrement=False, nullable=False),\n\tsa.ForeignKeyConstraint(['recording_platform_id'], [u'recording_platforms.recording_platform_id'], name=u'scripted_corpus_code_groups_recording_platform_id_fkey'),\n\tsa.PrimaryKeyConstraint('scripted_corpus_code_group_id', name=u'scripted_corpus_code_groups_pkey')\n\t)\n\top.create_index('corpus_codes_by_scripted_corpus_code_group_id', 'corpus_codes', ['scripted_corpus_code_group_id'], unique=False)\n\n\t# add references to scripted groups\n\top.add_column(u'corpus_codes', sa.Column('scripted_corpus_code_group_id', sa.INTEGER(), autoincrement=False, nullable=True))\n\top.create_index('corpus_codes_by_scripted_corpus_code_group_id', 'corpus_codes', ['scripted_corpus_code_group_id'], unique=False)\n","sub_path":"migrations/versions/98b45ec95d60_rename_scripted_corpus_code_groups.py","file_name":"98b45ec95d60_rename_scripted_corpus_code_groups.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"439739419","text":"# Source : https://leetcode.com/problems/path-sum/\n# Author : Phat Nguyen\n# Date : 2015-03-25\n\n\"\"\"\nPROBLEM:\nGiven a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.\n\nFor example:\nGiven the below binary tree and sum = 22,\n 5\n / \\\n 4 8\n / / \\\n 11 13 4\n / \\ \\\n 7 2 1\nreturn true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.\n\nSOLUTION:\n\n\"\"\"\n\n# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param root, a tree node\n # @param sum, an integer\n # @return a boolean\n def hasPathSum(self, root, sum):\n if not root: return False\n else: return self.hasPS(root, sum)\n \n def hasPS(self, root, sum):\n if not root.left and not root.right:\n if sum - root.val == 0: return True\n else: return False\n else:\n ans = False\n if root.left: ans = ans or self.hasPS(root.left, sum-root.val)\n if root.right: ans = ans or self.hasPS(root.right, sum-root.val)\n return ans\n \n","sub_path":"py/112.py","file_name":"112.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"230982455","text":"def electionWinner(votes):\r\n res ={}\r\n for cand in votes:\r\n res[cand]=res.get(cand,0)+1\r\n\r\n maxVotes = max(res.values())\r\n maxCands = [x for (x,y) in res.items() if y==maxVotes]\r\n maxCands.sort()\r\n return maxCands[-1]\r\n\r\ninput = ['Trump','Trump','Harry','Alex','Mary','Mary','Alex']\r\nprint(electionWinner(input))","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"491006156","text":"import aiml\nimport os\nimport time\nimport argparse\nimport pyttsx3\nimport smtplib\nimport webbrowser as wb\nimport wikipedia as wk\nimport datetime as dt\n\ndictionary = {'Google':'google', \"Facebook\":\"facebook\", \"youtube\":\"youtube\", \"Jira\":\"jira\", \"Confluence\":\"confluence\", \"instagram\":\"instagram\", \"hotstar\":\"hotstar\", \"gaana\":\"gaana\"}\n\nmode = \"text\"\nvoice = \"pyttsx3\"\nterminate = ['nothing bye', 'nothing buy', 'nothing shutdown', 'nothing exit', 'quit', 'gotosleep', 'nothing goodbye', 'goodbye']\n\n\ndef get_arguments():\n parser = argparse.ArgumentParser()\n optional = parser.add_argument_group('params')\n optional.add_argument('-v', '--voice', action='store_true', required=False,\n help='Enable voice mode')\n optional.add_argument('-g', '--gtts', action='store_true', required=False,\n help='Enable Google Text To Speech engine')\n arguments = parser.parse_args()\n return arguments\n\n\ndef gtts_speak(jarvis_speech):\n tts = gTTS(text=jarvis_speech, lang='en')\n tts.save('jarvis_speech.mp3')\n mixer.init()\n mixer.music.load('jarvis_speech.mp3')\n mixer.music.play()\n while mixer.music.get_busy():\n time.sleep(1)\n\n\ndef offline_speak(jarvis_speech):\n engine = pyttsx3.init()\n engine.say(jarvis_speech)\n engine.runAndWait()\n\n\ndef speak(jarvis_speech):\n if voice == \"gTTS\":\n gtts_speak(jarvis_speech)\n else:\n offline_speak(jarvis_speech)\n\n\ndef listen():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Talk to I.P.M \")\n r.pause_threshold = 0.8\n audio = r.listen(source)\n try:\n print (r.recognize_google(audio))\n return r.recognize_google(audio)\n except sr.UnknownValueError:\n speak(\n \"I couldn't understand what you said! Would you like to repeat?\")\n return(listen())\n except sr.RequestError as e:\n print(\"Could not request results from \" +\n \"Google Speech Recognition service; {0}\".format(e))\n\ndef wishme():\n hour = int(dt.datetime.now().hour)\n if (hour >= 0 and hour < 12):\n speak(\"Good Morning Sir, Have a Nice day\")\n elif (hour >= 12 and hour < 18):\n speak(\"Good Afternoon Sir, have a nice noon\")\n else:\n speak(\"Good Evening Sir, Have a nice evening\")\n speak(\"hello sir how may i help you\")\n\ndef sendemail(to, content):\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.login(\"dzkakadiya3@gmail.com\", \"Dhruv@81282\")\n server.sendmail(\"dzkakadiya3@gmail.com\", to, content)\n server.close()\n \nif __name__ == '__main__':\n wishme()\n try:\n import speech_recognition as sr\n mode = \"voice\"\n except ImportError:\n print(\"\\nInstall SpeechRecognition to use this feature.\" +\n \"\\nStarting text mode\\n\")\n \n kernel = aiml.Kernel()\n\n if os.path.isfile(\"bot_brain.brn\"):\n kernel.bootstrap(brainFile=\"bot_brain.brn\")\n else:\n kernel.bootstrap(learnFiles=\"std-startup.xml\", commands=\"load aiml b\")\n \n\n # kernel now ready for use\n while True:\n if mode == \"voice\":\n response = listen()\n else:\n response = input(\"Talk to I.P.M :- \")\n if response.lower().replace(\" \", \"\") in terminate:\n speak(\"okay nice to see you sir, goodbye\")\n break\n \n elif \"send email to\" in response :\n try:\n speak(\"what would you like to mail?\")\n content = listen()\n to = \"nevilparmar24@gmail.com\"\n sendemail(to, content)\n speak(\"email has been sent successfully\")\n except Exception as e:\n print(e)\n speak(\"sorry try again\")\n elif \"search about\" in response:\n try:\n lst = response.split(\" \")\n b = False\n string = \"\"\n for i in lst:\n if b == True:\n string = string + \"+\" + i\n if (i == \"about\"): \n b = True\n \n if string:\n print(string)\n wb.open(\"google.com/search?q=\" + string)\n else:\n speak(\"what you mean to say\")\n except Exception as e:\n print(e)\n speak(\"i cant find it\")\n elif \"open\" in response:\n try:\n for key,value in dictionary.items():\n if key.upper() in response.upper():\n br = value + \".com\"\n wb.open(br)\n speak(\"opened\")\n except Exception as e:\n print(e)\n speak(\"sorry\")\n elif \"time\" in response:\n strtime = dt.datetime.now().strftime(\"%H:%M:%S\")\n print(strtime)\n speak(f\"Sir, the time is {strtime}\")\n elif (\"about\" in response):\n try:\n speak(\"Sure sir,Searching.......\")\n response = response.replace(\"wikipedia\", \"\")\n response = response.replace(\"about\", \"\")\n response = response.replace(\"tell me \",\"\")\n print(response)\n results = wk.summary(response, sentences = 5)\n \n speak(\"According to your search\")\n print(results)\n speak(results)\n except Exception as e:\n print(\"information not available\")\n speak(\"information not available\")\n else:\n jarvis_speech = kernel.respond(response)\n print (\"ALEXA \" + jarvis_speech)\n speak(jarvis_speech)","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":5761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"168588209","text":"import os\nimport shutil\nimport numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom PIL import Image\nfrom Data import FlyGenerator\nimport settings\n\n\ntrain_data_gen_args = dict(rescale=1. / 255)\n'''\n featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=180,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=True,\n fill_mode='reflect')\n'''\n\ntest_data_gen_args = dict(rescale=1. / 255)\n\n\n# add functionality for splitting folders\ndef get_generators(image_dir, validation_pct=None):\n if validation_pct is None:\n train_generator, validation_generator, num_train_samples, num_test_samples = gen_from_folders(image_dir)\n else:\n train_generator, validation_generator, num_train_samples, num_test_samples = gen_from_image_lists(image_dir, validation_pct)\n\n settings.NUM_TRAIN_SAMPLES = num_train_samples\n settings.NUM_TEST_SAMPLES = num_test_samples\n\n return train_generator, validation_generator\n\n\ndef gen_from_image_lists(image_dir, validation_pct=20):\n \"\"\"\n Generate image batches for training and validation without physically splitting it on disk\n\n :param image_dir:\n :param validation_pct: integer between (0, 100)\n :return:\n \"\"\"\n\n global train_data_gen_args, test_data_gen_args\n\n image_lists = FlyGenerator.create_image_lists(image_dir, validation_pct)\n\n classes = list(image_lists.keys())\n print(classes)\n num_classes = len(classes)\n\n NUM_TRAIN_SAMPLES = 0\n NUM_TEST_SAMPLES = 0\n for i in range(num_classes):\n NUM_TRAIN_SAMPLES += len(image_lists[classes[i]]['training'])\n NUM_TEST_SAMPLES += len(image_lists[classes[i]]['validation'])\n\n train_datagen = FlyGenerator.CustomImageDataGenerator(**train_data_gen_args)\n\n test_datagen = FlyGenerator.CustomImageDataGenerator(**test_data_gen_args)\n\n train_generator = train_datagen.flow_from_image_lists(\n image_lists=image_lists,\n category='training',\n image_dir=image_dir,\n # save_to_dir='./output/augmented_data',\n target_size=(settings.MODEL_INPUT_HEIGHT, settings.MODEL_INPUT_WIDTH),\n batch_size=settings.BATCH_SIZE,\n class_mode=settings.CLASS_MODE,\n seed=settings.RANDOM_SEED)\n\n validation_generator = test_datagen.flow_from_image_lists(\n image_lists=image_lists,\n category='validation',\n image_dir=image_dir,\n target_size=(settings.MODEL_INPUT_HEIGHT, settings.MODEL_INPUT_WIDTH),\n batch_size=settings.BATCH_SIZE,\n class_mode=settings.CLASS_MODE,\n seed=settings.RANDOM_SEED)\n\n '''\n modify global variables if necessary: class label association, class weight matrix respectively\n '''\n settings.class_dict = train_generator.class2id\n print(\"label mapping is : \", settings.class_dict)\n settings.class_weight = {settings.class_dict['nonglomeruli']: 1, # 0 : 1\n settings.class_dict['glomeruli']: settings.weight_glom} # 1 : 25\n print(\"class weighting is : \", settings.class_weight)\n\n return train_generator, validation_generator, NUM_TRAIN_SAMPLES, NUM_TEST_SAMPLES\n\n\ndef gen_from_folders(image_dir):\n \"\"\"\n Generate image batches from train and test subdirectories\n\n :param image_dir:\n :return:\n \"\"\"\n\n global train_data_gen_args, test_data_gen_args\n\n # folders with split data\n DIR_TRAIN_GLOM = image_dir + \"/train/glomeruli\"\n DIR_TEST_GLOM = image_dir + \"/test/glomeruli\"\n DIR_TRAIN_NONGLOM = image_dir + \"/train/nonglomeruli\"\n DIR_TEST_NONGLOM = image_dir + \"/test/nonglomeruli\"\n\n NUM_TRAIN_SAMPLES = len(os.listdir(DIR_TRAIN_GLOM)) + len(os.listdir(DIR_TRAIN_NONGLOM))\n NUM_TEST_SAMPLES = len(os.listdir(DIR_TEST_GLOM)) + len(os.listdir(DIR_TEST_NONGLOM))\n\n TRAIN_DIR_PATH = image_dir + \"/train\"\n TEST_DIR_PATH = image_dir + \"/test\"\n\n train_datagen = ImageDataGenerator(**train_data_gen_args)\n test_datagen = ImageDataGenerator(**test_data_gen_args)\n\n train_generator = train_datagen.flow_from_directory(\n TRAIN_DIR_PATH,\n target_size=(settings.MODEL_INPUT_WIDTH, settings.MODEL_INPUT_HEIGHT),\n batch_size=settings.BATCH_SIZE,\n class_mode=settings.CLASS_MODE)\n\n # this is a similar generator, for validation data\n validation_generator = test_datagen.flow_from_directory(\n TEST_DIR_PATH,\n target_size=(settings.MODEL_INPUT_WIDTH, settings.MODEL_INPUT_HEIGHT),\n batch_size=settings.BATCH_SIZE,\n class_mode=settings.CLASS_MODE)\n\n if train_generator.class_indices != validation_generator.class_indices:\n raise ValueError\n\n settings.class_dict = train_generator.class_indices\n print(\"label mapping is : \", settings.class_dict)\n settings.class_weight = {settings.class_dict['nonglomeruli']: 1, # 0 : 1\n settings.class_dict['glomeruli']: settings.weight_glom} # 1 : 25\n print(\"class weighting is : \", settings.class_weight)\n\n #test_datagen.fit(train_generator)\n #train_datagen.fit(train_generator)\n\n return train_generator, validation_generator, NUM_TRAIN_SAMPLES, NUM_TEST_SAMPLES\n\n\ndef split_data_train_test_folders(image_dir, validation_pct=20):\n \"\"\"\n Create train and test subdirectories for every class folder found in image_dir\n\n :param image_dir: folder with data spit in classes\n :param validation_pct: integer between (0, 100)\n :return:\n\n +---image_dir\n | \\---glomeruli\n | \\---nonglomeruli\n +---split\n | +---train\n | \\---glomeruli\n | \\---nonglomeruli\n | +---test\n | \\---glomeruli\n | \\---nonglomeruli\n\n \"\"\"\n validation_pct /= 100 # validation_pct in interval (0, 1)\n\n # folders with unsplit data\n DIR_GLOM = image_dir + \"/glomeruli\"\n DIR_NONGLOM = image_dir + \"/nonglomeruli\"\n\n # go up one folder\n parent_dir = os.path.dirname(image_dir)\n\n # folders with split data\n DIR_TRAIN_GLOM = parent_dir + \"/split/train/glomeruli\"\n DIR_TEST_GLOM = parent_dir + \"/split/test/glomeruli\"\n DIR_TRAIN_NONGLOM = parent_dir + \"/split/train/nonglomeruli\"\n DIR_TEST_NONGLOM = parent_dir + \"/split/test/nonglomeruli\"\n\n os.makedirs(DIR_TRAIN_GLOM, exist_ok=True)\n os.makedirs(DIR_TEST_GLOM, exist_ok=True)\n os.makedirs(DIR_TRAIN_NONGLOM, exist_ok=True)\n os.makedirs(DIR_TEST_NONGLOM, exist_ok=True)\n\n files_glom = os.listdir(DIR_GLOM)\n files_nonglom = os.listdir(DIR_NONGLOM)\n\n nb_files_glom = len(files_glom)\n nb_files_nonglom = len(files_nonglom)\n\n for f in files_glom:\n if np.random.rand(1) < validation_pct: # and nb_files_glom_test < nb_files_glom // validation_pct:\n shutil.copy(DIR_GLOM + '/' + f, DIR_TEST_GLOM + '/' + f)\n else:\n shutil.copy(DIR_GLOM + '/' + f, DIR_TRAIN_GLOM + '/' + f)\n\n for f in files_nonglom:\n if np.random.rand(1) < validation_pct:\n shutil.copy(DIR_NONGLOM + '/' + f, DIR_TEST_NONGLOM + '/' + f)\n else:\n shutil.copy(DIR_NONGLOM + '/' + f, DIR_TRAIN_NONGLOM + '/' + f)\n\n\nif __name__ == '__main__':\n\n '''\n Split data in train and test \n '''\n dir = \"/Users/diana/Documents/2018_Glomeruli/data\"\n #split_data_train_test_folders(image_dir=dir, validation_pct=10)\n\n '''\n Augment training data for glomeruli class\n '''\n GLOM_TRAIN_DIR_PATH = \"/Users/diana/Documents/2018_Glomeruli/split/train/glomeruli/\"\n AUGM_GLOM_TRAIN_DIR_PATH = \"/Users/diana/Documents/2018_Glomeruli/split/train/augmented_glomeruli\"\n\n target_size = (512, 512)\n\n files = os.listdir(GLOM_TRAIN_DIR_PATH)\n\n x_train_glom = []\n\n for f in files:\n if f == '.DS_Store':\n continue\n path = GLOM_TRAIN_DIR_PATH + f\n x = Image.open(path)\n x_resize = Image.Image.resize(x, target_size)\n x_resize = np.asarray(x_resize, dtype='float32')\n x_resize /= 255\n x_train_glom.append(x_resize)\n\n x_train_glom = np.stack(x_train_glom, axis=0)\n\n\n train_data_gen_args = dict(\n rotation_range=90,\n width_shift_range=0.1,\n shear_range=0.1,\n zoom_range=0.1,\n fill_mode='reflect')\n\n train_datagen = ImageDataGenerator(**train_data_gen_args)\n\n train_generator = train_datagen.flow(\n x_train_glom,\n save_to_dir=AUGM_GLOM_TRAIN_DIR_PATH)\n\n train_datagen.fit(train_generator, augment=True, rounds=1)\n\n","sub_path":"Data/GetData.py","file_name":"GetData.py","file_ext":"py","file_size_in_byte":8777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"67146045","text":"# -*- coding: utf-8 -*-\n# @Author: jpch89\n# @Time: 18-9-4 上午7:25\n\n\"\"\"\n编写一个函数,其作用是将输入的字符串反转过来。\n\"\"\"\n\n\nclass Solution:\n def reverseString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n str_list = []\n for i in range(len(s) - 1, -1 , -1):\n str_list.append(s[i])\n return ''.join(str_list)\n","sub_path":"未分类/02字符串/01反转字符串.py","file_name":"01反转字符串.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"421063874","text":"#############################################################\n# #\n# MAC0122 Princípos de Desenvolvimento de Algoritmos #\n# #\n# MÓDULO util.py #\n# #\n# Contém funções auxiliares do EP6 #\n# #\n# Não altere nada neste arquivo. #\n# #\n# Não altere o nome do arquivo. #\n# # \n#############################################################\n\n# módulo para geração de números aleatorios\nimport random\n\n# para cronometrar o tempo das funções\nimport time\n\n# módulo responsável pela animação\nimport console\n\n# constantes\n# retângulo onde os pontos serão gerados é definido por\n# - canto inferior esquerdo [X_MIN,Y_MIN] e\n# - canto superior direito [X_MAX,Y_MAX].\nX_MIN = -1024\nY_MIN = -1024\nX_MAX = 1024\nY_MAX = 1024\nCANTOS = [[X_MIN,Y_MIN],[X_MAX,Y_MAX]]\n\n# cada ponto é representando por um para [x,y] \nX = 0 # abscissa do ponto é valor na posição 0 \nY = 1 # ordenada do ponto é valor na posição 1 \n\n#------------------------------------------------------------- \ndef gere_pontos(n, semente, cantos=CANTOS):\n '''(int, int, list) -> list\n\n Recebe um número inteiro não negativo `n`, um número inteiro \n `semente` e uma lista `cantos` com de pares de números inteiros \n [[x_min,y_min],[x_max,y_max]] que definem uma região retangular do \n plano cartesiano. \n\n A função cria e retorna uma lista de coordenadas inteiras de \n n pontos gerados aleatoriamente na região retangular. \n Assim, para cada ponto [x,y] na lista retornada temos que:\n\n - x e y são números inteiros;\n - x_min <= x < x_max\n - y_min <= y < y_max\n\n O valor de semente é usado para inicializar o gerador de números \n aleatórios do Python.\n\n Não altere está função.\n '''\n # avise que estamos trabalhando\n print(\"\\ngere_pontos(): gerando %d pontos ...\" %n)\n \n # crie a lista a ser retornada\n l_pontos = []\n \n # inicialize a semente do gerador \n random.seed(semente)\n\n # cantos da região retangular\n x_min, y_min = cantos[0]\n x_max, y_max = cantos[1]\n\n # gere os pontos\n for i in range(n):\n # sorteie uma posição no retângulo \n x = random.randrange(x_min,x_max)\n y = random.randrange(y_min,y_max)\n\n # coloque o ponto na lista\n l_pontos.append([x,y])\n\n # avise que terminamos o serviço e estamos voltando\n print(\"gere_pontos(): pontos gerados.\")\n \n return l_pontos\n \n#------------------------------------------------------------\ndef execute(par_mais_proximo, lista_pontos, ordene_x):\n '''(function, list, bool) -> None\n\n Recebe uma função `par_mais_proximo()`, uma lista de pontos\n `lista_pontos` e um booleano ordene_x. A função mede o consumo \n de tempo e imprime pequeno um pequeno relatório referente\n a execução da chamada\n\n para_mais_proximo(0,len(lista_pontos),lista_pontos)\n\n Se ordene_x == True, antes dessa chamada, a lista de \n ponto é ordenada em relação as coordenadas x (= da esquerda\n para a direita). O tempo dessa ordenação é levado em \n consideração.\n\n Nota:\n\n https://docs.python.org/3.0/library/time.html#time.clock\n\n time.clock():\n\n On Unix, return the current processor time as a floating point\n number expressed in seconds. The precision, and in fact the very\n definition of the meaning of “processor time”, depends on that of\n the C function of the same name, but in any case, this is the\n function to use for benchmarking Python or timing algorithms.\n\n On Windows, this function returns wall-clock seconds elapsed since\n the first call to this function, as a floating point number, based\n on the Win32 function QueryPerformanceCounter. The resolution is\n typically better than one microsecond.\n '''\n # começe a cronometrar \n start = time.clock()\n\n # função mac0122() necessita pré-processamento\n if ordene_x:\n # ordene os pontos de acordo com as coordenadas x (= abscissas)\n # chave = função que indica que a lista deve ser ordenada em relação\n # a coordenada X\n print(\"\\nexecute(): pontos sendo ordenados em relação a coordenada x...\")\n lista_pontos.sort(key=chave)\n print(\"execute(): pontos ordenados.\")\n \n # execute a função\n dist, par = par_mais_proximo(0,len(lista_pontos),lista_pontos)\n\n # trave o cronômetro \n end = time.clock()\n\n # calcule o tempo gasto\n elapsed = end - start\n\n print(\"\\nResultado: \")\n print(\" par mais próximo =\", par)\n # caso ainda não tenha implementado a função\n if dist == None:\n print(\" menor distância = None\")\n else:\n print(\" menor distância = %.2f\" %dist)\n print(\" tempo de execução = %.2fs\" %elapsed)\n\n\n#------------------------------------------------------------\ndef animacao(par_mais_proximo, lista_pontos):\n '''(function, list) -> None\n\n Recebe uma função `par_mais_proximo()` e uma lista de pontos\n `lista_pontos`. A função apresenta uma pequena aninamação da\n execução da chamada\n\n para_mais_proximo(0,len(lista_pontos),lista_pontos)\n '''\n global janela\n \n # crie uma janela com os pontos\n janela = console.Console(lista_pontos, CANTOS)\n\n # contemple os pontos\n pause()\n\n # determine o par mais próximo\n print(\"\\nVeja sua função em ação...\")\n dist, par = par_mais_proximo(0,len(lista_pontos),lista_pontos)\n\n # contemple as linhas indicando chamadas à função distancia()\n pause()\n\n # mostre apenas um par mais próximo\n janela.reset()\n janela.desenhe_linha(par)\n\n # mostre pequeno relatório da execução da função\n no_chamadas_dist = janela.no_call_dist()\n print(\"\\nResultado: \")\n print(\" par mais próximo =\", par)\n # caso ainda não tenha implementado a função\n if dist == None:\n print(\" menor distância = None\")\n else:\n print(\" menor distância = %.2f\" %dist)\n print(\" no. chamadas da função distancia() = %d\" %no_chamadas_dist)\n \n # contemple um par mais próximo antes de irmos embora\n janela.exitonclick() \n\n \n#------------------------------------------------------------\ndef pause(): \n '''(None) -> None\n\n Para a execução do programa até que um ENTER seja teclado.\n\n Não altere está função\n '''\n input(\"\\nPara continua, tecle ENTER _nesta_ janela. \")\n\n#------------------------------------------------------------\ndef chave(ponto):\n ''' (list) -> valor\n\n Recebe uma lista e retorna o valor da posição X.\n\n Usado pelo método sort() para ordenar os pontos \n de acordo com a coordenada X.\n '''\n return ponto[X]\n\n#------------------------------------------------------------\ndef desenhe_linha(p0, p1):\n '''(function) -> function\n\n Recebe a função distancia, desenha uma linha e retorna \n a distância entre os pontos.\n\n Não altere está função.\n '''\n if janela == None:\n print(\"ERRO >>> não estamos em uma animação\")\n return None\n janela.desenhe_linha([p0,p1])\n","sub_path":"ep6/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"60522586","text":"import xml.etree.cElementTree as ET\nimport re\nimport csv\nimport codecs\nimport cerberus\nfrom unittest import TestCase\n\nimport a_audit_data \nimport c_create_schema\n\nlower_case_colon = re.compile(r'^([a-z]|_)+:([a-z]|_)+')\nproblematic = re.compile(r'[=\\+/&<>;\\'\"\\?%#$@\\,\\. \\t\\r\\n]')\n\nOSM_PATH = \"data/bengaluru_india.osm\"\nNODE_TAGS_PATH = \"data/bi_nodes_tags.csv\"\nNODES_PATH = \"data/bi_nodes.csv\"\nWAYS_PATH = \"data/bi_ways.csv\"\nWAY_TAGS_PATH = \"data/bi_ways_tags.csv\"\nWAY_NODES_PATH = \"data/bi_ways_nodes.csv\"\n\nSCHEMA = c_create_schema.schema\n\nnode_fields = ['id', 'lat', 'lon', 'user', 'uid', 'version', 'changeset', 'timestamp']\nnode_tag_fields = ['id', 'key', 'value', 'type']\n\nbi_way_fields = ['id', 'user', 'uid', 'version', 'changeset', 'timestamp']\nbi_way_tag_fields = ['id', 'key', 'value', 'type']\nbi_way_node_fields = ['id', 'node_id', 'position']\n\n\ndef shape(elem, node_attr_fields=node_fields, way_attr_fields=bi_way_fields,\n problem_chars=problematic, default_tag_type='regular'):\n\n n_attributes = {}\n w_attributes = {}\n tags = []\n w_nodes = []\n \n if elem.tag == 'node':\n for attrib in elem.attrib:\n if attrib in node_fields:\n n_attributes[attrib] = elem.attrib[attrib]\n \n for child in elem:\n node_tag = {}\n if lower_case_colon.match(child.attrib['k']):\n node_tag['type'] = child.attrib['k'].split(':',1)[0]\n node_tag['key'] = child.attrib[ 'k'].split(':',1)[1]\n node_tag['id'] = elem.attrib['id']\n if child.attrib['k']==\"addr:street\" and a_audit_data.street_audit_2( child.attrib['k']):\n node_tag['value'] = a_audit_data.name_update(child.attrib['v'], a_audit_data.tomap)\n else:\n node_tag['value'] = child.attrib['v']\n tags.append(node_tag)\n elif problematic.match(child.attrib['k']):\n continue\n else:\n node_tag['type'] = 'regular'\n node_tag['key'] = child.attrib['k']\n node_tag['id'] = elem.attrib['id']\n if child.attrib['k']==\"addr:street\" and a_audit_data.street_audit_2( child.attrib['k']):\n node_tag['value'] = a_audit_data.name_update(child.attrib['v'], a_audit_data.tomap)\n else:\n node_tag['value'] = child.attrib['v']\n tags.append(node_tag)\n \n return {'node': n_attributes, 'node_tags': tags}\n \n elif elem.tag == 'way':\n for attrib in elem.attrib:\n if attrib in bi_way_fields:\n w_attributes[attrib] = elem.attrib[attrib]\n \n position = 0\n for child in elem:\n way_tag = {}\n way_node = {}\n \n if child.tag == 'tag':\n if lower_case_colon.match(child.attrib['k']):\n way_tag['type'] = child.attrib['k'].split(':',1)[0]\n way_tag['key'] = child.attrib['k'].split(':',1)[1]\n way_tag['id'] = elem.attrib['id']\n if child.attrib['k']==\"addr:street\" and a_audit_data.street_audit_2( child.attrib['k']):\n way_tag['value'] = a_audit_data.name_update(child.attrib['v'], a_audit_data.tomap)\n else:\n way_tag['value'] = child.attrib['v']\n tags.append(way_tag)\n elif problematic.match(child.attrib['k']):\n continue\n else:\n way_tag['type'] = 'regular'\n way_tag['key'] = child.attrib['k']\n way_tag['id'] = elem.attrib['id']\n if child.attrib['k']==\"addr:street\" and a_audit_data.street_audit_2( child.attrib['k']):\n way_tag['value'] = a_audit_data.name_update(child.attrib['v'], a_audit_data.tomap)\n else:\n way_tag['value'] = child.attrib['v']\n tags.append(way_tag)\n \n elif child.tag == 'nd':\n way_node['id'] = elem.attrib['id']\n way_node['node_id'] = child.attrib['ref']\n way_node['position'] = position\n position += 1\n w_nodes.append(way_node)\n \n return {'way': w_attributes, 'w_nodes': w_nodes, 'way_tags': tags}\n\n\n\ndef get(osm_file, tags=('node', 'way', 'relation')):\n\n context = ET.iterparse(osm_file, events=('start', 'end'))\n _, root = next(context)\n for event, elem in context:\n if event == 'end' and elem.tag in tags:\n yield elem\n root.clear()\n\n\ndef validate_ele(elem, validator, schema=SCHEMA):\n\n if validator.validate(elem, schema) is not True:\n field, errors = next(iter(validator.errors.items()))\n message_string = \"\\nElement of type '{0}' has the following errors:\\n{1}\"\n error_strings = (\n \"{0}: {1}\".format(k, v if isinstance(v, str) else \", \".join(v))\n for k, v in errors.items()\n )\n raise cerberus.ValidationError(\n message_string.format(field, \"\\n\".join(error_strings))\n )\n\n\nclass UnicodeDictWriter(csv.DictWriter, object):\n def writerow(self, row):\n super(UnicodeDictWriter, self).writerow({\n k: (v.encode('utf-8') if isinstance(v, str) else v) for k, v in list(row.items())\n })\n\n def writerows(self, rows):\n for row in rows:\n self.writerow(row)\n\n\n\ndef process(file_in, validate):\n with codecs.open(NODES_PATH, 'w') as nodes_file, \\\n codecs.open(NODE_TAGS_PATH, 'w') as nodes_tags_file, \\\n codecs.open(WAYS_PATH, 'w') as ways_file, \\\n codecs.open(WAY_NODES_PATH, 'w') as way_nodes_file, \\\n codecs.open(WAY_TAGS_PATH, 'w') as way_tags_file:\n\n nodes_writer = UnicodeDictWriter(nodes_file, node_fields)\n node_tags_writer = UnicodeDictWriter(nodes_tags_file, node_tag_fields)\n ways_writer = UnicodeDictWriter(ways_file, bi_way_fields)\n way_nodes_writer = UnicodeDictWriter(way_nodes_file, bi_way_node_fields)\n way_tags_writer = UnicodeDictWriter(way_tags_file, bi_way_tag_fields)\n\n nodes_writer.writeheader()\n node_tags_writer.writeheader()\n ways_writer.writeheader()\n way_nodes_writer.writeheader()\n way_tags_writer.writeheader()\n\n validator = cerberus.Validator()\n\n for elem in get(file_in, tags=('node', 'way')):\n el = shape(elem)\n if el:\n if validate is True:\n validate_ele(el, validator)\n\n if elem.tag == 'node':\n nodes_writer.writerow(el['node'])\n node_tags_writer.writerows(el['node_tags'])\n elif elem.tag == 'way':\n ways_writer.writerow(el['way'])\n way_nodes_writer.writerows(el['w_nodes'])\n way_tags_writer.writerows(el['way_tags'])\n\n\nif __name__ == '__main__':\n process(OSM_PATH, validate=True)","sub_path":"4. Wrangle OpenStreetMap data/d_a_init_db.py","file_name":"d_a_init_db.py","file_ext":"py","file_size_in_byte":7105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"548117152","text":"import pygame as pg\nimport pygame.mixer\nimport sys\nimport random\nimport time\n\npg.init()\npg.font.init()\npg.mixer.init()\n#pg.mixer.music.load(\"/Users/a123/Documents/ics/finalv/Dark_Tranquility.mp3\")\n#pick_sound = pg.mixer.Sound('/Users/a123/Documents/ics/finalv/Glass_and_Metal_Collision.wav')\nclock = pg.time.Clock()\npg.mixer.pre_init(44100, 16, 2, 4096)\n\ngameDisplay = pygame.display.set_mode((600, 500))\npg.mixer.music.set_volume(0.9)\npg.mixer.music.play(-1)\n\n# pg.mixer.Sound('background_music.mp3').play()\ngame_window = pg.display.set_mode((600, 500))\npg.display.set_caption('pick up the ball !!')\nwindow_color = (230, 230, 250)\nball_color = (165, 42, 42)\nrect_color = (0, 0, 0)\nscore = 0\nfont = pg.font.Font(None, 60) # (字体,大小)\nfont1 = pg.font.Font(None, 30)\n# ball_x = random.randint(20, 580)\n# ball_y = 20\n# move_x = 3\n# move_y = 3\n# mouse_x = 0\n# keymove_x = 7\n# keymove_y = 7\n# point = 1\n# count = 0\nname = 'your score:\\n'\n\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, (0, 0, 0))\n return textSurface, textSurface.get_rect()\n\n\ndef quitgame():\n pg.quit()\n # quit()\n\n\ndef myscore(point):\n global score\n score += point\n\n\ndef unpause():\n global pause\n pause = False\n\n\ndef paused():\n largeText = pg.font.SysFont(\"comicsans\", 115)\n TextSurf, TextRect = text_objects(\"Paused\", largeText)\n TextRect.center = (300, 250)\n gameDisplay.blit(TextSurf, TextRect)\n\n while pause:\n for event in pg.event.get():\n # print(event)\n if event.type == pg.QUIT:\n pg.quit()\n quit()\n\n # gameDisplay.fill(white)\n # button((0,255,0), 50, 50, 100, 80,'Click Me!!')\n button(\"Continue\", 100, 360, 140, 70, (255, 255, 255), (253, 245, 230), unpause)\n button(\"Quit\", 360, 360, 140, 70, (255, 255, 255), (253, 245, 230), quitgame)\n pg.display.update()\n clock.tick(15)\n\n\ndef game_over():\n largeText = pg.font.SysFont(\"comicsans\", 115)\n smallText = pg.font.SysFont('comicsansms', 40)\n TextSurf, TextRect = text_objects(\"Game Over\", largeText)\n TextRect.center = (300, 250)\n gameDisplay.blit(TextSurf, TextRect)\n\n while over:\n for event in pg.event.get():\n # print(event)\n if event.type == pg.QUIT:\n pg.quit()\n quit()\n\n button(\"Quit\", 230, 360, 140, 70, (255, 255, 255), (253, 245, 230), quitgame)\n pg.display.update()\n clock.tick(15)\n\n\ndef button(msg, x, y, w, h, ic, ac, action=None):\n global pause\n global over\n mouse = pg.mouse.get_pos()\n click = pg.mouse.get_pressed()\n\n if x + w > mouse[0] > x and y + h > mouse[1] > y:\n\n pg.draw.rect(gameDisplay, ac, (x, y, w, h))\n if click[0] == 1 and action != None:\n if action == unpause:\n action()\n return\n elif action == paused:\n pause = True\n paused()\n elif action == quitgame:\n quitgame()\n else:\n pg.draw.rect(gameDisplay, ic, (x, y, w, h))\n smallText = pg.font.SysFont('comicsansms', 40)\n textSurf, textRect = text_objects(msg, smallText)\n textRect.center = ((x + (w / 2)), (y + (h / 2)))\n gameDisplay.blit(textSurf, textRect)\n\n\nrun = True\npause = False\nover = False\n\n\ndef game_loop():\n global pause\n global run\n global score\n global over\n ball_x = random.randint(20, 580)\n ball_y = 20\n move_x = 3\n move_y = 3\n mouse_x = 0\n keymove_x = 7\n keymove_y = 7\n point = 1\n count = 0\n\n while run:\n game_window.fill(window_color)\n for event in pg.event.get():\n pos = pg.mouse.get_pos()\n if event.type == pg.QUIT:\n run = False\n pg.quit()\n\n keys = pg.key.get_pressed()\n if keys[pg.K_LEFT]:\n if mouse_x >= keymove_x:\n mouse_x -= keymove_x\n if keys[pg.K_RIGHT]:\n if mouse_x <= 500 - keymove_x:\n mouse_x += keymove_x\n if keys[pg.K_p]:\n pause = True\n paused()\n\n button(\"pause!\", 10, 20, 100, 50, (255, 255, 255), (255, 248, 220), paused)\n button(\"quit\", 10, 100, 100, 50, (255, 255, 255), (255, 248, 220), quitgame)\n\n mousex, mousey = pg.mouse.get_pos() # return the position of the mouse\n pg.draw.circle(game_window, ball_color, (ball_x, ball_y), 18)\n pg.draw.rect(game_window, rect_color, (mouse_x, 490, 100, 10)) # 定位在左上角\n my_text = font.render(str(score), True, (160, 82, 45))\n game_window.blit(my_text, (490, 50)) # 文字位置的横纵坐标\n my_text1 = font1.render(name, True, (160, 82, 45))\n game_window.blit(my_text1, (460, 20))\n ball_x += move_x\n ball_y += move_y\n if ball_x <= 20 or ball_x >= 580:\n move_x = -move_x\n if ball_y <= 20:\n move_y = -move_y\n elif mouse_x < ball_x < mouse_x + 100 and ball_y >= 470:\n pg.mixer.Sound.play(pick_sound)\n time.sleep(0.001)\n move_y = -move_y\n myscore(point)\n # score += point\n count += 1\n if count == 2:\n count = 0\n point += point\n if move_x > 0:\n move_x += 1\n else:\n move_x -= 1\n move_y -= 1\n elif ball_y >= 480 and (ball_x <= mouse_x or ball_x >= mouse_x + 100):\n over = True\n # game_over()\n return score\n break\n pg.display.update() # keep update,不会一闪而过\n time.sleep(0.001) # 每隔0.005s循环一次\n\n# game_loop()\n# print(game_loop())\n\n","sub_path":"ball_game.py","file_name":"ball_game.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"55299910","text":"#\n# @lc app=leetcode.cn id=450 lang=python3\n#\n# [450] 删除二叉搜索树中的节点\n#\n# https://leetcode-cn.com/problems/delete-node-in-a-bst/description/\n#\n# algorithms\n# Medium (35.95%)\n# Likes: 92\n# Dislikes: 0\n# Total Accepted: 5.3K\n# Total Submissions: 14.8K\n# Testcase Example: '[5,3,6,2,4,null,7]\\n3'\n#\n# 给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key\n# 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。\n#\n# 一般来说,删除节点可分为两个步骤:\n#\n#\n# 首先找到需要删除的节点;\n# 如果找到了,删除它。\n#\n#\n# 说明: 要求算法时间复杂度为 O(h),h 为树的高度。\n#\n# 示例:\n#\n#\n# root = [5,3,6,2,4,null,7]\n# key = 3\n#\n# ⁠ 5\n# ⁠ / \\\n# ⁠ 3 6\n# ⁠/ \\ \\\n# 2 4 7\n#\n# 给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。\n#\n# 一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。\n#\n# ⁠ 5\n# ⁠ / \\\n# ⁠ 4 6\n# ⁠/ \\\n# 2 7\n#\n# 另一个正确答案是 [5,2,6,null,4,null,7]。\n#\n# ⁠ 5\n# ⁠ / \\\n# ⁠ 2 6\n# ⁠ \\ \\\n# ⁠ 4 7\n#\n#\n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def deleteNode(self, root: TreeNode, key: int) -> TreeNode:\n # 画图\n # NOTE: root may be deleted\n # NOTE: need to consider the case where both left and right children exist\n headpre = TreeNode(0)\n headpre.right = root\n pre, cur = headpre, root\n while cur:\n if cur.val > key:\n pre = cur\n cur = cur.left\n elif cur.val < key:\n pre = cur\n cur = cur.right\n else:\n if cur.left and cur.right:\n child = cur.left\n childright = child.right\n curright = cur.right\n child.right = curright\n while curright.left:\n curright = curright.left\n curright.left = childright\n else:\n child = cur.left if cur.left else cur.right\n if pre.left == cur:\n pre.left = child\n else:\n pre.right = child\n break\n return headpre.right\n\n# @lc code=end\n","sub_path":"Medium/450.删除二叉搜索树中的节点.py","file_name":"450.删除二叉搜索树中的节点.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"421465866","text":"\nfrom . import odds, probability\nfrom .PMF import PMF\nfrom .Hist import Hist\n\nclass Suite(PMF):\n \"\"\"Represents a suite of hypotheses and their probabilities.\"\"\"\n\n @classmethod\n def fromList(cls,t,name=\"\"):\n hist = Hist.fromList(t)\n d = hist.getDict()\n return cls.fromDict(d)\n\n @classmethod\n def fromHist(cls,hist,name=None):\n if name is None:\n name = hist.name\n d = dict(hist.getDict())\n return cls.fromDict(d,name)\n\n @classmethod\n def fromDict(cls,d,name=\"\"):\n suite = cls(name=name)\n suite.setDict(d)\n suite.normalize()\n return suite\n\n @classmethod\n def fromCDF(cls,cdf,name=None):\n if name is None:\n name = cdf.name\n suite = cls(name=name)\n prev = 0.0\n for v, p in cdf.items():\n suite.incr(v,p-prev)\n prev = p\n return suite\n\n\n\n def update(self, data):\n \"\"\"Updates each hypothesis based on the data.\n\n data: any representation of the data\n\n returns: the normalizing constant\n \"\"\"\n for hypo in list(self.values()):\n like = self.likelihood(data, hypo)\n self.mult(hypo, like)\n return self.normalize()\n\n def logUpdate(self, data):\n \"\"\"Updates a suite of hypotheses based on new data.\n\n Modifies the suite directly; if you want to keep the original, make\n a copy.\n\n Note: unlike Update, LogUpdate does not normalize.\n\n Args:\n data: any representation of the data\n \"\"\"\n for hypo in self.values():\n like = self.logLikelihood(data, hypo)\n self.incr(hypo, like)\n\n def updateSet(self, dataset):\n \"\"\"Updates each hypothesis based on the dataset.\n\n This is more efficient than calling Update repeatedly because\n it waits until the end to Normalize.\n\n Modifies the suite directly; if you want to keep the original, make\n a copy.\n\n dataset: a sequence of data\n\n returns: the normalizing constant\n \"\"\"\n for data in dataset:\n for hypo in self.values():\n like = self.likelihood(data, hypo)\n self.mult(hypo, like)\n return self.normalize()\n\n def logUpdateSet(self, dataset):\n \"\"\"Updates each hypothesis based on the dataset.\n\n Modifies the suite directly; if you want to keep the original, make\n a copy.\n\n dataset: a sequence of data\n\n returns: None\n \"\"\"\n for data in dataset:\n self.logUpdate(data)\n\n def likelihood(self, data, hypo):\n \"\"\"Computes the likelihood of the data under the hypothesis.\n\n hypo: some representation of the hypothesis\n data: some representation of the data\n \"\"\"\n raise NotImplementedError\n\n def logLikelihood(self, data, hypo):\n \"\"\"Computes the log likelihood of the data under the hypothesis.\n\n hypo: some representation of the hypothesis\n data: some representation of the data\n \"\"\"\n raise NotImplementedError\n\n def print(self):\n \"\"\"Prints the hypotheses and their probabilities.\"\"\"\n for hypo, prob in sorted(self.items()):\n print(hypo, prob)\n\n def makeOdds(self):\n \"\"\"Transforms from probabilities to odds.\n\n Values with prob=0 are removed.\n \"\"\"\n for hypo, prob in self.items():\n if prob:\n self.set(hypo, odds(prob))\n else:\n self.remove(hypo)\n\n def makeProbs(self):\n \"\"\"Transforms from odds to probabilities.\"\"\"\n for hypo, odds in self.items():\n self.set(hypo, probability(odds))","sub_path":"bayes/Suite.py","file_name":"Suite.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"507775016","text":"from elasticsearch import Elasticsearch\nimport json\n\nes = Elasticsearch('192.168.2.90:9200/')\n\n#es.index(\"contacts\", \"person\", {\"name\":\"Joe Tester\", \"age\": 25, \"title\": \"QA Master\"})\n#es.index(\"contacts\", \"person\", {\"name\":\"Joe Tester\", \"age\": 25, \"title\": \"QA Master\"}, id=1)\n\n#es.index(\"contacts\", \"person\", {\"name\":\"Jessica Coder\", \"age\": 32, \"title\": \"Programmer\"}, id=2)\n\n#es.index(\"contacts\", \"person\", {\"name\":\"Freddy Tester\", \"age\": 29, \"title\": \"Office Assistant\"}, id=3)\n\n#es.refresh('contacts')\n\n#res = es.get('contacts', 'person', 2)\n\n#print(res)\n\n#res2 = es.search('name:joe OR name:freddy', index='contacts')\n\n#print(res2)\n\nquery = {'query': {\n 'filtered': {\n 'query': {\n 'query_string': {'query': 'FirstName:Fred'}}}}}\n\n#res3 = es.search(query, index='contacts')\nres3 = es.search(query, index='names')\n\nres3j = json.dumps(res3)\n\nprint(res3j)\n\n\n","sub_path":"code/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"477212545","text":"# ___________________________________________________________________________\n#\n# Pyomo: Python Optimization Modeling Objects\n# Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC\n# Under the terms of Contract DE-NA0003525 with National Technology and\n# Engineering Solutions of Sandia, LLC, the U.S. Government retains certain\n# rights in this software.\n# This software is distributed under the 3-clause BSD License.\n# ___________________________________________________________________________\n\n#\n# Robust Knapsack Problem\n#\n\nfrom pyomo.environ import ConcreteModel, Set, Binary, Var, Constraint\nfrom pyomo.environ import Objective, maximize, SolverFactory, ConstraintList\nfrom romodel import UncSet, UncParam\nfrom romodel.uncset import EllipsoidalSet, PolyhedralSet\nimport itertools\n\n\nv = {'hammer': 8, 'wrench': 3, 'screwdriver': 6, 'towel': 11}\nw = {'hammer': 5, 'wrench': 7, 'screwdriver': 4, 'towel': 3}\n\nlimit = 14\n\nM = ConcreteModel()\n\nM.ITEMS = Set(initialize=v.keys())\nM.x = Var(M.ITEMS, within=Binary)\n\n# Define Uncertainty set & uncertain parameters\nmu = w\nA = [[0.1, 0.01, 0.0, 0.0],\n [0.01, 0.1, 0.0, 0.0],\n [0.0, 0.0, 0.1, 0.0],\n [0.0, 0.0, 0.0, 0.1]]\ntools = ['hammer', 'wrench', 'screwdriver', 'towel']\nAdict = {(ti, tj): A[i][j]\n for i, ti in enumerate(tools)\n for j, tj in enumerate(tools)}\nperm = itertools.product([1, -1], repeat=len(tools))\nP = [dict(zip(tools, i)) for i in perm]\nrhs = [sum(p[t]*w[t] for t in tools) + 5.5 for p in P]\n\n\nM.U = UncSet()\nM.Ulib = EllipsoidalSet(mu, Adict)\nM.w = UncParam(M.ITEMS, uncset=M.U)\nw = M.w\n\n# Ellipsoidal uncertainty set direct: (w - mu)^T * A * (w - mu) <= 1\nlhs = 0\nfor i in M.ITEMS:\n for j in M.ITEMS:\n lhs += (w[i] - mu[i])*Adict[i, j]*(w[j] - mu[j])\nM.U.cons = Constraint(expr=lhs <= 1)\n\n# Polyhedral set:\n# direct\nM.P = UncSet()\nM.P.cons = ConstraintList()\nfor i, p in enumerate(P):\n M.P.cons.add(sum(M.w[t]*p[t] for t in tools) <= rhs[i])\n# library\nM.Plib = PolyhedralSet(P, rhs)\n\nM.value = Objective(expr=sum(v[i]*M.x[i] for i in M.ITEMS), sense=maximize)\nM.weight = Constraint(expr=sum(w[i]*M.x[i] for i in M.ITEMS) <= limit)\n\n# Set UncSet\nM.w.uncset = M.P\n\nsolver = SolverFactory('romodel.reformulation')\nsolver.solve(M, options={'solver': 'gurobi'})\nM.pprint()\n","sub_path":"examples/knapsack.py","file_name":"knapsack.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"163185373","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 13 22:32:47 2017\n\n@author: sominwadhwa\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 13 02:08:07 2017\n\n@author: sominwadhwa\n\"\"\"\n\nimport re\nfrom bs4 import BeautifulSoup\nimport time\nfrom datetime import datetime\nfrom selenium import webdriver\nChromeDriver = '/Users/sominwadhwa/chromedriver'\nbrowser = webdriver.Chrome(executable_path = ChromeDriver)\nurl = \"https://twitter.com/ThaneCityPolice/\"\n\ndef twt_scroller(url):\n browser.get(url)\n lastHeight = browser.execute_script(\"return document.body.scrollHeight\")\n ctr = 0 \n while True:\n browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(3) #For Reloading the page\n newHeight = browser.execute_script(\"return document.body.scrollHeight\")\n if newHeight == lastHeight or ctr ==15:\n break\n else:\n lastHeight = newHeight\n ctr+=1\n html = browser.page_source\n return html\n \ndef data_extract(url):\n tweet_list = []\n soup = BeautifulSoup(twt_scroller(url), \"html.parser\")\n crp = re.compile(r'MoreCopy link to TweetEmbed Tweet|Reply')\n wrd = re.compile(r'[A-Z]+[a-z]*')\n dgt = re.compile(r'\\d+') \n try:\n for i in soup.find_all('li', {\"data-item-type\":\"tweet\"}):\n if i.find('div', {\"data-user-id\":\"720135190916366336\"}) is not None:\n created_at = i.find('a',{'class':\"tweet-timestamp js-permalink js-nav js-tooltip\"})['title']\n text = i.p.get_text(\"\").strip().replace('\\n',' ').replace(\"'\",'') if i.p is not None else \"\"\n media = (True if i.find('div', {'class':\"AdaptiveMedia\"}) is not None else False) \n fr = (i.find('div', {'class': \"ProfileTweet-actionList js-actions\"}).get_text().replace('\\n','') if i.find('div', {'class': \"ProfileTweet-actionList js-actions\"}) is not None else \"\") \n params = [i + ': ' + j if len(dgt.findall(fr)) != 0 else '' for i, j in zip(wrd.findall(crp.sub('', fr)), dgt.findall(fr))]\n tweet_dict = {\n \"text\":text,\n \"engagements\":0,\n \"media\":media,\n \"params\":params,\n \"created_at\":created_at \n }\n \n tweet_list.append(tweet_dict)\n print (tweet_list)\n return tweet_list\n \n except (AttributeError, TypeError, KeyError, ValueError):\n print (\"ERRORRR!\")\n return 1\n\nif __name__ == \"__main__\":\n tweet_list = data_extract(url)\n \n for d in tweet_list:\n d[\"created_at\"] = datetime.strptime(d[\"created_at\"], '%I:%M %p - %d %b %Y')\n print (\"\\n\\n\\n\")\n for d in tweet_list:\n try:\n d[\"engagements\"] = int(float(d[\"engagements\"])) \n except (ValueError):\n d[\"engagements\"] = None\n for d in tweet_list:\n n = []\n for v in d[\"params\"]:\n val = [int(s) for s in v.split() if s.isdigit()]\n n.append(val)\n try:\n d[\"engagements\"] = sum(n[1] + n[3])\n except:\n pass\n del d[\"params\"]\n #del d['like_fave']\n #del d['share_rtwt']\n \n print (tweet_list)\n print (\"\\n\\n\")\n print (len(tweet_list))\n \n\"\"\"\n from pymongo import MongoClient\n client = MongoClient('mongodb://tweets_database:2222@ds145868.mlab.com:45868/tweets_database')\n db = client.tweets_database\n db.collection_BengaluruPolice.drop()\n collectionT = db.collection_ThanePolice\n collectionT.insert_many(tweet_list)\n\"\"\"","sub_path":"FetchData/ScrapeThane.py","file_name":"ScrapeThane.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"273606442","text":"# import os\r\n# os.system(\"ipconfig\")\r\n# os.popen(\"ipconfig\").read()\r\n\r\nname = ['alex','lizhengyu','zhangsan','lisi','monica','wangjie']\r\n\r\nname.insert(4,'minglong') #插入至第四个元素\r\n\r\nname.insert(-1,\"longde\")\r\n\r\nname2 = name[2:7] #取出2至7个元素赋值给name2\r\n\r\nname.remove('lizhengyu') #删除元素lizhengyu\r\n\r\ndel name[4:6] #删除元素,下标为4至6的,包括4但是不包括6\r\n\r\nname[3] = \"zhangwulong(zuzhang)\" #修改下标为3的元素为zhangwulong(zuzhang)\r\n\r\nnewname = name[0:-1:1] #切片,取第0个至-1个元素,但最后一个取不到每隔一个的都拿出来\r\nnewname2 = name[::1] #取出全部元素,隔一个切出一个\r\n\r\ndel name\r\n\r\n\r\nname = ['alex','lizhengyu','zhangsan','lisi','monica','wangjie',1,2,3,55,9,23,2,44,'zhangsan',9,'lisi']\r\nif 2 in name : #判断列表中是否存在这个元素\r\n num_of = name.count(2) #统计有多少个2\r\n posistion_of = name.index(9)\r\n name[posistion_of] = 999\r\n print( '[%s] 2 is/are in name,posistion: [%s]' % (num_of,posistion_of))\r\n print(name)\r\nfor a in range(name.count(9)):\r\n ele_index = name.index(9)\r\n name[ele_index] = 999\r\nprint(name)\r\n\r\nname.pop(1) #指定删除下标为1的元素\r\n\r\nname.extend(name) #加入一个name列表\r\n\r\n\r\ndudu = [1,2,3,'bb','cc',[1,2,3,4],88]\r\ndudu[5][1] = 1111111111111111111111\r\nprint(dudu) #修改列表dudu中的第五个元素里面的第一个元素为111111\r\n\r\n\r\n\r\nr = (1,2,3,4,5) #只读列表,元组\r\n","sub_path":"python_dev/oldboy_day1_列表.py","file_name":"oldboy_day1_列表.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"324156651","text":"'''The dagster-airflow operators.'''\nimport ast\nimport json\nimport logging\nimport os\n\nfrom abc import ABCMeta, abstractmethod\nfrom contextlib import contextmanager\n\nfrom six import string_types, with_metaclass\n\nfrom airflow.exceptions import AirflowException\nfrom airflow.operators.docker_operator import DockerOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.utils.file import TemporaryDirectory\nfrom docker import APIClient, from_env\n\nfrom dagster import seven\nfrom dagster.seven.json import JSONDecodeError\n\nfrom .format import format_config_for_graphql\nfrom .query import QUERY_TEMPLATE\n\n\nDOCKER_TEMPDIR = '/tmp'\n\nDEFAULT_ENVIRONMENT = {\n 'AWS_ACCESS_KEY_ID': os.getenv('AWS_ACCESS_KEY_ID'),\n 'AWS_SECRET_ACCESS_KEY': os.getenv('AWS_SECRET_ACCESS_KEY'),\n}\n\nLINE_LENGTH = 100\n\n\ndef parse_raw_res(raw_res):\n res = None\n # FIXME\n # Unfortunately, log lines don't necessarily come back in order...\n # This is error-prone, if something else logs JSON\n lines = list(filter(None, reversed(raw_res.split('\\n'))))\n\n for line in lines:\n try:\n res = json.loads(line)\n break\n # If we don't get a GraphQL response, check the next line\n except JSONDecodeError:\n continue\n\n return (res, raw_res)\n\n\ndef airflow_storage_exception(tmp_dir):\n return AirflowException(\n 'No storage config found -- must configure either filesystem or s3 storage for '\n 'the DagsterPythonOperator. Ex.: \\n'\n 'storage:\\n'\n ' filesystem:\\n'\n ' base_dir: \\'{tmp_dir}\\''\n '\\n\\n --or--\\n\\n'\n 'storage:\\n'\n ' s3:\\n'\n ' s3_bucket: \\'my-s3-bucket\\'\\n'.format(tmp_dir=tmp_dir)\n )\n\n\nclass DagsterOperator(with_metaclass(ABCMeta)): # pylint:disable=no-init\n '''Abstract base class for Dagster operators.\n\n Implement operator_for_solid to support dynamic generation of Airflow operators corresponding to\n the execution plan steps generated by a Dagster solid.\n '''\n\n @classmethod\n @abstractmethod\n def operator_for_solid(\n cls, handle, pipeline_name, env_config, mode, solid_name, step_keys, dag, dag_id, op_kwargs\n ):\n pass\n\n @classmethod\n def handle_errors(cls, res, raw_res):\n if res is None:\n raise AirflowException('Unhandled error type. Raw response: {}'.format(raw_res))\n\n if res.get('errors'):\n raise AirflowException('Internal error in GraphQL request. Response: {}'.format(res))\n\n if not res.get('data', {}).get('executePlan', {}).get('__typename'):\n raise AirflowException('Unexpected response type. Response: {}'.format(res))\n\n @classmethod\n def handle_result(cls, res):\n res_data = res['data']['executePlan']\n\n res_type = res_data['__typename']\n\n if res_type == 'PipelineConfigValidationInvalid':\n errors = [err['message'] for err in res_data['errors']]\n raise AirflowException(\n 'Pipeline configuration invalid:\\n{errors}'.format(errors='\\n'.join(errors))\n )\n\n if res_type == 'PipelineNotFoundError':\n raise AirflowException(\n 'Pipeline \"{pipeline_name}\" not found: {message}:'.format(\n pipeline_name=res_data['pipelineName'], message=res_data['message']\n )\n )\n\n if res_type == 'ExecutePlanSuccess':\n if res_data['hasFailures']:\n errors = [\n step['errorMessage'] for step in res_data['stepEvents'] if not step['success']\n ]\n raise AirflowException(\n 'Subplan execution failed:\\n{errors}'.format(errors='\\n'.join(errors))\n )\n\n return res\n\n if res_type == 'PythonError':\n raise AirflowException(\n 'Subplan execution failed: {message}\\n{stack}'.format(\n message=res_data['message'], stack=res_data['stack']\n )\n )\n\n # Catchall\n return res\n\n\n# pylint: disable=len-as-condition\nclass ModifiedDockerOperator(DockerOperator):\n \"\"\"ModifiedDockerOperator supports host temporary directories on OSX.\n\n Incorporates https://github.com/apache/airflow/pull/4315/ and an implementation of\n https://issues.apache.org/jira/browse/AIRFLOW-3825.\n\n :param host_tmp_dir: Specify the location of the temporary directory on the host which will\n be mapped to tmp_dir. If not provided defaults to using the standard system temp directory.\n :type host_tmp_dir: str\n \"\"\"\n\n def __init__(self, host_tmp_dir='/tmp', **kwargs):\n self.host_tmp_dir = host_tmp_dir\n kwargs['xcom_push'] = True\n super(ModifiedDockerOperator, self).__init__(**kwargs)\n\n @contextmanager\n def get_host_tmp_dir(self):\n '''Abstracts the tempdir context manager so that this can be overridden.'''\n with TemporaryDirectory(prefix='airflowtmp', dir=self.host_tmp_dir) as tmp_dir:\n yield tmp_dir\n\n def execute(self, context):\n '''Modified only to use the get_host_tmp_dir helper.'''\n self.log.info('Starting docker container from image %s', self.image)\n\n tls_config = self.__get_tls_config()\n if self.docker_conn_id:\n self.cli = self.get_hook().get_conn()\n else:\n self.cli = APIClient(base_url=self.docker_url, version=self.api_version, tls=tls_config)\n\n if self.force_pull or len(self.cli.images(name=self.image)) == 0:\n self.log.info('Pulling docker image %s', self.image)\n for l in self.cli.pull(self.image, stream=True):\n output = json.loads(l.decode('utf-8').strip())\n if 'status' in output:\n self.log.info(\"%s\", output['status'])\n\n with self.get_host_tmp_dir() as host_tmp_dir:\n self.environment['AIRFLOW_TMP_DIR'] = self.tmp_dir\n self.volumes.append('{0}:{1}'.format(host_tmp_dir, self.tmp_dir))\n\n self.container = self.cli.create_container(\n command=self.get_command(),\n environment=self.environment,\n host_config=self.cli.create_host_config(\n auto_remove=self.auto_remove,\n binds=self.volumes,\n network_mode=self.network_mode,\n shm_size=self.shm_size,\n dns=self.dns,\n dns_search=self.dns_search,\n cpu_shares=int(round(self.cpus * 1024)),\n mem_limit=self.mem_limit,\n ),\n image=self.image,\n user=self.user,\n working_dir=self.working_dir,\n )\n self.cli.start(self.container['Id'])\n\n res = []\n line = ''\n for new_line in self.cli.logs(container=self.container['Id'], stream=True):\n line = new_line.strip()\n if hasattr(line, 'decode'):\n line = line.decode('utf-8')\n self.log.info(line)\n res.append(line)\n\n result = self.cli.wait(self.container['Id'])\n if result['StatusCode'] != 0:\n raise AirflowException('docker container failed: ' + repr(result))\n\n if self.xcom_push_flag:\n # Try to avoid any kind of race condition?\n return '\\n'.join(res) + '\\n' if self.xcom_all else str(line)\n\n # This is a class-private name on DockerOperator for no good reason --\n # all that the status quo does is inhibit extension of the class.\n # See https://issues.apache.org/jira/browse/AIRFLOW-3880\n def __get_tls_config(self):\n # pylint: disable=no-member\n return super(ModifiedDockerOperator, self)._DockerOperator__get_tls_config()\n\n\nclass DagsterDockerOperator(ModifiedDockerOperator, DagsterOperator):\n '''Dagster operator for Apache Airflow.\n\n Wraps a modified DockerOperator incorporating https://github.com/apache/airflow/pull/4315.\n\n Additionally, if a Docker client can be initialized using docker.from_env,\n Unlike the standard DockerOperator, this operator also supports config using docker.from_env,\n so it isn't necessary to explicitly set docker_url, tls_config, or api_version.\n\n '''\n\n # py2 compat\n # pylint: disable=keyword-arg-before-vararg\n def __init__(\n self,\n step=None,\n config=None,\n pipeline_name=None,\n mode=None,\n step_keys=None,\n s3_bucket_name=None,\n *args,\n **kwargs\n ):\n self.step = step\n self.config = config\n self.pipeline_name = pipeline_name\n self.mode = mode\n self.step_keys = step_keys\n self.docker_conn_id_set = kwargs.get('docker_conn_id') is not None\n self.s3_bucket_name = s3_bucket_name\n self._run_id = None\n\n # We don't use dagster.check here to avoid taking the dependency.\n for attr_ in ['config', 'pipeline_name']:\n assert isinstance(getattr(self, attr_), string_types), (\n 'Bad value for DagsterDockerOperator {attr_}: expected a string and got {value} of '\n 'type {type_}'.format(\n attr_=attr_, value=getattr(self, attr_), type_=type(getattr(self, attr_))\n )\n )\n\n if self.step_keys is None:\n self.step_keys = []\n\n assert isinstance(self.step_keys, list), (\n 'Bad value for DagsterDockerOperator step_keys: expected a list and got {value} of '\n 'type {type_}'.format(value=self.step_keys, type_=type(self.step_keys))\n )\n\n bad_keys = []\n for ix, step_key in enumerate(self.step_keys):\n if not isinstance(step, string_types):\n bad_keys.append((ix, step_key))\n assert not bad_keys, (\n 'Bad values for DagsterDockerOperator step_keys (expected only strings): '\n '{bad_values}'\n ).format(\n bad_values=', '.join(\n [\n '{value} of type {type_} at index {idx}'.format(\n value=bad_key[1], type_=type(bad_key[1]), idx=bad_key[0]\n )\n for bad_key in bad_keys\n ]\n )\n )\n\n # These shenanigans are so we can override DockerOperator.get_hook in order to configure\n # a docker client using docker.from_env, rather than messing with the logic of\n # DockerOperator.execute\n if not self.docker_conn_id_set:\n try:\n from_env().version()\n except: # pylint: disable=bare-except\n pass\n else:\n kwargs['docker_conn_id'] = True\n\n # We do this because log lines won't necessarily be emitted in order (!) -- so we can't\n # just check the last log line to see if it's JSON.\n kwargs['xcom_all'] = True\n\n if 'environment' not in kwargs:\n kwargs['environment'] = DEFAULT_ENVIRONMENT\n\n super(DagsterDockerOperator, self).__init__(*args, **kwargs)\n\n @classmethod\n def operator_for_solid(\n cls, handle, pipeline_name, env_config, mode, solid_name, step_keys, dag, dag_id, op_kwargs\n ):\n tmp_dir = op_kwargs.pop('tmp_dir', DOCKER_TEMPDIR)\n host_tmp_dir = op_kwargs.pop('host_tmp_dir', seven.get_system_temp_directory())\n\n if 'storage' not in env_config:\n raise airflow_storage_exception(tmp_dir)\n\n # black 18.9b0 doesn't support py27-compatible formatting of the below invocation (omitting\n # the trailing comma after **op_kwargs) -- black 19.3b0 supports multiple python versions,\n # but currently doesn't know what to do with from __future__ import print_function -- see\n # https://github.com/ambv/black/issues/768\n # fmt: off\n return DagsterDockerOperator(\n step=solid_name,\n config=format_config_for_graphql(env_config),\n dag=dag,\n tmp_dir=tmp_dir,\n pipeline_name=pipeline_name,\n mode=mode,\n step_keys=step_keys,\n task_id=solid_name,\n host_tmp_dir=host_tmp_dir,\n **op_kwargs\n )\n # fmt: on\n\n @property\n def run_id(self):\n if self._run_id is None:\n return ''\n else:\n return self._run_id\n\n @property\n def query(self):\n step_keys = '[{quoted_step_keys}]'.format(\n quoted_step_keys=', '.join(\n ['\"{step_key}\"'.format(step_key=step_key) for step_key in self.step_keys]\n )\n )\n return QUERY_TEMPLATE.format(\n config=self.config.strip('\\n'),\n run_id=self.run_id,\n mode=self.mode,\n step_keys=step_keys,\n pipeline_name=self.pipeline_name,\n )\n\n def get_command(self):\n if self.command is not None and self.command.strip().find('[') == 0:\n commands = ast.literal_eval(self.command)\n elif self.command is not None:\n commands = self.command\n else:\n commands = self.query\n return commands\n\n def get_hook(self):\n if self.docker_conn_id_set:\n return super(DagsterDockerOperator, self).get_hook()\n\n class _DummyHook(object):\n def get_conn(self):\n return from_env().api\n\n return _DummyHook()\n\n def execute(self, context):\n if 'run_id' in self.params:\n self._run_id = self.params['run_id']\n elif 'dag_run' in context and context['dag_run'] is not None:\n self._run_id = context['dag_run'].run_id\n\n try:\n self.log.debug('Executing with query: {query}'.format(query=self.query))\n\n raw_res = super(DagsterDockerOperator, self).execute(context)\n self.log.info('Finished executing container.')\n\n (res, raw_res) = parse_raw_res(raw_res)\n\n self.handle_errors(res, raw_res)\n\n return self.handle_result(res)\n\n finally:\n self._run_id = None\n\n # This is a class-private name on DockerOperator for no good reason --\n # all that the status quo does is inhibit extension of the class.\n # See https://issues.apache.org/jira/browse/AIRFLOW-3880\n def __get_tls_config(self):\n # pylint:disable=no-member\n return super(DagsterDockerOperator, self)._ModifiedDockerOperator__get_tls_config()\n\n @contextmanager\n def get_host_tmp_dir(self):\n yield self.host_tmp_dir\n\n\nclass DagsterPythonOperator(PythonOperator, DagsterOperator):\n @classmethod\n def make_python_callable(cls, handle, pipeline_name, mode, env_config, step_keys):\n try:\n from dagster_graphql.cli import execute_query_from_cli\n except ImportError:\n raise AirflowException(\n 'To use the DagsterPythonOperator, dagster and dagster_graphql must be installed '\n 'in your Airflow environment.'\n )\n\n def python_callable(**kwargs):\n run_id = kwargs.get('dag_run').run_id\n query = QUERY_TEMPLATE.format(\n config=env_config,\n run_id=run_id,\n mode=mode,\n step_keys=json.dumps(step_keys),\n pipeline_name=pipeline_name,\n )\n\n # TODO: This removes config that we need to scrub for secrets, but it's very useful\n # for debugging to understand the GraphQL query that's being executed. We should update\n # to include the sanitized config.\n logging.info(\n 'Executing GraphQL query:\\n'\n + QUERY_TEMPLATE.format(\n config='REDACTED',\n run_id=run_id,\n mode=mode,\n step_keys=json.dumps(step_keys),\n pipeline_name=pipeline_name,\n )\n )\n\n res = json.loads(execute_query_from_cli(handle, query, variables=None))\n cls.handle_errors(res, None)\n return cls.handle_result(res)\n\n return python_callable\n\n @classmethod\n def operator_for_solid(\n cls, handle, pipeline_name, env_config, mode, solid_name, step_keys, dag, dag_id, op_kwargs\n ):\n if 'storage' not in env_config:\n raise airflow_storage_exception('/tmp/special_place')\n\n # black 18.9b0 doesn't support py27-compatible formatting of the below invocation (omitting\n # the trailing comma after **op_kwargs) -- black 19.3b0 supports multiple python versions,\n # but currently doesn't know what to do with from __future__ import print_function -- see\n # https://github.com/ambv/black/issues/768\n # fmt: off\n return PythonOperator(\n task_id=solid_name,\n provide_context=True,\n python_callable=cls.make_python_callable(\n handle,\n pipeline_name,\n mode,\n format_config_for_graphql(env_config),\n step_keys\n ),\n dag=dag,\n **op_kwargs\n )\n # fmt: on\n","sub_path":"python_modules/dagster-airflow/dagster_airflow/operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":17212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"608471423","text":"#!/usr/bin/env python\n\nimport argparse\nimport time\nimport json\nimport RPi.GPIO as GPIO\n\nfrom pythonosc import udp_client\n\nfrom pymemcache.client.base import Client\nGPIOState = Client(('localhost', 11211))\n\n##########\n# Config #\n##########\n\nwith open('/var/www/html/config.json') as config_file:\n config = json.load(config_file)\n\n##########\n# Config #\n##########\n\n###############\n# Send Output #\n###############\n\ndef send_OSC(json_raw):\n data = json.loads(json_raw)\n if __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--ip\", default=data[\"ip\"],\n help=\"The ip of the OSC server\")\n parser.add_argument(\"--port\", type=int, default=data[\"port\"],\n help=\"The port the OSC server is listening on\")\n args = parser.parse_args()\n\n client = udp_client.SimpleUDPClient(args.ip, args.port)\n\n client.send_message(data[\"command\"], data[\"value\"])\n\n print('OSC Command Received: '+ json_raw);\n\ndef button_pressed(GPIO, state):\n button_commands = config['GPIO'][i][\"commands\"]\n # Run each command\n for x in button_commands:\n if (x != \"\"):\n current_command = config['commands'][x][\"command\"]\n device = config['commands'][x][\"device\"]\n current_value = config['commands'][x][state]\n current_ip = config['osc_devices'][device][\"ip\"]\n current_port = config['osc_devices'][device][\"port\"]\n # if command state is null, do not run\n if (current_value != \"null\"):\n send_OSC('{ \"command\":\"'+ current_command + '\" , \"value\":'+ current_value+', \"ip\":\"'+current_ip+'\", \"port\":\"'+current_port+'\" }')\n print(\"Command Executed\" + x)\n\n###############\n# Send Output #\n###############\n\n########\n# GPIO #\n########\n\nGPIO.setmode(GPIO.BOARD)\n\nfor i in config['GPIO']:\n x = int(config['GPIO'][i]['GPIO-type'])\n y = int(config['GPIO'][i]['GPIO-Port'])\n GPIO.setup(y,x)\n GPIOState.set(str(y), GPIO.input(y))\n\ntry:\n print(\"Starting GPIO...\")\n while True:\n for i in config['GPIO']:\n x = int(config['GPIO'][i]['GPIO-Port'])\n y = config['GPIO'][i]['commands']\n z = int(config['GPIO'][i]['LED-IND'])\n if (config['GPIO'][i]['GPIO-type'] == \"1\"):\n if GPIO.input(x) == 1 and GPIOState.get(str(x)) == b'0':\n button_pressed(i, \"off\")\n print(i + \": Off\")\n if (z != 0):\n GPIO.output(z, True)\n GPIOState.set(str(x), 1)\n time.sleep(.1)\n if GPIO.input(x) == 0 and GPIOState.get(str(x)) == b'1':\n button_pressed(i, \"on\")\n print(i + \": On\")\n if (z != 0):\n GPIO.output(z, False)\n GPIOState.set(str(x), 0)\n time.sleep(.1)\nfinally:\n #cleanup the GPIO pins before ending\n GPIO.cleanup()\n\n########\n# GPIO #\n########\n","sub_path":"src/html/GPIO-OSC.py","file_name":"GPIO-OSC.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"79421079","text":"from unittest import TestCase\n\nfrom mock import Mock, patch\nfrom pynYNAB.schema.budget import Payee, Account\n\nimport python.ynab_client as ynab_client_module\nfrom python.functions import create_transaction_from_starling, create_transaction_from_monzo, get_subcategory_from_payee\n\nmockYnabClient = Mock(ynab_client_module)\n\n\ncreate_functions = {'monzo': create_transaction_from_monzo, 'starling': create_transaction_from_starling}\n\nclass CreateTests(TestCase):\n def check_notype(self,func_name):\n data = {}\n body, code = create_functions[func_name](data, ynab_client=mockYnabClient)\n self.assertEqual(code, 400)\n\n def test_notype(self):\n for func_name in create_functions:\n yield self.check_notype,func_name\n\n def check_wrongtype(self, func_name):\n data = dict(type='Meh')\n body, code = create_functions[func_name](data, ynab_client=mockYnabClient)\n self.assertEqual(code, 400)\n\n def test_wrongtype(self):\n for func_name in create_functions:\n yield self.check_wrongtype,func_name\n\n def check_nodata(self, func_name):\n data = {}\n body, code = create_functions[func_name](data, ynab_client=mockYnabClient)\n self.assertEqual(code, 400)\n\n def test_nodata(self):\n for func_name in create_functions:\n yield self.check_nodata,func_name\n\nclass CreateMonzoTests(TestCase):\n def test_typeOK_ynabsynccalled(self):\n data = dict(type='transaction.created')\n try:\n body, code = create_transaction_from_monzo(data, ynab_client=mockYnabClient)\n except KeyError:\n pass\n self.assertTrue(mockYnabClient.sync.called)\n\n @patch.object(mockYnabClient, 'getaccount',lambda account_name:None)\n def test_typeOK_noaccount(self):\n data = dict(type='transaction.created', data=dict(amount=10))\n def _getacount(accountname):\n return None\n body, code = create_transaction_from_monzo(data, ynab_client=mockYnabClient)\n self.assertEqual(code,400)\n\n @patch.object(mockYnabClient, 'getaccount', lambda account_name: Mock(Account))\n @patch.object(mockYnabClient, 'getpayee', lambda payee_name: Mock(Payee))\n @patch.object(mockYnabClient, 'containsDuplicate', lambda transaction: False)\n @patch('python.functions.get_subcategory_from_payee', lambda payee_name: Mock(Payee))\n def test_typeOK_payeefound(self):\n data = dict(type='transaction.created',\n data=dict(\n id='id',\n created='2017-05-7',\n amount=10, merchant=dict(name='merchant_name'),local_currency='',currency=''\n ))\n def _getacount(accountname):\n return None\n\n transaction_list=[]\n\n body, code = create_transaction_from_monzo(data, ynab_client=mockYnabClient)\n self.assertEqual(code, 201)\n transactions_append = mockYnabClient.client.budget.be_transactions.append\n self.assertTrue(transactions_append.called)\n self.assertEqual(transactions_append.call_count, 1)\n\n tup,dic = transactions_append.call_args\n self.assertEqual({},dic)\n self.assertEqual(len(tup),1)\n appended_transaction = tup[-1]\n\n self.assertTrue(mockYnabClient.client.push.called)\n tup, dic = mockYnabClient.client.push.call_args\n self.assertEqual({}, dic)\n self.assertEqual(len(tup), 1)\n self.assertEqual(1, tup[-1])\n","sub_path":"tests/unit/test_create.py","file_name":"test_create.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"150668045","text":"#Definition for singly-linked list.\nfrom typing import List\nimport sys\n\nimport logging\n#logging.basicConfig(level=logging.INFO, format=\"%(message)s\")\nlogging.basicConfig(level=logging.DEBUG, format=\"%(message)s\")\nimport sys\nsys.setrecursionlimit(1000000)\n\nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n return self.rec(candidates, 0, [], 0, target)\n\n def rec(self, S: List[int], i, comb, total, target) -> List[List[int]]:\n length = len(S)\n print(\"i:%s, length:%s\" % (i, length))\n if i >= length: return []\n for j in range(length):\n print(\"i:%s, j:%s\" % (i, j))\n if j < i: continue\n x = S[j]\n comb4 = comb[:]\n comb5 = comb[:]\n comb.append(x)\n comb1 = comb[:]\n comb2 = comb[:]\n comb3 = comb[:]\n\n total += x\n if total == target:\n return [comb1]\n elif total > target:\n return []\n else:\n tmp = []\n tmp += self.rec(S, i, comb2, total, target)\n tmp += self.rec(S, i+1, comb3, total, target)\n tmp += self.rec(S, i, comb4, total-x, target)\n tmp += self.rec(S, i+1, comb5, total-x, target)\n return tmp\n\n\nsamples = [\n ([2,3,6,7], 7, [[7], [2, 2, 3]]),\n]\nfor nums, k, expected in samples:\n print(\"-\"*20)\n ans = Solution().combinationSum(nums, k)\n assert ans == expected, \"(%s, %s) => %s but %s was expected\" % (nums, k, ans, expected)\n print(\"(%s, %s) = %s as expected!\" % (nums, k, ans))\n","sub_path":"lc/mdm/20190826_mdm_39_combination_sum.py","file_name":"20190826_mdm_39_combination_sum.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"266101362","text":"import datetime as dt\nfrom dateutil.parser import parse as dt_parse\nfrom django.core.management.base import BaseCommand\nfrom gdax_api.external import QuoteDownloader\nfrom bin import utils\n\n\nclass Command(BaseCommand):\n help = \"\"\"\n Download historical price data from GDAX.\n Please use UTC timestamps :D\n \"\"\"\n\n def add_arguments(self, parser):\n\n parser.add_argument(\n '--start_date',\n type=str,\n dest='start_date',\n nargs=1,\n help='Choose a start_date for download. Defaults 5 MINUTES prior to END_DATE'\n )\n parser.add_argument(\n '--end_date',\n type=str,\n dest='end_date',\n nargs=1,\n help='Choose a start_date for download. Defaults UTC now'\n )\n parser.add_argument(\n '--granularity',\n type=int,\n dest='granularity',\n nargs=1,\n help='Window in seconds for price history. Default 20'\n )\n parser.add_argument(\n '--max_failures',\n type=int,\n dest='max_failures',\n nargs=1,\n help='How many HTTP failures before shut down?'\n )\n parser.add_argument(\n '--product',\n type=str,\n dest='product',\n nargs='*',\n help='Products to download, eg. BTC-USD, LTC-BTC, etc. Multiple products possible.'\n )\n parser.add_argument(\n '--log_level',\n type=str,\n dest='log_level',\n nargs=1,\n help='Python logging level'\n )\n\n def handle(self, *args, **options):\n\n end_date = dt_parse(options['end_date'][0]) \\\n if options['end_date'] \\\n else dt.datetime.utcnow()\n start_date = dt_parse(options['start_date'][0]) \\\n if options['start_date'] \\\n else end_date - dt.timedelta(minutes=5)\n granularity = options['granularity'][0] if options['granularity'] else 60\n max_failures = options['max_failures'][0] if options['max_failures'] else 10\n product_list = options['product'] \\\n if options['product'] \\\n else utils.PRODUCT_LIST\n log_level = options['log_level'][0] if options['log_level'] else 'INFO'\n\n assert end_date > start_date\n\n qd = QuoteDownloader(log_level)\n qd.run(\n start_dt=start_date,\n end_dt=end_date,\n granularity=granularity,\n max_failures=max_failures,\n product_list=product_list\n )\n","sub_path":"money_squirrel/gdax_api/management/commands/download_gdax.py","file_name":"download_gdax.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"131592659","text":"\"\"\"Main module.\"\"\"\nimport os\n\nfrom contextlib import suppress\nfrom dataclasses import dataclass, fields, is_dataclass\nfrom typing import Any, Callable, ClassVar, Dict, Optional\n\n\n_TAccessor = Callable[[Any, Any], Any]\n\n\n@dataclass\nclass BaseAdapter:\n \"\"\"\n Base Class for Adapter pattern Models.\n \"\"\"\n\n __slots__ = tuple()\n _accessor: ClassVar[_TAccessor] = lambda el, tr: el\n _meta_key: ClassVar[str] = \"transformations\"\n\n @classmethod\n def from_any(\n cls,\n element: Any,\n *,\n accessor: Optional[_TAccessor] = None,\n **kwargs: Dict[str, Any]\n ) -> \"BaseAdapter\":\n if accessor is None:\n accessor = cls._accessor\n for cls_field in fields(cls):\n if cls_field.name in kwargs:\n continue\n value = element\n with suppress(KeyError):\n transformations = cls_field.metadata[cls._meta_key]\n for transformation in transformations:\n if is_dataclass(transformation):\n value = transformation.from_any(value, accessor=accessor)\n elif callable(transformation):\n value = transformation(value)\n else:\n value = accessor(value, transformation)\n kwargs[cls_field.name] = value\n return cls(**kwargs)\n\n @classmethod\n def from_dict(cls, element: Dict, **kwargs: Dict[str, Any]) -> \"BaseAdapter\":\n return cls.from_any(element, accessor=lambda el, tr: el[tr], **kwargs)\n\n @classmethod\n def from_env(cls, **kwargs: Dict) -> \"BaseAdapter\":\n return cls.from_any(None, accessor=lambda el, tr: os.environ[tr], **kwargs)\n","sub_path":"yaab/adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"203956719","text":"import requests\r\nimport pandas as pd\r\nfrom bs4 import BeautifulSoup\r\n\r\nurl = 'https://1000kitap.com/kitap/suc-ve-ceza--221003/incelemeler'\r\niste =requests.get(url)\r\ndosya = open(\"veri.txt\",\"w\", encoding=\"UTF-8\")\r\n\r\n\r\ndata = iste.content\r\nsoup = BeautifulSoup(data,'lxml')\r\n\r\ntablo = soup.find_all(\"div\",{\"class\":\"ana-orta\"})\r\nallicerik = soup.find_all(\"div\",{\"class\": \"icerik\"})\r\n#allokur = soup.find_all(\"a\", {\"class\":\"okur-adi\"})\r\ncount = 0\r\n\r\n\r\nfor icerik in allicerik:\r\n print(icerik.text)\r\n print(\"\\n\")\r\n count += 1\r\n dosya.write(icerik.text)\r\n dosya.write(\"\\n\") \r\n print(count)\r\n\r\n\r\n\r\n\"\"\"\r\nfor okur in allokur:\r\n veri = okur.text\r\n df = pd.DataFrame(veri, index=[1,2,3,4,5,6,7], columns = [\"isimler\"])\r\n print(df)\"\"\"\r\n\r\n\r\n","sub_path":"beat.py","file_name":"beat.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"488260752","text":"import math\n\n\ndef get_factors(num):\n factors = []\n for i in range(1, int(math.sqrt(num) + 1)):\n if num % i == 0:\n factors.append(i)\n other_factor = num / i\n if not (other_factor in factors) and other_factor != num:\n factors.append(int(num / i))\n\n return factors\n\n\ndef sum_list(nums):\n sum = 0\n for i in range(len(nums)):\n sum = sum + nums[i]\n return sum\n\n\ndef get_amicable_numbers(limit):\n amicable_numbers = []\n for i in range(limit):\n if not (i in amicable_numbers):\n factors_of_n = get_factors(i)\n n_sum_factors = sum_list(factors_of_n)\n if not (n_sum_factors in amicable_numbers) and i != n_sum_factors:\n factors_of_sum = get_factors(n_sum_factors)\n sum_sum_factors = sum_list(factors_of_sum)\n if sum_sum_factors == i:\n amicable_numbers.append(i)\n amicable_numbers.append(n_sum_factors)\n\n return amicable_numbers\n\n\namicable = get_amicable_numbers(10000)\nprint(amicable)\nprint(sum_list(amicable))\n","sub_path":"euler/problem21.py","file_name":"problem21.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"588361408","text":"import sys, os, random\nimport thread, socket\nimport urllib2 as urllib\n\nfrom utils import *\n\nfrom ConfigParser import RawConfigParser as ConfigParser\nfrom twisted.internet import reactor, protocol\nfrom twisted.internet.protocol import Factory\nfrom twisted.words.protocols import irc\nfrom colours import *\nfrom xml.etree import ElementTree\n\nfrom system.constants import *\nfrom system import faq\n\nfrom depends import mcbans_api as mcbans\n\nclass Bot(irc.IRCClient):\n\n # Channels\n joinchans = []\n channels = []\n \n chanlist = {}\n \n firstjoin = 1\n\n # Message queues\n messagequeue = []\n noticequeue = []\n \n # Quit quotes\n quotes = []\n \n # User system\n authorized = {}\n users = {}\n\n # Special IRC chars\n col = \"\u0003\" # Colour code\n bold = \"\u0002\" # Bold code\n under = \"\u001F\" # Underline code\n ital = \"\u001D\" # Italics code\n reverse = \"\u0016\" # Reverse code\n ctcp = \"\\1\" # CTCP code, as if we'll ever need this\n \n def prnt(self, msg):\n msg = string.replace(msg, self.bold, \"\")\n msg = string.replace(msg, self.under, \"\")\n msg = string.replace(msg, self.ital, \"\")\n msg = string.replace(msg, self.reverse, \"\")\n colprint(msg)\n self.logfile.write(\"%s\\n\" %(colstrip(msg)))\n self.flush()\n \n def parseQuotes(self):\n try:\n self.prnt(\"Reading in quit quotes from quits.txt...\")\n file = open(\"quotes.txt\", \"r\")\n data = file.read()\n self.quotes = data.split(\"\\n\")\n self.prnt(\"Read %s quotes.\" % len(self.quotes))\n except:\n return False\n else:\n return True\n \n def parseSettings(self):\n try:\n self.prnt(\"Reading in settings from settings.ini...\")\n oldchans = self.joinchans\n settings = ConfigParser()\n settings.read(\"settings.ini\")\n channels = settings.items(\"channels\")\n for element in self.joinchans:\n self.joinchans.remove(element)\n for element in channels:\n self.joinchans.append(element)\n if not element in oldchans and not self.firstjoin == 1:\n self.join(\"#%s\" % element[0])\n for element in oldchans:\n if element not in self.joinchans and not self.firstjoin == 1:\n self.part(\"#%s\" % element[0])\n self.password = settings.get(\"info\", \"password\")\n if not self.firstjoin == 1:\n self.sendmsg(\"nickserv\", \"IDENTIFY %s\" % self.password)\n self.loginpass = settings.get(\"info\", \"loginpass\")\n self.control_char = settings.get(\"info\", \"control_character\")\n self.data_dir = settings.get(\"info\", \"data_folder\")\n self.index_file = settings.get(\"info\", \"index_file\")\n self.api_key = settings.get(\"mcbans\", \"api_key\")\n except:\n return False\n else:\n self.prnt(\"Done!\")\n return True\n \n def __init__(self):\n # What's the name of our logfile?\n self.logfile = open(\"output.log\", \"a\")\n \n if not(self.parseSettings()):\n self.prnt(\"Unable to parse settings.ini. Does it exist? Bot will now quit.\")\n reactor.stop()\n exit()\n if not(self.parseQuotes()):\n self.prnt(\"Unable to parse quotes.txt. Does it exist? Bot will now quit.\")\n reactor.stop()\n exit()\n self.faq = faq.FAQ(self.data_dir)\n self.faq.listentries()\n self.mcb = mcbans.McBans(self.api_key)\n #Start the two loops for sending messages and notices\n self.messageLoop()\n self.noticeLoop()\n \n def flush(self):\n self.logfile.flush()\n \n def connectionLost(self, reason):\n # We lost connection. GTFO tiem.\n self.prnt(\"***Shutting down!***\")\n self.flush()\n \n @property\n def nickname(self):\n return self.factory.nickname\n\n def signedOn(self):\n # OK, we logged on successfully.\n # Log that we signed on.\n self.prnt(\"***Signed on as %s.***\" % self.nickname)\n # Log in with NickServ.\n self.sendmsg(\"NickServ\", \"IDENTIFY %s\" % self.password)\n # Join all the channels in the file, as parsed earlier.\n for element in self.joinchans:\n self.join(element[0])\n # Flush the logfile - so we can read it.\n self.flush()\n\n def joined(self, channel):\n # We joined a channel\n self.prnt(\"***Joined %s***\" % channel)\n self.channels.append(channel)\n if self.firstjoin == 1:\n self.firstjoin = 0\n # Flush the logfile\n self.who(channel)\n self.flush()\n \n def is_op(self, channel, user):\n if channel in self.chanlist.keys():\n if user in self.chanlist[channel].keys():\n return self.chanlist[channel][user][\"op\"]\n return False \n return False\n \n def is_voice(self, channel, user):\n if channel in self.chanlist.keys():\n if user in self.chanlist[channel].keys():\n return self.chanlist[channel][user][\"op\"]\n return False \n return False\n \n def set_op(self, channel, user, data):\n if isinstance(data, bool):\n if channel in self.chanlist.keys():\n if user in self.chanlist[channel].keys():\n self.chanlist[channel][user][\"op\"] = data\n else:\n raise ValueError(\"'data' must be either True or False\")\n \n def set_voice(self, channel, user, data):\n if isinstance(data, bool):\n if channel in self.chanlist.keys():\n if user in self.chanlist[channel].keys():\n self.chanlist[channel][user][\"op\"] = data\n else:\n raise ValueError(\"'data' must be either True or False\")\n \n def privmsg(self, user, channel, msg):\n # We got a message.\n # Define the userhost\n userhost = user\n # Get the username\n user = user.split(\"!\", 1)[0]\n authorized = False\n authtype = 0\n if self.is_op(channel, user) and user in self.authorized.keys():\n authorized = True\n authtype = 3\n elif self.is_op(channel, user):\n authorized = True\n authtype = 1\n elif user in self.authorized.keys():\n authorized = True\n authtype = 2\n if msg.startswith(self.control_char):\n command = msg.split(\" \")[0].strip(self.control_char)\n arguments = msg.split(\" \")\n if command == \"help\":\n if len(arguments) < 2:\n self.sendnotice(user, \"Syntax: %shelp \" % self.control_char)\n self.sendnotice(user, \"Available topics: about, login, logout, lookup\")\n if authorized:\n self.sendnotice(user, \"Admin topics: raw, quit\")\n else:\n if arguments[1] == \"about\":\n self.sendnotice(user, \"I'm the #MCBans IRC helper bot.\")\n self.sendnotice(user, \"I live in #mcbans on irc.esper.net\")\n elif arguments[1] == \"auth\":\n self.sendnotice(user, \"Auth is managed with %slogin and %slogout.\" % (self.control_char, self.control_char))\n self.sendnotice(user, \"If you change your nick, you will be logged out automatically.\")\n self.sendnotice(user, \"Channel ops also have some access.\" % (self.control_char, self.control_char))\n elif arguments[1] == \"login\":\n self.sendnotice(user, \"Syntax: %slogin \" % self.control_char)\n self.sendnotice(user, \"Logs you into the bot using a password set by the bot owner.\")\n self.sendnotice(user, \"See %shelp auth for more information.\" % self.control_char)\n elif arguments[1] == \"logout\":\n self.sendnotice(user, \"Syntax: %slogout\" % self.control_char)\n self.sendnotice(user, \"Logs you out of the bot, provided you were already logged in.\")\n self.sendnotice(user, \"See %shelp auth for more information.\" % self.control_char)\n elif arguments[1] == \"lookup\":\n self.sendnotice(user, \"Syntax: %slookup [type]\" % self.control_char)\n self.sendnotice(user, \"Used to make a lookup on the MCBans site, using the v2 API.\")\n self.sendnotice(user, \"Type is optional, but it can be local, global, minimal or all. If it is missing, it is presumed to be minimal.\")\n elif arguments[1] == \"ping\":\n self.sendnotice(user, \"Syntax: %sping \" % self.control_char)\n self.sendnotice(user, \"Retrieves the server information from a Beta/Release server.\")\n self.sendnotice(user, \"Can be useful to check if a server is accepting connections.\")\n elif user in self.authorized.keys():\n if arguments[1] == \"raw\":\n self.sendnotice(user, \"Syntax: %sraw \" % self.control_char)\n self.sendnotice(user, \"Sends raw data to the server.\")\n elif arguments[1] == \"quit\":\n self.sendnotice(user, \"Syntax: %squit [message]\" % self.control_char)\n self.sendnotice(user, \"Makes the bot quit, with an optional user-defined message.\")\n self.sendnotice(user, \"If no message is defined, uses a random quote.\")\n else:\n self.sendnotice(user, \"Unknown help topic: %s\" % arguments[1])\n elif command == \"login\":\n if len(arguments) < 2:\n self.sendnotice(user, \"Syntax: %slogin \" % self.control_char)\n self.sendnotice(user, \"The password is set by the owner of the bot.\")\n else:\n passw = arguments[1]\n if passw == self.loginpass:\n self.authorized[user] = userhost.split(\"!\", 1)[1]\n self.sendnotice(user, \"You have been logged in successfully.\")\n self.prnt(\"%s logged in successfully.\" % user)\n else:\n self.sendnotice(user, \"Incorrect password! Check for case and spacing!\")\n self.prnt(\"%s tried to log in with an invalid password!\" % user)\n self.flush()\n return\n elif command == \"logout\":\n if user in self.authorized.keys():\n del self.authorized[user]\n self.sendnotice(user, \"You have been logged out successfully.\")\n else:\n self.sendnotice(user, \"You were never logged in. Please note that you are logged out automatically when you nick.\")\n elif command == \"quit\":\n if authorized and authtype > 1:\n if len(arguments) < 2:\n self.squit()\n else:\n self.squit(\" \".join(arguments[1:]))\n else:\n self.sendnotice(user, \"You do not have access to this command.\")\n elif command == \"raw\":\n if authorized and authtype > 1:\n if not len(arguments) < 2:\n self.sendnotice(user, \"Done!\")\n self.sendLine(\" \".join(arguments[1:]))\n else:\n self.sendnotice(user, \"Syntax: %sraw \" % self.control_char)\n else:\n self.sendnotice(user, \"You do not have access to this command.\")\n elif command == \"lookup\":\n if len(arguments) > 1:\n data = self.mcb.lookup(arguments[1], user)\n try:\n error = data[\"error\"]\n self.sendmsg(channel, \"Error: %s\" % data[\"error\"])\n except:\n if len(arguments) > 2:\n type = arguments[2]\n if type == \"local\":\n if authorized:\n self.sendmsg(channel, \"Listing local bans for %s...\" % arguments[1])\n if len(data[\"local\"]) > 0:\n for element in data[\"local\"]:\n server = element.split(\" .:. \")[0].encode(\"ascii\", \"ignore\")\n reason = element.split(\" .:. \")[1].encode(\"ascii\", \"ignore\")\n self.sendmsg(channel, \"%s: %s\" % (server, reason.decode('string_escape')))\n else:\n self.sendmsg(channel, \"No local bans.\")\n else:\n self.sendnotice(user, \"Listing local bans for %s...\" % arguments[1])\n if len(data[\"local\"]) > 0:\n for element in data[\"local\"]:\n server = element.split(\" .:. \")[0].encode(\"ascii\", \"ignore\")\n reason = element.split(\" .:. \")[1].encode(\"ascii\", \"ignore\")\n self.sendnotice(user, \"%s: %s\" % (server, reason.decode('string_escape')))\n else:\n self.sendnotice(user, \"No local bans.\")\n elif type == \"global\":\n if authorized:\n self.sendmsg(channel, \"Listing global bans for %s...\" % arguments[1])\n if len(data[\"global\"]) > 0:\n for element in data[\"global\"]:\n server = element.split(\" .:. \")[0].encode(\"ascii\", \"ignore\")\n reason = element.split(\" .:. \")[1].encode(\"ascii\", \"ignore\")\n self.sendmsg(channel, \"%s: %s\" % (server, reason.decode('string_escape')))\n else:\n self.sendmsg(channel, \"No global bans.\")\n else:\n self.sendnotice(user, \"Listing global bans for %s...\" % arguments[1])\n if len(data[\"global\"]) > 0:\n for element in data[\"global\"]:\n server = element.split(\" .:. \")[0].encode(\"ascii\", \"ignore\")\n reason = element.split(\" .:. \")[1].encode(\"ascii\", \"ignore\")\n self.sendmsg(channel, \"%s: %s\" % (server, reason.decode('string_escape')))\n else:\n self.sendnotice(user, \"No global bans.\")\n elif type == \"minimal\":\n if authorized:\n self.sendmsg(channel, \"Reputation for %s: %.2f/10\" % (arguments[1], data[\"reputation\"]))\n self.sendmsg(channel, \"Total bans: %s\" % data[\"total\"])\n else:\n self.sendnotice(user, \"Reputation for %s: %.2f/10\" % (arguments[1], data[\"reputation\"]))\n self.sendnotice(user, \"Total bans: %s\" % data[\"total\"])\n elif type == \"all\":\n if authorized:\n self.sendmsg(channel, \"Listing everything for %s...\" % arguments[1])\n self.sendmsg(channel, \"Reputation for %s: %.2f/10\" % (arguments[1], data[\"reputation\"]))\n self.sendmsg(channel, \"Total bans: %s\" % data[\"total\"])\n self.sendmsg(channel, \"Listing local bans for %s...\" % arguments[1])\n if len(data[\"local\"]) > 0:\n for element in data[\"local\"]:\n server = element.split(\" .:. \")[0].encode(\"ascii\", \"ignore\")\n reason = element.split(\" .:. \")[1].encode(\"ascii\", \"ignore\")\n self.sendmsg(channel, \"%s: %s\" % (server, reason.decode('string_escape')))\n else:\n self.sendmsg(channel, \"No local bans.\")\n self.sendmsg(channel, \"Listing global bans for %s...\" % arguments[1])\n if len(data[\"global\"]) > 0:\n for element in data[\"global\"]:\n server = element.split(\" .:. \")[0].encode(\"ascii\", \"ignore\")\n reason = element.split(\" .:. \")[1].encode(\"ascii\", \"ignore\")\n self.sendmsg(channel, \"%s: %s\" % (server, reason.decode('string_escape')))\n else:\n self.sendmsg(channel, \"No global bans.\")\n else:\n self.sendnotice(user, \"Listing everything for %s...\" % arguments[1])\n self.sendnotice(user, \"Listing everything for %s...\" % arguments[1])\n self.sendnotice(user, \"Reputation for %s: %.2f/10\" % (arguments[1], data[\"reputation\"]))\n self.sendnotice(user, \"Total bans: %s\" % data[\"total\"])\n self.sendnotice(user, \"Listing local bans for %s...\" % arguments[1])\n if len(data[\"local\"]) > 0:\n for element in data[\"local\"]:\n server = element.split(\" .:. \")[0].encode(\"ascii\", \"ignore\")\n reason = element.split(\" .:. \")[1].encode(\"ascii\", \"ignore\")\n self.sendnotice(user, \"%s: %s\" % (server, reason.decode('string_escape')))\n else:\n self.sendnotice(user, \"No local bans.\")\n self.sendnotice(user, \"Listing global bans for %s...\" % arguments[1])\n if len(data[\"global\"]) > 0:\n for element in data[\"global\"]:\n server = element.split(\" .:. \")[0].encode(\"ascii\", \"ignore\")\n reason = element.split(\" .:. \")[1].encode(\"ascii\", \"ignore\")\n self.sendnotice(user, \"%s: %s\" % (server, reason.decode('string_escape')))\n else:\n self.sendnotice(user, \"No global bans.\")\n else:\n if authorized:\n self.sendmsg(channel, \"Reputation for %s: %.2f/10\" % (arguments[1], data[\"reputation\"]))\n self.sendmsg(channel, \"Total bans: %s\" % data[\"total\"])\n else:\n self.sendnotice(user, \"Reputation for %s: %.2f/10\" % (arguments[1], data[\"reputation\"]))\n self.sendnotice(user, \"Total bans: %s\" % data[\"total\"])\n else:\n if authorized:\n self.sendmsg(channel, \"Reputation for %s: %.2f/10\" % (arguments[1], data[\"reputation\"]))\n self.sendmsg(channel, \"Total bans: %s\" % data[\"total\"])\n else:\n self.sendnotice(user, \"Reputation for %s: %.2f/10\" % (arguments[1], data[\"reputation\"]))\n self.sendnotice(user, \"Total bans: %s\" % data[\"total\"])\n else:\n self.sendnotice(user, \"Syntax: %slookup [type]\" % self.control_char)\n elif command == \"msg\":\n self.sendnotice(user, \"The msg command is under construction!\")\n elif command == \"mcbmsg\":\n self.sendnotice(user, \"The mcbmsg command is under construction!\")\n elif command == \"ping\":\n derp = 0\n if len(arguments) > 1:\n ip = arguments[1]\n if \":\" in ip:\n server, port = ip.split(\":\", 1)\n try:\n port = int(port)\n except:\n if authorized:\n self.sendmsg(channel, \"%s is an invalid port number.\" % port)\n else:\n self.sendnotice(user, \"%s is an invalid port number.\" % port)\n derp = 1\n else:\n server, port = ip, 25565\n if derp == 0:\n try:\n s = socket.socket(\n socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(5.0)\n s.connect((server, port))\n s.send(\"\\xFE\")\n data = s.recv(1)\n \n if data.startswith(\"\\xFF\"):\n data = s.recv(255)\n s.close()\n data = data[3:]\n finlist = data.split(\"\\xA7\")\n lastelement = \"\"\n\n finished = []\n\n for element in finlist:\n donestr = \"\"\n for character in element:\n if ord(character) in range(128) and not ord(character) == 0:\n donestr = donestr + character.encode(\"ascii\", \"ignore\")\n finished.append(donestr.strip(\"\\x00\"))\n \n if authorized:\n self.sendmsg(channel, \"Server info: %s (%s/%s)\" % (finished[0], finished[1], finished[2]))\n else:\n self.sendnotice(user, \"Server info: %s (%s/%s)\" % (finished[0], finished[1], finished[2]))\n else:\n if authorized:\n self.sendmsg(channel, \"That doesn't appear to be a Minecraft server.\")\n else:\n self.sendnotice(user, \"That doesn't appear to be a Minecraft server.\")\n except Exception as e:\n self.sendmsg(channel, \"Error: %s\" % e)\n elif msg.startswith(\"??\"):\n parts = msg.split(\" \")\n if len(parts) > 1:\n if parts[0] == \"??\": # Check in channel\n if len(parts) > 1:\n data = self.faq.get(parts[1].lower())\n if(data[0]):\n for element in data[1]:\n self.sendmsg(channel, \"(%s) %s\" % (parts[1].lower(), element))\n else:\n if data[1] is ERR_NO_SUCH_ENTRY:\n self.sendnotice(user, \"No such entry: %s\" % parts[1].lower())\n else:\n self.sendnotice(user, \"Unable to load entry: %s\" % parts[1].lower())\n else:\n self.sendnotice(user, \"Please provide a help topic. For example: ?? help\")\n elif parts[0] == \"??>\": # Check in channel with target\n if len(parts) > 2:\n data = self.faq.get(parts[2].lower())\n if(data[0]):\n for element in data[1]:\n self.sendmsg(channel, \"%s: (%s) %s\" % (parts[1], parts[2].lower(), element))\n else:\n if data[1] is ERR_NO_SUCH_ENTRY:\n self.sendnotice(user, \"No such entry: %s\" % parts[2].lower())\n else:\n self.sendnotice(user, \"Unable to load entry: %s\" % parts[2].lower())\n else:\n self.sendnotice(user, \"Please provide a help topic and target user. For example: ??> helpme help\")\n elif parts[0] == \"??>>\": # Check in message to target\n if len(parts) > 2:\n data = self.faq.get(parts[2].lower())\n if(data[0]):\n for element in data[1]:\n self.sendmsg(parts[1], \"(%s) %s\" % (parts[2].lower(), element))\n self.sendnotice(user, \"Topic '%s' has been sent to %s.\" % (parts[2].lower(), parts[1]))\n else:\n if data[1] is ERR_NO_SUCH_ENTRY:\n self.sendnotice(user, \"No such entry: %s\" % parts[2].lower())\n else:\n self.sendnotice(user, \"Unable to load entry: %s\" % parts[2].lower())\n else:\n self.sendnotice(user, \"Please provide a help topic and target user. For example: ??>> helpme help\")\n elif parts[0] == \"??<\": # Check in message to self\n if len(parts) > 1:\n data = self.faq.get(parts[1].lower())\n if(data[0]):\n for element in data[1]:\n self.sendnotice(user, \"(%s) %s\" % (parts[1].lower(), element))\n else:\n if data[1] is ERR_NO_SUCH_ENTRY:\n self.sendnotice(user, \"No such entry: %s\" % parts[1].lower())\n else:\n self.sendnotice(user, \"Unable to load entry: %s\" % parts[1].lower())\n else:\n self.sendnotice(user, \"Please provide a help topic. For example: ??< help\")\n elif parts[0] == \"??+\": # Add or append to a topic\n if authorized:\n if len(parts) > 2:\n data = self.faq.set(parts[1].lower(), \" \".join(parts[2:]), MODE_APPEND)\n self.faq.listentries()\n if(data[0]):\n self.sendnotice(user, \"Successfully added to the topic: %s\" % parts[1].lower())\n else:\n self.sendnotice(user, \"Unable to add to the topic: %s\" % parts[1].lower())\n if data[1] is ERR_NO_SUCH_ENTRY:\n self.sendnotice(user, \"Entry does not exist.\")\n else:\n self.sendnotice(user, \"Please report this to the MCBans staff.\")\n else:\n self.sendnotice(user, \"Please provide a help topic and some data to append. For example: ??+ help This is what you do..\")\n else:\n self.sendnotice(user, \"You do not have access to this command.\")\n elif parts[0] == \"??~\": # Add or replace topic\n if authorized:\n if len(parts) > 2:\n data = self.faq.set(parts[1].lower(), \" \".join(parts[2:]), MODE_REPLACE)\n self.faq.listentries()\n if(data[0]):\n self.sendnotice(user, \"Successfully replaced topic: %s\" % parts[1].lower())\n else:\n self.sendnotice(user, \"Unable to replace the topic: %s\" % parts[1].lower())\n if data[1] is ERR_NO_SUCH_ENTRY:\n self.sendnotice(user, \"Entry does not exist.\")\n else:\n self.sendnotice(user, \"Please report this to the MCBans staff.\")\n else:\n self.sendnotice(user, \"Please provide a help topic and some data to use. For example: ??~ help This is what you do..\")\n else:\n self.sendnotice(user, \"You do not have access to this command.\")\n elif parts[0] == \"??-\": # Remove topic\n if authorized:\n if len(parts) > 1:\n data = self.faq.set(parts[1].lower(), '', MODE_REMOVE)\n self.faq.listentries()\n if(data[0]):\n self.sendnotice(user, \"Successfully removed the topic: %s\" % parts[1].lower())\n else:\n self.sendnotice(user, \"Unable to remove the topic: %s\" % parts[1].lower())\n if data[1] is ERR_NO_SUCH_ENTRY:\n self.sendnotice(user, \"Entry does not exist.\")\n else:\n self.sendnotice(user, \"Please report this to the MCBans staff.\")\n else:\n self.sendnotice(user, \"Please provide a help topic to remove. For example: ??- help\")\n else:\n self.sendnotice(user, \"You do not have access to this command.\")\n # Flush the logfile\n self.flush()\n # Log the message\n self.prnt(\"<%s:%s> %s\" % (user, channel, msg))\n \n def squit(self, reason = \"\"):\n if not reason == \"\":\n self.sendLine(\"QUIT :\"+reason)\n else:\n quitmsg = self.quotes[random.randint(0, len(self.quotes))].strip(\"\\r\")\n self.sendLine(\"QUIT :%s\" % quitmsg)\n self.prnt(\"***QUITTING!***\")\n data = open(\"quitted\", \"w\")\n data.write(\"1\")\n data.flush()\n data.close()\n \n def left(self, channel):\n # We left a channel.\n self.prnt(\"***Left %s***\" % channel)\n # Flush the logfile\n self.flush()\n \n def ctcpQuery(self, user, me, messages):\n name = user.split(\"!\", 1)[0]\n self.prnt(\"[%s] %s\" % (user, messages))\n # It's a CTCP query!\n if messages[0][0].lower() == \"version\":\n self.ctcpMakeReply(name, [(messages[0][0], \"A Python bot written for #mcbans\")])\n elif messages[0][0].lower() == \"finger\":\n self.ctcpMakeReply(name, [(messages[0][0], \"No. Just, no.\")])\n # Flush the logfile\n self.flush()\n # [gdude2002|away!colesgaret@86-41-192-29-dynamic.b-ras1.lmk.limerick.eircom.net:NotchBot [('CLIENTINFO', None)]]\n \n def modeChanged(self, user, channel, set, modes, args):\n # Mode change.\n userhost = user\n user = user.split(\"!\", 1)[0]\n try:\n if set:\n self.prnt(\"***%s sets mode %s +%s %s***\" % (user, channel, modes, \" \".join(args)))\n i = 0\n for element in modes:\n if element is \"o\":\n self.set_op(channel, args[i], True)\n if element is \"v\":\n self.set_op(channel, args[i], True)\n i += 1\n else:\n self.prnt(\"***%s sets mode %s -%s %s***\" % (user, channel, modes, \" \".join(args)))\n i = 0\n for element in modes:\n if element is \"o\":\n self.set_op(channel, args[i], False)\n if element is \"v\":\n self.set_op(channel, args[i], False)\n i += 1\n except Exception:\n pass\n # Flush the logfile\n self.flush()\n \n def kickedFrom(self, channel, kicker, message):\n # Onoes, we got kicked!\n self.prnt(\"***Kicked from %s by %s: %s***\" % (channel, kicker, message))\n # Flush the logfile\n self.flush()\n \n def nickChanged(self, nick):\n # Some evil muu changed MY nick!\n self.prnt(\"***Nick changed to %s***\" % nick)\n # Flush the logfile\n self.flush()\n \n def userJoined(self, user, channel):\n # Ohai, welcome to mah channel!\n self.prnt(\"***%s joined %s***\" % (user, channel))\n # Flush the logfile\n self.flush()\n \n def userLeft(self, user, channel):\n # Onoes, bai!\n self.prnt(\"***%s left %s***\" % ((user.split(\"!\")[0]), channel))\n # Flush the logfile\n self.flush()\n \n def userKicked(self, kickee, channel, kicker, message):\n # Mwahahaha, someone got kicked!\n kickee = kickee.split(\"!\", 1)[0]\n kicker = kicker.split(\"!\", 1)[0]\n self.prnt(\"***%s was kicked from %s by %s [%s]***\" % (kickee, channel, kicker, message))\n # Flush the logfile\n self.flush()\n\n def action(self, user, channel, data):\n # Someone did /me.\n userhost = user\n user = user.split(\"!\", 1)[0]\n self.prnt(\"* %s:%s %s\" % (user, channel, data))\n # Flush the logfile\n self.flush()\n\n def irc_QUIT(self, user, params):\n # Someone quit.\n userhost = user\n user = user.split('!')[0]\n quitMessage = params[0]\n self.prnt(\"***%s has left irc: %s***\" % (user, quitMessage))\n # Flush the logfile\n self.flush()\n \n def topicUpdated(self, user, channel, newTopic):\n # Topic was changed. Also called on a channel join.\n userhost = user\n user = user.split(\"!\")[0]\n self.prnt(\"***%s set topic %s to \\\"%s%s15\\\"***\" % (user, channel, newTopic, self.col))\n # Flush the logfile\n self.flush()\n \n def irc_NICK(self, prefix, params):\n # Someone changed their nick.\n oldnick = prefix.split(\"!\", 1)[0]\n newnick = params[0]\n self.prnt(\"***%s is now known as %s***\" % (oldnick, newnick))\n if oldnick in self.authorized.keys():\n self.sendnotice(newnick, \"You have been logged out for security reasons. This happens automatically when you change your nick.\")\n del self.authorized[oldnick]\n for element in self.chanlist.keys():\n if oldnick in self.chanlist[element].keys():\n oldpart = self.chanlist[element][oldnick]\n self.chanlist[element][newnick] = oldpart\n del self.chanlist[element][oldnick]\n # Flush the logfile\n self.flush()\n \n def messageLoop(self, wut=None):\n self.m_protect = 0\n while self.m_protect < 5:\n try:\n item = self.messagequeue.pop(0).split(\":\", 1)\n user = item[0]\n message = item[1]\n self.sendmessage(user, message)\n except IndexError:\n pass\n except:\n try:\n print(\"Failed to send message!\")\n print(user+\" -> \"+message)\n except:\n pass\n self.m_protect = self.m_protect + 1\n reactor.callLater(2.5, self.messageLoop, ())\n \n def noticeLoop(self, wut=None):\n self.n_protect = 0\n while self.n_protect < 5:\n try:\n item = self.noticequeue.pop(0).split(\":\", 1)\n user = item[0]\n message = item[1]\n self.sendntc(user, message)\n except IndexError:\n pass\n except:\n try:\n print(\"Failed to send notice!\")\n print(user+\" -> \"+message)\n except:\n pass\n self.n_protect = self.n_protect + 1\n reactor.callLater(2.5, self.noticeLoop, ())\n \n def who(self, channel):\n \"List the users in 'channel', usage: client.who('#testroom')\"\n self.sendLine('WHO %s' % channel)\n\n def irc_RPL_WHOREPLY(self, *nargs):\n \"Receive WHO reply from server\"\n # ('apocalypse.esper.net', ['McPlusPlus_Testing', '#minecraft', 'die', 'inafire.com', 'apocalypse.esper.net', 'xales|gone', 'G*', '0 xales'])\n \n our_server = nargs[0]\n data = nargs[1]\n \n our_nick = data[0]\n channel = data[1]\n ident = data[2] # Starts with a ~ if there's no identd present\n host = data[3]\n server = data[4]\n nick = data[5]\n status = data[6] # H - not away, G - away, * - IRCop, @ - op, + - voice\n gecos = data[7] # Hops, realname\n \n if not channel in self.chanlist.keys():\n self.chanlist[channel] = {}\n \n done = {}\n done[\"ident\"] = ident\n done[\"host\"] = host\n done[\"server\"] = server\n done[\"realname\"] = gecos.split(\" \")[1]\n done[\"op\"] = False\n done[\"voice\"] = False\n done[\"oper\"] = False\n done[\"away\"] = False\n for char in status:\n if char is \"@\":\n done[\"op\"] = True\n if char is \"+\":\n done[\"voice\"] = True\n if char is \"*\":\n done[\"oper\"] = True\n if char is \"G\":\n done[\"away\"] = True\n self.chanlist[channel][nick] = done\n\n def irc_RPL_ENDOFWHO(self, *nargs):\n \"Called when WHO output is complete\"\n # ('eldridge.esper.net', ['McPlusPlus_Testing', '#mc++', 'End of /WHO list.'])\n server = nargs[0]\n data = nargs[1]\n my_nick = data[0]\n channel = data[1]\n message = data[2]\n print(\"%s users on %s\" % (len(self.chanlist[channel]), channel))\n\n def irc_unknown(self, prefix, command, params):\n \"Print all unhandled replies, for debugging.\"\n # if command == \"RPL_NAMREPLY\":\n # ['McPlusPlus_Testing', '@', '#hollow_testing', 'McPlusPlus_Testing @DerpServ @g']\n # print (\"Users on %s: %s\" % (params[2], params[3]))\n # if command == \"RPL_ENDOFNAMES\":\n # print (\"Name list for %s is finished.\" % (params[1]))\n\n\n\n#-#################################-#\n# |\n# UTILITY # FUNCTIONS #\n# |\n#-#################################-#\n\n def cmsg(self, message):\n # Send a message to all joined channels\n for element in self.joinchans:\n self.sendmsg(\"#\"+element[0], message.encode('ascii','ignore'))\n \n def cnotice(self, message):\n # Notice all channels\n for element in self.joinchans:\n self.sendnotice(\"#\"+element[0], message.encode('ascii','ignore'))\n \n # Don't use this directy, use sendmsg\n def sendmessage(self, user, message):\n if user == \"NickServ\":\n self.prnt(\"--> <%s> %s\" % (user, (\"*\" *len(message))))\n else:\n self.prnt(\"--> <%s> %s\" % (user, message))\n self.msg(user, message)\n # Flush the logfile\n self.flush()\n \n # Don't use this directy, use sendnotice\n def sendntc(self, user, message):\n self.prnt(\"--> -%s- %s\" % (user, message))\n self.notice(user, message)\n # Flush the logfile\n self.flush()\n \n def sendmsg(self, user, message):\n self.messagequeue.append(str(user)+\":\"+str(message))\n \n def sendnotice(self, user, message):\n self.noticequeue.append(str(user)+\":\"+str(message))\n \n def senddescribe(self, user, message):\n self.prnt(\"--> * %s: %s\" % (user, message))\n self.describe(user, message)\n # Flush the logfile\n self.flush()\n\n def identify(self):\n self.sendmsg(\"NickServ\", \"IDENTIFY %s\" % self.password)\n\nclass BotFactory(protocol.ClientFactory):\n protocol = Bot\n\n def __init__(self):\n # Initialize!\n settings = ConfigParser()\n settings.read(\"settings.ini\")\n self.nickname = settings.get(\"info\", \"nickname\")\n\n def prnt(self, msg):\n colprint(msg)\n self.logfile = open(\"output.log\", \"a\")\n self.logfile.write(\"%s\\n\" %(colstrip(msg)))\n self.logfile.flush()\n self.logfile.close()\n \n def clientConnectionLost(self, connector, reason):\n # We died. Onoes!\n self.prnt(\"Lost connection: %s\" % (reason))\n\n def clientConnectionFailed(self, connector, reason):\n # Couldn't connect. Daww!\n self.prnt(\"Could not connect: %s\" % (reason))","sub_path":"system/irc.py","file_name":"irc.py","file_ext":"py","file_size_in_byte":41655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"48286854","text":"import re, random\n\nvalidator = \"^[ a-z]{,}$\"\n\nalph = \" abcdefghijklmnopqrstuvwxyz\"\nalph = list(alph)\ncopy_alph = \"abcdefghijklmnopqrstuvwxyz\"\nlen_copy_alph = len(copy_alph)\ncopy_alph_list = list(copy_alph)\nrandom_alph = list(copy_alph) # алфавіт, який змінюється рандомно\nrandom.shuffle(random_alph) # <- алфавіт змінюється рандомно\nrandom_alph_list = list(random_alph)\ndict_alph = {}\ni = 0\nwhile i < len(copy_alph):\n dict_alph[copy_alph[i]] = i\n i += 1\n\ndict_rand = {}\na = 0\nwhile a < len(random_alph):\n dict_rand[random_alph[a]] = a\n a += 1\n\nDIR_NAME = ''\nFILE_NAME_MESSAGE = 'modules\\Permutation\\message.txt'\nFILE_NAME_CIPHERTEXT = 'modules\\Permutation\\cipher_text.txt'\nFILE_NAME_KEY = 'modules\\Permutation\\key.txt'\n\n\ndef Generate_Key():\n key = random.choice(copy_alph)\n key_fie_name = DIR_NAME + FILE_NAME_KEY\n f = open(key_fie_name, 'w')\n f.write(key)\n f.close()\n print('Новий ключ згенеровано :', key)\n return key\n\ndef Cipher():\n while True:\n print(\"\\nВведіть повідомлення для шифрування(1) або зчитайте з файлу(2): \", end=\"\")\n b = input()\n if b == '1':\n message = input()\n if re.match(validator, message):\n break\n else:\n print(\"Ви ввели неправильне повідомлення\")\n elif b == '2':\n mess_file_name = DIR_NAME + FILE_NAME_MESSAGE\n f = open(mess_file_name, 'r')\n message = f.read()\n if re.match(validator, message):\n print('Текс повідомлення: ', message)\n break\n else:\n print(\"Ви ввели неправильне повідомлення\")\n else:\n continue\n\n v = ''\n t = 0\n i = 0\n mess_num = []\n new_mess = []\n while i < len(message):\n v = message[i]\n iaa = dict_alph[v]\n mess_num.append(iaa)\n t = int(mess_num[i])\n new_mess += random_alph[t]\n i += 1\n\n print(f'\\nРезультат п1: {new_mess}')\n\n# Part 2\n while True:\n print(\"\\nВведіть ключ(1) або згенеруйте(2): \", end=\"\")\n c = input()\n if c == '1':\n key = input()\n if len(key) == 1 and re.match(validator, key):\n mess_file_name = DIR_NAME + FILE_NAME_MESSAGE\n f = open(mess_file_name, 'w')\n f.write(message)\n f.close()\n break\n else:\n print(\"Ви ввели неправильний ключ\")\n elif c == '2':\n key = Generate_Key()\n key_fie_name = DIR_NAME + FILE_NAME_KEY\n f = open(key_fie_name, 'w')\n f.write(key)\n f.close()\n break\n else:\n continue\n\n key = dict_alph[key]\n new_mess2 = ''\n for a in message:\n new_mess2 += copy_alph_list[(dict_rand[a] - key) % len_copy_alph] if a != \" \" else ' '\n\n new_mess2 = list(new_mess2)\n print(f'\\nРезультат п2: {new_mess2}')\n\ndef Uncipher():\n pass\n\n","sub_path":"Cryptography/Early_Ciphers/App/modules/Permutation/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"438086362","text":"import os\nimport cv2\nfrom tqdm import tqdm\n\nsrc_base = 'cropped'\n# 清理无法读取的图像\nfor p in tqdm(os.listdir(src_base)):\n pt = os.path.join(src_base, p)\n im = cv2.imread(pt)\n if im is None:\n os.remove(pt)\n print('-[INFO] remove', p)\n","sub_path":"clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"508096202","text":"def bak(k):\n if k == m:\n for i in arr:\n print(i, end=' ')\n print()\n return\n for i in range(1, n+1):\n if k > 0:\n if arr[k-1] >= i:\n continue\n if not isused[i]:\n isused[i] = 1\n arr[k] = i\n bak(k+1)\n isused[i] = 0\n\nn, m = map(int, input().split())\narr = [0] * m\nisused = [0] * (n+1)\nbak(0)\n","sub_path":"baekjoon/baekjoon_15650.py","file_name":"baekjoon_15650.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"336955742","text":"import traceback\nfrom optparse import OptionParser\n\nfrom email_attach import get_unseen_msg_attachments\nfrom parse_order import parse_document\nfrom spreadsheet_update import insert_new_order\nimport settings\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\nhandler = logging.FileHandler(settings.log_name)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\n\ndef main():\n parser = OptionParser()\n options, _ = parser.parse_args()\n logger.info('Start process')\n attaches = get_unseen_msg_attachments()\n for attach in attaches:\n try:\n order = parse_document(attach)\n except Exception as e:\n logger.error('Attach is not PDF or: %s', traceback.print_exc())\n continue\n insert_new_order(order)\n logger.info('End process')\n\nif __name__ == '__main__':\n main()\n","sub_path":"email_parser/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"255673397","text":"'''\nCreated on 03.07.2013\n\n@author: abb\n'''\n\nfrom BeautifulSoup import BeautifulSoup\nimport urllib\n\nINPUT_FILE = 'subscriptions.xml'\nOUTPUT_FILE = 'nice_opml.xml'\n\nif __name__ == '__main__':\n with open(INPUT_FILE) as input_fd:\n soup = BeautifulSoup(input_fd)\n with open(OUTPUT_FILE, 'wb+') as output_fd:\n output_fd.write('\\n')\n output_fd.write('\\t\\n')\n output_fd.write('\\t\\n')\n for outline in soup.findAll('outline'):\n outline_data = {\n 'type': 'rss',\n 'text': outline['text'],\n 'xmlUrl': outline['xmlurl']\n }\n if 'type' in outline:\n outline_data['type'] = outline['type']\n url_parts = outline['xmlurl'].split('?')\n if len(url_parts) > 1:\n outline_data['xmlUrl'] = '?'.join([url_parts[0], urllib.quote(url_parts[1])])\n output_fd.write('\\t\\t\\n' % outline_data)\n output_fd.write('\\t\\n')\n output_fd.write('\\n')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"577550098","text":"#!/usr/bin/env python3\n\n# Simple Ping script\n# By Stian Kristoffersen\n\nimport subprocess\nimport ipaddress\nfrom subprocess import Popen, PIPE\n\n\n# Ping function\ndef ping_network(network):\n\n for ip in network.hosts():\n ip = str(ip)\n toping = Popen(['ping', '-c', '3', ip], stdout=PIPE)\n output = toping.communicate()[0]\n hostalive = toping.returncode\n if hostalive == 0:\n print(ip, 'is reachable')\n else:\n print(ip, 'is unreachable')\n\n\n# Main function\ndef main():\n network = ipaddress.ip_network('192.168.1.0/24')\n ping_network(network)\n\n\nif __name__ == '__main__': main()\n","sub_path":"ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"141115581","text":"import urllib.request\r\nfrom urllib.error import URLError, HTTPError, ContentTooShortError\r\n\r\n\r\nclass pproxy:\r\n def __init__(self, url, user_agent, num_retriew=2):\r\n self.url = url\r\n self.use_agent = user_agent\r\n self.num_retriew = num_retriew\r\n\r\n def run(self):\r\n print(self.url)\r\n request = urllib.request.Request(self.url)\r\n request.add_header('user-agent', self.use_agent)\r\n try:\r\n html = urllib.request.urlopen(request).read()\r\n except(URLError, HTTPError, ContentTooShortError) as e:\r\n print(e.reason)\r\n html = None\r\n if self.num_retriew > 0:\r\n if hasattr(e, 'code') and 500 <= e.code < 600:\r\n return self.run(self.num_retriew - 1)\r\n return html\r\n\r\n\r\nif __name__ == '__main__':\r\n user_agent = \"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Mobile Safari/537.36\"\r\n pr = pproxy(\"http://example.python-scraping.com/sitemap.xml\",user_agent)\r\n pr.run()\r\n","sub_path":"05spider/urllib/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"137882202","text":"# -*-coding:utf-8-*-\r\n\r\nfrom global_utils import es_xnr_2 as es_xnr,fb_xnr_retweet_timing_list_index_name,fb_xnr_retweet_timing_list_index_type\r\n\r\ndef retweet_timing_list_mappings():\r\n\tindex_info = {\r\n\t\t'settings':{\r\n\t\t\t'number_of_replicas':0,\r\n\t\t\t'number_of_shards':5\r\n\t\t},\r\n\t\t'mappings':{\r\n\t\t\tfb_xnr_retweet_timing_list_index_type:{\r\n\t\t\t\t'properties':{\r\n\t\t\t\t\t'xnr_user_no':{\r\n\t\t\t\t\t\t'type':'string',\r\n\t\t\t\t\t\t'index':'not_analyzed'\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'mid':{\r\n\t\t\t\t\t\t'type':'string',\r\n\t\t\t\t\t\t'index':'not_analyzed'\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'uid':{\r\n\t\t\t\t\t\t'type':'string',\r\n\t\t\t\t\t\t'index':'not_analyzed'\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'nick_name':{\r\n\t\t\t\t\t\t'type':'string',\r\n\t\t\t\t\t\t'index':'not_analyzed'\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'photo_url':{\r\n\t\t\t\t\t\t'type':'string',\r\n\t\t\t\t\t\t'index':'no'\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'timestamp':{ # 该微博发布时间\r\n\t\t\t\t\t\t'type':'long'\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'timestamp_set':{ # 计划发送时间\r\n\t\t\t\t\t\t'type':'long'\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'timestamp_post':{ # 实际发送时间\r\n\t\t\t\t\t\t'type':'long'\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'compute_status':{ # 发送状态 0- 未发送 1- 已发送\r\n\t\t\t\t\t\t'type':'long'\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif not es_xnr.indices.exists(index=fb_xnr_retweet_timing_list_index_name):\r\n\r\n\t\tes_xnr.indices.create(index=fb_xnr_retweet_timing_list_index_name,body=index_info,ignore=400)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n\tretweet_timing_list_mappings()\r\n","sub_path":"xnr_0429/xnr/fb_xnr_retweet_timing_list_mappings.py","file_name":"fb_xnr_retweet_timing_list_mappings.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"390667005","text":"import numpy as np\nimport math\n\ndef RMSE(y_test, y_pred):\n sum = 0\n N = len(y_pred)\n for i in range(N):\n sum += float(y_test[i] - y_pred[i])**2\n return math.sqrt(sum / N) \n \ndef R2(y_test, y_pred):\n sum1 = 0\n sum2 = 0\n avg = np.mean(y_test)\n for i in range(len(y_test)):\n sum1 += (float(y_pred[i]) - float(y_test[i]))**2\n sum2 += (float(y_test[i]) - float(avg))**2\n return 1 - sum1 / sum2\n ","sub_path":"HomeTask/HomeTask/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"427010262","text":"from django.shortcuts import render, redirect\nfrom .models import Personnel\nfrom .models import Poste\n\nfrom .forms import PersonnelForm\nfrom .forms import PosteForm\n# Create your views here.\n\ndef index(request):\n personnels = Personnel.objects.all()\n return render(request, 'personnels/index.html', {'personnels': personnels})\n\ndef personnel_form(request, id=0):\n if request.method == \"GET\":\n if id==0:\n form = PersonnelForm()\n else:\n personnel = Personnel.objects.get(pk=id)\n form = PersonnelForm(instance=personnel)\n\n return render(request, 'personnels/personnel-form.html', {'form' : form})\n else:\n if id==0:\n form = PersonnelForm(request.POST)\n else:\n personnel = Personnel.objects.get(pk=id)\n form = PersonnelForm(request.POST, instance=personnel)\n if form.is_valid():\n form.save()\n return redirect('personnels:index')\n\n\ndef personnel_delete(request, id):\n personnel= Personnel.objects.get(pk=id)\n personnel.delete()\n return redirect('personnels:index')\n\ndef posteIndex(request):\n postes = Poste.objects.all()\n return render(request, 'postes/index.html', {'postes': postes})\n\n\n\ndef poste_form(request, id=0):\n if request.method == \"GET\":\n if id==0:\n form = PosteForm()\n else:\n poste = Poste.objects.get(pk=id)\n form = PosteForm(instance=poste)\n\n return render(request, 'postes/poste-form.html', {'form' : form})\n else:\n if id==0:\n form = PosteForm(request.POST)\n else:\n poste = Poste.objects.get(pk=id)\n form = PosteForm(request.POST, instance=poste)\n if form.is_valid():\n form.save()\n return redirect('personnels:poste.index')\n\n\ndef poste_delete(request, id):\n poste= Poste.objects.get(pk=id)\n poste.delete()\n return redirect('personnels:poste.index')\n","sub_path":"personnels/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"37429655","text":"\"\"\"\nRiya loves to play with strings. She discoverd her own kind of strings which passed the Riya's Test. When split from the middle, the string gives two halves having the same characters and same frequency of each character. If the number of characters in the string are odd, ignore the middle character and check for the 2 halves to pass the Riya's Test. For example, papa passes the Riya's Test, since the two halves pa and pa have the same characters with the same frequency.\neefefe and bananb pass Riya's Test. Note that motor, abcd, color, flipflop fails Riya's Test. Given a string, find out whether the string passes Riya's Test or not.\n\n\nInput: the First line of input contains a single integer T, i.e number of test cases.Each test case contains a string A \" containing lowercase English alphabet\".\n\n\nOutput: For each test case, Print \"YES\" if string Pass in Riya test else \"NO\".\n\n\nConstraints:\n\n1 ≤ T ≤ 100\n2 ≤ Length of string A ≤ 1000\n\nExample:\nInput:\n6\nlala\ncolor\nmotor\npqrpqr\nabbaab\nabdbc\n\n\nOutput:\nYES\nNO\nNO\nYES\nNO\nNO\n\n\n\nExplanation :\n Test Case 1: string lala passes Riya's Test, as the strings gives two halves having the same characters and same frequency of each character.\n\"\"\"\n\n\ndef riyas_test(str):\n l = len(str)\n if l % 2 == 0:\n first, second = str[:int(l / 2)], str[int(l / 2):]\n else:\n first, second = str[:int(l / 2)], str[int(l / 2) + 1:]\n if sorted(first) == sorted(second):\n return \"YES\"\n else:\n return \"NO\"\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n str = input()\n print(riyas_test(str))\n","sub_path":"practice/Basic/riyas_test.py","file_name":"riyas_test.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"510819687","text":"#双联词学习\nimport importlib,sys\nimportlib.reload(sys)\n\nimport nltk\n\n# 举例解释双联词\nsent = \"to be or not to be\"\ntokens = nltk.word_tokenize(sent)\nbigrm = nltk.bigrams(tokens)\nprint(*map(' '.join, bigrm), sep=', ')\n\ndef generate_model(cfdist, word, num=10):\n for i in range(num):\n print(word),\n word = cfdist[word].max()\n\n# 加载语料库\ntext = nltk.corpus.genesis.words('english-kjv.txt')\n\n# 生成双连词\nbigrams = nltk.bigrams(text)\n\n# 生成条件频率分布\ncfd = nltk.ConditionalFreqDist(bigrams)\n\n# 以we开头,生成双联词概率分布图\nfd = cfd[\"we\"]\nfd.plot(10)\n\n# 以we开头,生成随机串\ngenerate_model(cfd, 'we')","sub_path":"练习/bigrams_le.py","file_name":"bigrams_le.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"596420700","text":"from chronon import Process\nfrom chronon import ProcessManager\nfrom chronon import EventManager\nfrom datetime import datetime, timedelta\nimport pandas as pd\n\n\ndef test_wait_for_time():\n pm = ProcessManager()\n df = pd.DataFrame({'integer_test': [1], 'float_test': [1.1]})\n\n class TestProcess(Process):\n def definition(self, user):\n yield user.waits(1)\n yield user.waits(1.1)\n yield user.waits(df['integer_test'].values[0])\n yield user.waits(df['float_test'].values[0])\n yield user.waits(datetime(2021, 1, 1))\n yield user.waits(timedelta(minutes=1))\n user.set_checkpoint('Finished')\n\n pm.attach_process(TestProcess)\n em = EventManager(pm)\n em.create_user('user_test')\n em.run()\n assert em.checkpoints['instant'][0] == 1609459264.2\n","sub_path":"tests/core/test_user.py","file_name":"test_user.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"105281681","text":"from functools import reduce\nfrom operator import mul\nfrom pathlib import Path\n\n\ndef get_puzzle_input(test_case=0):\n file_path = \"input.txt\" if test_case == 0 else f\"test_input_{test_case}.txt\"\n with open(Path(__file__).parent.absolute() / file_path, \"r\") as f:\n [timestamp, bus_ids] = f.read().splitlines()\n bus_ids = bus_ids.split(\",\")\n return (int(timestamp), [x if x == \"x\" else int(x) for x in bus_ids])\n\n\ndef solution1(lines):\n (timestamp, bus_ids) = lines\n current_timestamp = timestamp\n f_bus_ids = [x for x in bus_ids if x != \"x\"]\n while True:\n for bus_id in f_bus_ids:\n if current_timestamp % bus_id == 0:\n return bus_id * (current_timestamp - timestamp)\n current_timestamp += 1\n\n\ndef chinese_remainder_theorem(mods, rems):\n n = reduce(mul, mods)\n binixis_sum = 0\n for i in range(len(mods)):\n ni = n // mods[i]\n xi = pow(ni, -1, mods[i])\n binixis_sum += xi * rems[i] * ni\n return binixis_sum % n\n\n\ndef solution2(lines):\n mods_and_rems = [(x, -i) for i, x in enumerate(lines[1]) if x != \"x\"]\n mods, rems = zip(*mods_and_rems)\n return chinese_remainder_theorem(mods, rems)\n\n\nif __name__ == \"__main__\":\n from sys import argv\n\n puzzle_input = get_puzzle_input(\n argv[argv.index(\"--test\") + 1] if \"--test\" in argv[1:] else 0\n )\n print(solution1(puzzle_input))\n print(solution2(puzzle_input))\n","sub_path":"2020/day13/day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"201104603","text":"from django.shortcuts import render\nfrom .forms import SubscriberForm, PostsForm, EmailSentForm\nfrom .models import Subscribers, Posts, EmailSent\nfrom datetime import datetime\nfrom pytz import timezone\nfrom django.core.mail import EmailMessage\nfrom decouple import config\ndef my_scheduled_job():\n import facebook\n graph = facebook.GraphAPI(config('FACEBOOK_USER_TOKEN'))\n post = graph.get_object(id=config('GNDEC_PAGE_ID'), fields='feed')\n post_id = post['feed']['data'][0]['id']\n post_date_time = post['feed']['data'][0]['created_time'][:-5]\n #facebook provie post time in UTC so we have to convert it into IST\n date_str = post_date_time\n datetime_obj_naive = datetime.strptime(date_str, \"%Y-%m-%dT%H:%M:%S\")\n datetime_obj_pacific = timezone('UTC').localize(datetime_obj_naive)\n datetime_obj_pacific = datetime_obj_pacific.astimezone(timezone('Asia/Kolkata'))\n #date of post\n post_date = datetime_obj_pacific.strftime(\"%Y-%m-%d\")\n #time of post\n post_time = datetime_obj_pacific.strftime(\"%H:%M:%S(%Z)\")\n #facebook post data\n message = post['feed']['data'][0]['message']\n\n #last post id to whom email was sent\n last_email_post = EmailSent.objects.last()\n last_email_post = last_email_post.post_id\n\n\n #subscriber\n subscribers = Subscribers.objects.all().values_list('email')\n last_entry = Posts.objects.last()\n if not last_entry.post_id == post_id:\n Posts.objects.create(created_time = post_time, created_date = post_date, post_id = post_id, message = message)\n\n if not last_email_post == post_id:\n for users in subscribers:\n\t #for emailid in users:\n toemail = users[0]\n subject = 'New post @TNP GNDEC '+post_date+' '+post_time\n msg_body = '*You are getting multiple emails because it is beta version of our app. Just bear with us.*\\n'+' '+message+'\\n \\n' '*Team*''\\n \\n''*Jugadi Time*\\n(https://jugaditi.me)'\n email = EmailMessage(subject, msg_body, to=[toemail])\n email.send()\n EmailSent.objects.create(post_id = post_id)\n\n else:\n if not last_email_post == post_id:\n for users in subscribers:\n\t #for emailid in users:\n toemail = users[0]\n subject = 'New post @TNP GNDEC '+post_date+' '+post_time\n msg_body = '*You are getting multiple emails because it is beta version of our app. Just bear with us.*\\n'+' '+message+'\\n \\n' '*Team*''\\n \\n''*Jugadi Time*(https://jugaditi.me)'\n email = EmailMessage(subject, msg_body, to=[toemail])\n email.send()\n EmailSent.objects.create(post_id = post_id)\n","sub_path":"subscribers/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"451608063","text":"import uuid\nfrom datetime import date\nfrom decimal import Decimal\nfrom unittest.mock import patch\n\nimport pytest\nimport requests_mock\nfrom django.test import TestCase\n\nfrom api.common import cache_storage\nfrom api.common.models import RoomRate\nfrom api.hotel import converter\nfrom api.hotel.adapters import hotel_service\nfrom api.hotel.adapters.hotelbeds.transport import HotelBedsTransport\nfrom api.hotel.adapters.stub.stub import StubHotelAdapter\nfrom api.hotel.converter.google import GoogleHotelSearchRequest\nfrom api.hotel.converter.google_models import RoomParty\nfrom api.hotel.hotel_model import HotelSpecificSearch, RoomOccupancy, HotelLocationSearch\nfrom api.tests import test_objects\nfrom api.tests.utils import load_test_resource\nfrom api.view.exceptions import AvailabilityException\n\n\nclass TestHotelService(TestCase):\n def test_search_by_hotel_id(self):\n search_request = HotelSpecificSearch(\n hotel_id=\"A1H2J6\",\n start_date=date(2020, 1, 20),\n end_date=date(2020, 1, 27),\n occupancy=RoomOccupancy(2, 1),\n crs=\"stub\",\n )\n\n hotel = hotel_service.search_by_id(search_request)\n self.assertIsNotNone(hotel)\n\n def test_search_by_location(self):\n search_request = HotelLocationSearch(\n location_name=\"SFO\",\n start_date=date(2020, 1, 20),\n end_date=date(2020, 1, 27),\n occupancy=RoomOccupancy(2, 1),\n crs=\"stub\",\n )\n\n hotel = hotel_service.search_by_location(search_request)\n self.assertIsNotNone(hotel)\n self.assertEqual(\"2020-01-20\", str(hotel[0].start_date))\n self.assertEqual(\"2020-01-27\", str(hotel[0].end_date))\n self.assertTrue(len(hotel[0].hotel_details.amenities) >= 3)\n\n def test_min_nightly_rates_included_in_response(self):\n search_request = HotelLocationSearch(\n location_name=\"SFO\",\n start_date=date(2020, 1, 20),\n end_date=date(2020, 1, 22),\n occupancy=RoomOccupancy(2, 1),\n crs=\"stub\",\n )\n\n room_rate = test_objects.room_rate(rate_key=\"foo\", total=\"100\", base_rate=\"80\", tax_rate=\"20\")\n room_type = test_objects.room_type(rates=[room_rate])\n\n hotel = test_objects.hotel()\n hotel.start_date = date(2020, 1, 1)\n hotel.end_date = date(2020, 1, 3) # Two room nights\n hotel.room_types = [room_type]\n\n stub_adapter = StubHotelAdapter()\n stub_adapter.search_by_location = lambda x: [hotel]\n\n with patch(\"api.hotel.adapters.adapter_service.get_adapters\") as mock_adapter_service:\n mock_adapter_service.return_value = [stub_adapter]\n hotels = hotel_service.search_by_location(search_request)\n\n # Two Room Nights, So average nightly rate is 0.5 Total\n # Average is applied after default markup of 18%\n self.assertEqual(Decimal(\"59.00\"), hotels[0].average_nightly_rate)\n self.assertEqual(Decimal(\"47.20\"), hotels[0].average_nightly_base)\n self.assertEqual(Decimal(\"11.80\"), hotels[0].average_nightly_tax)\n\n def test_search_by_hotel_id_google(self):\n search_request = HotelSpecificSearch(\n hotel_id=\"A1H2J6\",\n start_date=date(2020, 1, 20),\n end_date=date(2020, 1, 27),\n occupancy=RoomOccupancy(2, 1),\n crs=\"stub\",\n )\n\n google_search_request = GoogleHotelSearchRequest(\n api_version=1,\n transaction_id=str(uuid.uuid4()),\n hotel_id=search_request.hotel_id,\n start_date=search_request.start_date,\n end_date=search_request.end_date,\n party=RoomParty(adults=search_request.occupancy.adults, children=[]),\n )\n\n hotel = hotel_service.search_by_id(search_request)\n google_hotel = converter.google.convert_hotel_response(google_search_request, hotel)\n\n self.assertIsNotNone(google_hotel)\n\n def test_markups_applied_and_stored_in_cache(self):\n search_request = HotelLocationSearch(\n location_name=\"SFO\",\n start_date=date(2020, 1, 20),\n end_date=date(2020, 1, 27),\n occupancy=RoomOccupancy(2, 1),\n crs=\"stub\",\n )\n\n hotels = hotel_service.search_by_location(search_request)\n\n room_rates = [x for hotel in hotels for room_type in hotel.room_types for x in room_type.rates]\n assert len(room_rates) > 10\n\n for room_rate in room_rates:\n crs_rate: RoomRate = cache_storage.get(room_rate.rate_key)\n assert crs_rate is not None\n assert crs_rate.total.amount < room_rate.total.amount\n\n def test_error_in_api_response(self):\n error_response = load_test_resource(\"hotelbeds/error-response.json\")\n with requests_mock.Mocker() as mocker:\n mocker.post(HotelBedsTransport.get_hotels_url(), text=error_response)\n search_request = HotelLocationSearch(\n location_name=\"SFO\",\n start_date=date(2020, 1, 20),\n end_date=date(2020, 1, 27),\n occupancy=RoomOccupancy(2, 1),\n crs=\"hotelbeds\",\n )\n\n with pytest.raises(AvailabilityException) as e:\n hotel_service.search_by_location(search_request)\n\n assert \"The check-in must be in the future\" in e.value.detail\n\n def test_calculate_min_nightly_tate(self):\n rate_one = test_objects.room_rate(rate_key=\"one\", total=\"200\", tax_rate=\"40\", base_rate=\"160\")\n rate_two = test_objects.room_rate(rate_key=\"two\", total=\"500\", tax_rate=\"350\", base_rate=\"85\")\n rate_three = test_objects.room_rate(rate_key=\"three\", total=\"100\", tax_rate=\"15\", base_rate=\"85\")\n rate_four = test_objects.room_rate(rate_key=\"four\", total=\"120\", tax_rate=\"25\", base_rate=\"95\")\n\n room_type_one = test_objects.room_type(rates=[rate_one, rate_two])\n room_type_two = test_objects.room_type(rates=[rate_three, rate_four])\n\n hotel = test_objects.hotel()\n hotel.start_date = date(2020, 1, 1)\n hotel.end_date = date(2020, 1, 2)\n hotel.room_types = [room_type_one, room_type_two]\n\n # Room Nights = 1\n min_nightly_base, min_nightly_tax, min_nightly_total = hotel_service._calculate_min_nightly_rates(hotel)\n assert min_nightly_base == 85\n assert min_nightly_tax == 15\n assert min_nightly_total == 100\n\n # Room Nights = 2\n hotel.end_date = date(2020, 1, 3)\n min_nightly_base, min_nightly_tax, min_nightly_total = hotel_service._calculate_min_nightly_rates(hotel)\n assert min_nightly_base == 42.5\n assert min_nightly_tax == 7.50\n assert min_nightly_total == 50\n\n # Same Date, Room Nights = 1\n hotel.end_date = date(2020, 1, 1)\n min_nightly_base, min_nightly_tax, min_nightly_total = hotel_service._calculate_min_nightly_rates(hotel)\n assert min_nightly_base == 85\n assert min_nightly_tax == 15\n assert min_nightly_total == 100\n","sub_path":"api/tests/unit/test_hotel_service.py","file_name":"test_hotel_service.py","file_ext":"py","file_size_in_byte":7050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"310727065","text":"'''\n *\n * Copyright (C) 2020 Universitat Politècnica de Catalunya.\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'''\n\n# -*- coding: utf-8 -*-\n\n# Basic modules\nimport os\nimport json\nimport logging\nimport logging.config\nimport zlib\nimport time\n\n# 3rd party modules\nimport requests\n\n# Own modules\nfrom db_manager import Db, Connector\nfrom utils import download_file, hash_file, lsh_file, hash_string, utc_now\nfrom utils import extract_location, extract_components, extract_domain, clean_subdomain\n\nlogging.config.fileConfig('../logging.conf')\n\nlogger = logging.getLogger(\"DATA_MANAGER\")\n\n\ndef insert_url(db, request, insert_ts, update_ts):\n \"\"\" Inserts the URL data into the database and returns the URL Connector. \"\"\"\n\n # If the url is not present, the data is embedded into the url, or the resource was blocked, skip it\n if \"url\" not in request.keys() or request[\"url\"][:5] == \"data:\" or request[\"url\"][:6] == \"chrome\":\n return None\n url = Connector(db, \"url\")\n resource_type = Connector(db, \"type\")\n if not resource_type.load(hash_string(request[\"type\"])):\n resource_type.values[\"name\"] = request[\"type\"]\n if not resource_type.save():\n resource_type.load(hash_string(request[\"type\"]))\n components = extract_components(request[\"url\"])\n root_url = components['netloc'] + components['path']\n if not url.load(hash_string(root_url)):\n for key in request.keys():\n if key == 'requests':\n continue\n url.values[key] = request[key]\n url.values[\"type\"] = resource_type.values[\"id\"]\n url.values[\"headers\"] = str(request[\"headers\"])\n url.values[\"scheme\"] = components[\"scheme\"]\n url.values[\"netloc\"] = components[\"netloc\"]\n url.values[\"path\"] = components[\"path\"]\n url.values[\"hostname\"] = components[\"hostname\"]\n url.values[\"port\"] = components[\"port\"]\n url.values[\"params\"] = components[\"params\"]\n url.values[\"query\"] = components[\"query\"]\n url.values[\"fragment\"] = components[\"fragment\"]\n url.values[\"username\"] = components[\"username\"]\n url.values[\"password\"] = components[\"password\"]\n url.values[\"insert_date\"] = insert_ts\n url.values[\"update_timestamp\"] = update_ts\n third_party = Connector(db, \"domain\")\n main_domain = clean_subdomain(components[\"netloc\"].lower())\n if not third_party.load(hash_string(main_domain)):\n third_party.values[\"name\"] = main_domain\n third_party.values[\"insert_date\"] = insert_ts\n third_party.values[\"update_timestamp\"] = update_ts\n if not third_party.save():\n third_party.load(hash_string(main_domain))\n url.values[\"domain\"] = third_party.values[\"id\"]\n if not url.save():\n url.load(hash_string(root_url))\n return url\n\n\ndef manage_request(db, process, domain, request, plugin, temp_folder):\n \"\"\" Inserts the URL data if non-existent and downloads/beautifies if needed \"\"\"\n\n t = utc_now()\n # Insert new URL info\n url = insert_url(db, request, t, t)\n if not url:\n return\n\n # Creates the relation between domain <-> url <-> plugin\n components = extract_components(request[\"url\"])\n root_url = components['netloc'] + components['path']\n url_type = Connector(db, \"type\")\n url_type.load(url.values[\"type\"])\n\n resource_id = None\n\n # Download resource in temp file if needed\n if url_type.values[\"download\"]:\n os.makedirs(os.path.join(os.path.abspath(\".\"), temp_folder), exist_ok=True)\n filename = os.path.join(temp_folder, domain.values[\"name\"] + '.tmp')\n if download_url(process, url.values[\"url\"], filename):\n hash_code = hash_file(filename)\n size = os.stat(filename).st_size\n\n # Compress the code\n with open(filename, 'rb') as f:\n code = f.read()\n compressed_code = zlib.compress(code)\n\n # Insert resource\n resource = Connector(db, \"resource\")\n if not resource.load(hash_code):\n resource.values[\"file\"] = compressed_code\n resource.values[\"size\"] = size\n resource.values[\"fuzzy_hash\"] = lsh_file(filename)\n resource.values[\"insert_date\"] = t\n resource.values[\"update_timestamp\"] = t\n if not resource.save():\n max = 30\n # Wait until the other thread saves the file inside the database (or 30s max)\n while not resource.load(hash_code) and max > 0:\n max -= 1\n time.sleep(1)\n resource_id = resource.values[\"id\"]\n db.call(\"ComputeResourceType\", values=[resource_id])\n db.call(\"ComputeResourcePopularityLevel\", values=[resource_id])\n\n # Remove temp file\n os.remove(filename)\n\n if not resource_id:\n logger.error(\"(proc. %s) Error #4: Resource not correctly saved\" % process)\n\n # Compute the url length (without the domain and path)\n query_length = 0\n if url.values[\"params\"] is not None:\n query_length += len(url.values[\"params\"])\n if url.values[\"query\"] is not None:\n query_length += len(url.values[\"query\"])\n if url.values[\"fragment\"] is not None:\n query_length += len(url.values[\"fragment\"])\n if url.values[\"username\"] is not None:\n query_length += len(url.values[\"username\"])\n if url.values[\"password\"] is not None:\n query_length += len(url.values[\"password\"])\n\n domain.add_double(url, plugin, {\"resource_id\": resource_id, \"query_length\": query_length,\n \"insert_date\": t, \"update_timestamp\": t})\n\n if not resource_id:\n query = \"INSERT INTO log (domain_id, plugin_id, url) VALUES (%s, %s, %s)\"\n db.custom(query=query, values=[domain.values[\"id\"], plugin.values[\"id\"], request[\"url\"]])\n else:\n query = \"INSERT INTO log (domain_id, plugin_id, url, resource_id) VALUES (%s, %s, %s, %s)\"\n db.custom(query=query, values=[domain.values[\"id\"], plugin.values[\"id\"], request[\"url\"], resource_id])\n\n # Add subdomain or third party\n# subdomain = components[\"netloc\"].lower()\n# main_domain = clean_subdomain(subdomain)\n# if main_domain == domain.values[\"name\"]:\n# subdomain = subdomain.partition(\".\")[0]\n# sub = Connector(db, \"subdomain\")\n# if not sub.load(hash_string(subdomain)):\n# sub.values[\"name\"] = subdomain\n# if not sub.save():\n# sub.load(hash_string(subdomain))\n# t = utc_now()\n# domain.add(sub, {\"insert_date\": t, \"update_timestamp\": t})\n# else:\n# third_party = Connector(db, \"third_party\")\n# if not third_party.load(hash_string(main_domain)):\n# third_party.values[\"name\"] = main_domain\n# if not third_party.save():\n# third_party.load(hash_string(main_domain))\n# t = utc_now()\n# domain.add(third_party, {\"insert_date\": t, \"update_timestamp\": t})\n\n\ndef download_url(process, url, filename):\n \"\"\" Downloads the given url into the given filename. \"\"\"\n\n with open(filename, 'wb') as f:\n try:\n f, headers = download_file(url=url, destination=f)\n except requests.exceptions.SSLError:\n try:\n requests.packages.urllib3.disable_warnings()\n f, headers = download_file(url=url, destination=f, verify=False)\n except Exception as e:\n logger.error(\"(proc. %s) Error #1: %s\" % (process, str(e)))\n return False\n except UnicodeError as e:\n logger.error(\"(proc. %s) Error #2: Couldn't download url %s with error %s\" % (process, url, str(e)))\n return False\n except Exception as e:\n logger.error(\"(proc. %s) Error #3: %s\" % (process, str(e)))\n return False\n logger.debug(\"(proc. %s) Found external resource %s\" % (process, url))\n return True\n\n\ndef get_network(log_entries):\n \"\"\" Reads the performance log entries and computes a network traffic dictionary based on the actual requests. \"\"\"\n\n network_traffic = {}\n for log_entry in log_entries:\n message = json.loads(log_entry[\"message\"])\n method = message[\"message\"][\"method\"]\n params = message[\"message\"][\"params\"]\n if method not in [\"Network.requestWillBeSent\", \"Network.responseReceived\", \"Network.loadingFinished\"]:\n continue\n if method != \"Network.loadingFinished\":\n request_id = params[\"requestId\"]\n loader_id = params[\"loaderId\"]\n if loader_id not in network_traffic:\n network_traffic[loader_id] = {\"requests\": {}, \"encoded_data_length\": 0}\n if request_id == loader_id:\n if \"redirectResponse\" in params:\n network_traffic[loader_id][\"encoded_data_length\"] += params[\"redirectResponse\"][\"encodedDataLength\"]\n if method == \"Network.responseReceived\":\n network_traffic[loader_id][\"type\"] = params[\"type\"]\n network_traffic[loader_id][\"url\"] = params[\"response\"][\"url\"]\n network_traffic[loader_id][\"remote_IP_address\"] = None\n if \"remoteIPAddress\" in params[\"response\"].keys():\n network_traffic[loader_id][\"remote_IP_address\"] = params[\"response\"][\"remoteIPAddress\"]\n network_traffic[loader_id][\"encoded_data_length\"] += params[\"response\"][\"encodedDataLength\"]\n network_traffic[loader_id][\"headers\"] = params[\"response\"][\"headers\"]\n network_traffic[loader_id][\"status\"] = params[\"response\"][\"status\"]\n network_traffic[loader_id][\"security_state\"] = params[\"response\"][\"securityState\"]\n network_traffic[loader_id][\"mime_type\"] = params[\"response\"][\"mimeType\"]\n if \"via\" in params[\"response\"][\"headers\"]:\n network_traffic[loader_id][\"cached\"] = True\n else:\n if request_id not in network_traffic[loader_id][\"requests\"]:\n network_traffic[loader_id][\"requests\"][request_id] = {\"encoded_data_length\": 0}\n if \"redirectResponse\" in params:\n network_traffic[loader_id][\"requests\"][request_id][\"encoded_data_length\"] += params[\"redirectResponse\"][\"encodedDataLength\"]\n if method == \"Network.responseReceived\":\n network_traffic[loader_id][\"requests\"][request_id][\"type\"] = params[\"type\"]\n network_traffic[loader_id][\"requests\"][request_id][\"url\"] = params[\"response\"][\"url\"]\n network_traffic[loader_id][\"requests\"][request_id][\"remote_IP_address\"] = None\n if \"remoteIPAddress\" in params[\"response\"].keys():\n network_traffic[loader_id][\"requests\"][request_id][\"remote_IP_address\"] = params[\"response\"][\"remoteIPAddress\"]\n network_traffic[loader_id][\"requests\"][request_id][\"encoded_data_length\"] += params[\"response\"][\"encodedDataLength\"]\n network_traffic[loader_id][\"requests\"][request_id][\"headers\"] = params[\"response\"][\"headers\"]\n network_traffic[loader_id][\"requests\"][request_id][\"status\"] = params[\"response\"][\"status\"]\n network_traffic[loader_id][\"requests\"][request_id][\"security_state\"] = params[\"response\"][\"securityState\"]\n network_traffic[loader_id][\"requests\"][request_id][\"mime_type\"] = params[\"response\"][\"mimeType\"]\n if \"via\" in params[\"response\"][\"headers\"]:\n network_traffic[loader_id][\"requests\"][request_id][\"cached\"] = 1\n else:\n request_id = params[\"requestId\"]\n encoded_data_length = params[\"encodedDataLength\"]\n for loader_id in network_traffic:\n if request_id == loader_id:\n network_traffic[loader_id][\"encoded_data_length\"] += encoded_data_length\n elif request_id in network_traffic[loader_id][\"requests\"]:\n network_traffic[loader_id][\"requests\"][request_id][\"encoded_data_length\"] += encoded_data_length\n return network_traffic\n\n","sub_path":"code/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":12840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"603199860","text":"import os\nfrom concurrent import futures\nfrom itertools import product\n\nimport numpy as np\nimport imageio\nfrom .volume_classes import _normalize_index\n\n\nclass KnossosDataset(object):\n block_size = 128\n\n @staticmethod\n def _chunks_dim(dim_root):\n files = os.listdir(dim_root)\n files = [f for f in files if os.path.isdir(os.path.join(dim_root, f))]\n return len(files)\n\n def get_shape_and_grid(self):\n cx = self._chunks_dim(self.path)\n y_root = os.path.join(self.path, 'x0000')\n cy = self._chunks_dim(y_root)\n z_root = os.path.join(y_root, 'y0000')\n cz = self._chunks_dim(z_root)\n\n grid = (cz, cy, cx)\n shape = tuple(sh * self.block_size for sh in grid)\n return shape, grid\n\n def __init__(self, path, file_prefix, load_png):\n self.path = path\n self.ext = 'png' if load_png else 'jpg'\n self.file_prefix = file_prefix\n\n self._ndim = 3\n self._chunks = self._ndim * (self.block_size,)\n self._shape, self._grid = self.get_shape_and_grid()\n self.n_threads = 1\n\n @property\n def dtype(self):\n return 'uint8'\n\n @property\n def ndim(self):\n return self._ndim\n\n @property\n def chunks(self):\n return self._chunks\n\n @property\n def shape(self):\n return self._shape\n\n def load_block(self, grid_id):\n # NOTE need to reverse grid id, because knossos folders are stored in x, y, z order\n block_path = ['%s%04i' % (dim, gid) for dim, gid in zip(('x', 'y', 'z'),\n grid_id[::-1])]\n dim_str = '_'.join(block_path)\n fname = '%s_%s.%s' % (self.file_prefix, dim_str, self.ext)\n block_path.append(fname)\n path = os.path.join(self.path, *block_path)\n data = np.array(imageio.imread(path)).reshape(self._chunks)\n return data\n\n def coords_in_roi(self, grid_id, roi):\n # block begins and ends\n block_begin = [gid * self.block_size for gid in grid_id]\n block_end = [beg + ch for beg, ch in zip(block_begin, self.chunks)]\n\n # get roi begins and ends\n roi_begin = [rr.start for rr in roi]\n roi_end = [rr.stop for rr in roi]\n\n tile_bb, out_bb = [], []\n # iterate over dimensions and find the bb coordinates\n for dim in range(3):\n # calculate the difference between the block begin / end\n # and the roi begin / end\n off_diff = block_begin[dim] - roi_begin[dim]\n end_diff = roi_end[dim] - block_end[dim]\n\n # if the offset difference is negative, we are at a starting block\n # that is not completely overlapping\n # -> set all values accordingly\n if off_diff < 0:\n begin_in_roi = 0 # start block -> no local offset\n begin_in_block = -off_diff\n # if this block is the beginning block as well as the end block,\n # we need to adjust the local shape accordingly\n shape_in_roi = block_end[dim] - roi_begin[dim]\\\n if block_end[dim] <= roi_end[dim] else roi_end[dim] - roi_begin[dim]\n\n # if the end difference is negative, we are at a last block\n # that is not completely overlapping\n # -> set all values accordingly\n elif end_diff < 0:\n begin_in_roi = block_begin[dim] - roi_begin[dim]\n begin_in_block = 0\n shape_in_roi = roi_end[dim] - block_begin[dim]\n\n # otherwise we are at a completely overlapping block\n else:\n begin_in_roi = block_begin[dim] - roi_begin[dim]\n begin_in_block = 0\n shape_in_roi = self.chunks[dim]\n\n # append to bbs\n tile_bb.append(slice(begin_in_block, begin_in_block + shape_in_roi))\n out_bb.append(slice(begin_in_roi, begin_in_roi + shape_in_roi))\n\n return tuple(tile_bb), tuple(out_bb)\n\n def _load_roi(self, roi):\n # snap roi to grid\n ranges = [range(rr.start // self.block_size,\n rr.stop // self.block_size if\n rr.stop % self.block_size == 0 else rr.stop // self.block_size + 1)\n for rr in roi]\n grid_points = product(*ranges)\n\n # init data (dtype is hard-coded to uint8)\n roi_shape = tuple(rr.stop - rr.start for rr in roi)\n data = np.zeros(roi_shape, dtype='uint8')\n\n def load_tile(grid_id):\n tile_data = self.load_block(grid_id)\n tile_bb, out_bb = self.coords_in_roi(grid_id, roi)\n data[out_bb] = tile_data[tile_bb]\n\n if self.n_threads > 1:\n with futures.ThreadPoolExecutor(self.n_threads) as tp:\n tasks = [tp.submit(load_tile, sp) for sp in grid_points]\n [t.result() for t in tasks]\n else:\n [load_tile(sp) for sp in grid_points]\n #\n return data\n\n def __getitem__(self, index):\n return self._load_roi(_normalize_index(index, self.shape))\n\n\nclass KnossosFile(object):\n \"\"\" Wrapper for knossos file structure\n \"\"\"\n # NOTE: the file mode is a dummy parameter to be consistent with other file impls\n def __init__(self, path, mode='r', load_png=True):\n if not os.path.exists(os.path.join(path, 'mag1')):\n raise RuntimeError(\"Not a knossos file structure\")\n self.path = path\n self.load_png = load_png\n self.file_name = os.path.split(self.path)[1]\n\n def __getitem__(self, key):\n ds_path = os.path.join(self.path, key)\n if not os.path.exists(ds_path):\n raise ValueError(\"Invalid key %s\" % key)\n file_prefix = '%s_%s' % (self.file_name, key)\n return KnossosDataset(ds_path, file_prefix, self.load_png)\n","sub_path":"cluster_tools/utils/knossos_wrapper.py","file_name":"knossos_wrapper.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"218226375","text":"#!/usr/bin/env python\nimport os\nimport re\nimport sys\n\nclass SMSong(object):\n path = None\n\n title = None\n subtitle = None\n artist = None\n genre = None\n origin = None\n credit = None\n songfile = None\n bpms = None\n version = None\n\n def __init__(self, songfile_path=None):\n super(SMSong, self).__init__()\n if (songfile_path != None):\n self.path = songfile_path\n self.parse_songfile(songfile_path)\n\n def __str__(self):\n return \"<{} {} title={}, artist={}>\".format(\n self.__class__.__name__,\n hex(id(self)),\n self.title,\n self.artist\n )\n\n @classmethod\n def csv_header(self, delim=','):\n return delim.join([\n \"title\",\n \"subtitle\",\n \"artist\",\n \"genre\",\n \"songfile\"\n ])\n\n def parse_songfile(self, path):\n field_re = re.compile(r\"#(?P.+):(?P.*);\")\n songfile = open(path, \"r\")\n charbuf = \"\"\n\n while True:\n char = songfile.read(1)\n if (not char):\n break\n\n if (char not in ['\\r', '\\n']):\n charbuf += char\n\n if (char == ';'):\n match = field_re.search(charbuf)\n if (match):\n prop = match.group(\"property\")\n value = match.group(\"value\")\n self._store_property(prop, value)\n\n charbuf = \"\"\n\n songfile.close()\n return True\n\n def csv(self, delim=','):\n values = [\n self.title,\n self.subtitle,\n self.artist,\n self.genre,\n self.songfile\n ]\n return delim.join([v if v else \"\" for v in values])\n\n def _store_property(self, prop, value):\n prop_to_attr = {\n \"TITLE\" : \"title\",\n \"SUBTITLE\" : \"subtitle\",\n \"ARTIST\" : \"artist\",\n \"GENRE\" : \"genre\",\n \"ORIGIN\" : \"origin\",\n \"CREDIT\" : \"credit\",\n \"MUSIC\" : \"songfile\",\n \"BPMS\" : \"bpms\",\n \"VERSION\" : \"version\"\n }\n prop_key = prop.upper()\n if (prop_key in prop_to_attr):\n attr = prop_to_attr[prop_key]\n if (attr == \"version\"):\n value = float(value)\n elif (attr == \"songfile\"):\n value = os.path.join(self.path, value)\n elif (attr == \"bpms\"):\n bpms = []\n bpm_pairs = value.split(\",\")\n for bpm_pair in bpm_pairs:\n bpm_strs = bpm_pair.split(\"=\")\n bpms += [float(bpm_str) for bpm_str in bpm_strs]\n\n value = bpms\n\n setattr(self, attr, value)\n\n return True\n\ndef generate_csv(songs):\n csvstr = SMSong.csv_header() + '\\n'\n for song in songs:\n csvstr += song.csv() + '\\n'\n return csvstr\n\ndef main(argv):\n if (len(argv) > 1):\n path = argv[1]\n\n songs = []\n songfile_exts = [\".sm\", \".ssc\", \".dwi\"]\n parsed_songfiles = []\n for root, subdirs, files in os.walk(path):\n songfiles = [f for f in files if os.path.splitext(f)[1] in songfile_exts]\n for songfile in songfiles:\n songfile_name = os.path.splitext(songfile)[0]\n if (songfile_name not in parsed_songfiles):\n songfile_path = os.path.join(root, songfile)\n song = SMSong(songfile_path)\n songs.append(song)\n parsed_songfiles.append(songfile_name)\n\n csv = generate_csv(songs)\n print >> sys.stdout, csv\n else:\n print(\"Usage: {} \".format(os.path.basename(argv[0])))\n\nif (__name__ == \"__main__\"):\n sys.exit(main(sys.argv))\n","sub_path":"smsongpackinfo.py","file_name":"smsongpackinfo.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"171906255","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Aug 21 17:42:22 2020\r\n\r\n@author: lizet\r\n\"\"\"\r\nfrom pathlib import Path\r\n\r\nimport numpy as np\r\nfrom LogFile import LogFile\r\nfrom engine import *\r\n\r\n\r\nclass ScreeninResults():\r\n \"\"\"\r\n All the screeining results are here.\r\n \"\"\"\r\n def __init__(self, screening_out_folder):\r\n \"\"\"\r\n Take the screeining folder and search into it all the information\r\n\r\n Parameters\r\n ----------\r\n screeining_out_folder : TYPE\r\n DESCRIPTION.\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n self.screening_path = Path(screening_out_folder)\r\n self.receptors_path = {} # keys are the receptor name\r\n self.ligands = {} #\r\n self.results = {}\r\n self.ligandCode = {}\r\n\r\n for rec in self.screening_path.iterdir():\r\n if rec.is_dir():\r\n print(rec.name)\r\n self.receptors_path[rec.name] = rec\r\n ligs = []\r\n for lig in rec.iterdir():\r\n if lig.is_dir():\r\n ligs.append(lig.name)\r\n self.ligands[rec.name] = ligs\r\n self.get_receptor_results(rec.name)\r\n self.write_receptor_results(rec.name)\r\n self.num_receptors = len(self.receptors_path)\r\n\r\n def get_receptor_results(self, receptor):\r\n \"\"\"\r\n Look into all the ligands inside a receptor folder\r\n then look for each ligand log file and take read it\r\n\r\n Parameters\r\n ----------\r\n receptor : str\r\n name of the receptor.\r\n\r\n \"\"\"\r\n\r\n ligands = self.ligands[receptor]\r\n self.results[receptor] = np.zeros((len(ligands), 4))\r\n self.ligandCode[receptor] = {}\r\n # for l, j in zip(self.ligands, range(self.totalLigands)):\r\n for j, l in enumerate(self.ligands[receptor]):\r\n # should be use enumerate insted\r\n # seems to be the same as for l in enumerate(self.ligand):\r\n # use l[0] as j and l[1] as l\r\n lig_folder = self.receptors_path[receptor] / l\r\n try:\r\n ligData = LogFile(lig_folder)\r\n except:\r\n print(lig_folder.name)\r\n print('error at ligand {} log_file_not_found'.format(lig_folder.name))\r\n# print(l, j)\r\n self.ligandCode[receptor][j] = l\r\n self.results[receptor][j][0] = j\r\n self.results[receptor][j][1] = ligData.best\r\n self.results[receptor][j][2] = ligData.ave3\r\n self.results[receptor][j][3] = ligData.ave\r\n ndxSorted = self.results[receptor][:, 1].argsort()\r\n self.results[receptor] = self.results[receptor][ndxSorted]\r\n return self.ligandCode[receptor], self.results[receptor]\r\n\r\n def write_receptor_results(self, receptor, file_name='result.txt'):\r\n \"\"\"\r\n create a filer result.txt and write the receptor result\r\n input: --- file_path\r\n\r\n \"\"\"\r\n file = self.receptors_path[receptor] / file_name\r\n with open(file, 'w+') as result:\r\n result.write(\"\\\r\n# =========================================================================== #\\n\\\r\n# # Results of Vina Screening # #\\n\\\r\n# =========================================================================== #\\n\\\r\n# #\\n\\\r\n# The first column is the name of the ligand #\\n\\\r\n# The Second column is the value of the best pose #\\n\\\r\n# The Third column is the value of the average of the first three poses #\\n\\\r\n# The fourth column is th value of the average of all poses #\\n\\\r\n# #\\n\\\r\n# #\\n\\\r\n# =========================================================================== #\\n\\n \")\r\n\r\n result.write(\" LigandName\tBestScore\tAverageFT\tAverageAll \\n\")\r\n for i in self.results[receptor]:\r\n # print(i)\r\n # result.write(\" {0}\\t{1:.1f}\\t\\t{2:.2f}\\t\\t{3:.2f}\\n\".format(b.ligandCode[i[0]], i[1], i[2], i[3]))\r\n result.write(\" {0:14s}{1:6.1f}{2:17.2f}{3:16.2f}\\n\".format(\r\n self.ligandCode[receptor][i[0]].ljust(4), i[1], i[2], i[3]))\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n import argparse\r\n\r\n # Create the parser\r\n my_parser = argparse.ArgumentParser(description='List the content of a folder')\r\n\r\n # Add the arguments\r\n my_parser.add_argument('-r', '--results',\r\n metavar='vina results',\r\n type=str,\r\n help='the path to vina results',\r\n default='./',\r\n required=False)\r\n\r\n my_parser.add_argument('-o', '--out',\r\n metavar='out file name',\r\n type=str,\r\n help='the name of the out put file',\r\n default='result.txt',\r\n required=False)\r\n\r\n\r\n args = my_parser.parse_args()\r\n input_path = args.results\r\n output_name = args.out\r\n sr = ScreeninResults(input_path)\r\n","sub_path":"mscreen/analysis/old/ScreeninResults.py","file_name":"ScreeninResults.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"319497288","text":"import random\nfrom statistics import mean \n\nclass Ability:\n def __init__(self, name, attack_strength):\n self.name = name\n self.attack_strength = attack_strength\n\n def attack(self):\n return random.randint(0, self.attack_strength)\n\nclass Armor:\n def __init__(self, name, max_block):\n self.name = name\n self.max_block = max_block\n\n def block(self):\n return random.randint(0, self.max_block)\n\nclass Hero:\n def __init__(self, name, starting_health=100):\n self.abilities = []\n self.armors = []\n self.name = name\n self.starting_health = starting_health\n self.current_health = starting_health\n self.deaths = 0\n self.kills = 0\n\n def is_alive(self):\n return self.current_health > 0\n\n def add_ability(self, ability):\n self.abilities.append(ability)\n\n def add_weapon(self, Weapon):\n self.abilities.append(Weapon)\n\n def add_armor(self, armor):\n self.armors.append(armor)\n\n def add_kill(self, num_kills):\n self.kills += num_kills\n \n def add_deaths(self, num_deaths):\n self.deaths += num_deaths\n \n def attack(self):\n return sum((ability.attack() for ability in self.abilities))\n\n def defend(self):\n return sum((armor.block() for armor in self.armors))\n\n def take_damage(self, damage):\n self.current_health -= max(0, damage - self.defend())\n\n def fight(self, opponent):\n if not self.abilities and not opponent.abilites:\n print('Draw!')\n\n while self.is_alive() and opponent.is_alive():\n self.take_damage(opponent.attack())\n opponent.take_damage(self.attack())\n\n if opponent.is_alive():\n print(f'{opponent.name} won the match!')\n opponent.add_kill(1)\n self.add_deaths(1)\n return self\n\n elif self.is_alive():\n print(f'{self.name} won the match!')\n self.add_kill(1)\n opponent.add_deaths(1)\n return opponent\n\n else:\n print(f'{self.name} and {opponent.name} have both died...')\n\nclass Weapon(Ability):\n def attack(self):\n return random.randint(self.attack_strength // 2, self.attack_strength)\n\nclass Team:\n def __init__(self, name):\n self.name = name\n self.heroes = []\n\n def add_hero(self, hero):\n self.heroes.append(hero)\n \n def remove_hero(self, name):\n for hero in self.heroes:\n if name == hero.name:\n self.heroes.remove(hero)\n return 1\n else:\n return 0\n\n def view_all_heroes(self):\n for self.hero in range(len(self.heroes)): \n print(self.heroes[self.hero].name) \n\n def attack(self, other_team):\n team_one = self.heroes\n team_two = other_team.heroes\n \n while team_one and team_two:\n team_one_fighter = random.choice(team_one)\n team_two_fighter = random.choice(team_two)\n\n loser = team_one_fighter.fight(team_two_fighter)\n\n if loser:\n if loser == team_one_fighter:\n team_one.remove(loser)\n\n else:\n team_two.remove(loser)\n \n if team_one:\n return 1\n \n def revive_heroes(self, health=100):\n for hero in self.heroes:\n hero.current_health = 100\n\n def stats(self):\n for hero in self.heroes:\n if(hero.deaths > 0):\n print(\"{}: {}\".format(self.name, (hero.kills/hero.deaths)))\n else:\n print(\"{}: {}\".format(self.name, hero.kills))\n\n # got help from Mo Drame\n def healthCheck(self):\n total = 0\n for hero in self.heroes:\n total += hero.current_health\n return total\n\nclass Arena:\n def __init__(self):\n self.team_one = None\n self.team_two = None\n\n def create_ability(self):\n a_name = input(\"What should the abilities name be?\")\n a_damage = input(\"What should the damage amount be?\")\n\n return Ability(a_name, int(a_damage))\n\n def create_weapon(self):\n w_name = input(\"What should the weapons name be?\")\n w_damage = input(\"What should the damage amount be?\")\n\n return Weapon(w_name, int(w_damage))\n\n def create_armor(self):\n ar_name = input(\"What should the piece of armors name be?\")\n ar_block = input(\"What should the block amount be?\")\n\n return Armor(ar_name, int(ar_block))\n\n def create_hero(self):\n\n hero_name = input('What would you like to name the hero? \\n')\n hero = Hero(hero_name)\n\n return hero\n # got help from Mo Drame\n def build_team_one(self):\n t1_name = input(\"What is your team's name?\")\n number_of_heroes = int(input(\"How many heroes are on the team?\"))\n self.team_one = Team(t1_name)\n while number_of_heroes > 0:\n number_of_heroes -= 1\n self.team_one.heroes.append(self.create_hero())\n\n for hero in self.team_one.heroes:\n print(\"We are going to add a piece of armor for your hero.\")\n hero.armors.append(self.create_armor())\n print(\"We are going to add an ability for your hero.\")\n hero.abilities.append(self.create_ability())\n print(\"We are going to add a piece of weaponry for your hero.\")\n hero.abilities.append(self.create_weapon())\n # got help from Mo Drame\n def build_team_two(self):\n t2_name = input(\"What is your team's name?\")\n number_of_heroes = int(input(\"How many heroes are on the team?\"))\n self.team_two = Team(t2_name)\n while number_of_heroes > 0:\n number_of_heroes -= 1\n self.team_two.heroes.append(self.create_hero())\n\n for hero in self.team_two.heroes:\n print(\"We are going to add a piece of armor for your hero.\")\n hero.armors.append(self.create_armor())\n print(\"We are going to add an ability for your hero.\")\n hero.abilities.append(self.create_ability())\n print(\"We are going to add a piece of weaponry for your hero.\")\n hero.abilities.append(self.create_weapon())\n\n def team_battle(self):\n self.team_one.attack(self.team_two)\n\n # got help from Mo Drame\n def show_stats(self):\n print('\\n')\n print(\"Statistics:\")\n print(\"-------------\\n\")\n\n if self.team_one.healthCheck() < 1:\n print(self.team_two.name + \" Wins\")\n print(\"------------------\")\n print(\"Surviving Heroes:\")\n for x in self.team_two.heroes:\n if x.current_health > 0:\n print(x.name)\n elif self.team_two.healthCheck() < 1:\n print(self.team_one.name + \" Wins\")\n print(\"------------------\")\n print(\"Surviving Heroes:\")\n for x in self.team_one.heroes:\n if x.current_health > 0:\n print(x.name)\n\n print(\"Team Kill/Death - Ratio :\")\n self.team_one.stats()\n self.team_two.stats()\n\nif __name__ == \"__main__\":\n game_is_running = True\n\n # Instantiate Game Arena\n arena = Arena()\n\n #Build Teams\n arena.build_team_one()\n arena.build_team_two()\n\n while game_is_running:\n\n arena.team_battle()\n arena.show_stats()\n play_again = input(\"Play Again? Y or N: \")\n\n #Check for Player Input\n if play_again.lower() == \"n\":\n game_is_running = False\n\n else:\n #Revive heroes to play again\n game_is_running = True","sub_path":"superheroes.py","file_name":"superheroes.py","file_ext":"py","file_size_in_byte":7658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"260033367","text":"\n\nfrom xai.brain.wordbase.verbs._jackknife import _JACKKNIFE\n\n#calss header\nclass _JACKKNIFED(_JACKKNIFE, ):\n\tdef __init__(self,): \n\t\t_JACKKNIFE.__init__(self)\n\t\tself.name = \"JACKKNIFED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"jackknife\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_jackknifed.py","file_name":"_jackknifed.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"278452799","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 15 01:09:48 2021\n\n@author: user\n\"\"\"\n\nin_line=input(\"輸入一整數序列為:\")\n#in_line=\"23 34 34 5 5 34 34\"\nin_line2=[]\nin_line=in_line.split(' ')\nfor i in in_line:\n in_line2.append(int(i))\n \ntime_list=[]\nalist=[]\n\nin_line2.sort()\nfor i in in_line2:\n if i not in alist:\n alist.append(i)\n time_list.append(in_line2.count(i))\np=1\nfor n,i in enumerate(time_list): \n if len(in_line)/2 < i:\n print(\"過半元素為:\",alist[n])\n p=2\nif p==1:\n print(\"過半元素為:NO\")\n\n","sub_path":"11_Q12.py","file_name":"11_Q12.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"629222397","text":"# import sys\n# import json\n# import socket\n# import threading\n# import numpy\n# sys.path.append('/home/thammasorn/anaconda2/lib/python2.7/site-packages')\n# import cv2\n\n# DRONE_ID = 1\n\n# class photoSender(threading.Thread):\n# #finish -checked\n# def __init__(self): \n# threading.Thread.__init__(self)\n# self.DRONE_ID = DRONE_ID\n\n# #finish -checked\n# def run(self):\n# s = socket.socket() # Create a socket object\n# host = socket.gethostname() # Get local machine name\n# host = \"10.0.0.101\"\n# port = 10000 # Reserve a port for your service.\n# s.connect((host, port))\n# #*****add code for take image and send it\n# cap = cv2.VideoCapture(0)\n# ret,frame = cap.read()\n# cv2.imwrite(\"temp.jpg\",frame)\n# with open(\"temp.jpg\", \"rb\") as imageFile:\n# s.send(imageFile.read())\n# s.close\n# sender = photoSender()\n# sender.start()\n\n#!/usr/bin/python\nimport socket\nimport cv2\nimport numpy\ndef imgSender():\n TCP_IP = '10.0.0.101'\n TCP_PORT = 10000\n\n sender_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sender_socket.bind((\"10.0.0.1\",8000))\n sender_socket.sendto(\"imgPos1.jpg\", (\"10.0.0.101\", 10001))\n\n sock = socket.socket()\n sock.connect((TCP_IP, TCP_PORT))\n\n capture = cv2.VideoCapture(0)\n ret, frame = capture.read()\n\n encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90]\n result, imgencode = cv2.imencode('.jpg', frame, encode_param)\n data = numpy.array(imgencode)\n stringData = data.tostring()\n\n sock.send( str(len(stringData)).ljust(16));\n sock.send( stringData );\n sock.close()\n\n decimg=cv2.imdecode(data,1)\n cv2.imshow('CLIENT',decimg)\n cv2.waitKey(0)\n cv2.destroyAllWindows() \n\n\nimgSender()","sub_path":"Ground Station/example_code/Send Image/sender/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"477367759","text":"from nltk.tokenize import word_tokenize\nimport numpy as np\nfrom math import log\nimport matplotlib.pyplot as plt\n\n\nclass LSA(object):\n\n def __init__(self, stopwords, ignorechars):\n self.stopwords = stopwords\n self.ignorechars = ignorechars\n self.word_dict = {}\n self.doc_count = 0\n self.keys = None\n self.A = None\n self.U = None\n self.S = None\n self.Vt = None\n\n def parse(self, doc):\n tokens = word_tokenize(doc)\n for token in tokens:\n token = token.lower()\n if token in self.stopwords:\n continue\n if token not in self.word_dict:\n self.word_dict[token] = []\n self.word_dict[token].append(self.doc_count)\n self.doc_count += 1\n\n def build(self, use_tfidf=False):\n self.keys = [k for k in self.word_dict.keys() if len(self.word_dict[k]) > 1]\n self.keys.sort()\n\n self.A = np.zeros((len(self.keys), self.doc_count))\n for i, k in enumerate(self.keys):\n for d in self.word_dict[k]:\n self.A[i, d] += 1\n\n if use_tfidf:\n rows, cols = self.A.shape\n words_per_doc = np.sum(self.A, axis=0)\n doc_per_word = np.sum(np.asarray(self.A > 0, 'i'), axis=1)\n\n for i in range(rows):\n for j in range(cols):\n self.A[i, j] = (self.A[i, j] / words_per_doc[j]) * log(float(cols) / doc_per_word[i])\n\n def calc(self):\n # U: coordinates of each word in concept space\n # S: singular values\n # Vt: coordinates of each document in concept space\n self.U, self.S, self.Vt = np.linalg.svd(self.A)\n\n def plot_data(self):\n plt.title(\"LSA\")\n\n rows, cols = self.U.shape\n\n dim_1 = []\n dim_2 = []\n\n # for i in range(rows):\n # dim_1.append(self.U[i, -2])\n # dim_2.append(self.U[i, -3])\n\n\n plt.xlim([-0.6, 0.6])\n plt.ylim([-0.6, 0.6])\n\n plt.show()\n\n\n","sub_path":"LSA/LSA.py","file_name":"LSA.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"321386400","text":"from django.db import models\n\nfrom django.contrib.auth.models import User\n\nfrom api.models import DeviceToken\nfrom api.models import DeviceToken\nfrom api.firebase_cloud_messaging import FireBaseMassagingDeal\nfrom api.constants import FirebaseCloudMessagingCase\n\nfrom items.models import Item\nfrom item_contacts.models import ItemContact\nfrom prefecturas.models import Municipio, Departamento, RegionClassed\nfrom profiles.models import Profile\nfrom solicitudes.models import Solicitud\nfrom direct_messages.models import DirectMessageContent, DirectMessage\nfrom django.db.models.signals import post_save, m2m_changed\n\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom django.core.mail import send_mail\nimport firebase_admin\n\n\n\n\nclass Aviso(models.Model):\n\t'''\n\tGenericForeignKeyを使うことでitemcontactのやり取りや、direct_messages、申請者が現れたことをAvisoという単一のクラスで表示する。\n\tこれにより各インスタンを時間順に表示させる事ができる\t\n\t'''\n\t#aviso_user = models.ForeignKey(Profile, on_delete=models.PROTECT, null=True)\n\taviso_user = models.ForeignKey(Profile, on_delete=models.PROTECT, null=True)\n\t#aviso_to = models.ForeignKey(User, on_delete=models.PROTECT, null=True)\n\tcontent_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True)\n\tobject_id = models.PositiveIntegerField()\n\tcontent_object = GenericForeignKey('content_type', 'object_id')\n\tchecked = models.BooleanField(default=False)\n\tcreated_at = models.DateTimeField(auto_now=True)\n\t\n\tdef __str__(self):\n\t\treturn str(self.aviso_user)\n\n\n\n\n\ndef sendMail(subject, content, message_to):\n\n\tmessage_from = \"from@sharexela.ga\"\n\tsend_mail(subject, content, message_from, message_to)\n\n\n\n\ndef itemitemcontact_m2m_changed_receiver(sender, instance, action, *args, **kwargs):\n\t\"\"\"機能\n\titem_obj.item_contactsにItemContactオブジェクトを追加した時に\n\t通知するユーザー毎にAvisoオブジェクトを生成する。\n\t\"\"\"\n\t\"\"\"テスト項目\n\n\tItemContactオブジェクトが生成されたらItem.item_contacts(ManyToManyField)に当該オブジェクトが追加される。\n\tItemContactオブジェクトが生成されたらAvisoオブジェクトが少なくと1つ以上生成される。\n\titem_m2m_changed_receiver内のitem_contact_objectsが時系列順にItemContactオブジェクトが並んでいる。\n\titem_contact_objは時系列順に並べたitem_contact_objectsのうち最後のオブジェクトである。\n\titem_contact_objectsのカウントが0の場合、生成されるAvisoオブジェクトは一つのみである。\n\titem_contact_objectsのカウントが0の場合、生成されるAvisoオブジェクトのaviso_user値は記事作成者のProfileオブジェクトである。\n\titem_contact_objectsのカウントが0以外の場合、生成されるAvisoオブジェクトの数はコメント送信者を除く重複なしのpost_userの数またはその数+1である。\n\titem_contact_objectsのカウントが0以外の場合、生成されるAvisoオブジェクトのaviso_user値はコメント送信者以外のProfileオブジェクトである。\n\titem_contact_objectsに記事作成者(owner_user)が含まれていない場合、記事作成者がprofilesに含まれる。\n\n\t\"\"\"\n\tif action == \"post_add\":\n\t\t\n\t\titem_obj = instance\n\t\towner_user = Profile.objects.get(user=item_obj.user)\n\t\titem_contact_objects = item_obj.item_contacts.all().order_by('timestamp')\n\t\titem_contact_obj = item_contact_objects.last()\n\n\t\tprofiles = [item_contact.post_user for item_contact in item_contact_objects]\n\t\tprofiles.append(owner_user)\n\t\tprofiles = set(profiles)\n\t\tfor profile_obj in profiles:\n\t\t\tif profile_obj == item_contact_obj.post_user:\n\t\t\t\tcontinue \n\t\t\taviso_user = profile_obj\n\t\t\t\n\t\t\tAviso.objects.create(\n\t\t\t\taviso_user=aviso_user,\n\t\t\t\tcontent_type=ContentType.objects.get_for_model(item_obj.item_contacts.all().last()),\n\t\t\t\tobject_id=item_obj.item_contacts.all().last().id\n\t\t\t\t)\n\n\t\t\t#data = {\"item_obj\":item_obj.title }\n\n\t\t\tfcmd_obj = FireBaseMassagingDeal()\n\t\t\tfcmd_obj.getDeviceToken(aviso_user.user)\n\t\t\tfcmd_obj.makeNotification(case=FirebaseCloudMessagingCase.ITEMCONTACT_ADDED_TO_ITEM)\n\t\t\t#fcmd_obj.makeNotification(case=FirebaseCloudMessagingCase.ITEMCONTACT_ADDED_TO_ITEM, data=data)\n\t\t\tfcmd_obj.makeMessage()\n\t\t\ttry:\n\t\t\t\tfcmd_obj.sendMessage()\t\t\t\n\t\t\texcept firebase_admin._messaging_utils.UnregisteredError:\n\t\t\t\tprint(\"Firebaseのエラー\")\n\n\t\t\t# emailを送信するロジックを挿入\n\t\t\tsubject = \"ShareXekla Siguió un comentario\"\n\t\t\tcontent = item_obj.title + \"\\n\" \n\t\t\tmessage_to = [aviso_user.user.email]\n\t\t\tsendMail(subject, content, message_to)\t\n\t\t\n\nm2m_changed.connect(itemitemcontact_m2m_changed_receiver, sender=Item.item_contacts.through)\n\n\n\n\n\ndef itemsolicitudes_m2m_changed_receiver(sender, instance, action, pk_set, *args, **kwargs):\n\t\n\t\"\"\"機能\n\titem_obj.solicitudesにSolicitudオブジェクトを追加した時に\n\t通知するユーザーにAvisoオブジェクトを生成する。\n\t\"\"\"\n\t\n\tif action == \"post_add\":\n\t\t#print(pk_set)\n\t\tsolicitudes_pk_list = list(pk_set)\n\t\tadded_pk = max(solicitudes_pk_list)\n\n\t\tif type(instance) != Item:\n\t\t\treturn \n\t\titem_obj = instance\n\t\t#print(\"TYPE\")\n\t\t#print(type(item_obj))\n\t\towner_user = Profile.objects.get(user=item_obj.user)\n\t\t#item_contact_objects = item_obj.item_contacts.all().order_by('timestamp')\n\t\t#item_contact_obj = item_contact_objects.last()\n\n\t\taviso_user = owner_user\n\t\tAviso.objects.create(\n\t\t\taviso_user=aviso_user,\n\t\t\tcontent_type=ContentType.objects.get_for_model(item_obj.solicitudes.all().last()),\n\t\t\tobject_id=added_pk)\n\n\t\tdata = {\"item_obj\":item_obj.title }\n\n\t\tfcmd_obj = FireBaseMassagingDeal()\n\t\tfcmd_obj.getDeviceToken(aviso_user.user)\n\t\tfcmd_obj.makeNotification(case=FirebaseCloudMessagingCase.CREATED_SOLICITUD, data=data)\n\t\tfcmd_obj.makeMessage()\n\t\tfcmd_obj.sendMessage()\n\n\t\t\n\t\t# emailを送信するロジックを挿入\n\t\tsubject = \"ShareXekla Solicitud de transacción\"\n\t\tcontent = item_obj.title + \"\\n\" \n\t\tmessage_to = [aviso_user.user.email]\n\t\tsendMail(subject, content, message_to)\t\n\n\n\t\t\n\nm2m_changed.connect(itemsolicitudes_m2m_changed_receiver, sender=Item.solicitudes.through)\n\n\n\n\n\ndef solicitud_post_save_receiver(sender, instance,created, *args, **kwargs):\n\t\"\"\"機能\n\tSolicitudインスタンスが変更されたときにインスタンスのacceptedがTrueかどうかチェックする。\n\tTrueの場合には他にもDirectMessageオブジェクトを作成するロジックを追加する。\n\n\t残念ながらsolicitud.acceptedをTrueに変えたときには最初にDirectMessageが生成され、その後Item.direct_messageに\n\t紐付けられるので現状firebaseのfcmを送信する事ができない。Itemオブジェクト変更後に発火するシグナルを準備する。\n\t\"\"\"\n\t\n\t\n\t#solicitudオブジェクトの変更があったときに以下のロジックに従ってDirectMessageオブジェクトが生成される\n\tif created == True:\n\t\treturn\n\tsolicitud_obj = instance\n\n\titem_obj = solicitud_obj.item_set.all().first()\n\n\tif item_obj == None:\n\t\treturn\n\n\tif solicitud_obj.accepted == True and item_obj.direct_message is None:\n\t\towner = Profile.objects.get(user=item_obj.user)\n\t\tparticipant = solicitud_obj.applicant\n\t\tdm_obj = DirectMessage.objects.create(\n\t\t\towner = owner, \n\t\t\tparticipant = participant,\n\t\t\t)\n\n\t\titem_obj.direct_message = dm_obj\n\t\titem_obj._aviso_user = participant\n\t\titem_obj.save(update_fields=[\"direct_message\"])\n\t\t#deadlineをTrueに変更する\n\t\titem_obj.deadline = True\n\t\titem_obj.save()\n\t\treturn\n\telse:\n\t\t#print(\"不発です\")\n\t\treturn\n\n\npost_save.connect(solicitud_post_save_receiver, sender=Solicitud )\n\n\n\n\ndef directmessage_post_save_receiver(sender, instance, created, *args, **kwargs):\n\t\"\"\"\n\t上記のsolicitud_post_save_receiverでDirectMessageオブジェクトが作成される。\n\tそれをトリガーにavisoオブジェクトを生成する。\n\n\t\"\"\"\n\tif created == False:\n\t\treturn\n\n\n\n\tdm_obj = instance\n\taviso_user = dm_obj.participant\n\n\n\taviso_obj = Aviso.objects.create(\n\t\taviso_user=aviso_user, \n\t\tcontent_type=ContentType.objects.get_for_model(dm_obj), \n\t\tobject_id=dm_obj.id,\n\t\t)\n\n\t#aviso_obj.aviso_user.add(aviso_user)\n\n\ttry:\n\t\titem_obj = Item.objects.get(direct_message__id=dm_obj.id)\n\n\t\t\n\t\t\t\n\t\t#item_obj = dm_obj.item_set.all().first()\n\t\tdata = {\"item_obj\":item_obj.title }\n\t\tfcmd_obj = FireBaseMassagingDeal()\n\t\tfcmd_obj.getDeviceToken(aviso_user.user)\n\t\t#fcmd_obj.makeNotification(case=FirebaseCloudMessagingCase.CREATED_DIRECTMESSAGE)\n\t\tfcmd_obj.makeNotification(case=FirebaseCloudMessagingCase.CREATED_DIRECTMESSAGE, data=data)\n\t\tfcmd_obj.makeMessage()\n\t\tfcmd_obj.sendMessage()\n\t\t\n\t\t#emailの送信を実装\n\t\tsubject = \"ShareXekla Ha sido elegido para hacer negocios con usted\"\n\t\tcontent = item_obj.title + \"\\n\" \n\t\tmessage_to = [aviso_user.user.email]\n\t\tsendMail(subject, content, message_to)\n\t\t\n\texcept:\n\t\t#sub_item_post_save_receiver()を使ってfcmとemailを送信する\n\t\tpass\n\n\t\npost_save.connect(directmessage_post_save_receiver, sender=DirectMessage )\n\n\n\n\n\n\n\ndef sub_item_post_save_receiver(sender, instance, created, update_fields, *args, **kwargs):\n\t\"\"\"テスト実行\n\t\n\t\"\"\"\n\n\tif created == True:\n\t\treturn\n\n\n\t#update_fieldsにdirect_messageがある場合にはfcm及びemailを送信する\n\t#update_fieldsを設定する場所はitemオブジェクトにdm_objを設定する場所、つまりこのファイルのsolicitud_post_save_receiverで実行する。\n\tif update_fields == None:\n\t\treturn\n\n\tif \"direct_message\" in update_fields:\n\n\t\titem_obj = instance\n\t\taviso_user = getattr(instance, '_aviso_user', None) #participantに該当する\n\n\t\tdata = {\"item_obj\":item_obj.title }\n\t\tfcmd_obj = FireBaseMassagingDeal()\n\t\tfcmd_obj.getDeviceToken(aviso_user.user)\n\t\t#fcmd_obj.makeNotification(case=FirebaseCloudMessagingCase.CREATED_DIRECTMESSAGE)\n\t\tfcmd_obj.makeNotification(case=FirebaseCloudMessagingCase.CREATED_DIRECTMESSAGE, data=data)\n\t\tfcmd_obj.makeMessage()\n\t\tfcmd_obj.sendMessage()\t\n\t\t\n\t\t#emailの送信\n\t\tsubject = \"ShareXekla Ha sido elegido para hacer negocios con usted\"\n\t\tcontent = item_obj.title + \"\\n\" \n\t\tmessage_to = [aviso_user.user.email]\n\t\tsendMail(subject, content, message_to)\t\t\n\n\npost_save.connect(sub_item_post_save_receiver, sender=Item )\n\n\n\n\n\n\n\ndef dm_content_m2m_receiver(sender, instance, action, pk_set, *args, **kwargs):\n\t\"\"\"\n\tダイレクトメッセージの送り主がメッセージを送信するたびに\n\tdm_objにdm_contentがaddされる。これをトリガーとしてAvisoオブジェクトが生成する。\n\n\taviso_user = 通知を送る相手\n\t\"\"\"\t\n\tif action == \"post_add\":\n\t\tdm_obj = instance\n\t\t#dm_content_objects = dm_obj.direct_message_contents.all()\n\t\tdm_content_objects_pk_set = list(pk_set)\n\t\tadded_pk = max(dm_content_objects_pk_set)\n\t\tdm_content_obj = DirectMessageContent.objects.get(id=added_pk)\n\n\n\t\tif dm_obj.owner != dm_content_obj.profile:\n\t\t\taviso_user = dm_obj.owner\n\t\telse:\n\t\t\taviso_user = dm_obj.participant\n\t\n\n\t\taviso_obj = Aviso.objects.create(\n\t\t\taviso_user = aviso_user, \n\t\t\tcontent_type=ContentType.objects.get_for_model(dm_content_obj), \n\t\t\tobject_id=dm_content_obj.id,\n\t\t\t)\n\n\n\t\titem_obj = Item.objects.get(direct_message=dm_obj)\n\t\tdata = {\"item_obj\":item_obj.title }\t\n\n\n\t\tfcmd_obj = FireBaseMassagingDeal()\n\t\tfcmd_obj.getDeviceToken(aviso_user.user)\n\t\t#fcmd_obj.makeNotification(case=FirebaseCloudMessagingCase.CREATED_DM_CONTENT)\n\t\tfcmd_obj.makeNotification(case=FirebaseCloudMessagingCase.CREATED_DM_CONTENT, data=data)\n\t\tfcmd_obj.makeMessage()\n\t\tfcmd_obj.sendMessage()\n\n\t\t#emailの送信を実装\n\t\tsubject = \"ShareXekla Tiene un mensaje\"\n\t\tcontent = item_obj.title + \"\\n\" \n\t\tmessage_to = [aviso_user.user.email]\n\t\tsendMail(subject, content, message_to)\t\t\t\n\n\nm2m_changed.connect(itemsolicitudes_m2m_changed_receiver, sender=DirectMessage.direct_message_contents.through)\n\n\n\n\n\ndef user_post_save_receiver(sender, instance, created, *args, **kwargs):\n\t\"\"\"\n\tuserオブジェクトが生成されたら自動的にProfileオブジェクトを生成する仕組み\n\t\"\"\"\n\tif created == False:\n\t\treturn \n\telif created == True:\n\t\tuser_obj = instance\n\t\tadm0 = \"Guatemala\"\n\t\tadm1 = \"Quetzaltenango\"\n\t\tadm2 = \"Quetzaltenango\"\n\t\tProfile.objects.create(user=user_obj, adm0=adm0, adm1=adm1, adm2=adm2)\n\t\tDeviceToken.objects.create(user=user_obj)\n\t\treturn \n\n\npost_save.connect(user_post_save_receiver, sender=User)\n\n\n\n\n\n\ndef change_adm1_and_adm2_by_point_of_profile_obj(sender, instance, created, update_fields, *args, **kwargs):\n\t\"\"\"機能\n\tProfileオブジェクトのpoint属性が変更された時呼び出される。point値に基づいて\n\tDepartamentoやMunicipioの値を変更する\n\n\n\t\"\"\"\n\tif created == True:\n\t\treturn \n\tif update_fields == None:\n\t\treturn\n\tif \"point\" in update_fields:\n\t\tprint(\"pointをもとにadm1,adm2を修正\")\n\t\tprofile_obj = instance\n\t\tpoint = profile_obj.point\n\t\tdepartament_obj = Departamento.objects.get(adm1_es=profile_obj.adm1).geom\n\t\tprint(departament_obj.contains(point))\n\t\t#含まれている時 -> 何もしない\n\n\t\t#含まれていない時 -> オブジェクトを変更する\n\t\tif departament_obj.contains(point) == False:\n\t\t\tprint(\"pointをもとにadm1を修正\")\n\t\t\tfor dep in Departamento.objects.all():\n\t\t\t\tif dep.geom.contains(point):\n\t\t\t\t\tprofile_obj.adm1 = dep.adm1_es\n\t\t\t\t\tprofile_obj.save()\n\n\t\t#Municipioオブジェクトの取得\n\t\tmuni_obj = Municipio.objects.get(adm2_es=profile_obj.adm2).geom\n\n\t\t#含まれていない時 -> オブジェクトを変更する\n\t\tif muni_obj.contains(point) == False:\n\t\t\tprint(\"pointをもとにadm2を修正\")\n\t\t\trc_obj = RegionClassed.objects.get(departamento__adm1_es=profile_obj.adm1)\n\t\t\tfor muni in rc_obj.municipios.all():\n\t\t\t\tif muni.geom.contains(point):\n\t\t\t\t\tprofile_obj.adm2 = muni.adm2_es\n\t\t\t\t\tprofile_obj.save()\n\t\treturn\n\n\t#変更できなかった場合には通知を送信する仕組みを実装する(後で)\n\npost_save.connect(change_adm1_and_adm2_by_point_of_profile_obj, sender=Profile)\n\n\n\n","sub_path":"avisos/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"450819330","text":"#Depth First Search\n\nfrom gridGame import gridGame\n\nclass Depth:\n\n #Gamestate\n game = None\n moveStack = []\n stateSet = []\n\n def __init__(self):\n self.game = gridGame()\n self.game.promptUser()\n self.game.genSolved()\n self.game.startClock()\n print(self.game)\n self.solve2(0)\n\n\n def solve2(self, depth):\n\n if self.game.checkWin():\n print(self.game.printMoves())\n print(\"!!!!!!!VICTORY!!!!!!!!!\")\n return True\n\n if depth > 30:\n print(\"DEPTH LIMIT REACHED\")\n return False\n\n if self.game.toString() in self.stateSet:\n return False\n\n self.stateSet.append(self.game.toString())\n\n\n\n for move in self.game.validMoves():\n\n self.game.makeMove(move[0], move[1])\n self.moveStack.append(move)\n solved = self.solve2(depth+1)\n\n if solved:\n return True\n\n self.game.undo(move[0], move[1])\n self.moveStack.pop()\n\n\n return False\n\n\n def solve(self, depth):\n #limit depth\n if depth > 30:\n print(\"DEPTH LIMIT REACHED\")\n return False\n\n solved = False\n #Iterate over each possible move\n for move in self.game.validMoves():\n\n self.moveStack.append(move)\n #Make the next move\n self.game.makeMove(move[0], move[1])\n\n #If after making the move we're in an already visited state, then return False\n #Else, add it to the state set\n\n if self.game.toString() in self.stateSet:\n self.game.undo(move[0], move[1])\n #continue\n else:\n self.stateSet.append(self.game.toString())\n\n #If game is won, print and return True, to let higher levels know not to recurse anymore\n if self.game.checkWin():\n print(\"SUCCESS\\n\")\n\n return True\n\n #If game is not won, continue going deeper\n solved = self.solve(depth+1)\n #If found a solutin, break recusion\n if solved: return True\n\n #If this path did not result in a solution, time to take another\n #Pop off the move we took, undo it, and let loop continue\n self.game.undo(move[0], move[1])\n self.moveStack.pop()\n\n\n\n\n\n\nif __name__ == '__main__':\n\n solver = Depth()","sub_path":"depth.py","file_name":"depth.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"374077601","text":"import tempfile\nimport shutil\nimport os\n\nfrom django.test import TransactionTestCase\nfrom django.contrib.auth.models import Group\nfrom django.core.files.uploadedfile import UploadedFile\n\nfrom hs_core import hydroshare\nfrom hs_core.hydroshare import utils\nfrom hs_core.testing import MockIRODSTestCaseMixin\n\n\nclass TestMODFLOWModelInstanceMetaData(MockIRODSTestCaseMixin, TransactionTestCase):\n def setUp(self):\n super(TestMODFLOWModelInstanceMetaData, self).setUp()\n self.group, _ = Group.objects.get_or_create(name='Resource Author')\n self.user = hydroshare.create_account(\n 'user1@nowhere.com',\n username='user1',\n first_name='Creator_FirstName',\n last_name='Creator_LastName',\n superuser=False,\n groups=[self.group]\n )\n\n self.res = hydroshare.create_resource(\n resource_type='MODFLOWModelInstanceResource',\n owner=self.user,\n title='Test MODFLOW Model Instance Resource'\n )\n\n self.resGenModelProgram = hydroshare.create_resource(\n resource_type='ModelProgramResource',\n owner=self.user,\n title='Model MODFLOW Program Resource'\n )\n\n self.resMODFLOWModelProgram = hydroshare.create_resource(\n resource_type='ModelProgramResource',\n owner=self.user,\n title='Model Program Resource 2'\n )\n\n self.temp_dir = tempfile.mkdtemp()\n\n d = 'hs_modflow_modelinstance/tests/modflow_example/'\n self.file_list = []\n self.file_names = []\n self.sample_nam_name = 'example.nam'\n self.sample_nam_name2 = 'example2.nam'\n self.sample_dis_file = 'example.dis'\n for file in os.listdir(d):\n self.file_names.append(file)\n target_temp_file = os.path.join(self.temp_dir, file)\n shutil.copy(\"{}{}\".format(d, file), target_temp_file)\n if self.sample_nam_name == file:\n self.sample_nam_obj = open(target_temp_file, 'r')\n elif self.sample_nam_name2 == file:\n self.sample_nam_obj2 = open(target_temp_file, 'r')\n elif self.sample_dis_file == file:\n self.sample_dis_obj = open(target_temp_file, 'r')\n else:\n self.file_list.append(target_temp_file)\n\n self.file_name = \"MIR.txt\"\n temp_text_file = os.path.join(self.temp_dir, self.file_name)\n text_file = open(temp_text_file, 'w')\n text_file.write(\"Model Instance resource files\")\n self.text_file_obj = open(temp_text_file, 'r')\n\n def tearDown(self):\n super(TestMODFLOWModelInstanceMetaData, self).tearDown()\n if os.path.exists(self.temp_dir):\n shutil.rmtree(self.temp_dir)\n\n def test_metadata_extraction(self):\n # test allowed file type is '.*'\n self.assertEqual(self.res.get_supported_upload_file_types(), '.*')\n\n # there should not be any content file\n self.assertEqual(self.res.files.all().count(), 0)\n\n # Upload any file type should pass both the file pre add check post add check\n files = [UploadedFile(file=self.sample_nam_obj, name=self.sample_nam_obj.name)]\n utils.resource_file_add_pre_process(resource=self.res, files=files, user=self.user,\n extract_metadata=False)\n\n utils.resource_file_add_process(resource=self.res, files=files, user=self.user,\n extract_metadata=False)\n # here are the things that the modflow modelinstance should include from the .nam file\n # GroundWaterFlow\n # flowPackage: 'LPF', 'UZF'(?)\n #\n # GeneralElements\n # modelSolver: 'SIP'\n # outputcontrolpackage: 'OC', 'GAGE'\n #\n # BoundaryCondition\n # head_dependent_flux_boundary_packages: 'SFR', 'GHB', 'UZF'(?)\n # specified_flux_boundary_packages: 'WEL'\n\n self.assertEqual(self.res.metadata.general_elements.modelSolver, 'SIP')\n self.assertTrue(self.res.metadata.ground_water_flow.unsaturatedZonePackage)\n self.assertIn(\n 'GHB',\n self.res.metadata.boundary_condition.get_head_dependent_flux_boundary_packages()\n )\n self.assertIn(\n 'SFR',\n self.res.metadata.boundary_condition.get_head_dependent_flux_boundary_packages()\n )\n self.assertIn(\n 'WEL',\n self.res.metadata.boundary_condition.get_specified_flux_boundary_packages()\n )\n self.assertIn(\n 'OC',\n self.res.metadata.general_elements.get_output_control_package()\n )\n self.assertIn(\n 'GAGE',\n self.res.metadata.general_elements.get_output_control_package()\n )\n\n def test_metadata_extraction_DIS_file(self):\n # Extract Metadata from DIS File\n files = [UploadedFile(file=self.sample_dis_obj, name=self.sample_dis_obj.name)]\n utils.resource_file_add_pre_process(resource=self.res,\n files=files,\n user=self.user,\n extract_metadata=False)\n utils.resource_file_add_process(resource=self.res,\n files=files,\n user=self.user,\n extract_metadeta=False)\n\n # ---Tests for Grid Dimensions\n # Number of Layers\n self.assertEqual(self.res.metadata.grid_dimensions.numberOfLayers, str(4))\n # Type of Rows\n self.assertEqual(self.res.metadata.grid_dimensions.typeOfRows, 'Regular')\n # Number of Rows\n self.assertEqual(self.res.metadata.grid_dimensions.numberOfRows, str(20))\n # Type of Columns\n self.assertEqual(self.res.metadata.grid_dimensions.typeOfColumns, 'Regular')\n # Number of Columns\n self.assertEqual(self.res.metadata.grid_dimensions.numberOfColumns, str(15))\n\n # ---Tests for Stress Period\n # Stress Period Type\n self.assertEqual(self.res.metadata.stress_period.stressPeriodType, 'Steady and Transient')\n\n # ---Tests for Study Area\n # Total Length\n self.assertEqual(self.res.metadata.study_area.totalLength, str(20*2000.0)) # double\n # Total Width\n self.assertEqual(self.res.metadata.study_area.totalWidth, str(15*2000.0)) # double\n","sub_path":"hs_modflow_modelinstance/tests/test_modflow_modelinstance_metadata_extraction.py","file_name":"test_modflow_modelinstance_metadata_extraction.py","file_ext":"py","file_size_in_byte":6490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"83541924","text":"############################################################\n# Module : combine models\n# Date : April 24th, 2017\n# Author : Xiao Ling\n############################################################\n\nimport os\nimport math\nimport numpy as np\nimport networkx as nx\nfrom sklearn.metrics import r2_score\nfrom sklearn.linear_model import ElasticNet\nimport pickle\n\n\nfrom app import *\nfrom utils import *\nfrom scripts import *\nfrom scripts.graph import *\nfrom experiments.argmax import *\nfrom experiments.rank_all import *\nfrom experiments.elastic_net import *\n\n\n############################################################\n'''\n\tmodel and feature space representation\n'''\nwinner = 'ppdb-ngram-1|[phi^out(s)-phi^out(t)]|num_adv=2|alpha=0.9|l1=0.9'\npath = os.path.join(work_dir['results'],winner + '/model')\n\nprint('\\n\\t>> loading model from ' + winner)\nwith open(path,'rb') as h:\n\tmodel = pickle.load(h)\n\nnum_adv = 2\ndata_set = 'ppdb-ngram-1'\n\nw2idx_path = os.path.join( work_dir['assets']\n\t , 'w2idx-' + str(num_adv) + '.pkl')\n\nprint('\\n\\t>> loading word to index')\nwith open(w2idx_path,'rb') as h:\n\tw2idx = pickle.load(h)\n\nprint('\\n\\t>> constructing feature functions')\nfix, rho = 'o' , rho_out( GRAPH[data_set], w2idx )\nOP , op = '-' , vec_subtract\nphi = to_x(rho,op)\n\nSAVE = True\n\n############################################################\n'''\n\trun on all data set\n'''\ndecide = decide_fn_both(G_ppng, model, phi)\nresults_dir = os.path.join(work_dir['results'], 'combined/' + winner)\n\nprint('\\n\\t>> ranking moh-ppdb with ppdb-ngram graph ...')\nrank_all_gold( test['moh-ppdb']\n\t , decide\n\t , os.path.join(results_dir, 'moh-ppdb.txt')\n\t , refresh = False\n\t , save = SAVE )\n\nif False:\n\n\tprint('\\n\\t>> making directory ' + results_dir)\n\tif not os.path.exists(results_dir):\n\t\tos.mkdir(results_dir)\n\n\tprint('\\n\\t>> ranking moh-no-ties with ppdb-ngram graph ...')\n\trank_all_gold( test['moh-no-tie']\n\t\t , decide\n\t\t , os.path.join(results_dir, 'moh-no-tie.txt')\n\t\t , refresh = False\n\t\t , save = SAVE )\n\n\n\tprint('\\n\\t>> ranking ccb-no-ties with ppdb-ngram graph ...')\n\trank_all_gold( test['ccb-no-tie']\n\t\t , decide\n\t\t , os.path.join(results_dir, 'ccb-no-tie.txt')\n\t\t , refresh = False\n\t\t , save = SAVE )\n\n\n\tprint('\\n\\t>> ranking bcs with ppdb-ngram graph ...')\n\trank_all_gold( test['bcs']\n\t\t , decide\n\t\t , os.path.join(results_dir, 'bcs.txt')\n\t\t , refresh = False\n\t\t , save = SAVE )\n\n\tprint('\\n\\t>> ranking ccb with ppdb-ngram graph ...')\n\trank_all_gold( test['ccb']\n\t\t , decide\n\t\t , os.path.join(results_dir, 'ccb.txt')\n\t\t , refresh = False\n\t\t , save = SAVE )\n\n\tprint('\\n\\t>> ranking moh with ppdb-ngram graph ...')\n\trank_all_gold( test['moh']\n\t\t , decide\n\t\t , os.path.join(results_dir, 'moh.txt')\n\t\t , refresh = False\n\t\t , save = SAVE )\n\n\n","sub_path":"experiments/elastic_net/script/combine_3.py","file_name":"combine_3.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"473527177","text":"import os\nimport re\nimport math\n\n\n\ndef main():\n data_dir = \"./Data/\"\n stop = set([\"a\", \"the\", \"this\", \"that\", \"an\", \"and\",\n \"are\", \"is\", \"\", \"on\", \"in\", \"for\", \"it\",\n \"to\", \"as\", \"also\", \"yet\", \"both\", \"from\",\n \"of\", \"been\", \"being\", \"while\", \"their\",\n \"be\", \"by\", \"only\", \"your\", \"you\", \"with\"]) # 禁用词表\n\n # 计算tf\n tf = {}\n doc_num = 0\n for file_name in os.listdir(data_dir):\n doc_num += 1\n file_path = os.path.join(data_dir, file_name)\n with open(file_path, \"r\") as fr:\n text_str = fr.read()\n word_list = re.split(\"[\\d\\s\\,\\.\\(\\)\\:]+\", text_str)\n print(word_list)\n word_count_dic = {}\n word_num = 0\n for _word in word_list:\n word = _word.lower()\n if word in stop:\n continue\n if word not in word_count_dic:\n word_count_dic[word] = 0\n word_count_dic[word] += 1\n word_num += 1\n for k, v in word_count_dic.items():\n tf[(k, file_name)] = v/word_num\n print(tf)\n\n\n\n # 计算idf\n word_exist_in_file_num = {}\n for word, file_name in tf.keys():\n if word not in word_exist_in_file_num:\n word_exist_in_file_num[word] = 0\n word_exist_in_file_num[word] += 1\n idf = {}\n for k, v in word_exist_in_file_num.items():\n idf[k] = math.log(v/(1+doc_num))\n\n # 计算tf_idf\n tf_idf = {}\n for k, v in tf.items():\n word, file_name = k\n tf_idf[k] = v * idf[word]\n\n # # 排序输出(全局)\n # sort_tf_idf = sorted(tf_idf.items(), key=lambda x: x[1], reverse=True)\n # for k, v in sort_tf_idf:\n # print(k, v)\n #\n # 按文档排序\n tf_idf_file = {}\n for (word, file_name), tf_idf_val in tf_idf.items():\n if file_name not in tf_idf_file:\n tf_idf_file[file_name] = {}\n tf_idf_file[file_name][word] = tf_idf_val\n for k, v in tf_idf_file.items():\n sort_tf_idf_each_file = sorted(v.items(), key=lambda x: x[1], reverse=True)[:20]\n print(k)\n for word, tf_idf_val in sort_tf_idf_each_file:\n print(word, tf_idf_val)\n print(\"-\"*100)\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"work_10.2/Homework/word_practice.py","file_name":"word_practice.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"192169412","text":"import requests\nfrom save.save import h\nfrom lxml import etree\nurl = \"https://www.xicidaili.com/nn/3\"\nresponse = requests.get(url, headers=h())\nwith open(\"西刺代理检测.html\" ,\"w\", encoding=\"utf-8\")as file:\n file = file.write(response.text)\nresponse = response.text\nresponse = etree.HTML(response)\nm = response.xpath('//table[@id=\"ip_list\"]/tr')\nlist = []\nfor ip in m[1:] :\n ip = ip.xpath('./td/text()')\n ipm = ip[0]\n dkh = ip[1]\n xy = ip[5].lower()\n if xy == \"https\":\n dict = {}\n dict[xy] = ipm + \":\" + dkh\n list.append(dict)\nprint(list)\n","sub_path":"python/4.20/西刺代理检测.py","file_name":"西刺代理检测.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"271496921","text":"class Boy:\n\t'boy class for all boys'\n\n\tdef __init__(self, name, atr, gfbudget, intelli, min_atr_req, type):\n\t\t'constructor'\n\t\tself.name = name\n\t\t'''@ivar: name of boy'''\n\t\tself.atr = atr\n\t\t'''@ivar: attractiveness of boy'''\n\t\tself.gfbudget = gfbudget\n\t\t'''@ivar: girlfriend budget of boy'''\n\t\tself.intelli = intelli\n\t\t'''@ivar: intelligence of boy'''\n\t\tself.min_atr_req = min_atr_req\n\t\t'''@ivar: minimum attractiveness requirement of boy'''\n\t\tself.type = type\n\t\t'''@ivar: type of boy'''\n\n\tdef is_elligible(self, mbudget, atr):\n\t\t'checks the elligibility of a given Girl, for the current instance of Boy class'\n\t\tif (self.gfbudget >= mbudget) and (atr >= self.min_atr_req):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False","sub_path":"q8/boys.py","file_name":"boys.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"299089058","text":"import cv2\r\nimport numpy as np\r\nimport os\r\nfrom matplotlib import pyplot as plt\r\nimport random\r\n\r\n# This code extracts 100 x 100 size Wally Images\r\n# pixel_size = 100\r\n# pixel_delta = pixel_size/2\r\n# for i in range(1,16):\r\n# \twally = cv2.imread(\"imageset/\"+str(i)+\".jpg\")\r\n# \timg = cv2.imread(\"imageset/\"+str(i)+\"_ans.jpg\",0)\r\n# \tM = cv2.moments(img)\r\n# \tcx = int(M['m10']/M['m00'])\r\n# \tcy = int(M['m01']/M['m00'])\r\n# \textract = wally[(cy-pixel_delta):(cy+pixel_delta),(cx-pixel_delta):(cx+pixel_delta)]\r\n# \tcv2.imwrite(\"extract/\"+str(i)+\"_extract.jpg\",extract)\r\n\r\n# Extract wally\r\n# x = 30\r\n# y = 30\r\n# for i in range(1,16):\r\n# \twally = cv2.imread(\"imageset/\"+str(i)+\".jpg\")\r\n# \timg = cv2.imread(\"imageset/\"+str(i)+\"_face.jpg\",0)\r\n# \tcoord = np.unravel_index(np.argmax(img),img.shape)\r\n# \tcy = coord[0]\r\n# \tcx = coord[1]\r\n# \tprint (cx,cy)\r\n# \textract = wally[(cy-y/2):(cy+y/2),(cx-x/2):(cx+x/2)]\r\n# \tcv2.imwrite(\"extract_face/\"+str(i)+\"_extract.jpg\",extract)\r\n\r\n# Extract background\r\ndef extractBackground(output_filename):\r\n\tx = 50\r\n\ty = 50\r\n\tfileout = open(output_filename,\"wb\")\r\n\tinfo = np.array([30000,50,50,3],np.uint32)\r\n\tout = np.array([],np.uint8)\r\n\tfor i in range(1,16):\r\n\t\tprint (i)\r\n\t\twally = cv2.imread(\"imageset/\"+str(i)+\".jpg\")\r\n\t\timg = cv2.imread(\"imageset/\"+str(i)+\"_ans.jpg\",0)\r\n\t\tfor j in range(2000):\r\n\t\t\twhile True:\r\n\t\t\t\tcx = random.randint(0,wally.shape[1]-x)\r\n\t\t\t\tcy = random.randint(0,wally.shape[0]-y)\r\n\t\t\t\tif img[cy,cx]!=255:\r\n\t\t\t\t\textract = wally[cy:cy+y,cx:cx+x]\r\n\t\t\t\t\textract = extract.flatten()\r\n\t\t\t\t\tout = np.concatenate((out,extract))\r\n\t\t\t\t\tbreak\r\n\t\t\t\telse:\r\n\t\t\t\t\tcontinue\r\n\t\t\t\t\t# print (\"Caught a blacked out area\")\r\n\t\t\t\t\t# print (cy,cx)\r\n\tnp.savez_compressed(fileout,info=info,image_vector=out)\r\nextractBackground(\"background.npz\")\r\n#Scale imagesets to correct size\r\n# x = 2800\r\n# y = 1760\r\n# dst = np.zeros((1760,2800,3),np.uint8)\r\n# for i in range(1,16):\r\n# \twally = cv2.imread(\"imageset/\"+str(i)+\".jpg\")\r\n# \tscaled = cv2.resize(wally,(x,y))\r\n# \tcv2.imwrite(\"scaled_imageset/\"+str(i)+\".jpg\",scaled)\r\n\r\n","sub_path":"extract_wally.py","file_name":"extract_wally.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"442181891","text":"from bisect import bisect_left\nfrom datetime import datetime\nimport pytz\nfrom utils import log\n\ntimezone = pytz.timezone('America/Sao_Paulo')\n\n\nclass Transport:\n '''interface for transport type classes'''\n\n def next_departure(self, tg_timestamp, lst_range):\n pass\n\n def validate_request(self, tg_timestamp, args=[1]):\n '''validate params before process the bus schedule'''\n try:\n rng = None\n if len(args) != 0:\n rng = int(args[0])\n if rng < 1:\n return f'{rng} não dá, né amigão...'\n else:\n rng = 1\n return self.next_departure(tg_timestamp, rng)\n except (TypeError, ValueError):\n error_msg = 'o parametro tem que ser um número...'\n log.error(error_msg)\n return error_msg\n\n def nearest_time(self, time, times):\n '''find the next time base on telegram datetime'''\n pos = bisect_left(a=times, x=time, hi=len(times) - 1)\n if pos == 0:\n return times[0]\n if pos == len(times):\n return times[-1]\n after = times[pos]\n \n log.debug(f'pos {pos}, after: {after}')\n return after\n\n # rng = value range\n def next_items(self, rng, time, times):\n '''return 'n' next itens in the datetime list based on 'time' and 'rng' params'''\n if(rng is 1):\n return time.strftime('%H:%M')\n idx = times.index(time)\n last_idx = idx + rng\n next_items_lst = [datetime.strftime(d, '%H:%M')\n for d in times[idx: last_idx]]\n res = '\\n'\n\n return res.join(next_items_lst)\n\n def prepare_time(self, tg_timestamp):\n '''convert telegram datetime to São Paulo timezone'''\n sp_time = tg_timestamp.astimezone(timezone).replace(\n year=1900, day=1, month=1, tzinfo=None)\n \n return sp_time\n","sub_path":"services/transport.py","file_name":"transport.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"100019310","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom enum import IntEnum\nfrom typing import List, Tuple\n\nimport cv2\nimport numpy as np\n\nfrom utils.resourceloader import ResourceLoader\nfrom utils.bgextractor import BackgroundExtractor\n\n\nclass KeyValue(IntEnum):\n KEY_C = 1\n KEY_D = 2\n KEY_E = 3\n KEY_F = 4\n KEY_G = 5\n KEY_A = 6\n KEY_B = 7\n KEY_Cs = KEY_Db = 8\n KEY_Ds = KEY_Eb = 9\n KEY_Fs = KEY_Gb = 10\n KEY_Gs = KEY_Ab = 11\n KEY_As = KEY_Bb = 12\n\n @staticmethod\n def ordered_keys():\n return [KeyValue.KEY_C, KeyValue.KEY_Cs,\n KeyValue.KEY_D, KeyValue.KEY_Ds,\n KeyValue.KEY_E,\n KeyValue.KEY_F, KeyValue.KEY_Fs,\n KeyValue.KEY_G, KeyValue.KEY_Gs,\n KeyValue.KEY_A, KeyValue.KEY_As,\n KeyValue.KEY_B]\n\n @staticmethod\n def to_string(key_value: int) -> str:\n if key_value is None or key_value < 1 or key_value > 12:\n return \"\"\n return [\"\", \"C\", \"D\", \"E\", \"F\", \"G\", \"A\", \"B\", \"C#\", \"D#\", \"F#\", \"G#\", \"A#\"][key_value]\n\n @staticmethod\n def sharp(key_value: int) -> int:\n if key_value < 1 or key_value > 12:\n return 0\n keys = KeyValue.ordered_keys()\n return keys[(keys.index(key_value) + 1) % len(keys)]\n\n @staticmethod\n def flat(key_value: int) -> int:\n if key_value < 1 or key_value > 12:\n return 0\n keys = KeyValue.ordered_keys()\n return keys[(keys.index(key_value) + len(keys) - 1) % len(keys)]\n\n\nclass KeyMask:\n\n id: KeyValue\n octave: int\n\n def __init__(self, contour, yf, yi=0):\n if len(contour) != 4:\n raise RuntimeError(\"Invalid key contours\")\n\n self.id = None\n self.octave = 0\n\n self.yi = yi\n self.yf = yf\n\n contour.sort(key=lambda p: p[1])\n\n initial_points = contour[0:2]\n initial_points.sort(key=lambda p: p[0])\n\n final_points = contour[2:4]\n final_points.sort(key=lambda p: p[0])\n\n self.x1i = KeyMask.calc_x(yi, *initial_points[0], *final_points[0])\n self.x1f = KeyMask.calc_x(yf, *initial_points[0], *final_points[0])\n\n self.x2i = KeyMask.calc_x(yi, *initial_points[1], *final_points[1])\n self.x2f = KeyMask.calc_x(yf, *initial_points[1], *final_points[1])\n\n # utils\n self.xi = int((self.x2i + self.x1i) / 2)\n self.xf = int((self.x2f + self.x1f) / 2)\n self.pi = (self.xi, self.yi)\n self.pf = (self.xf, self.yf)\n\n @property\n def contour(self) -> List[Tuple[int, int]]:\n return [(self.x2i, self.yi), (self.x1i, self.yi), (self.x1f, self.yf), (self.x2f, self.yf)]\n\n @property\n def area(self) -> int:\n return cv2.contourArea(np.array(self.contour))\n\n @property\n def left_line(self) -> List[Tuple[int, int]]:\n return [(self.x1i, self.yi), (self.x1f, self.yf)]\n\n @property\n def right_line(self) -> List[Tuple[int, int]]:\n return [(self.x2i, self.yi), (self.x2f, self.yf)]\n\n @property\n def pixel_value(self) -> int:\n return KeyMask.encode(self.id, self.octave)\n\n @staticmethod\n def calc_x(y: float, x1: float, y1: float, x2: float, y2: float) -> int:\n return int((x2 - x1) * (y - y1) / (y2 - y1) + x1)\n\n @staticmethod\n def decode(pixel: int) -> Tuple[KeyValue, int]:\n octave = (pixel & 0b011110000) >> 4\n note = (pixel & 0b01111)\n return KeyValue(note), octave\n\n @staticmethod\n def encode(note: KeyValue, octave: int) -> int:\n if note is None:\n return 255\n return (int(note) & 0b01111) | ((octave & 0b01111) << 4)\n\n\nclass KeyboardMask:\n edges: np.ndarray\n thresh: np.ndarray\n vlimit: int\n bkeys: List[KeyMask]\n wkeys: List[KeyMask]\n\n def __init__(self, keyboard: np.ndarray):\n\n shape = keyboard.shape\n if len(shape) > 2:\n shape = (shape[0], shape[1])\n\n self.edges = np.zeros(shape)\n self.thresh = np.zeros(shape)\n\n self.vlimit = shape[0]\n\n self.bkeys = []\n self.wkeys = []\n\n def addKey(self, contour: list):\n\n if len(contour) != 4:\n raise RuntimeError(\"Invalid key contours\")\n\n key = KeyMask(contour, self.vlimit)\n self.bkeys.append(key)\n\n def createMask(self, visual: bool = False):\n\n # Font cuz unicorns exist\n font = cv2.FONT_HERSHEY_SIMPLEX\n\n mask = np.zeros(self.thresh.shape).astype('uint8')\n\n swap = False\n for key in self.wkeys:\n # Create the key in mask\n if visual:\n cv2.fillPoly(mask, [np.intp(key.contour)], 64 if swap else 32)\n swap = not swap\n\n text = KeyValue.to_string(key.id) + str(key.octave)\n cv2.putText(mask, text, (key.xf, self.thresh.shape[0] - 50), font, 0.4, 255, 1, cv2.LINE_AA)\n else:\n cv2.fillPoly(mask, [np.intp(key.contour)], key.pixel_value)\n\n for key in self.bkeys:\n # Create the key in mask\n if visual:\n cv2.fillPoly(mask, [np.intp(key.contour)], 127)\n\n text = KeyValue.to_string(key.id) + str(key.octave)\n cv2.putText(mask, text, (key.xi, 50), font, 0.4, 255, 1, cv2.LINE_AA)\n else:\n cv2.fillPoly(mask, [np.intp(key.contour)], key.pixel_value)\n\n return mask\n\n @property\n def top_x_array(self):\n return np.ravel(sorted([[k.x1i, k.x2i] for k in self.bkeys], key=lambda p: p[0]))\n\n @property\n def bottom_x_array(self):\n return np.ravel(sorted([[k.x1f, k.x2f] for k in self.bkeys], key=lambda p: p[0]))\n\n @property\n def black_x_array(self):\n return [i for i in zip(self.top_x_array, self.bottom_x_array)]\n\n\nclass Keyboard:\n resource: ResourceLoader\n image: np.ndarray\n cropped: np.ndarray\n mask: KeyboardMask\n\n def __init__(self, resource: ResourceLoader):\n \"\"\"\n\n :param resource: Video\n \"\"\"\n\n self.resource = resource\n resource.create(\"keyboard\")\n\n self.image = None\n self.cropped = None\n self.mask = None\n\n def loadImage(self, auto=True, debug=False):\n\n image_name = self.resource[\"keyboard\"]\n\n if not image_name.exists():\n\n if not auto:\n raise RuntimeError(str(image_name) + \" doesn't exists!\")\n\n if debug:\n print(\"Creating keyboard imagem ...\")\n\n background = BackgroundExtractor(self.resource.videoname).run()\n cv2.imwrite(str(image_name), background)\n\n if debug:\n print(\"Done!\")\n\n self.image = cv2.cvtColor(background, cv2.COLOR_GRAY2BGR)\n else:\n self.image = cv2.imread(str(image_name))\n","sub_path":"src/pianovision/keyboard/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"495848111","text":"from collections import namedtuple\r\nimport items\r\nfrom random import choice, randint\r\nfrom globals import news\r\nimport wlib\r\n\r\nBadge = namedtuple(\"Badge\", \"name condition reward appearance color\")\r\n\r\ndef trapstep(player, map):\r\n pass\r\n \r\ndef wander1reward():\r\n pass\r\n \r\ndef gray_badge(badge, gray_color=0):\r\n return list(map(lambda b: (b[0], gray_color), badge))\r\n \r\ndef badge_check(player):\r\n if len(player.zones_visited) == 3 and \"wanderer1\" not in player.badges:\r\n player.badges.add(\"wanderer1\")\r\n name = choice(list(items.items.keys()))\r\n player.inventory.append(items.make_item(name))\r\n news.append(\"you acheived Wanderer One! Your prize is a %s\" % name)\r\n if len(player.zones_visited) == 2 and \"wanderer2\" not in player.badges:\r\n player.badges.add(\"wanderer2\")\r\n player.inventory.append(items.make_item(\"a teleporter\"))\r\n if player.gold >= 30 and \"wanderer1\" not in player.badges:\r\n player.badges.add(\"milionair\")\r\n if player.swims >= 100 and \"wanderer1\" not in player.badges:\r\n player.badges.add(\"swimer\")\r\n if player.ktn >= 7 and \"wanderer1\" not in player.badges:\r\n player.badges.add(\"murderer\")\r\n \r\n \r\n \r\n\r\n \r\ndef badge_check2(player):\r\n badge_conditions = [\r\n (\"wanderer1\", lambda p: len(p.zones_visited) >= 3, items.make_item(choice(list(items.items.keys())))),\r\n (\"wanderer2\", lambda p: len(p.zones_visited) >= 2, items.make_item(\"a teleporter\")),\r\n (\"milionair\", lambda p: p.gold >= 50, items.make_item(\"amazon\")),\r\n (\"swimer\", lambda p: p.swims >= 100, items.make_item(\"amazon\")),\r\n (\"murderer\", lambda p: p.ktn >= 7, items.make_item(\"amazon\"))]\r\n badges = list(filter(lambda b: b[1](player), badge_conditions))\r\n for name, f, item in badges:\r\n if name not in player.badges: \r\n player.badges.add(\"%s\" % name)\r\n news.append(\"you have gotten the %s badge\" % name)\r\n player.inventory.append(item)\r\n \r\n \r\n \r\nw1_viewl1 = [\r\n\" \",\r\n\" w1 \",\r\n' \" \" ']\r\n \r\nw1_viewl2 = [\r\n\"_= =_\",\r\n\"\\\\ /\",\r\n' == ']\r\n \r\nw1_viewl3 = [\r\n\" <> \",\r\n\" + + \",\r\n' ']\r\n \r\nw1_view = [(w1_viewl1, 3), (w1_viewl2, 21), (w1_viewl3, 2)] \r\n \r\nsw_viewl1 = [ \r\n\" ~ ~ \",\r\n \" sw \",\r\n \" ~ ~ \" ]\r\n \r\nsw_viewl2 = [\r\n \"_ <> _\",\r\n\"\\\\ /\",\r\n \" () \" ]\r\n \r\nsw_viewl3 = [ \r\n\" \",\r\n\" ( ) \",\r\n\" \"]\r\n\r\nsw_view = [(sw_viewl1, 12), (sw_viewl2, 21), (sw_viewl3, 5)] \r\n\r\nw2_viewl1 = [\r\n\" \",\r\n\" w2 \",\r\n' ' ]\r\n \r\nw2_viewl2 = [\r\n\"_ <> _\",\r\n\"\\\\ /\",\r\n' :: ' ]\r\n \r\nw2_viewl3 = [\r\n\" \\ / \",\r\n\" \",\r\n' \" \" ' ]\r\n\r\nw2_viewl4 = [\r\n\" \",\r\n\" # # \",\r\n' ' ]\r\n\r\nw2_view = [(w2_viewl1, 14), (w2_viewl2, 21), (w2_viewl3, 3), (w2_viewl4, 2)]\r\n\r\nmi_viewl1 = [\r\n\"_ <> _\",\r\n\"\\\\ $$ /\",\r\n' == ' ]\r\n \r\nmi_viewl2 = [\r\n\" = = \",\r\n\" 0 0 \",\r\n' ' ]\r\n \r\nmi_viewl3 = [\r\n\" \",\r\n\" \",\r\n' * * ' ]\r\n\r\n\r\n\r\nmi_view = [(mi_viewl1, 21), (mi_viewl2, 2), (mi_viewl3, 0)]\r\n\r\nMM_viewl1 = [\r\n\" < > \",\r\n\" MM \",\r\n' < > ' ]\r\n \r\nMM_viewl2 = [\r\n\" <> \",\r\n\" % % \",\r\n' ' ]\r\n \r\nMM_viewl3 = [\r\n\"_ _\",\r\n\"\\ /\",\r\n' WW ' ]\r\n\r\nMM_view = [(MM_viewl1, 5), (MM_viewl2, 14), (MM_viewl3, 21)]\r\n\r\n \r\nbadges = [ Badge(\"wanderer1\", trapstep, wander1reward, w1_view, 3),\r\n Badge(\"wanderer2\", trapstep, wander1reward, w2_view, 2), \r\n Badge(\"murderer\", trapstep, wander1reward, MM_view, 9),\r\n Badge(\"milionair\", trapstep, wander1reward, mi_view, 21),\r\n Badge(\"swimer\", trapstep, wander1reward, sw_view, 12)]","sub_path":"acheivements.py","file_name":"acheivements.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"234540390","text":"\"\"\"Test sobel vs gradient.\"\"\"\nimport os\nfrom typing import Tuple\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport src.constants as cst\nimport src.plot_utils.latex_style as lsty\nimport src.plot_utils.xarray_panels as xp\nimport src.time_wrapper as twr\nfrom scipy import signal\n\n\ndef sobel_np(values: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Sobel operator on np array.\n\n https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html\n\n Args:\n values (np.ndarray): values to differentiate.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: gx, gy\n \"\"\"\n sobel = np.array(\n [\n [1 + 1j, 0 + 2j, -1 + 1j],\n [2 + 0j, 0 + 0j, -2 + 0j],\n [1 - 1j, 0 - 2j, -1 - 1j],\n ]\n ) # Gx + j*Gy\n grad = signal.convolve2d(values, sobel, boundary=\"symm\", mode=\"same\")\n return np.real(grad), np.imag(grad)\n\n\n@twr.timeit\ndef sobel_vs_grad() -> None:\n \"\"\"\n Sobel versus dimension.\n \"\"\"\n lsty.mpl_params()\n\n ds = xr.open_dataset(cst.DEFAULT_NC)\n da_temp = ds.PCA_VALUES.isel(time=cst.EXAMPLE_TIME_INDEX)\n\n pc1_y: xr.DataArray = da_temp.isel(pca=0)\n pc1_y.values = sobel_np(pc1_y.values)[1]\n pc2_y: xr.DataArray = da_temp.isel(pca=1)\n pc2_y.values = sobel_np(pc2_y.values)[1]\n pc3_y: xr.DataArray = da_temp.isel(pca=2)\n pc3_y.values = sobel_np(pc3_y.values)[1]\n\n xp.sep_plots(\n [pc1_y, pc2_y, pc3_y],\n [\"$G_y$ * PC1\", \"$G_y$ * PC2\", \"$G_y$ * PC3\"],\n [[-40, 40], [-40, 40], [-40, 40]],\n )\n\n plt.savefig(\n os.path.join(cst.FIGURE_PATH, \"RUN_\" + cst.RUN_NAME + \"_example_pcy.png\")\n )\n plt.clf()\n\n pc1_x: xr.DataArray = da_temp.isel(pca=0)\n pc1_x.values = sobel_np(pc1_x.values)[0]\n pc2_x: xr.DataArray = da_temp.isel(pca=1)\n pc2_x.values = sobel_np(pc2_x.values)[0]\n pc3_x: xr.DataArray = da_temp.isel(pca=2)\n pc3_x.values = sobel_np(pc3_x.values)[0]\n\n xp.sep_plots(\n [pc1_x, pc2_x, pc3_x],\n [\"$G_x$ * PC1\", \"$G_x$ * PC2\", \"$G_x$ * PC3\"],\n [[-40, 40], [-40, 40], [-40, 40]],\n )\n\n plt.savefig(\n os.path.join(cst.FIGURE_PATH, \"RUN_\" + cst.RUN_NAME + \"_example_pcx.png\")\n )\n plt.clf()\n\n da_y = ds.PCA_VALUES.isel(time=cst.EXAMPLE_TIME_INDEX).differentiate(cst.Y_COORD)\n xp.sep_plots(\n [da_y.isel(pca=0), da_y.isel(pca=1), da_y.isel(pca=2)],\n [\"PC1 y-grad\", \"PC2 y-grad\", \"PC3 y-grad\"],\n [[-20, 20], [-20, 20], [-20, 20]],\n )\n\n plt.savefig(\n os.path.join(cst.FIGURE_PATH, \"RUN_\" + cst.RUN_NAME + \"_example_pc_y.png\")\n )\n plt.clf()\n\n da_x = ds.PCA_VALUES.isel(time=cst.EXAMPLE_TIME_INDEX).differentiate(cst.X_COORD)\n xp.sep_plots(\n [da_x.isel(pca=0), da_x.isel(pca=1), da_x.isel(pca=2)],\n [\"PC1 x-grad\", \"PC2 x-grad\", \"PC3 x-grad\"],\n [[-20, 20], [-20, 20], [-20, 20]],\n )\n\n plt.savefig(\n os.path.join(cst.FIGURE_PATH, \"RUN_\" + cst.RUN_NAME + \"_example_pc_x.png\")\n )\n plt.clf()\n\n\ndef sobel_scharr_test() -> None:\n \"\"\"Test scharr / sobel.\"\"\"\n da = xr.DataArray(np.random.randn(15, 30), dims=[cst.X_COORD, cst.Y_COORD])\n # kernel = xr.DataArray(filter, dims=[\"kx\", \"ky\"])\n # da_new = da.rolling(XC=3, YC=3).construct(XC=\"kx\", YC=\"ky\").dot(kernel)\n val = da.values\n print(\"val\", val)\n\n # print(da_new)\n scharr = np.array(\n [\n [-3 - 3j, 0 - 10j, +3 - 3j],\n [-10 + 0j, 0 + 0j, +10 + 0j],\n [-3 + 3j, 0 + 10j, +3 + 3j],\n ]\n ) # Gx + j*Gy\n sobel = np.array(\n [\n [1 + 1j, 0 + 2j, -1 + 1j],\n [2 + 0j, 0 + 0j, -2 + 0j],\n [1 - 1j, 0 - 2j, -1 - 1j],\n ]\n ) # Gx + j*Gy\n\n for filt in [sobel, scharr]:\n\n grad = signal.convolve2d(val, filt, boundary=\"symm\", mode=\"same\")\n\n gx = np.real(grad)\n gy = np.imag(grad)\n\n print(gx)\n print(gy)\n # print(grad)\n\n _, (ax_orig, ax_mag, ax_ang) = plt.subplots(3, 1, figsize=(6, 15))\n ax_orig.imshow(val, cmap=\"gray\")\n ax_orig.set_title(\"Original\")\n ax_orig.set_axis_off()\n ax_mag.imshow(np.absolute(grad), cmap=\"gray\")\n ax_mag.set_title(\"Gradient magnitude\")\n ax_mag.set_axis_off()\n ax_ang.imshow(np.angle(grad), cmap=\"hsv\") # hsv is cyclic, like angles\n ax_ang.set_title(\"Gradient orientation\")\n ax_ang.set_axis_off()\n # fig.show()\n plt.savefig(\"example.png\")\n\n\ndef grad_v() -> None:\n \"\"\"Gradient in v direction.\"\"\"\n ds = xr.open_dataset(cst.DEFAULT_NC)\n da_y = ds.PCA_VALUES.isel(time=cst.EXAMPLE_TIME_INDEX).differentiate(cst.Y_COORD)\n xp.sep_plots(\n [da_y.isel(pca=0), da_y.isel(pca=1), da_y.isel(pca=2)],\n [\"PC1 y-grad\", \"PC2 y-grad\", \"PC3 y-grad\"],\n )\n\n pc_y_grad_name = os.path.join(\n cst.FIGURE_PATH, \"RUN_\" + cst.RUN_NAME + \"_y_grad.png\"\n )\n plt.savefig(pc_y_grad_name)\n plt.clf()\n\n\nif __name__ == \"__main__\":\n sobel_vs_grad()\n # python3 src/sobel.py\n","sub_path":"src/models/sobel.py","file_name":"sobel.py","file_ext":"py","file_size_in_byte":5031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"60809938","text":"#!/usr/bin/python\n\nfrom modules import util\nfrom konlpy.tag import Komoran\nimport re\n\n\npath = \"C:\\\\crawllica_output\\\\191017\\\\1630\\\\D_K_01\"\nfilelist = util.get_filelist(path)\n\n\nfile = filelist[0]\nwith open(file, 'r', encoding='utf-8') as fp:\n komoran = Komoran()\n lines = []\n while True:\n try:\n line = fp.readline()\n if not line: \n break\n\n line = re.sub(\"\\xa0\", \" \", line).strip()\n if line == \"\" : \n continue\n\n tokens = komoran.pos(line)\n if len(tokens) == 0: \n continue\n\n lines.append(tokens)\n\n except Exception as e:\n print(e)\n continue\n\nfor line in lines:\n print(line)","sub_path":"prototype/analysis/analyza/komorantest.py","file_name":"komorantest.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"280222882","text":"from scanner import *\nimport sys\nimport os\n\ndef main():\n\n f = sys.argv[1]\n evaluate(scan(f))\n \ndef scan(name):\n\n s = Scanner(os.path.join(sys.path[0],name))\n num = []\n token = s.readfloat()\n while (token != \"\"):\n num.append(token)\n token = s.readfloat()\n s.close\n return num\n\ndef evaluate(name):\n\n largest = name[0]\n for i in range(0, len(name), 1):\n if( name[i] > largest):\n largest = name[i]\n print(\"The highest number is \", largest)\n\nmain()\n","sub_path":"final/dul/pi.py","file_name":"pi.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"86533676","text":"import json\nimport sys\nimport spotipy\nimport spotipy.util as util\nimport pprint\n\nuser_id = \"1239227809\"\nscope = 'playlist-read-private playlist-modify-private playlist-read-collaborative playlist-modify-public'\nclient_id = \"c39874c67d6244969b9bff05d5004c90\"\nclient_secret = \"34d28707c0544ce9a9a080cb42c9b972\"\ntoken = util.prompt_for_user_token(user_id,scope, client_id = client_id, client_secret = client_secret, redirect_uri = \"https://example.com/callback/\")\n#client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)\n#sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\nsp = spotipy.Spotify(auth = token)\n\nname1 = input(\"Song #1 Name: \") + \" \"\nartist1 = input(\"Song #1 Artist: \")\nname2 = input(\"Song #2 Name: \") + \" \"\nartist2 = input(\"Song #2 Artist: \")\nname3 = input(\"Song #3 Name: \") + \" \"\nartist3 = input(\"Song #3 Artist: \")\nname4 = input(\"Song #4 Name: \") + \" \"\nartist4 = input(\"Song #4 Artist: \")\nname5 = input(\"Song #5 Name: \") + \" \"\nartist5 = input(\"Song #5 Artist: \")\n\nname = \"newSongs\"\n\nresult1 = sp.search(q= name1 + artist1, limit=1)\nid1 = result1['tracks']['items'][0]['id']\nresult2 = sp.search(q= name2 + artist2, limit=1)\nid2 = result2['tracks']['items'][0]['id']\nresult3 = sp.search(q= name3 + artist3, limit=1)\nid3 = result3['tracks']['items'][0]['id']\nresult4 = sp.search(q= name4 + artist4, limit=1)\nid4 = result4['tracks']['items'][0]['id']\nresult5 = sp.search(q= name5 + artist5, limit=1)\nid5 = result5['tracks']['items'][0]['id']\n\norig_ids = [id1, id2, id3, id4, id5]\n\norig_tracks = []\norig_features = []\n\nfor i in orig_ids:\n orig_tracks.append(sp.track(i))\n orig_features.append(sp.audio_features(i))\n\norig_data = [] \n\nrecommend = sp.recommendations(seed_tracks = orig_ids, limit = 100)\n\nrecommend_ids = []\n\nfor i in recommend['tracks']:\n recommend_ids.append(i['id'])\n\nrecommend_tracks = []\nrecommend_features = []\n\nfor i in recommend_ids:\n recommend_tracks.append(sp.track(i))\n recommend_features.append(sp.audio_features(i))\n\nrecommend_data = []\n\nprint(\"[popularity, explicit, duration, tempo, mode, danceability, energy, speechiness, loudness, acousticness, artist, name]\", \"\\n\")\n\nprint(\"\\n\", \"Input data\", \"\\n\")\n\nfor i in range(0, len(orig_ids)):\n orig_data.append([orig_tracks[i]['popularity'], orig_tracks[i]['explicit'],\n orig_features[i][0]['duration_ms'],\n orig_features[i][0]['tempo'],\n orig_features[i][0]['mode'],\n orig_features[i][0]['danceability'],\n orig_features[i][0]['energy'],\n orig_features[i][0]['speechiness'],\n orig_features[i][0]['loudness'],\n orig_features[i][0]['acousticness'],\n orig_tracks[i]['artists'][0]['name'],\n orig_tracks[i]['name']])\n\nfor i in orig_data:\n print(i, \"\\n\")\n\nprint(\"\\n\", \"Output data\", \"\\n\")\n\nfor i in range(0, len(recommend_ids)):\n recommend_data.append([recommend_tracks[i]['popularity'], recommend_tracks[i]['explicit'],\n recommend_features[i][0]['duration_ms'],\n recommend_features[i][0]['tempo'],\n recommend_features[i][0]['mode'],\n recommend_features[i][0]['danceability'],\n recommend_features[i][0]['energy'],\n recommend_features[i][0]['speechiness'],\n recommend_features[i][0]['loudness'],\n recommend_features[i][0]['acousticness'],\n recommend_tracks[i]['artists'][0]['name'],\n recommend_tracks[i]['name']])\n\nfor i in recommend_data:\n print(i, \"\\n\")\n \n#playlist_id = sp.user_playlist_create(user_id, name)['id']\n\n#sp.user_playlist_add_tracks(user_id, playlist_id, [id1, id2, id3, id4, id5])\n\n \n\n \n\n\n","sub_path":"code/jsonloader.py","file_name":"jsonloader.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"372080420","text":"#!/usr/bin/env python3\n\"\"\"Plot the live microphone signal(s) with matplotlib.\n\nMatplotlib and NumPy have to be installed.\n\n\"\"\"\nimport argparse\nimport queue\nimport sys\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sounddevice as sd\nimport librosa\nimport librosa.display\nimport collections\n\n\ndef int_or_str(text):\n \"\"\"Helper function for argument parsing.\"\"\"\n try:\n return int(text)\n except ValueError:\n return text\n\n\nparser = argparse.ArgumentParser(add_help=False)\nparser.add_argument(\n '-l', '--list-devices', action='store_true',\n help='show list of audio devices and exit')\nargs, remaining = parser.parse_known_args()\nif args.list_devices:\n print(sd.query_devices())\n parser.exit(0)\nparser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n parents=[parser])\nparser.add_argument(\n 'channels', type=int, default=[1], nargs='*', metavar='CHANNEL',\n help='input channels to plot (default: the first)')\nparser.add_argument(\n '-d', '--device', type=int_or_str,\n help='input device (numeric ID or substring)')\nparser.add_argument(\n '-w', '--window', type=float, default=200, metavar='DURATION',\n help='visible time slot (default: %(default)s ms)')\nparser.add_argument(\n '-i', '--interval', type=float, default=30,\n help='minimum time between plot updates (default: %(default)s ms)')\nparser.add_argument(\n '-b', '--blocksize', type=int, help='block size (in samples)')\nparser.add_argument(\n '-r', '--samplerate', type=float, help='sampling rate of audio device')\nparser.add_argument(\n '-n', '--downsample', type=int, default=10, metavar='N',\n help='display every Nth sample (default: %(default)s)')\nargs = parser.parse_args(remaining)\nif any(c < 1 for c in args.channels):\n parser.error('argument CHANNEL: must be >= 1')\nmapping = [c - 1 for c in args.channels] # Channel numbers start with 1\nq = queue.Queue()\nmpl.use('TKAgg', force=True)\nfig, ax = plt.subplots()\nd = collections.deque(maxlen=10000)\n\ndef audio_callback(indata, frames, time, status):\n \"\"\"This is called (from a separate thread) for each audio block.\"\"\"\n # if status:\n # print(status, file=sys.stderr)\n # Fancy indexing with mapping creates a (necessary!) copy:\n q.put(indata[::args.downsample, mapping])\n\ntry:\n stream = sd.InputStream(\n device=args.device, channels=max(args.channels),\n samplerate=args.samplerate, callback=audio_callback)\n with stream:\n try:\n while True:\n # print(\"stream params\", stream.blocksize, stream.samplerate, stream.samplesize, stream.latency)\n sd.sleep(3 * 1000)\n data_raw = [(q.get_nowait()).flatten() for i in range(q.qsize())]\n d.extend(data_raw)\n frames = (np.hstack(d)).flatten()\n melspec = librosa.feature.melspectrogram(y=frames, sr=stream.samplerate, n_mels=224, fmax=4000)\n print(f\"Frames array: {frames.shape}, Melspec array: {melspec.shape}\")\n data_out = librosa.core.power_to_db(melspec, ref=np.max)\n librosa.display.specshow(data_out, y_axis='mel', fmax=4000, x_axis='time')\n plt.draw()\n plt.pause(0.0001)\n plt.clf()\n except KeyboardInterrupt:\n pass\n\nexcept Exception as e:\n parser.exit(type(e).__name__ + ': ' + str(e))\n","sub_path":"edge/live_melspec.py","file_name":"live_melspec.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"364766501","text":"import random\n\ndef counting_sort(A, k):\n\t'''\n\tInput: Sequence A containing elements in the range 0 to k, integer k where k is the maximum value in A.\n\tOutput: Sorted sequence B\n\n\tSorts in O(n) time and 3n space\n\t'''\n\tn = len(A)\n\tB = [0 for n in A]\n\tC = [0 for n in range(k+1)]\n\tfor j in range(n):\n\t\tC[A[j]] += 1\n\t#C[i] now contains the number of elements in A equal to i\t\n\tfor i in range(1,k+1):\n\t\tC[i] += C[i-1] \n\tC = [n-1 for n in C]\n\t#C[i] now contains the number of elements in A less than or equal to i\n\t#Do the sorting into B\n\tfor j in range(n-1, -1, -1):\n\t\tB[C[A[j]]] = A[j]\n\t\tC[A[j]] -= 1 #if there are duplicates in A, this puts the duplicate(s) in the position before A[j]\n\treturn B\n\n\nif __name__ == '__main__':\n\tA = [2, 5, 3, 0, 2, 3, 0, 3] \n\tk = max(A)\n\tprint(counting_sort(A,k))\n\n","sub_path":"Python3/counting_sort.py","file_name":"counting_sort.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"266947438","text":"import os\nimport io\nimport hashlib\nimport logging\n\nfrom PIL import Image\nfrom django.core.cache import cache\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImageThumbnailMixin:\n \"\"\"\n Before to use, you should set IMAGE_FIELD, THUMBNAIL_FIELD, BASE_SIZE first,\n\n for example:\n\n class User(models.Model, ImageThumbnailMixin):\n name = models.CharField(max_length=100)\n avatar = models.ImageField(upload_to=settings.UPLOAD_TO, null=True, blank=True)\n thumbnail = models.Image(upload_to=settings.UPLOAD_TO, null=True, blank=True)\n\n IMAGE_FIELD, THUMBNAIL_FIELD, BASE_SIZE = \"avatar\", \"thumbnail\", 100\n\n def save(self, *args, **kwargs):\n res = super().save(*args, **kwargs)\n self.create_thumbnail() # should put after super calling\n return res\n\n \"\"\"\n\n IMAGE_FIELD, THUMBNAIL_FIELD, THUMBNAIL_BASE_SIZE = None, None, 200\n\n def __init__(self, *args, **kwargs):\n assert self.IMAGE_FIELD is not None, \"ImageThumbnailMixin should set IMAGE_FIELD first\"\n assert self.THUMBNAIL_FIELD is not None, \"ImageThumbnailMixin should set THUMBNAIL_FIELD first\"\n self.key_prefix = \"IMAGE_CACHE_{0}\".format(self.__class__.__name__)\n super(ImageThumbnailMixin, self).__init__(*args, **kwargs)\n\n def cache_old_image_md5(self):\n image_md5 = self.get_image_md5()\n key = \"{0}_{1}\".format(self.key_prefix, self.id)\n cache.set(key, image_md5)\n\n def get_image_md5(self):\n image = getattr(self, self.IMAGE_FIELD)\n if not image or not image._file:\n return None\n md5 = hashlib.md5()\n for chunk in image.chunks():\n md5.update(chunk)\n val = md5.hexdigest()\n image.seek(0)\n logger.debug(\"Image md5 val: %s\", val)\n return val\n\n def image_changed(self):\n key = \"{0}_{1}\".format(self.key_prefix, self.id)\n cached_md5 = cache.get(key)\n new_md5 = self.get_image_md5()\n logger.debug(\"Cached Image Md5: %s\", cached_md5)\n logger.debug(\"New Image Md5: %s\", new_md5)\n if cached_md5 != new_md5:\n self.cache_old_image_md5()\n return cached_md5 != new_md5\n\n def get_image_format(self):\n try:\n image = getattr(self, self.IMAGE_FIELD)\n f = io.BytesIO(image.read())\n img = Image.open(f)\n image.seek(0)\n return img.format\n except OSError as exc:\n logger.error(\"Get image file format error: %s\", exc)\n return None\n\n def create_thumbnail(self):\n \"\"\"\n Create model image field thumbnail\n \"\"\"\n\n image_field = getattr(self, self.IMAGE_FIELD)\n thumbnail_field = getattr(self, self.THUMBNAIL_FIELD)\n\n logger.debug(\"===== Now check the image validation: %s\", image_field.name)\n img_format = self.get_image_format()\n # image field not set or file is not image or image not changed\n if not image_field or not img_format or not self.image_changed():\n logger.error(\"===== Skip create thumbnail\")\n return\n logger.debug(\"Done\")\n\n logger.debug(\"====== Now Create thumbnail for the given image: %s\", image_field.name)\n\n django_type = \"image/{0}\".format(img_format.lower())\n pil_type, file_extension = \"jpeg\", 'jpg'\n\n if django_type == \"image/png\":\n pil_type, file_extension = 'png', 'png'\n img = Image.open(io.BytesIO(image_field.read()))\n w_percent = self.THUMBNAIL_BASE_SIZE / float(img.size[0])\n h_size = int(float(img.size[1]) * w_percent)\n img.thumbnail([self.THUMBNAIL_BASE_SIZE, h_size], Image.ANTIALIAS)\n\n temp_handler = io.BytesIO()\n img.save(temp_handler, pil_type)\n temp_handler.seek(0)\n base_name = os.path.splitext(os.path.split(image_field.name)[-1])[0]\n file_name = '{0}_thumbnail.{1}'.format(base_name, file_extension)\n suf = SimpleUploadedFile(file_name, temp_handler.read(),\n content_type=django_type)\n thumbnail_field.save(file_name, suf, save=False)\n\n logger.debug(\"Done\")\n","sub_path":"common/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"419201572","text":"import argparse\nimport requests\nimport html\n\nparser = argparse.ArgumentParser()\nparser.add_argument('question_number', type=int)\nparser.add_argument('label', type=str)\nargs = parser.parse_args()\n\nsession = requests.Session()\n\nURL = 'https://api.stackexchange.com/2.2/questions'\n\n\nclass QuotaOverflow(Exception):\n pass\t\n \n \ndef get_pagesizes_range(number):\n result = []\n for _ in range(number // 100):\n result.append(100)\n if number % 100 != 0:\n result.append(number % 100)\n return result\n \n \ndef top_questions(number, label):\n pagesizes = get_pagesizes_range(number)\n try:\n top_ques = []\n for page, pagesize in enumerate(pagesizes, 1):\n \t params = {\"page\": page, \"pagesize\": pagesize,\n \t \"order\": \"desc\", \"sort\": \"votes\",\n \t \"tagged\": label, \"site\": \"stackoverflow\"}\n \t resp = session.get(URL, params=params).json()[\"items\"]\n \t for item in resp:\n \t \ttitle = html.unescape(item[\"title\"])\n \t \tquestion_id = item['question_id']\n \t \ttop_ques.append((title, question_id))\n return top_ques\n except Exception:\n \traise QuotaOverflow(\"only make 300 requests per day\")\n \t\n \t\ndef top_answer(question_id):\n link = f'{URL}/{question_id}/answers'\n params = {\"pagesize\": 1, \"order\": \"desc\",\t\n \"sort\": \"votes\", \"site\": \"stackoverflow\"}\n try:\n \tresp = session.get(link, params=params).json()[\"items\"]\n \tanswer = resp[0]['answer_id']\n \treturn answer\n except Exception:\n \traise QuotaOverflow(\"only make 300 requests per day\")\n \t\n \t\ndef main():\n label = args.label\n question_number = args.question_number\n print(f'Top {question_number} questions with tag {label}')\n \n if question_number >= 300:\n \tprint(\"only make 300 requests per day\")\n \treturn\n \t\n questions = top_questions(question_number, label)\n for title, question_id in questions:\n \tanswer_id = top_answer(question_id)\n \tlink_to_answer = f'https://stackoverflow.com/a/{answer_id}'\n \tprint(title, \",answer:\", link_to_answer)\n \t\nif __name__ == \"__main__\":\n main()\t\n \t\n","sub_path":"so.py","file_name":"so.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"54033329","text":"from queries import Neo4JQueryRunner\nfrom consts import *\nimport pandas as pd\nimport numpy as np\nimport sys\n\ninput_filename = sys.argv[1]\n\nNEO4J_URL = sys.argv[2]\nNEO4J_USER = sys.argv[3]\nNEO4J_PASSWORD = sys.argv[4]\n\ndata = pd.read_csv(input_filename, dtype=str).to_dict('records')\n\nrunner = Neo4JQueryRunner(NEO4J_URL, NEO4J_USER, NEO4J_PASSWORD)\n\nprint(\"Uploading relationships...\")\nfor relation in data:\n try:\n id_start = relation['id_start']\n except BaseException:\n print('id_start not present in file! Aborting...')\n try:\n id_end = relation['id_end']\n except BaseException:\n print('id_end not present in file! Aborting...')\n try:\n rel_type = relation['type']\n except BaseException:\n print('type not present in file! Aborting...')\n\n properties = \"\"\n if len(relation) >= 4:\n properties += \" {\"\n for key in relation:\n if key not in ['id_start', 'id_end', 'type']:\n properties += \"{}: '{}',\".format(key, relation[key])\n properties = properties[:-1] + \"}\"\n\n statement_create = \"\"\"\n MATCH (a), (b) \n WHERE ID(a) = {}\n AND ID(b) = {}\n MERGE (a)-[r:{}{}]->(b)\n \"\"\".format(id_start, id_end, rel_type, properties)\n runner.run_query(statement_create)\n\nrunner.close()\n\nprint(\"Done!\")","sub_path":"etl_assessores_alerj/neo4j-upload.py","file_name":"neo4j-upload.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"67298331","text":"from read_files import *\nfrom func_s import write_csv_r\n\n\ntemp_list =[]\n\nfor item in main_list:\n str_num = main_list.index(item)\n col_a = item[0]\n if type(col_a) != int and 'ДО/УРО' in col_a:\n print(col_a)\n if col_a not in dict_sroki:\n temp_list.append([col_a])\n\nwrite_csv_r(temp_list, 'dog_bez_srokov')","sub_path":"proverka_srokov.py","file_name":"proverka_srokov.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"508325519","text":"from django.shortcuts import render\n\nfrom articles.models import Articles\n\n\ndef articles_list(request, article_type):\n articles = Articles.objects.filter(article_type=article_type).order_by('-id')\n context = {\n \"articles\": articles,\n }\n return render(request, 'articles/articles_list.html', context)\n","sub_path":"app/articles/views/articles_list.py","file_name":"articles_list.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"396764544","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def diameterOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root:\n return 0\n \n max_dia, max_len = self.mydiameterOfBinaryTree(root)\n return max_dia\n \n def mydiameterOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # Leaf node condition\n if not root.left and not root.right:\n return 0, 0\n else:\n # Get left subtree's length and dia\n left_len = 0\n left_dia = 0\n if root.left:\n left_dia, left_len = self.mydiameterOfBinaryTree(root.left)\n \n # Get right subtree's length and dia\n right_len = 0\n right_dia = 0\n if root.right:\n right_dia, right_len = self.mydiameterOfBinaryTree(root.right)\n \n # Calculate the root's dia based on left and right subtrees\n root_dia = 0\n if root.left and root.right:\n root_dia = right_len + left_len + 2\n elif root.left:\n root_dia = left_len + 1\n elif root.right:\n root_dia = right_len + 1\n\n # Return the length and dia accordingly\n root_len = max(right_len, left_len) + 1\n root_dia = max(root_dia, left_dia, right_dia)\n \n return root_dia, root_len\n","sub_path":"543. Diameter of Binary Tree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"80573645","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2021/4/30 0030 23:04\r\n# @Author : Daniel Zhang\r\n# @Email : zhangdan_nuaa@163.com\r\n# @File : networks.py\r\n# @Software: PyCharm\r\n\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.nn.parallel import data_parallel\r\n\r\nfrom ACGAN.CustomLayers import GenInitialBlock, GenGeneralResBlock, GenFinalResBlock, \\\r\n DisInitialBlock, DisGeneralResBlock, DisFinalBlock\r\n\r\n\r\nclass Generator(nn.Module):\r\n def __init__(self, cdim=3, hdim=512, channels=[64, 128, 256, 512, 512, 512],\r\n image_size=256, class_num=10, is_mnist=False):\r\n super().__init__()\r\n self.class_num = class_num\r\n if is_mnist:\r\n assert (2 ** len(channels)) * 7 == image_size, '网络层数与图像大小不匹配'\r\n else:\r\n assert (2 ** len(channels)) * 4 == image_size, '网络层数与图像大小不匹配'\r\n\r\n self.layers = nn.ModuleList()\r\n self.layers.append(GenInitialBlock(cdim, hdim, class_num, is_mnist))\r\n\r\n cc, sz = hdim, 4\r\n for ch in channels[::-1]:\r\n self.layers.append(GenGeneralResBlock(in_channels=cc, out_channels=ch, feature_size=sz,\r\n cdim=cdim, class_num=class_num))\r\n cc, sz = ch, sz * 2\r\n self.layers.append(GenFinalResBlock(in_channels=cc, feature_size=sz, cdim=cdim, class_num=class_num))\r\n\r\n # 残差上采样\r\n self.upsampler = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)\r\n\r\n def forward(self, z, label):\r\n label_onehot = torch.zeros(len(label), self.class_num).to(label.device).scatter_(1, label.reshape(-1, 1), 1)\r\n y, out = z, None\r\n for block in self.layers:\r\n y, rgb = block(y, label_onehot)\r\n\r\n if rgb is None:\r\n out += y\r\n break\r\n if out is None:\r\n out = rgb\r\n else:\r\n out = self.upsampler(out) + rgb\r\n return out\r\n\r\n\r\nclass Discriminator(nn.Module):\r\n def __init__(self, cdim=3, hdim=512, channels=[64, 128, 256, 512, 512, 512],\r\n image_size=256, class_num=10, is_mnist=False):\r\n super().__init__()\r\n if is_mnist:\r\n assert (2 ** len(channels)) * 7 == image_size, '网络层数与图像大小不匹配'\r\n else:\r\n assert (2 ** len(channels)) * 4 == image_size, '网络层数与图像大小不匹配'\r\n\r\n self.layers = nn.ModuleList()\r\n cc, sz = channels[0], image_size\r\n self.layers.append(DisInitialBlock(cdim, out_channels=cc, feature_size=sz))\r\n for ch in channels[1:]:\r\n self.layers.append(DisGeneralResBlock(cdim, cc, ch, sz // 2))\r\n cc, sz = ch, sz // 2\r\n self.layers.append(DisFinalBlock(cdim, in_channels=cc, out_channels=hdim,\r\n feature_size=sz // 2, class_num=class_num, is_mnist=is_mnist))\r\n\r\n # 残差下采样\r\n self.downsampler = nn.AvgPool2d(2)\r\n\r\n def forward(self, rgb):\r\n y = rgb\r\n for i, block in enumerate(self.layers):\r\n if i >= 1:\r\n rgb = self.downsampler(rgb)\r\n y = block(y, rgb)\r\n return y\r\n\r\n\r\nclass ACGAN(nn.Module):\r\n def __init__(self, cdim=3, hdim=512, channels=[64, 128, 256, 512, 512, 512],\r\n image_size=256, class_num=10, is_mnist=False):\r\n super().__init__()\r\n\r\n self.hdim = hdim\r\n self.dis = Discriminator(cdim, hdim, channels, image_size, class_num, is_mnist)\r\n self.gen = Generator(cdim, hdim, channels, image_size, class_num, is_mnist)\r\n\r\n def discriminate(self, x):\r\n out = data_parallel(self.dis, x)\r\n logits, probs = out[:, 0], out[:, 1:]\r\n return logits, probs\r\n\r\n def generate(self, z, label):\r\n y = data_parallel(self.gen, (z, label))\r\n return y\r\n\r\n\r\nif __name__ == '__main__':\r\n latent_code = torch.zeros((2, 128)).uniform_(-1, 1)\r\n class_num = 10\r\n label = torch.randint(0, 10, size=(2, ))\r\n\r\n gen = Generator(cdim=3, hdim=128, channels=[32, 64, 128],\r\n image_size=32, class_num=class_num, is_mnist=False)\r\n img = gen(latent_code, label)\r\n print(img.shape)\r\n\r\n # n = 0\r\n # for name, param in gen.named_parameters():\r\n # # print(name)\r\n # # print(param.shape)\r\n # print(torch.mean(param))\r\n # print(torch.std(param))\r\n # print('-----')\r\n # n += torch.prod(torch.tensor(param.shape))\r\n # print(n)\r\n\r\n dis = Discriminator(cdim=3, hdim=128, channels=[32, 64, 128],\r\n image_size=32, class_num=class_num, is_mnist=False)\r\n logit = dis(img)\r\n print(logit.shape)\r\n\r\n # n = 0\r\n # for name, param in dis.named_parameters():\r\n # # print(name)\r\n # # print(param.shape)\r\n # print(torch.mean(param))\r\n # print(torch.std(param))\r\n # print('-----')\r\n # n += torch.prod(torch.tensor(param.shape))\r\n # print(n)\r\n","sub_path":"ACGAN/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":5016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"643918880","text":"'''\nLoading the data from ../data/*\n\nData retrieved from https://www.hlnug.de/messwerte/luft/recherche-1\n\nFiles:\nfrdbrgr_170300_170320.txt \nhanau_170300_170320.txt \nost_170300_170320.txt\n\n@author: Dario Hett\n'''\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom datetime import timedelta\n\ndef load_data():\n ''' Loads the respective data. \n \n Adjust files\n '''\n files = [\"frdbrgr_170300_170320.txt\", \"hanau_170300_170320.txt\", \"ost_170300_170320.txt\"]\n path = \"../data/\"\n\n header_dict = {'Benzol[µg/m³]' : 'benzol',\n 'Kohlenmonoxid (CO)[mg/m³]' : 'co',\n 'Kohlenwasserstoffe ohne Methan[mg/m³]' : 'carbhydros',\n 'Luftdruck[hPa]' : 'hpa',\n 'Methan[mg/m³]' : 'ch4',\n 'Ozon (O3)[µg/m³]' : 'o3',\n 'PM10[µg/m³]' : 'pm10',\n 'PM2,5[µg/m³]' : 'pm2.5',\n 'Relative Luftfeuchtigkeit[%]' : 'humidity',\n 'Schwefeldioxid (SO2)[µg/m³]' : 'so2',\n 'Staub[µg/m³]' : 'dust',\n 'Stickstoffdioxid (NO2)[µg/m³]' : 'no2',\n 'Stickstoffmonoxid (NO)[µg/m³]' : 'no',\n 'Temperatur[°C]' : 'temp',\n 'Toluol[µg/m³]' : 'toluol',\n 'Windgeschwindigkeit[m/s]' : 'windspeed',\n 'Windrichtung[Grad]' : 'winddirection',\n 'Datum' : 'date',\n 'Zeit' : 'time',\n 'm-/p-Xylol[µg/m³]' : 'xylol-mp',\n 'o-Xylol[µg/m³]' : 'xylol-o'}\n\n for file in files:\n new = pd.read_csv(path+file, sep=';', header='infer', skip_blank_lines=False, engine = 'python',\n index_col=False, parse_dates = [0,1], dayfirst=True, decimal=',', thousands='.',\n na_values = ['-'])\n new.rename(columns = header_dict,inplace=True)\n try:\n frames.append(new)\n loc.append(file)\n except: \n frames = [new]\n loc = [file]\n \n df = pd.concat(frames, axis=0, join='outer', ignore_index=False, keys=loc,\n levels=None, names=None, verify_integrity=False, copy=False) \n\n df = df.droplevel(1,axis=0)\n\n assert(len(df.columns) == len(header_dict)) # Header dict was constructred from the unions.\n del new, file\n\n # Set types.\n df[df.columns[2:]].astype('float', copy=False)\n\n df.loc[df.time == \"24:00\",'date'] = df.loc[df.time == \"24:00\",'date'] + timedelta(days=1)\n df.loc[df.time == \"24:00\",'time'] = \"00:00\"\n df['time'] = pd.to_timedelta(df.time+':00', unit='H')\n df['date'] = pd.to_datetime(df.date, format=\"%Y-%m-%d\")\n df['datetime'] = df['time']+df['date']\n\n return df, files, header_dict","sub_path":"src/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"535937022","text":"#!/usr/bin/env python\n# encoding: utf-8\nfrom annoy import AnnoyIndex\n\ntest_dims = [64]\nfor dim in test_dims:\n a = AnnoyIndex(dim, 'angular')\n d = AnnoyIndex(dim, 'dot')\n e = AnnoyIndex(dim, 'euclidean')\n a.set_seed(123)\n d.set_seed(123)\n e.set_seed(123)\n vectors = open('item_vector.txt').readlines()\n for index, vector in enumerate(vectors):\n v = [float(x) for x in vector.split(',')]\n a.add_item(index, v)\n d.add_item(index, v)\n e.add_item(index, v)\n a.build(3)\n a.save('points.angular.annoy.{}'.format(dim))\n d.build(3)\n d.save('points.dot.annoy.{}'.format(dim))\n e.build(3)\n e.save('points.euclidean.annoy.{}'.format(dim))\n","sub_path":"src/test/resources/makeindex.py","file_name":"makeindex.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"587168617","text":"# 1029. Two City Scheduling (HARD)\n#\n# There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].\n#\n# Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.\n#\n#\n#\n# Example 1:\n#\n# Input: [[10,20],[30,200],[400,50],[30,20]]\n# Output: 110\n# Explanation:\n# The first person goes to city A for a cost of 10.\n# The second person goes to city A for a cost of 30.\n# The third person goes to city B for a cost of 50.\n# The fourth person goes to city B for a cost of 20.\n#\n# The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.\n\nclass Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n #Redo later\n diff=sorted(costs,key=lambda cost:cost[0]-cost[1])\n result=0\n for i in range(len(diff)//2):\n result=result+diff[i][0]\n for i in range(len(diff)//2,len(diff)):\n result=result+diff[i][1]\n return result\n","sub_path":"leetcode problems/1029.Two City Scheduling.py","file_name":"1029.Two City Scheduling.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"359065863","text":"import pandas as pd\nimport os\nfrom rdkit import Chem\nimport math\nimport numpy as np\nfrom shutil import copyfile\n\npathToProjHome = \"../\"\nTruthFilePath = \"truth\"\n\n\ndef extract_pdbid_from_name(target):\n retlist = []\n f = open(pathToProjHome + 'pdbbind_index/INDEX_all_name.2019')\n for line in f.readlines():\n splitted = line.strip().split(' ')\n pdbid = splitted[0]\n pro_id = splitted[2]\n if pro_id == target:\n retlist.append(pdbid)\n f.close()\n return retlist\n \n\ndef load_data():\n target_pdbs = extract_pdbid_from_name(\"P56817\") # P56817 :BACE\n print(target_pdbs)\n tmpdatapack = []\n \n arr1 = [\"PDBID\"]\n arr2 = [\"SMILE\"]\n arr3 = [\"LIG_ID\"]\n arr4 = [\"affinity\"] # not used in smile_comp\n arr_col = arr1 + arr2 + arr3 + arr4\n\n checkSameSMILES = {}\n\n if not os.path.exists(\"truth\"):\n os.mkdir(\"truth\")\n\n f = open(pathToProjHome + 'pdbbind_index/INDEX_all.2019')\n for line in f.readlines():\n ligand_id = line.strip().split('(')[1].split(')')[0]\n lines = line.split('/')[0].strip().split(' ')\n pdbid = lines[0]\n \n if pdbid not in target_pdbs:\n continue\n \n if '~' in lines[3]:\n continue\n elif '<' in lines[3]:\n continue\n elif '>' in lines[3]:\n continue\n else:\n measure = lines[3].split('=')[0]\n value = float(lines[3].split('=')[1][:-2])\n unit = lines[3].split('=')[1][-2:]\n \n # all thyroid receptor beta is ki/kd values \n #if measure != \"IC50\":\n # continue\n\n if not os.path.exists(pathToProjHome + \"pdbbind_files/\" + pdbid): # some pdbid only exists in the index files\n print(\"pdbid not found\")\n continue\n \n sdfMOLs = Chem.MolFromMolFile(pathToProjHome + \"pdbbind_files/\" + pdbid + \"/\" + pdbid + \"_ligand.sdf\", sanitize=False)\n if not sdfMOLs:\n print(\"not a valid mol-ligand1:\", pdbid)\n continue\n\n pvalue = -np.log10(value) + 6\n \n # for truth ligand/protein file for conformer generation processes\n copyfile(pathToProjHome + \"pdbbind_files/\" + pdbid + \"/\" + pdbid + \"_ligand.sdf\", TruthFilePath + \"/\" + pdbid + \"_ligand.sdf\")\n copyfile(pathToProjHome + \"pdbbind_files/\" + pdbid + \"/\" + pdbid + \"_protein.pdb\", TruthFilePath + \"/\" + pdbid + \"_protein.pdb\")\n \n smi = Chem.MolToSmiles(sdfMOLs)\n print(smi)\n if smi not in checkSameSMILES:\n checkSameSMILES[smi] = 1\n else:\n continue\n\n tmpdatapack.append([pdbid] + [smi] + [ligand_id] + [pvalue])\n\n if len(tmpdatapack) == 10:\n break\n\n print(len(tmpdatapack))\n df = pd.DataFrame(tmpdatapack, columns=arr_col)\n df.to_csv(\"data_for_smilecomp_bace.csv\", index=False)\n f.close()\n\n\nload_data()\n","sub_path":"bace_chembl_cd/make_data_smilecomp.py","file_name":"make_data_smilecomp.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"193905008","text":"#!/usr/bin/env python3\nimport os, sys\nif __name__ == '__main__':\n sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))\n\nfrom flask import Flask, render_template, request, redirect, jsonify, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager, login_required, login_user, logout_user\n\nAPPLICATION_NAME = \"Item Catalog\"\n\napp = Flask(__name__)\napp.config.from_object('app.config')\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"showLogin\"\n\ndb = SQLAlchemy(app)\n\n# Register blueprint(s)\nfrom app.auth.controller import auth, getUserInfo\nfrom app.api.controller import api\nfrom app.controller import mod_catalog as catalog\n\napp.register_blueprint(auth)\napp.register_blueprint(api)\napp.register_blueprint(catalog)\n\n# Connect to Database and create database session\ndb.create_all()\n\n# flask_login: callback to reload the user object \n@login_manager.user_loader\ndef load_user(userid):\n try: \n return getUserInfo(userid)\n except:\n return None\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=5000)","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"316941354","text":"#!/usr/bin/python\n########################################################################################################################\n#\n# Copyright (c) 2014, Regents of the University of California\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n########################################################################################################################\n\n'''Grid Object'''\n__author__ = \"Jaeduk Han\"\n__maintainer__ = \"Jaeduk Han\"\n__email__ = \"jdhan@eecs.berkeley.edu\"\n__status__ = \"Prototype\"\n\nimport numpy as np\n\nclass GridObject():\n \"\"\"Layout abstracted grid class\"\"\"\n type=\"native\"\n name=None\n libname=None\n xy = np.array([0, 0]) # Cooridinate\n _xgrid=np.array([])\n _ygrid=np.array([])\n max_resolution=10 #maximum resolution to handle floating point numbers\n\n @property\n def height(self): return abs(self.xy[0][1]-self.xy[1][1])\n\n @property\n def width(self): return abs(self.xy[0][0]-self.xy[1][0])\n\n def __init__(self, name, libname, xy, _xgrid=np.array([0]), _ygrid=np.array([0])):\n \"\"\"\n Constructor\n\n\n \"\"\"\n self.name = name\n self.libname=libname\n self.xy=xy\n self._xgrid=_xgrid\n self._ygrid=_ygrid\n\n def display(self):\n \"\"\"Display object information\"\"\"\n #print(\" \" + self.name + \" xy:\" +str(np.around(self.xy, decimals=self.max_resolution).tolist()))\n print(\" \" + self.name + \" width:\" + str(np.around(self.width, decimals=self.max_resolution))\n + \" height:\" + str(np.around(self.height, decimals=self.max_resolution)))\n\n def export_dict(self):\n \"\"\"Export object information\"\"\"\n export_dict={'type':self.type,\n 'xy0':np.around(self.xy[0,:], decimals=self.max_resolution).tolist(),\n 'xy1':np.around(self.xy[1,:], decimals=self.max_resolution).tolist()}\n if not self._xgrid.tolist()==[]:\n export_dict['xgrid']=np.around(self._xgrid, decimals=self.max_resolution).tolist()\n if not self._ygrid.tolist()==[]:\n export_dict['ygrid']=np.around(self._ygrid, decimals=self.max_resolution).tolist()\n return export_dict\n\n def _add_grid(self, grid, v):\n grid.append(v)\n grid.sort()\n return grid\n\n def add_xgrid(self, x):\n self._xgrid=self._add_grid(self._xgrid, x)\n\n def add_ygrid(self, y):\n self._ygrid=self._add_grid(self._ygrid, y)\n\n def get_xgrid(self):\n return self._xgrid\n\n def get_ygrid(self):\n return self._ygrid\n\n def _get_absgrid_coord(self, v, grid, size):\n # notation\n # physical grid: 0----grid0----grid1----grid2----...----gridN---size\n # abstracted grid: 0 0 0 1 1 2 2 N N N+1\n # This matches well with stacking grids\n quo=np.floor(np.divide(v, size))\n mod=v-quo*size #mod=np.mod(v, size) not working well\n mod_ongrid=np.searchsorted(grid+1e-10, mod) #add 1e-10 to handle floating point precision errors\n #print('physical:' + str(v.tolist()) + ' size:'+ str(size) +\n # ' quo:' + str(quo.tolist()) + ' mod:' + str(mod) +\n # ' abs:' + str(np.add(np.multiply(quo,grid.shape[0]), mod_ongrid).tolist()))\n return np.add(np.multiply(quo,grid.shape[0]), mod_ongrid)\n\n def _get_phygrid_coord(self, v, grid, size):\n quo=np.floor(np.divide(v, grid.shape[0]))\n mod = np.mod(v, grid.shape[0]) #mod = v - quo * grid.shape[0]\n return np.add(np.multiply(quo,size), np.take(grid,mod))\n\n def get_absgrid_coord_x(self, x):\n return self._get_absgrid_coord(x, self._xgrid, self.width).astype(int)\n\n def get_absgrid_coord_y(self, y):\n return self._get_absgrid_coord(y, self._ygrid, self.height).astype(int)\n\n def get_absgrid_coord_xy(self, xy):\n _xy=np.vstack((self.get_absgrid_coord_x(xy.T[0]), self.get_absgrid_coord_y(xy.T[1]))).T\n if _xy.shape[0]==1: return _xy[0]\n else: return _xy\n\n def get_absgrid_coord_region(self, xy0, xy1):\n _xy0 = np.vstack((self.get_absgrid_coord_x(xy0.T[0]), self.get_absgrid_coord_y(xy0.T[1]))).T\n _xy1 = np.vstack((self.get_absgrid_coord_x(xy1.T[0]), self.get_absgrid_coord_y(xy1.T[1]))).T\n if _xy0.shape[0] == 1: _xy0 = _xy0[0]\n if _xy1.shape[0] == 1: _xy1 = _xy1[0]\n #upper right boundary adjust\n #check by re-converting to physical grid and see if the points are within original [xy0, xy1]\n xy0_check = self.get_phygrid_coord_xy(_xy0)[0]\n xy1_check = self.get_phygrid_coord_xy(_xy1)[0]\n #if _xy1[1]==8:\n # print(\"phy:\"+str(xy0)+\" \"+str(xy1)+\" abs:\"+str(_xy0)+\" \"+str(_xy1)+\" chk:\"+str(xy0_check)+\" \"+str(xy1_check))\n xy0_check = np.around(xy0_check, decimals=self.max_resolution)\n xy1_check = np.around(xy1_check, decimals=self.max_resolution)\n xy0 = np.around(xy0, decimals=self.max_resolution)\n xy1 = np.around(xy1, decimals=self.max_resolution)\n\n if xy0_check[0] > xy0[0] and xy0_check[0] > xy1[0]: _xy0[0] -= 1\n if xy1_check[0] > xy0[0] and xy1_check[0] > xy1[0]: _xy1[0] -= 1\n if xy0_check[1] > xy0[1] and xy0_check[1] > xy1[1]: _xy0[1] -= 1\n if xy1_check[1] > xy0[1] and xy1_check[1] > xy1[1]: _xy1[1] -= 1\n #if _xy1[1]==7:\n # print(\"phy:\"+str(xy0)+\" \"+str(xy1)+\" abs:\"+str(_xy0)+\" \"+str(_xy1)+\" chk:\"+str(xy0_check)+\" \"+str(xy1_check))\n #print(xy1)\n\n return(np.vstack((_xy0, _xy1)))\n\n def get_phygrid_coord_x(self, x):\n return self._get_phygrid_coord(x, self._xgrid, self.width)\n\n def get_phygrid_coord_y(self, y):\n return self._get_phygrid_coord(y, self._ygrid, self.height)\n\n def get_phygrid_coord_xy(self, xy):\n return np.vstack((self.get_phygrid_coord_x(xy.T[0]), self.get_phygrid_coord_y(xy.T[1]))).T\n\n\nclass PlacementGrid(GridObject):\n \"\"\"Placement grid class\"\"\"\n type = 'placement'\n\n\nclass RouteGrid(GridObject):\n \"\"\"Routing grid class\"\"\"\n type='route'\n _xwidth=np.array([])\n _ywidth=np.array([])\n _viamap=dict()\n\n def __init__(self, name, libname, xy, xgrid, ygrid, xwidth, ywidth, viamap=None):\n \"\"\"\n Constructor\n\n\n \"\"\"\n self.name = name\n self.libname=libname\n self.xy=xy\n self._xgrid=xgrid\n self._ygrid=ygrid\n self._xwidth=xwidth\n self._ywidth=ywidth\n self._viamap=viamap\n\n def _get_route_width(self, v, _width):\n \"\"\" get metal width \"\"\"\n #quo=np.floor(np.divide(v, self._width.shape[0]))\n mod=np.mod(v, _width.shape[0])\n #if not isinstance(mod, int):\n # print(v, _width, mod)\n return _width[mod]\n\n def get_xwidth(self): return self._xwidth\n\n def get_ywidth(self): return self._ywidth\n\n def get_viamap(self): return self._viamap\n\n def get_route_width_xy(self, xy):\n \"\"\" get metal width vector\"\"\"\n return np.array([self._get_route_width(xy[0], self._xwidth),\n self._get_route_width(xy[1], self._ywidth)])\n\n def get_vianame(self, xy):\n \"\"\" get vianame\"\"\"\n mod = np.array([np.mod(xy[0], self._xgrid.shape[0]), np.mod(xy[1], self._ygrid.shape[0])])\n for vianame, viacoord in self._viamap.items():\n if viacoord.ndim==1:\n if np.array_equal(mod, viacoord): return vianame\n else:\n for v in viacoord:\n if np.array_equal(mod,v):\n return vianame\n\n def display(self):\n \"\"\"Display object information\"\"\"\n display_str=\" \" + self.name + \" width:\" + str(np.around(self.width, decimals=self.max_resolution))\\\n + \" height:\" + str(np.around(self.height, decimals=self.max_resolution))\\\n + \" xgrid:\" + str(np.around(self._xgrid, decimals=self.max_resolution))\\\n + \" ygrid:\" + str(np.around(self._ygrid, decimals=self.max_resolution))\\\n + \" xwidth:\" + str(np.around(self._xwidth, decimals=self.max_resolution))\\\n + \" ywidth:\" + str(np.around(self._ywidth, decimals=self.max_resolution))\\\n + \" viamap:{\"\n for vm_name, vm in self._viamap.items():\n display_str+=vm_name + \": \" + str(vm.tolist()) + \" \"\n display_str+=\"}\"\n print(display_str)\n\n def export_dict(self):\n export_dict=GridObject.export_dict(self)\n export_dict['xwidth'] = np.around(self._xwidth, decimals=self.max_resolution).tolist()\n export_dict['ywidth'] = np.around(self._ywidth, decimals=self.max_resolution).tolist()\n export_dict['viamap'] = dict()\n for vn, v in self._viamap.items():\n export_dict['viamap'][vn]=[]\n for _v in v:\n export_dict['viamap'][vn].append(_v.tolist())\n return export_dict\n\n def update_viamap(self, viamap):\n self._viamap=viamap\n\nif __name__ == '__main__':\n lgrid=GridObject()\n print('LayoutGrid test')\n lgrid._xgrid = np.array([0.2, 0.4, 0.6])\n lgrid._ygrid = np.array([0, 0.4, 0.9, 1.2, 2, 3])\n lgrid.width = 1.2\n lgrid.height = 3.2\n phycoord = np.array([[-0.2, -0.2], [0, 2], [4,2.2], [0.5, 1.5], [1.3, 3.6], [8,2.3]])\n print(\" xgrid:\"+str(lgrid._xgrid)+\" width:\"+str(lgrid.width))\n print(\" ygrid:\"+str(lgrid._ygrid)+\" height:\"+str(lgrid.height))\n print('physical grid to abstract grid')\n print(\" input:\"+str(phycoord.tolist()))\n abscoord=lgrid.get_absgrid_coord_xy(phycoord)\n print(\" output:\"+str(abscoord.tolist()))\n print('abstract grid to physical grid')\n phycoord=lgrid.get_phygrid_coord_xy(abscoord).tolist()\n print(\" output:\"+str(phycoord))\n","sub_path":"GridObject.py","file_name":"GridObject.py","file_ext":"py","file_size_in_byte":10939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"409528049","text":"from django.conf.urls import patterns, url\n#from django.contrib.auth.decorators import login_required\nfrom socializer import views\n\nurlpatterns = patterns('',\n\turl(r'^register/$', views.RegisterView, name='register'),\n\turl(r'^login/$', views.user_login, name='login'),\n\turl(r'^logout/$', views.user_logout, name='logout'),\n\turl(r'^$', views.index, name='index'),\n\turl(r'^search/$', views.search_view, name='search'), # ADD NEW PATTERN!\n\t#url(r'^restricted/', views.restricted, name='restricted'),\n\t#url(r'^films/$', views.films, name='films'),\n\t#url(r'^recommend/$', views.recommend, name='recommend'),\n\t#url(r'^like_category/$', views.like_category, name='like_category'),\n\t#url(r'^voting/$', views.voting, name = 'voting'),\n)","sub_path":"socializer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"393727261","text":"# ---------------- User Configuration Settings for speed-cam.py ---------------------------------\n# Ver 8.4 speed-cam.py picam480 Stream Variable Configuration Settings\n\n#######################################\n# speed-cam.py plugin settings\n#######################################\n\n# Calibration Settings\n# --------------------\ncalibrate = False # Create a calibration image file with calibration hash markers 10 px per mark\n\n# Motion Event Settings\n# ---------------------\nMIN_AREA = 200 # Default= 200 Exclude all contours less than or equal to this sq-px Area\nx_diff_max = 90 # Default= 90 Exclude if max px away >= last motion event x pos\nx_diff_min = 1 # Default= 1 Exclude if min px away <= last event x pos\ntrack_timeout = 0.0 # Default= 0.0 Optional seconds to wait after track End (Avoid dual tracking)\nevent_timeout = 0.7 # Default= 0.7 seconds to wait for next motion event before starting new track\nlog_data_to_CSV = False # Default= False True = Save log data as CSV comma separated values\n\n# Camera Settings\n# ---------------\nWEBCAM = False # Default= False False=PiCamera True=USB WebCamera\n\n# Pi Camera Settings\n# ------------------\nCAMERA_WIDTH = 640 # Default= 640 Image stream width for opencv motion scanning default=320\nCAMERA_HEIGHT = 480 # Default= 480 Image stream height for opencv motion scanning default=240\nCAMERA_FRAMERATE = 20 # Default = 30 Frame rate for video stream V2 picam can be higher\n\n# Camera Image Settings\n# ---------------------\nimage_path = \"media/security\" # folder name to store images\nimage_prefix = \"scam-\" # image name prefix security camera\nimage_show_motion_area = False # True= Display motion detection rectangle area on saved images\nimage_filename_speed = False # True= Prefix filename with speed value\nimage_text_on = False # True= Show Text on speed images False= No Text on images\nimage_bigger = 1.5 # Default= 1.5 Resize saved speed image by value\nimage_font_size = 18 # Default= 18 Font text height in px for text on images\nimageRecentMax = 10 # 0=off Maintain specified number of most recent files in motionRecentDir\nimageRecentDir = \"media/recent/security\" # default= \"media/recent\" save recent files directory path\n\n# Optional Manage SubDir Creation by time, number of files or both\n# ----------------------------------------------------------------\nimageSubDirMaxHours = 0 # 0=off or specify MaxHours - Creates New dated sub-folder if MaxHours exceeded\nimageSubDirMaxFiles = 0 # 0=off or specify MaxFiles - Creates New dated sub-folder if MaxFiles exceeded\n\n# ---------------------------------------------- End of User Variables -----------------------------------------------------\n","sub_path":"plugins/secpicam480.py","file_name":"secpicam480.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"218638755","text":"def verification(A,B):\n# B \\subset A, we check if a solution of A is divisable by 10\n# Can be done in linear time\n# The problem is in NP\n c = 0\n for i in range(0,B.len()):\n c = c + B[i]\n if c % 10 == 0:\n return 1\n return 0\n","sub_path":"Algorithms and Data Structures/Python Exercises/Exercise_91.py","file_name":"Exercise_91.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"30088930","text":"import json\nimport boto3\ndynamodb = boto3.resource('dynamodb')\n\ndef lambda_handler(event, context):\n table = dynamodb.Table('Loan')\n table.delete_item(\n Key={\n 'id': event['params']['path']['id']\n }\n )\n response={\"output\":\"Loan has been deleted\"}\n return response\n","sub_path":"loan-id-delete.py","file_name":"loan-id-delete.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"503250128","text":"\"\"\"\nAllow checking files for ignored status in gitignore files in the repo.\n\"\"\"\nfrom pathlib import Path\nfrom typing import List\n\nimport gitignorefile\n\nfrom md2cf.console_output import error_console\n\n\nclass GitRepository:\n \"\"\"\n Represents a Git repository by finding the .git folder at the root\n of the tree. Note that there are cases where .git folders may exist\n in other parts of the tree. For example in terraform repositories\n the .terraform folder may contain copies of the tree including the .git\n folder. This can be handled by initializing the GitRepository from a\n known git root. After that all files will be correctly handled by the\n is_ignored() method.\n \"\"\"\n\n def __init__(self, repo_path: Path, use_gitignore=True):\n self.use_gitignore = use_gitignore\n self.root_dir = self._find_root_dir(repo_path) if use_gitignore else None\n\n @staticmethod\n def _find_root_dir(start_path: Path):\n \"\"\"\n Traverse the parents of the start_path until we find a .git directory\n :param start_path: A file or directory path to start searching from\n :return: The root directory of the git repo.\n \"\"\"\n fs_root = Path(\"/\")\n p = start_path.absolute()\n if p.is_file():\n p = p.parent\n while p != fs_root:\n git_dir = p.joinpath(\".git\")\n if git_dir.exists() and git_dir.is_dir():\n return p\n p = p.parent\n error_console.log(\n f\":warning-emoji: Directory {start_path} is not part of a git \"\n f\"repository: gitignore checking disabled.\"\n )\n return None\n\n def collect_gitignores(self, filepath: Path) -> List[Path]:\n \"\"\"\n Collect all .gitignore files from start location to the root of the\n repository. Filepath is assumed to be a subdirectory of the git root.\n If not, an error is printed and an empty list is returned.\n\n :param filepath: The path to start searching for .gitignore files\n :return: List of paths to .gitignore files relevant for start_path\n \"\"\"\n fs_root = Path(\"/\")\n ret = list()\n\n p = filepath.absolute()\n if p.is_file():\n p = p.parent\n while p != fs_root:\n gitignore_file = p.joinpath(\".gitignore\")\n if gitignore_file.exists() and gitignore_file.is_file():\n ret.append(gitignore_file)\n if p == self.root_dir:\n return ret\n p = p.parent\n\n # if not .git directory found, we're not in a git repo and gitignore files\n # cannot be trusted.\n return list()\n\n def is_ignored(self, filepath: Path) -> bool:\n \"\"\"\n Check if filepath is ignored in the git repository by fetching all gitignores\n in the tree down to the git root and checking all of them.\n\n :param filepath: Path to the file to check if it is ignored.\n :return: True if the file is ignored in any .gitignore file\n \"\"\"\n if not self.use_gitignore:\n return False\n if self.root_dir is None:\n return False\n gitignores = self.collect_gitignores(filepath)\n matchers = [gitignorefile.parse(str(g)) for g in gitignores]\n return any([m(str(filepath)) for m in matchers])\n","sub_path":"md2cf/ignored_files.py","file_name":"ignored_files.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"274624328","text":"def lerMatriz ():\r\n lista1 = []\r\n matriz = []\r\n for i in range(6):\r\n for x in range(3):\r\n n = int(input('numero? '))\r\n lista1.append(n)\r\n matriz.append(lista1)\r\n lista1 = []\r\n return matriz\r\n\r\n#################################################\r\n\r\ndef maiorElemento(matriz):\r\n maior = 0\r\n posicao = [0,0]\r\n for i in matriz:\r\n for x in i:\r\n if x > maior:\r\n maior = x\r\n posicao[0] = i.index(x)\r\n posicao[1] = matriz.index(i)\r\n posicaoReal = '{} é o maior número, que fica na {}° linha e na {}° Coluna.'.format(maior, posicao[1]+1, posicao[0]+1)\r\n return posicaoReal\r\n\r\n#################################################\r\n\r\ndef menorElemento(matriz):\r\n menor = 999999999\r\n posicao = [0,0]\r\n for i in matriz:\r\n for x in i:\r\n if x < menor:\r\n menor = x\r\n posicao[0] = i.index(x)\r\n posicao[1] = matriz.index(i)\r\n posicaoReal = '{} é o menor número, que fica na {}° linha e na {}° Coluna.'.format(menor, posicao[1]+1, posicao[0]+1)\r\n return posicaoReal\r\n\r\n#################################################\r\n\r\nmatriz = lerMatriz()\r\n\r\nprint(maiorElemento(matriz))\r\nprint(menorElemento(matriz))\r\n\r\nfor i in matriz:\r\n print(i)\r\n","sub_path":"Lista de exercicios 5/Q6.py","file_name":"Q6.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"577419217","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_score\n# 基于梯度下降的逻辑回归实现\n\n\nclass NaiveBayes:\n def __init__(self):\n self.model = {} # key 为类别名 val 为字典PClass表示该类的该类,PFeature:{}对应对于各个特征的概率\n\n def calEntropy(self, y): # 计算熵\n valRate = y.value_counts().apply(lambda x: x / y.size) # 频次汇总 得到各个特征对应的概率\n valEntropy = np.inner(valRate, np.log2(valRate)) * -1\n return valEntropy\n\n def fit(self, xTrain, yTrain=pd.Series()):\n if not yTrain.empty: # 如果不传,自动选择最后一列作为分类标签\n xTrain = pd.concat([xTrain, yTrain], axis=1)\n self.model = self.buildNaiveBayes(xTrain)\n return self.model\n\n def buildNaiveBayes(self, xTrain):\n yTrain = xTrain.iloc[:, -1]\n\n yTrainCounts = yTrain.value_counts() # 频次汇总 得到各个特征对应的概率\n\n yTrainCounts = yTrainCounts.apply(lambda x: (\n x + 1) / (yTrain.size + yTrainCounts.size)) # 使用了拉普拉斯平滑\n retModel = {}\n for nameClass, val in yTrainCounts.items():\n retModel[nameClass] = {'PClass': val, 'PFeature': {}}\n\n propNamesAll = xTrain.columns[:-1]\n allPropByFeature = {}\n for nameFeature in propNamesAll:\n allPropByFeature[nameFeature] = list(\n xTrain[nameFeature].value_counts().index)\n # print(allPropByFeature)\n for nameClass, group in xTrain.groupby(xTrain.columns[-1]):\n for nameFeature in propNamesAll:\n eachClassPFeature = {}\n propDatas = group[nameFeature]\n propClassSummary = propDatas.value_counts() # 频次汇总 得到各个特征对应的概率\n for propName in allPropByFeature[nameFeature]:\n if not propClassSummary.get(propName):\n propClassSummary[propName] = 0 # 如果有属性灭有,那么自动补0\n Ni = len(allPropByFeature[nameFeature])\n propClassSummary = propClassSummary.apply(\n lambda x: (x + 1) / (propDatas.size + Ni)) # 使用了拉普拉斯平滑\n for nameFeatureProp, valP in propClassSummary.items():\n eachClassPFeature[nameFeatureProp] = valP\n retModel[nameClass]['PFeature'][nameFeature] = eachClassPFeature\n\n return retModel\n\n def predictBySeries(self, data):\n curMaxRate = None\n curClassSelect = None\n for nameClass, infoModel in self.model.items():\n rate = 0\n rate += np.log(infoModel['PClass'])\n PFeature = infoModel['PFeature']\n\n for nameFeature, val in data.items():\n propsRate = PFeature.get(nameFeature)\n if not propsRate:\n continue\n rate += np.log(propsRate.get(val, 0)) # 使用log加法避免很小的小数连续乘,接近零\n if curMaxRate == None or rate > curMaxRate:\n curMaxRate = rate\n curClassSelect = nameClass\n return curClassSelect\n\n def predict(self, data):\n if isinstance(data, pd.Series):\n return self.predictBySeries(data)\n return data.apply(lambda d: self.predictBySeries(d), axis=1)\n\n\ndata2 = pd.read_csv(r\"..\\datasets\\D2_iris\\iris.data\", header=None)\nmapping = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}\ndata2 = data2.replace({4: mapping})\nX_train, X_test, y_train, y_test = train_test_split(\n data2.iloc[:, :-1], data2.iloc[:, -1], test_size=0.2, random_state=0)\ntrain = pd.concat([X_train, y_train], axis=1)\ntest = pd.concat([X_test, y_test], axis=1)\n# 下面注释的是另一个数据集\n# data1 = pd.read_csv(r\"..\\datasets\\D1_australian\\australian.dat\",header = None,sep=' ')\n# X_train, X_test, y_train, y_test = train_test_split(data1.iloc[:,:-1], data1.iloc[:,-1], test_size = 0.2, random_state=0)\n# train = pd.concat([X_train,y_train],axis=1)\n# test = pd.concat([X_test,y_test],axis=1)\n\nnaiveBayes = NaiveBayes()\ntreeData = naiveBayes.fit(train)\nresult = naiveBayes.predict(test)\n\nacc = accuracy_score(y_test, result)\nf1mi = f1_score(y_test, result, average='micro')\nf1ma = f1_score(y_test, result, average='macro')\nrs = recall_score(y_test, result, average='macro')\nps = precision_score(y_test, result, average='macro')\n\n\ny_pre = result\nconfus = confusion_matrix(y_test, y_pre)\nprint(confus)\n\n# 对混淆矩阵画图\nplt.matshow(confus, cmap=plt.cm.Blues_r)\nplt.colorbar()\n# 添加内部数字标签\nfor x in range(len(confus)):\n for y in range(len(confus)):\n plt.annotate(confus[x, y], xy=(\n x, y), horizontalalignment='center', verticalalignment='center')\n\n# plt.title('confusion matrix')\nplt.xlabel('True label')\nplt.ylabel('Predocted label')\nplt.savefig('./figure/mc3.svg', format='svg')\n\nplt.figure(figsize=(12, 6))\n# r2值图, X轴是参数取值\nlb = ['recall_score_macro', 'accuracy_score',\n 'precision_score_macro', 'f1_score_macro', 'f1_score_micro']\nplt.ylabel(\"value(0~1)\")\nfor x in range(5):\n plt.bar([x], [rs, acc, ps, f1ma, f1mi][x], width=0.3, label=lb[x])\n\nplt.legend(loc='upper left')\nplt.xticks([])\nplt.ylim((0.5, 1))\nplt.savefig('./figure/hl3.svg', format='svg')","sub_path":"PYTHON/ass2/source code/NaiveBayes.py","file_name":"NaiveBayes.py","file_ext":"py","file_size_in_byte":5614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"117303714","text":"import hashlib\nimport binascii\nimport wallet\nimport codecs\nimport base58\nimport config\nimport bech32\n\nOP_DUP = '76'\nOP_HASH160 = 'a9'\nOP_EQUALVERIFY = '88'\nOP_CHECKSIG = 'ac'\nSIGHASH_ALL = '01'\n\nclass Input():\n\tdef __init__(self, prev_txid, vout, sign_key, script_sig = 1):\n\t\tself.prev_txid = get_lnf(prev_txid)\n\t\tself.vout = get_int_lnf(vout, 8)\n\t\tif script_sig == 1:\n\t\t\tself.sign_key = sign_key\n\t\t\tsignature = binascii.hexlify(self.sign_key['sign']).decode()\n\t\t\tpublic_key = binascii.hexlify(self.sign_key['pub_key'].to_string()).decode()\n\t\t\tpublic_key = wallet.get_compressed_key('04' + public_key)\n\t\t\tlen_pub_key = hex(int(len(public_key) / 2))[2:]\n\t\t\tlen_signature = hex(int((len(signature) + len(SIGHASH_ALL))/ 2))[2:]\n\t\t\tself.script_sig = len_signature + signature + SIGHASH_ALL + len_pub_key + public_key\n\t\telse:\n\t\t\tself.script_sig = script_sig\n\t\tself.script_len = hex(int(len(self.script_sig) / 2))[2:]\n\t\tif (len(self.script_sig) < 2):\n\t\t\tself.script_len = '0' + self.script_len\n\t\tself.sequence = 'ffffffff'\n\n\tdef input_concat(self):\n\t\treturn self.prev_txid + self.vout + self.script_len + self.script_sig + self.sequence\n\n\tdef get_input(self):\n\t\tdata = {}\n\t\tdata['txid'] = self.prev_txid\n\t\tdata['vout'] = self.vout\n\t\tdata['script_len'] = self.script_len\n\t\tdata['script_sig'] = self.script_sig\n\t\tdata['sequence'] = self.sequence\n\t\treturn data\n\t\t\nclass Output():\n\tdef __init__(self, value, recipient_addr, segwit = 0):\n\t\tself.value = get_int_lnf(value, 16)\n\t\tif segwit == 0:\n\t\t\taddress_decode = binascii.hexlify(base58.b58decode(recipient_addr)).decode('utf-8')\n\t\t\tencrypted_key = address_decode[2:-8]\n\t\t\tlen_pub_hash = hex(int(len(encrypted_key) / 2))[2:]\n\t\t# if segwit == 1:\n\t\t# \taddress_decode, data = bech32.decode('tb', recipient_addr)\n\t\t# \tprint(\"First param: %s\\nSecond param\")\n\t\t# \tlen_pub_hash = hex(int(len(encrypted_key) / 2))[2:]\n\t\tself.script_pubkey = OP_DUP+OP_HASH160+len_pub_hash+encrypted_key+OP_EQUALVERIFY+OP_CHECKSIG\n\t\tself.script_len = hex(int(len(self.script_pubkey) / 2))[2:]\n\n\tdef output_concat(self):\n\t\treturn self.value + self.script_len + self.script_pubkey\n\n\tdef get_output(self):\n\t\toutput = {}\n\t\toutput['value'] = self.value\n\t\toutput['script_len'] = self.script_len\n\t\toutput['script_pubkey'] = self.script_pubkey\n\t\treturn output\n\nclass Transaction():\n\tdef __init__(self, version, inputs, outputs, locktime):\n\t\tself.version = get_int_lnf(version, 8)\n\t\tself.sigwit = 0\n\t\tself.input_count = self.count_arg(inputs)\n\t\tself.inputs = []\n\t\t# if self.input_count == '01':\n\t\t# \tself.inputs.append(inputs)\n\t\t# else:\n\t\tfor elem in inputs:\n\t\t\tself.inputs.append(elem)\n\t\tself.output_count = self.count_arg(outputs)\n\t\tself.outputs = []\n\t\t# if self.output_count == '01':\n\t\t# \tself.outputs.append(outputs)\n\t\t# else:\n\t\tfor elem in outputs:\n\t\t\tself.outputs.append(elem)\n\t\tself.locktime = get_int_lnf(locktime, 8)\n\n\tdef count_arg(self, data):\n\t\tif type(data) == list:\n\t\t\tcount = len(data)\n\t\t\tcount = hex(count)[2:]\n\t\t\twhile len(count) != 2:\n\t\t\t\tcount = '0' + count\n\t\telse:\n\t\t\treturn '01'\n\t\treturn count\n\n\tdef transaction_hash_calculate(self):\n\t\tfor elem in self.inputs:\n\t\t\tconcat_inputs += elem.input_concat()\n\t\tfor elem in self.outputs:\n\t\t\tconcat_outpts += elem.output_concat()\n\t\tconcate = self.version + self.input_count + self.concat_inputs + self.concat_outpts + self.locktime\n\t\tconcate = bytes(concate, 'utf-8')\n\t\tcon_hash = hashlib.sha256(concate).hexdigest()\n\t\treturn(con_hash)\n\n\tdef get_full_transaction(self):\n\t\ttransaction = {}\n\t\ttransaction['version'] = self.version\n\t\ttransaction['input_count'] = self.input_count\n\t\ttransaction['input'] = []\n\t\tfor elem in self.inputs:\n\t\t\ttransaction['input'].append(elem)\n\t\ttransaction['output_count'] = self.output_count\n\t\ttransaction['output'] = []\n\t\tfor elem in self.outputs:\n\t\t\ttransaction['output'].append(elem)\n\t\ttransaction['locktime'] = self.locktime\n\t\tif self.sigwit == 1:\n\t\t\ttransaction['marker'] = self.marker\n\t\t\ttransaction['flag'] = self.flag\n\t\t\ttransaction['witness'] = []\n\t\t\tfor elem in self.witness:\n\t\t\t\ttransaction['witness'].append(elem) \n\t\treturn transaction\n\t\t\nclass CoinbaseInput(Input):\n\tdef __init__(self, height):\n\t\tself.prev_txid = '0'*64\n\t\tself.vout = 'f'*8\n\t\tself.height = get_int_lnf(height, 6)\n\t\tself.script_sig = '03' + self.height + '2f48616f4254432f53756e204368756e2059753a205a6875616e67205975616e2c2077696c6c20796f75206d61727279206d653f2f06fcc9cacc19c5f278560300'\n\t\tself.script_len = hex(int(len(self.script_sig) / 2))[2:]\n\t\tself.sequence = 'ffffffff'\n\t\t\n\nclass CoinbaseTransaction(Transaction):\n\tdef __init__(self, height = 0, reward = 50):\n\t\ttry:\n\t\t\tf = open('minerkey', 'r')\n\t\texcept IOError:\n\t\t\tprint(\"Create file mainerkey with WIF key!!\")\n\t\t\treturn\n\t\tprivate_key = wallet.WIF_to_key(f.read())\n\t\tinputik = []\n\t\tinputik.append(CoinbaseInput(height))\n\t\tbitcoin_address = wallet.get_bitcoin_address(private_key)\n\t\t# print(\"Bitcoin address \", bitcoin_address)\n\t\toutput = []\n\t\toutput.append(Output(reward * pow(10, 8), bitcoin_address))\n\t\tTransaction.__init__(self, 1, inputik, output, 0)\n\t\n\tdef get_info(self):\n\t\treturn Transaction.get_full_transaction(self)\n\ndef get_int_lnf(data, lens):\n\tif type(data) != int:\n\t\tdata = int(data)\n\tdata = hex(data)[2:]\n\twhile len(data) != lens:\n\t\tdata = '0' + data\n\tlnf = codecs.encode(codecs.decode(data, 'hex')[::-1], 'hex').decode()\n\treturn(lnf)\n\ndef get_lnf(data):\n\treturn codecs.encode(codecs.decode(data, 'hex')[::-1], 'hex').decode()\n","sub_path":"teamcoin/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":5372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"549880126","text":"import datetime\r\nfrom time import mktime\r\n\r\nimport feedparser\r\n\r\nfrom exante_test.apps.feed.models import FeedEntry\r\nfrom exante_test.apps.feed.providers.abstract import AbstractProvider\r\n\r\n\r\nclass RSSProvider(AbstractProvider):\r\n name = 'rss'\r\n\r\n def __init__(self, feed):\r\n super(RSSProvider, self).__init__(feed)\r\n\r\n def update(self):\r\n d = feedparser.parse(self.feed.url)\r\n\r\n latest_entry = self.get_latest_entry()\r\n\r\n entry_values = []\r\n for entry in d.entries:\r\n entry_created_at = datetime.datetime.fromtimestamp(mktime(entry.published_parsed))\r\n\r\n if latest_entry and latest_entry.created_at.replace(tzinfo=None) >= entry_created_at:\r\n break\r\n entry_values.append(\r\n FeedEntry(\r\n feed=self.feed,\r\n title=entry.title,\r\n description=entry.description,\r\n category=self.get_category_by_title(entry.category),\r\n created_at=entry_created_at\r\n )\r\n )\r\n FeedEntry.objects.bulk_create(entry_values)","sub_path":"exante_test/apps/feed/providers/rss.py","file_name":"rss.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"109144406","text":"from typing import List\n\n\ndef waysToMakeFair(nums: List[int]) -> int:\n count = 0\n a = sum(nums[::2])#奇数和\n b = sum(nums[1::2])#偶数和\n for i in range(len(nums)):\n if i % 2 == 0:\n js = a - nums[i]#以后的偶数和\n\n\n\n\nprint(waysToMakeFair([2, 1, 6, 4]))\n","sub_path":"Python/leetcode/week/Solution_1122_03.py","file_name":"Solution_1122_03.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"427487816","text":"from discord.ext import commands\nimport discord\nimport datetime\nimport os\nprefix = os.getenv(\"PREFIX\")\n\nclass mute(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def mutehelp(self, ctx):\n embed = discord.Embed(\n colour=0xc57694,\n timestamp=datetime.datetime.utcnow(),\n )\n embed.add_field(name=\"**What First?**\", value=\"1. Make A Mute Role Name 'mute-inferno' and Make Sure It Is Configured In Channel Settings. Click [Here](https://prnt.sc/s9ghy1) For An Example!\\n2. Make Sure Inferno Has Admin and Can Assign The Mute Role\\n3. If Everything Is Set Up Right, You Should Be Good To Go!\", inline=False)\n embed.add_field(name=\"**Why?**\", value=\"The Reason For Me Choosing This Form of Muting is To Give Server Owners/Admin The Choice To Not Have Muting, If They Do Not Want Muting Through Inferno, They Simply Don't Add The Role.\", inline=False)\n embed.add_field(name=\"**Usage**\", value=f\"`{prefix}mute [@Jinxy#0117]` — Assigns The Mute Role.\\n`{prefix}unmute [@Jinxy#0117]` — Removes The Mute Role.\", inline=False)\n embed.set_author(name=\"Mute Help!\", url=\"https://discord.gg/dystopia\", icon_url=self.bot.user.avatar_url)\n embed.set_thumbnail(url=self.bot.user.avatar_url)\n embed.set_footer(text=f\"{ctx.guild.name}\")\n\n await ctx.send(embed=embed)\n\n @commands.command()\n @commands.has_permissions(administrator=True)\n async def mute(self, ctx, member: discord.Member=None):\n if not member:\n await ctx.send(\"`You forgot to mention a user!`\")\n return\n role = discord.utils.get(ctx.guild.roles, name=\"mute-inferno\")\n await member.add_roles(role)\n await ctx.send(f\"`{member.name}#{member.discriminator}` was muted by `{ctx.author}`.\")\n @mute.error\n async def mute_error(self, ctx, error):\n if isinstance(error, commands.CheckFailure):\n await ctx.send(\"You are not allowed to mute people\")\n\n @commands.command()\n @commands.has_permissions(administrator=True)\n async def unmute(self, ctx, member: discord.Member=None):\n if not member:\n await ctx.send(\"`You forgot to mention a user!`\")\n return\n role = discord.utils.get(ctx.guild.roles, name=\"mute-inferno\")\n await member.remove_roles(role)\n await ctx.send(f\"`{member.name}#{member.discriminator}` was unmuted by `{ctx.author}`.\")\n @mute.error\n async def unmute_error(self, ctx, error):\n if isinstance(error, commands.CheckFailure):\n await ctx.send(\"`You are not allowed to unmute people`\")\n\ndef setup(bot):\n bot.add_cog(mute(bot))","sub_path":"cogs/mute.py","file_name":"mute.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"508604456","text":"from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import create_engine, Column, Integer, String\n\nBase = declarative_base()\n\nclass FacePattern(Base):\n __tablename__ = 'face_pattern'\n id = Column(Integer, primary_key=True)\n file_name = Column(String)\n file_hash = Column(Integer)\n pattern_identity = Column(String)\n encodings = Column(String)","sub_path":"face_recognition/sqlite_db/db_classes.py","file_name":"db_classes.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"501866783","text":"import time\nfrom threading import Thread\nfrom typing import Dict\n\nimport requests\nimport json\n\nfrom django.conf import settings\n\nfrom .models import Pin\nimport logging\n\nTOKEN = settings.MY_CONFIG.get('blynkToken', 'd31c99e1598a4e6f8d9e0c95838ff754')\nURL = settings.MY_CONFIG.get('blynkUrl', 'http://blynk-cloud.com')\n\n\nclass Blynk:\n HEADER = {'Content-Type': 'application/json'}\n\n def __init__(self, url, token):\n self.url = url\n self.token = token\n\n def get_pin_value(self, pin):\n data_base_value = Pin.get_value(pin)\n try:\n result = requests.get(f'{self.url}/{self.token}/get/{pin}', verify=False).json() or data_base_value\n if isinstance(result, list):\n result = float(result[0])\n except Exception as err:\n logging.error(err)\n result = data_base_value\n return int(result)\n\n def update_pin_value(self, pin: str, value: int) -> bool:\n if not isinstance(value, int):\n raise Exception(\"Valor enviado não é válido. Envie um inteiro\")\n return requests.put(f'{URL}/{TOKEN}/update/{pin}', json.dumps([value]), headers=self.HEADER, verify=False).ok\n\n\nclass BlynkThreadTime(Thread):\n def __init__(self, pin_name):\n super().__init__()\n self.irrigating_time = 0.0\n self.pin = pin_name\n self.name = self.pin\n self._stop = False\n\n def set_irrigate_time(self, irrigate_time):\n self.irrigating_time = irrigate_time\n\n def run(self):\n while not self._stop:\n time.sleep(self.irrigating_time)\n res = blynk.update_pin_value(self.pin, 0)\n if res:\n print(\"Terminou\")\n self._stop = True\n\n\nblynk = Blynk(URL, TOKEN)\nth_pin: Dict = {pin.name: BlynkThreadTime(pin.name) for pin in Pin.objects.all()}\n","sub_path":"smart_garden_web/blynk/blynk.py","file_name":"blynk.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"8861210","text":"import os\nimport sys\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'\nsys.path.insert(0,'.')\nsys.path.insert(0,'..')\n\nfrom pdfreports.models import Slug, Paragraph\nfrom fund.models import Fund\nfrom textchunks.models import Section, TextChunk\nfrom django.contrib.contenttypes.models import ContentType\n\n\nslugs = Slug.objects.all()\npars = Paragraph.objects.all()\n\nslugtosection = {}\nfor index, slug in enumerate(slugs):\n fund_type = ContentType.objects.get(app_label=\"fund\", model=\"Fund\")\n section = Section(code=slug.name, display_title=slug.name, content_type=fund_type)\n section.save()\n slugtosection[slug.pk] = section\n\nfor par in pars:\n try:\n obj = par.fund\n textchunk = TextChunk(body=par.body, content_object=obj, section = slugtosection[par.slug.pk])\n textchunk.save()\n except:\n obj = par.manager\n textchunk = TextChunk(body=par.body, content_object=obj, section = slugtosection[par.slug.pk])\n textchunk.save()\n \n ","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"616844716","text":"# runtime: 79.84%, memory usage: 5.81%\ndef isPowerOfFour(num: int) -> bool:\n # return num & (num - 1) == (num - 1) % 3 == 0\n zero_count = 0\n\n if num <= 0:\n return False\n\n while num > 1:\n if num & 1:\n return False\n else:\n zero_count += 1\n\n num >>= 1\n\n return zero_count & 1 == 0\n\n\nif __name__ == '__main__':\n print(isPowerOfFour(2)) # False\n print(isPowerOfFour(4)) # True\n print(isPowerOfFour(-64)) # False\n","sub_path":"lc_solutions/bit_manipulation/power_of_four-342/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"123033440","text":"import json\nimport os\nimport matplotlib\nfrom pprint import pprint\nmatplotlib.use('Agg')\n\nfrom matplotlib import pyplot as plt\nplt.figure(figsize=(20,10))\n\ndef re_x():\n ax = plt.subplot(111)\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 0.7, box.height])\n\ndef generate_required(save):\n book_ps = save[\"book_dir\"].split('/')\n book = book_ps[-2]\n keys = map(lambda x: x/10, range(11))\n skeys = map(str, keys)\n xs, cp, cbp, icbp = [], [], [], []\n for known_percent in skeys:\n #unseen = save[known_percent][\"unseen\"]\n dkeys = [\"correct\", \"total\", \"real_word_error\", \"correctable\", \"uncorrectable\"]\n cumulative = {}\n for dkey in dkeys:\n cumulative[dkey] = 0\n cumulative[dkey] += save[known_percent][\"unseen\"][dkey]\n cumulative[dkey] += save[known_percent][\"included\"][dkey]\n\n correct_percent = cumulative[\"correct\"]/cumulative[\"total\"]\n\n to_suggest = cumulative[\"total\"] - \\\n (cumulative[\"correct\"] + cumulative[\"real_word_error\"])\n\n correctable_percent = cumulative[\"correctable\"]/to_suggest\n uncorrectable_percent = cumulative[\"uncorrectable\"]/to_suggest\n xs.append(known_percent)\n cp.append(correct_percent)\n cbp.append(correctable_percent)\n icbp.append(uncorrectable_percent)\n\n return (xs, cp, cbp, icbp, book)\n\nfmap = {}\nfmap['hi'] = dict(map(lambda x: x.strip().split('_'), open(\"hi.fmap\")))\nfmap['ml'] = dict(map(lambda x: x.strip().split('_'), open(\"ml.fmap\")))\npprint(fmap)\n\nbbanchor = (1,0.5)\ndpi = 200\n\nfor lang in ['hi', 'ml']:\n saves = []\n for dr, drs, fls in os.walk('output/%s-final'%(lang)):\n for fn in fls:\n fn_with_path = dr + '/' + fn\n saves.append(json.load(open(fn_with_path)))\n\n values = map(generate_required, saves)\n xs, cps, cbps, icbps, books = zip(*values)\n\n re_x()\n handles = []\n for x, y, book in zip(xs, cps, books):\n print(book, lang)\n p, = plt.plot(x, y, label=fmap[lang][book])\n handles.append(p)\n plt.xlabel(\"fraction of data in vocabulary\")\n plt.ylabel(\"correct percent\")\n\n plt.legend(handles=handles, loc='center left', bbox_to_anchor=bbanchor)\n plt.savefig(\"output/images/all_correct_%s.png\"%(lang), dpi=dpi)\n plt.clf()\n\n re_x()\n handles = []\n for x, y, book in zip(xs, cbps, books):\n p, = plt.plot(x, y, label=fmap[lang][book])\n handles.append(p)\n plt.xlabel(\"fraction of data in vocabulary\")\n plt.ylabel(\"correctable percent\")\n\n plt.legend(handles=handles, loc='center left', bbox_to_anchor=bbanchor)\n plt.savefig(\"output/images/all_correctable_%s.png\"%(lang), dpi=dpi)\n plt.clf()\n\n re_x()\n handles = []\n for x, y, book in zip(xs, icbps, books):\n p, = plt.plot(x, y, label=fmap[lang][book])\n handles.append(p)\n plt.xlabel(\"fraction of data in vocabulary\")\n plt.ylabel(\"uncorrectable percent\")\n\n plt.legend(handles=handles, loc='center left', bbox_to_anchor=bbanchor)\n plt.savefig(\"output/images/all_uncorrectable_%s.png\"%(lang), dpi=dpi)\n plt.clf()\n","sub_path":"src/experiments/leave_one_out_analysis.py","file_name":"leave_one_out_analysis.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"407891233","text":"from time import sleep\n\nclass Clock(object):\n\tdef __init__ (self, second=0, minute=0, hour=0):\n\t\tself.second = second\n\t\tself.minute = minute\n\t\tself.hour = hour\n\n\tdef run(self):\n\t\tself.second += 1\n\t\tif self.second == 60:\n\t\t\tself.minute += 1\n\t\t\tself.second = 0\n\t\t\tif self.minute == 60:\n\t\t\t\tself.hour += 1\n\t\t\t\tself.minute = 0 \n\t\t\t\tif self.hour == 24:\n\t\t\t\t\tself.hour = 0\n\tdef show(self):\n\t\treturn (\"{0:0>2}:{1:0>2}:{2:0>2}\".format(self.hour, self.minute, self.second))\n\nclock = Clock(20, 36, 11)\n\nwhile True:\n\tprint(clock.show())\n\tsleep(1)\n\tclock.run()\n\n\n\n\n\n","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"397191498","text":"#!/usr/bin/env python\n\n# The Expat License\n#\n# Copyright (c) 2017, Shlomi Fish\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\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 FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nimport sys\n\nif sys.version_info > (3,):\n long = int\n xrange = range\n\n\ndef calc(q):\n probs = [1.0]\n for x in xrange(1, 51):\n p = 1 - x / q\n new_probs = []\n for i in xrange(x+1):\n # print(\"%d %d\" % (i,x))\n new_probs.append((0 if (i == x) else probs[i] * (1-p)) +\n (0 if (i == 0) else (p * probs[i-1])))\n probs = new_probs\n return probs[20]\n\n\nlow = float(50)\nhigh = float(100000)\n\nwhile True:\n m = ((low + high) / 2)\n v_m = calc(m)\n print(\"%.40f = %.40f\" % (m, v_m))\n if v_m > 0.02:\n low = m\n elif v_m < 0.02:\n high = m\n else:\n break\n","sub_path":"project-euler/286/euler_286_v1.py","file_name":"euler_286_v1.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"536177856","text":"import os\nimport re\nimport nltk\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\n\n\nclass Model:\n def __init__(self):\n self.logit_regressor = LogisticRegression(random_state=42)\n self.data_loader = DataLoader()\n self.model = None\n\n def run(self):\n x_train_vec, y_train, x_val_vec, y_val, x_test_vec, y_test = self.data_loader.run()\n print(\"Model Training...\")\n self.model = self.logit_regressor.fit(x_train_vec, y_train)\n print(classification_report(y_val, self.model.predict(x_val_vec)))\n\n\nclass DataLoader:\n def __init__(self, train_path='Corona_NLP_train.csv', test_path='Corona_NLP_test.csv'):\n self.train_df = pd.read_csv(train_path, encoding='latin-1')\n self.test_df = pd.read_csv(test_path, encoding='latin-1')\n self.stopWord = stopwords.words('english')\n self.covid_corpus = None\n\n def visualize_labels(self):\n labels = ['Positive', 'Negative', 'Neutral', 'Extremely Positive', 'Extremely Negative']\n colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#ff5645']\n explode = (0.05, 0.05, 0.05, 0.05, 0.05)\n plt.pie(self.train_df.Sentiment.value_counts(), colors=colors, labels=labels,\n autopct='%1.1f%%', startangle=90, pctdistance=0.85, explode=explode)\n centre_circle = plt.Circle((0, 0), 0.70, fc='white')\n fig = plt.gcf()\n fig.gca().add_artist(centre_circle)\n plt.tight_layout()\n plt.show()\n\n def run(self):\n print(\"DataLoader running...\")\n train, test = self.preprocess()\n x_train = train.Corpus\n y_train = train.Sentiment\n x_test = test.Corpus\n y_test = test.Sentiment\n\n x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=42)\n print(\"Train Shape...\\nX: {}\\nY: {}\\nValidation Shape...\\nX: {}\\nY: {}\\nTest Shape...\\nX: {}\\nY: {}\\n\".format(\n x_train.shape, y_train.shape, x_val.shape, y_val.shape, x_test.shape, y_test.shape))\n\n vectorizer = CountVectorizer(stop_words='english', ngram_range=(1, 2), min_df=5).fit(self.covid_corpus)\n\n x_train_vec = vectorizer.transform(x_train)\n x_val_vec = vectorizer.transform(x_val)\n x_test_vec = vectorizer.transform(x_test)\n\n return x_train_vec, y_train, x_val_vec, y_val, x_test_vec, y_test\n\n def preprocess(self):\n self.train_df['Identity'] = 0\n self.test_df['Identity'] = 1\n covid = pd.concat([self.train_df, self.test_df])\n covid.reset_index(drop=True, inplace=True)\n # Shrink 5 classes to 3 classes.\n # Extremely Postive -> Positive\n # Extremely Negative -> Negative\n covid['Sentiment'] = covid['Sentiment'].str.replace('Extremely Positive', 'Positive')\n covid['Sentiment'] = covid['Sentiment'].str.replace('Extremely Negative', 'Negative')\n\n covid = covid.drop('ScreenName', axis=1)\n covid = covid.drop('UserName', axis=1)\n\n # labels = ['Positive', 'Negative', 'Neutral']\n # colors = ['lightblue', 'lightsteelblue', 'silver']\n # explode = (0.1, 0.1, 0.1)\n # plt.pie(covid.Sentiment.value_counts(), colors=colors, labels=labels,\n # shadow=300, autopct='%1.1f%%', startangle=90, explode=explode)\n # plt.show()\n\n covid['Sentiment'] = covid['Sentiment'].map({'Neutral': 0, 'Positive': 1, 'Negative': 2})\n covid['OriginalTweet'] = covid['OriginalTweet'].apply(lambda x: self.clean(x))\n\n covid = covid[['OriginalTweet', 'Sentiment', 'Identity']]\n\n covid['Corpus'] = [nltk.word_tokenize(text) for text in covid.OriginalTweet]\n lemma = nltk.WordNetLemmatizer()\n covid.Corpus = covid.apply(lambda x: [lemma.lemmatize(word) for word in x.Corpus], axis=1)\n covid.Corpus = covid.apply(lambda x: \" \".join(x.Corpus), axis=1)\n\n self.covid_corpus = covid.Corpus\n\n train = covid[covid.Identity == 0]\n test = covid[covid.Identity == 1]\n train.drop('Identity', axis=1, inplace=True)\n test.drop('Identity', axis=1, inplace=True)\n test.reset_index(drop=True, inplace=True)\n\n return train, test\n\n def clean(self, text):\n text = re.sub(r'http\\S+', \" \", text)\n text = re.sub(r'@\\w+', ' ', text)\n text = re.sub(r'#\\w+', ' ', text)\n text = re.sub(r'\\d+', ' ', text)\n text = re.sub('r<.*?>', ' ', text)\n text = text.split()\n text = \" \".join([word for word in text if word not in self.stopWord])\n\n return text\n\n\nmodel = Model()\nmodel.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"139528670","text":"import http.server\n\nPORT = 8003\n\nclass Handler(http.server.CGIHTTPRequestHandler):\n cgi_directories = ['/cgi/']\n\nwith http.server.HTTPServer(('127.0.0.1', PORT), Handler) as httpd:\n print('serving at port', PORT)\n httpd.serve_forever()\n","sub_path":"example04_cgi.py","file_name":"example04_cgi.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"293044124","text":"#########################################################################################################\n#########################################################################################################\n## Greig Cowan\n## 31st August 2015\n#########################################################################################################\n#########################################################################################################\n\nimport GaudiKernel.SystemOfUnits as Units\nfrom Gaudi.Configuration import *\nfrom PhysSelPython.Wrappers import AutomaticData, Selection, SelectionSequence\nfrom Configurables import FilterDesktop\nfrom Configurables import DaVinci\nfrom Configurables import DecayTreeTuple\nfrom Configurables import TupleToolDecay\nfrom Configurables import GaudiSequencer\nfrom Configurables import CombineParticles\nfrom Configurables import CondDB\nfrom Configurables import LoKi__Hybrid__TupleTool\nfrom Configurables import LoKi__Hybrid__TupleTool\nfrom Configurables import LoKi__Hybrid__EvtTupleTool\nfrom Configurables import MCTupleToolHierarchy\nfrom Configurables import TupleToolMCTruth\nfrom Configurables import TupleToolMCBackgroundInfo\nfrom Configurables import TupleToolTISTOS, TriggerTisTos\n\nEVTMAX = -1\nMODE = 'data'\nOUTPUTLEVEL = ERROR\n\nlocation='/Event/Dimuon/Phys/B2XMuMu_Line/Particles'\n\n#########################################################################################################\n# Set up the MCDecayTreeTuples for each of the decays that we are interested in.\n# We want to save all of the generated events for each mode.\n#########################################################################################################\nfrom Configurables import MCDecayTreeTuple, MCTupleToolKinematic, MCTupleToolHierarchy, LoKi__Hybrid__MCTupleTool\n\n# LoKi variables\nLoKi_Photos = LoKi__Hybrid__MCTupleTool(\"LoKi_Photos\")\nLoKi_Photos.Variables = {\n \"nPhotons\" : \"MCNINTREE ( ('gamma'==MCABSID) )\",\n \"MC_PT\" : \"MCPT\",\n \"MC_THETA\" : \"MCTHETA\",\n \"MC_ETA\" : \"MCETA\",\n \"MC_PHI\" : \"MCPHI\",\n \"MC_ABSID\" : \"MCABSID\"\n }\n\nmctuple_B2Kmumu = MCDecayTreeTuple( 'MCTuple_B2Kmumu' )\nmctuple_B2Kmumu.Decay = \"[ (Beauty & LongLived) --> ^(J/psi(1S) -> ^mu+ ^mu- ...) ^K+ ... ]CC\"\nmctuple_B2Kmumu.Branches = {\n 'B' : \"[ (Beauty & LongLived) --> ^(J/psi(1S) -> mu+ mu- ...) K+ ... ]CC\",\n 'Kplus' : \"[ (Beauty & LongLived) --> ^(J/psi(1S) -> mu+ mu- ...) ^K+ ... ]CC\",\n 'psi' : \"[ (Beauty & LongLived) --> ^(J/psi(1S) -> mu+ mu- ...) K+ ... ]CC\",\n 'muplus' : \"[ (Beauty & LongLived) --> ^(J/psi(1S) -> ^mu+ mu- ...) K+ ... ]CC\",\n 'muminus' : \"[ (Beauty & LongLived) --> ^(J/psi(1S) -> mu+ ^mu- ...) K+ ... ]CC\",\n }\n\n# List of the mc tuples\nmctuples = [\n mctuple_B2Kmumu\n ]\n\nfor tup in mctuples:\n tup.addTool(MCTupleToolKinematic())\n tup.MCTupleToolKinematic.Verbose=True\n tup.addTool(LoKi_Photos)\n tup.ToolList = [ \"MCTupleToolHierarchy\"\n , \"MCTupleToolKinematic\"\n , \"LoKi::Hybrid::MCTupleTool/LoKi_Photos\" # doesn't work with DaVinci v36r6\n ]\n tup.addTool(TupleToolMCTruth, name = \"TruthTool\")\n tup.addTool(TupleToolMCBackgroundInfo, name = \"BackgroundInfo\")\n tup.ToolList += [\"TupleToolMCTruth/TruthTool\"]\n tup.ToolList += [\"TupleToolMCBackgroundInfo/BackgroundInfo\"]\n\nif OUTPUTLEVEL == DEBUG:\n from Configurables import PrintMCTree, PrintMCDecayTreeTool\n mctree = PrintMCTree(\"PrintTrue\")\n mctree.addTool( PrintMCDecayTreeTool )\n mctree.PrintMCDecayTreeTool.Information = \"Name M P Px Py Pz Pt Vx Vy Vz\"\n mctree.ParticleNames = [ \"B+\", \"B-\" ]\n mctree.Depth = 3 # down to the K and mu\n\n#########################################################################################################\n# Now set up the DecayTreeTuples for the reconstructed particles\n#########################################################################################################\ntupletools = []\ntupletools.append(\"TupleToolPrimaries\")\ntupletools.append(\"TupleToolKinematic\")\ntupletools.append(\"TupleToolGeometry\")\ntupletools.append(\"TupleToolTrackInfo\")\ntupletools.append(\"TupleToolPid\")\ntupletools.append(\"TupleToolRecoStats\")\ntupletools.append(\"TupleToolEventInfo\")\ntriglist = [\n \"L0PhysicsDecision\"\n ,\"L0MuonDecision\"\n ,\"L0DiMuonDecision\"\n ,\"L0MuonHighDecision\"\n ,\"L0HadronDecision\"\n ,\"L0ElectronDecision\"\n ,\"L0PhotonDecision\"\n ,\"Hlt1DiMuonHighMassDecision\"\n ,\"Hlt1DiMuonLowMassDecision\"\n ,\"Hlt1SingleMuonNoIPDecision\"\n ,\"Hlt1SingleMuonHighPTDecision\"\n ,\"Hlt1TrackAllL0Decision\"\n ,\"Hlt1TrackMuonDecision\"\n ,\"Hlt1TrackPhotonDecision\"\n ,\"Hlt1L0AnyDecision\"\n ,\"Hlt2SingleElectronTFLowPtDecision\"\n ,\"Hlt2SingleElectronTFHighPtDecision\"\n ,\"Hlt2DiElectronHighMassDecision\"\n ,\"Hlt2DiElectronBDecision\"\n ,\"Hlt2B2HHLTUnbiasedDecision\"\n ,\"Hlt2Topo2BodySimpleDecision\"\n ,\"Hlt2Topo3BodySimpleDecision\"\n ,\"Hlt2Topo4BodySimpleDecision\"\n ,\"Hlt2Topo2BodyBBDTDecision\"\n ,\"Hlt2Topo3BodyBBDTDecision\"\n ,\"Hlt2Topo4BodyBBDTDecision\"\n ,\"Hlt2TopoMu2BodyBBDTDecision\"\n ,\"Hlt2TopoMu3BodyBBDTDecision\"\n ,\"Hlt2TopoMu4BodyBBDTDecision\"\n ,\"Hlt2TopoE2BodyBBDTDecision\"\n ,\"Hlt2TopoE3BodyBBDTDecision\"\n ,\"Hlt2TopoE4BodyBBDTDecision\"\n ,\"Hlt2MuonFromHLT1Decision\"\n ,\"Hlt2DiMuonDecision\"\n ,\"Hlt2DiMuonDetachedDecision\"\n ,\"Hlt2DiMuonDetachedHeavyDecision\"\n ,\"Hlt2DiMuonLowMassDecision\"\n ,\"Hlt2DiMuonJPsiDecision\"\n ,\"Hlt2DiMuonJPsiHighPTDecision\"\n ,\"Hlt2DiMuonPsi2SDecision\"\n ,\"Hlt2DiMuonBDecision\"\n]\nTISTOSTool = TupleToolTISTOS('TISTOSTool')\nTISTOSTool.VerboseL0 = True\nTISTOSTool.VerboseHlt1 = True\nTISTOSTool.VerboseHlt2 = True\nTISTOSTool.TriggerList = triglist[:]\nTISTOSTool.addTool( TriggerTisTos, name=\"TriggerTisTos\")\n\nLoKi_B = LoKi__Hybrid__TupleTool(\"LoKi_B\")\nLoKi_B.Variables = {\n \"Best_PV_CORRM\" : \"BPVCORRM\",\n \"Best_PV_Eta\" : \"BPVETA\",\n \"ETA\" : \"ETA\",\n \"PHI\" : \"PHI\",\n \"LOKI_FDCHI2\" : \"BPVVDCHI2\",\n \"LOKI_FDS\" : \"BPVDLS\",\n \"LOKI_DIRA\" : \"BPVDIRA\",\n \"LOKI_DTF_CTAU\" : \"DTF_CTAU( 0, True )\",\n \"LOKI_DTF_CTAUS\" : \"DTF_CTAUSIGNIFICANCE( 0, True )\",\n \"LOKI_DTF_CHI2NDOF\" : \"DTF_CHI2NDOF( True )\",\n \"LOKI_DTF_CTAUERR\" : \"DTF_CTAUERR( 0, True )\",\n \"LOKI_MASS_JpsiConstr\" : \"DTF_FUN ( M , False , 'J/psi(1S)' )\" ,\n \"LOKI_DTF_VCHI2NDOF\" : \"DTF_FUN ( VFASPF(VCHI2/VDOF) , True )\",\n }\n\nLoKi_psi = LoKi__Hybrid__TupleTool(\"LoKi_psi\")\nLoKi_psi.Variables = {\n \"q_PV_constr_B_constr\" : \"DTF_FUN ( M , True , 'B+' )\" ,\n \"q_PV_constr\" : \"DTF_FUN ( M , True )\" ,\n \"q_B_constr\" : \"DTF_FUN ( M , False , 'B+' )\" ,\n \"q_no_constr\" : \"DTF_FUN ( M , False )\" ,\n }\n\nLoKi_Mu = LoKi__Hybrid__TupleTool(\"LoKi_Mu\")\nLoKi_Mu.Variables = {\n \"NSHAREDMU\" : \"NSHAREDMU\"\n }\n\ntuple_B2Kmumu = DecayTreeTuple(\"Tuple_B2Kmumu\")\ntuple_B2Kmumu.Inputs = [ location ]\ntuple_B2Kmumu.ToolList = tupletools[:]\ntuple_B2Kmumu.Decay = '[B+ -> ^(J/psi(1S) -> ^mu+ ^mu-) ^K+]CC'\ntuple_B2Kmumu.Branches = {\n \"B\" : \"[B+ -> (J/psi(1S) -> mu+ mu-) K+]CC\",\n \"Kplus\" : \"[B+ -> (J/psi(1S) -> mu+ mu-) ^K+]CC\",\n \"psi\" : \"[B+ -> ^(J/psi(1S) -> mu+ mu-) K+]CC\",\n \"muplus\" : \"[B+ -> (J/psi(1S) -> ^mu+ mu-) K+]CC\",\n \"muminus\": \"[B+ -> (J/psi(1S) -> mu+ ^mu-) K+]CC\",\n }\nfor particle in [\"B\", \"Kplus\", \"psi\", \"muplus\", \"muminus\"]:\n tuple_B2Kmumu.addTool(TupleToolDecay, name = particle)\n\n# List of the reconstructed tuples\ntuples = [ tuple_B2Kmumu\n ]\n\nfor tup in tuples:\n tup.ReFitPVs = True\n if MODE == \"MC\":\n tup.addTool(TupleToolMCTruth, name = \"TruthTool\")\n tup.addTool(TupleToolMCBackgroundInfo, name = \"BackgroundInfo\")\n tup.ToolList += [\"TupleToolMCTruth/TruthTool\"]\n tup.ToolList += [\"TupleToolMCBackgroundInfo/BackgroundInfo\"]\n\n tup.B.addTool( LoKi_B )\n tup.B.ToolList += [\"LoKi::Hybrid::TupleTool/LoKi_B\"]\n tup.psi.addTool( LoKi_psi )\n tup.psi.ToolList += [\"LoKi::Hybrid::TupleTool/LoKi_psi\"]\n tup.muplus.addTool( LoKi_Mu )\n tup.muplus.ToolList += [\"LoKi::Hybrid::TupleTool/LoKi_Mu\"]\n tup.muminus.addTool( LoKi_Mu )\n tup.muminus.ToolList += [\"LoKi::Hybrid::TupleTool/LoKi_Mu\"]\n for particle in [ tup.B ]:\n particle.addTool(TISTOSTool, name = \"TISTOSTool\")\n particle.ToolList += [ \"TupleToolTISTOS/TISTOSTool\" ]\n\n##################################################################\n# If we want to write a DST do this\n##################################################################\nfrom DSTWriters.microdstelements import *\nfrom DSTWriters.Configuration import (SelDSTWriter,\n stripDSTStreamConf,\n stripDSTElements\n )\nSelDSTWriterElements = {\n 'default' : stripDSTElements()\n }\nSelDSTWriterConf = {\n 'default' : stripDSTStreamConf()\n }\nif MODE == 'MC':\n dstWriter = SelDSTWriter( \"MyDSTWriter\",\n StreamConf = SelDSTWriterConf,\n MicroDSTElements = SelDSTWriterElements,\n OutputFileSuffix ='MC',\n SelectionSequences = sc.activeStreams()\n )\n\n###################### DAVINCI SETTINGS ############################################\nDaVinci().SkipEvents = 0 #1945\nDaVinci().PrintFreq = 1000\nDaVinci().EvtMax = EVTMAX\nDaVinci().TupleFile = \"DVTuples1.root\"\nDaVinci().HistogramFile = 'DVHistos.root'\nDaVinci().InputType = \"DST\"\nDaVinci().Simulation = False\nDaVinci().Lumi = True\nDaVinci().DataType = \"2012\"\nCondDB( LatestGlobalTagByDataType = '2012' )\n\nif False: # Add the DST writing algorithms\n DaVinci().appendToMainSequence( [ dstWriter.sequence(), printTree ] )\n\nif True: # Add the ntuple writing algorithms\n DaVinci().UserAlgorithms = [\n tuple_B2Kmumu\n ]\n if MODE == 'MC':\n DaVinci().Simulation = True\n DaVinci().Lumi = False\n DaVinci().UserAlgorithms += [\n mctuple_B2Kmumu\n ]\n\nif OUTPUTLEVEL == DEBUG:\n DaVinci().MoniSequence += [ mctree ]\n\nfrom Configurables import DaVinciInit\nDaVinciInit().OutputLevel = OUTPUTLEVEL\n\nif MODE != \"MC\":\n from Configurables import LumiIntegrateFSR, LumiIntegratorConf\n LumiIntegrateFSR('IntegrateBeamCrossing').SubtractBXTypes = ['None']\n\nMessageSvc().Format = \"% F%60W%S%7W%R%T %0W%M\"\n\n###################################################################################\n####################### THE END ###################################################\n###################################################################################\n","sub_path":"rd/MoM/python/DV_B2Kll_2012.py","file_name":"DV_B2Kll_2012.py","file_ext":"py","file_size_in_byte":10815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"340624930","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nfrom setuptools import setup, find_packages\n\nentry_points = \"\"\"\n[glue.plugins]\nglue_geospatial=glue_geospatial:setup\n\"\"\"\n\ntry:\n import pypandoc\n LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst')\nexcept (IOError, ImportError):\n with open('README.md') as infile:\n LONG_DESCRIPTION = infile.read()\n\nwith open('glue_geospatial/version.py') as infile:\n exec(infile.read())\n\nsetup(name='glue-geospatial',\n version=__version__,\n description='Experimental glue plugin for geospatial imagery',\n long_description=LONG_DESCRIPTION,\n url=\"https://github.com/glue-viz/glue-geospatial\",\n author='',\n author_email='',\n packages = find_packages(),\n package_data={},\n entry_points=entry_points,\n install_requires=['glueviz', 'rasterio']\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"121434291","text":"#This is the call file for the machine_move\nimport tic_tac_object_4\n\nprint(\"Hello! And welcome to Tic_Tac_Machine\"'\\n')\n\n# UNHIGHLIGHT THE BELOW IN PRODUCTION\n# player_1_ID = input(\"Who is Player 1: \")\n# player_1_level = input(\"Enter player level /10: \")\n# player_2_ID = input(\"Who is Player 2: \")\n# player_2_level = input(\"Enter player level /10: \")\n# level = input(\"Enter player level /10: \")\n# number_of_games = input(\"How many games would you like to play: \")\n\n# CHANGE THE BELOW AROUND TO PLAY THE GAME YOU WANT\n# LEVEL ONLY MATTERS FOR MACHINE. LEVEL 1 IS THE HUGE FILE, LEVEL 2 IS CONDENSED\nplayer_1_ID = 'machine'\nplayer_1_level = 1\nplayer_2_ID = 'human'\nplayer_2_level = 2\nnumber_of_games = 3\n\n\ngames_dictionary_library = {}\ngame_id = 0\nwhile game_id < int(number_of_games):\n print('\\n'\"Game ID: \" + str(game_id) + \">>>>>\")\n Game = tic_tac_object_4.Game(player_1_ID, player_1_level, player_2_ID, player_2_level)\n Game.play_game()\n games_dictionary_library[game_id] = Game.move_list, Game.winner_id\n game_id += 1\n Game.Game_Board.print_board_dict()\n print(Game.Game_Board.move_list)\n\nplayer_1_count = 0\nplayer_2_count = 0\nplayer_draw_count = 0\nfor game in games_dictionary_library:\n if games_dictionary_library[game][1] == 'Player_1':\n player_1_count += 1\n if games_dictionary_library[game][1] == 'Player_2':\n player_2_count += 1\n if games_dictionary_library[game][1] == 'Null':\n player_draw_count += 1\n\nwin_ratio = player_1_count/game_id\n\nprint(\"Player_1 won: \" + str(player_1_count) + \" times.\")\nprint(\"Player_2 won: \" + str(player_2_count) + \" times.\")\nprint(\"Draws happened: \" + str(player_draw_count) + \" times.\")\nprint(\"Player 1 win ratio: \" + str(round(win_ratio, 2)))\n","sub_path":"tic_tac_object_call.py","file_name":"tic_tac_object_call.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"139369685","text":"\"\"\"\nAnimal Shelter\n\nAn animal shelter, which holds only dogs and cats, operates in a strictly \"first in, first out\" basis.\nPeople must adopt either the \"oldest\" (based on arrival time) of all animals at the shelter, or\nthey can selet whether they would prefer a dog or a cat (and will recieve the oldest animal of that\ntype).\n\nThey cannot select which specific animal they would like. Create the data structures to maintain this system\nand implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may use the\nbuilt-in LinkedList data structure.\n\"\"\"\n\n\nfrom dataclasses import dataclass\nfrom collections import deque\n\n\n@dataclass\nclass Animal:\n name: str\n order: int = 0\n\n\nclass Cat(Animal):\n pass\n\n\nclass Dog(Animal):\n pass\n\n\n@dataclass\nclass Node:\n value: str\n next: \"Node\"\n\n\nclass AnimalShelter:\n \"\"\"This is my implementation of the animal shelter\"\"\"\n\n def __init__(self):\n self.head = None\n self.current = None\n\n def enqueue(self, animal: Animal):\n node = Node(animal, None)\n\n if not self.head:\n self.head = node\n self.current = node\n else:\n self.current.next = node\n self.current = node\n\n def dequeue_cat(self) -> Cat:\n return self.dequeue(Cat)\n\n def dequeue_dog(self) -> Dog:\n return self.dequeue(Dog)\n\n def dequeue(self, animal_type=None) -> Animal:\n if not self.head:\n raise ValueError(\"Shelter is empty\")\n\n value = self.head\n prev = None\n\n if animal_type:\n while not isinstance(value.value, animal_type):\n prev = value\n value = value.next\n\n if prev:\n prev.next = value.next\n else:\n self.head = self.head.next\n\n value.next = None\n return value\n\n\nclass BookAnimalShelter:\n def __init__(self):\n self.dogs = deque()\n self.cats = deque()\n self.order = 0\n\n def enqueue(self, animal):\n animal.order = self.order\n self.order += 1\n\n if isinstance(animal, Dog):\n self.dogs.append(animal)\n else:\n self.cats.append(animal)\n\n def dequeue(self):\n if not self.dogs:\n return self.dequeue_cat()\n elif not self.cats:\n return self.dequeue_dog()\n\n cat = self.cats[0]\n dog = self.dogs[0]\n\n if dog.order > cat.order:\n return self.dequeue_cat()\n else:\n return self.dequeue_dog()\n\n def dequeue_cat(self):\n return self.cats.popleft()\n\n def dequeue_dog(self):\n return self.dogs.popleft()\n\n\nif __name__ == \"__main__\":\n shelter = BookAnimalShelter()\n shelter.enqueue(Cat(\"Thunder\"))\n shelter.enqueue(Dog(\"Lala\"))\n shelter.enqueue(Cat(\"Inácio\"))\n shelter.enqueue(Dog(\"Tove\"))\n\n print(shelter.dequeue())\n print(shelter.dequeue_dog())\n print(shelter.dequeue_cat())\n\n shelter.enqueue(Dog(\"Dog\"))\n\n print(shelter.dequeue())\n","sub_path":"python/stacks_queues/question_3_6.py","file_name":"question_3_6.py","file_ext":"py","file_size_in_byte":2999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"295411052","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport dgl\nimport dgl.function as fn\n\nfrom layers.wls_layer import WLSMLPLayer\nfrom layers.mlp_readout_layer import MLPReadout\n\nclass WLSMLPNetSBM(nn.Module):\n def __init__(self, net_params):\n super().__init__()\n\n n_iter = net_params.pop('n_iter')\n num_node_types = net_params.pop('in_dim')\n embed_dim, hidden_dim, out_dim = net_params.pop('embed_dim'), net_params.pop('hidden_dim'), net_params.pop('out_dim')\n n_mlp_layer, scale_mlp, dropout = net_params.pop('n_mlp_layer'), net_params.pop('scale_mlp'), net_params.pop('dropout')\n self.n_classes = net_params.pop('n_classes')\n\n hidden_dim = hidden_dim + (hidden_dim % 2)\n out_dim = out_dim + (out_dim % 2)\n\n layers = []\n\n _layer = WLSMLPLayer(embed_dim, hidden_dim, n_mlp_layer, scale_mlp, dropout, **net_params)\n layers.append(_layer)\n layers.append(nn.BatchNorm1d(hidden_dim))\n\n for _ in range(n_iter - 2):\n _layer = WLSMLPLayer(hidden_dim, hidden_dim, n_mlp_layer, scale_mlp, dropout, **net_params)\n layers.append(_layer)\n layers.append(nn.BatchNorm1d(hidden_dim))\n\n _layer = WLSMLPLayer(hidden_dim, out_dim, n_mlp_layer, scale_mlp, dropout, **net_params)\n layers.append(_layer)\n layers.append(nn.BatchNorm1d(out_dim))\n \n self.n_embedding = nn.Embedding(num_node_types, embed_dim)\n self.layers = nn.ModuleList(layers)\n self.classifier = MLPReadout(out_dim, self.n_classes)\n\n def forward(self, graph, node_feat, edge_feat, snorm_n, snorm_e):\n node_feat = self.n_embedding(node_feat)\n\n for layer in self.layers:\n if not isinstance(layer, nn.BatchNorm1d):\n node_feat = layer(graph, node_feat)\n else:\n node_feat = layer(node_feat)\n\n predict = self.classifier(node_feat)\n\n return predict\n\n def loss(self, predict, label):\n # calculating label weights for weighted loss computation\n V = label.size(0)\n label_count = torch.bincount(label)\n label_count = label_count[label_count.nonzero()].squeeze()\n cluster_sizes = torch.zeros(self.n_classes).long().cuda()\n cluster_sizes[torch.unique(label)] = label_count\n weight = (V - cluster_sizes).float() / V\n weight *= (cluster_sizes>0).float()\n \n # weighted cross-entropy for unbalanced classes\n criterion = nn.CrossEntropyLoss(weight=weight)\n loss = criterion(predict, label)\n\n return loss\n\n\n \n","sub_path":"graphsim-code-wls/nets/SBMs_node_classification/wls_net.py","file_name":"wls_net.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"147949500","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score, accuracy_score\nimport dataset_utils\nfrom scipy import interp\nfrom collections import defaultdict\nnp.random.seed(7)\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nimport keras\nfrom keras.layers import Input, Dense, Dropout\nfrom keras.models import Model\nfrom keras import regularizers\ntf.set_random_seed(1)\n\n\n# Hyper-parameters\nEPOCH = 500\nBATCH_SIZE = 24\nLR = 0.001\nK = 5\n\n\ndef make_base_model(n_input, n_hidden):\n \"\"\"\n Creates the keras neural network.\n Architecture: genes -> gene sets -> hidden layer -> output; drugs -> hidden layer -> output\n :param n_input: number of genes\n :param n_hidden: number of gene sets\n :return: keras neural net\n \"\"\"\n inputs = Input(shape=(n_input,), name='gene_input')\n pathways = Dense(\n n_hidden,\n activation='relu',\n kernel_initializer='glorot_normal',\n # kernel_regularizer=regularizers.l1(0.0012) #0.001\n )(inputs)\n\n drug_input = Input(shape=(2,), name='drug_input')\n x = keras.layers.concatenate([pathways, drug_input])\n\n predictions = Dense(1, activation='sigmoid', kernel_initializer='glorot_normal')(x)\n\n model = Model(inputs=[inputs, drug_input], outputs=predictions)\n\n # Configure a model for categorical classification.\n model.compile(optimizer=tf.train.AdamOptimizer(LR),\n loss=keras.losses.binary_crossentropy,\n metrics=[keras.metrics.binary_accuracy])\n return model\n\n\n# Zero out weights that do not correspond to relation\nclass ZeroWeights(keras.callbacks.Callback):\n def __init__(self, t):\n super(ZeroWeights, self).__init__()\n self.t = t\n\n def on_train_begin(self, logs=None):\n self.zero_weights()\n\n def on_batch_end(self, batch, logs=None):\n self.zero_weights()\n\n def zero_weights(self):\n w, b = self.model.layers[1].get_weights()\n self.model.layers[1].set_weights([w * self.t, b])\n\n\ndef get_edges(top_sets=None):\n \"\"\"\n Reads in the adjacency matrix between genes and gene sets.\n :return: adjacency matrix\n \"\"\"\n if top_sets:\n df = dataset_utils.top_gene_set_connections(top_sets)\n else:\n df = pd.read_csv(\"connections_1.csv\", index_col=0)\n return df.values\n\n\ndef run():\n gene_set_mapping = {}\n with open(\"gene_set_mapping.txt\", \"r\") as f:\n for line in f:\n tokens = line.split()\n gene_set_mapping[int(tokens[0])] = tokens[1]\n\n all_auc = defaultdict(list)\n tprs = defaultdict(list)\n aucs = defaultdict(list)\n acc = defaultdict(float)\n pos = ['c', 'l', 't', 'cl']\n mean_fpr = np.linspace(0, 1, 100)\n\n for j in range(1):\n c_train_sets, c_test_sets, c_val_sets = dataset_utils.kfold_train_test_sets('../c_rnaseq_scaled_symbols.csv', seed=j*j)\n l_train_sets, l_test_sets, l_val_sets = dataset_utils.kfold_train_test_sets('../l_rnaseq_scaled_symbols.csv', seed=j*j)\n t_train_sets, t_test_sets, t_val_sets = dataset_utils.kfold_train_test_sets('../t_rnaseq_scaled_symbols.csv', seed=j*j)\n\n cl_test = pd.read_csv('../cell_lines_scaled_symbols.csv', index_col=0)\n cl_test = cl_test.fillna(0)\n cl_test = np.array(cl_test)\n\n cl_test_data, cl_test_drug, cl_test_labels = cl_test[:, :-3], cl_test[:, -3:-1], cl_test[:, -1]\n\n train_sets = []\n val_sets = []\n for i in range(5):\n train_sets.append(pd.concat([c_train_sets[i], l_train_sets[i], t_train_sets[i]]))\n val_sets.append(pd.concat([c_val_sets[i], l_val_sets[i], t_val_sets[i]]))\n\n t = get_edges(\"noreg_top_sets.txt\")\n\n for k in range(5):\n train, val, c_test, l_test, t_test = train_sets[k], val_sets[k], c_test_sets[k], l_test_sets[k], t_test_sets[k]\n train, val, c_test, l_test, t_test = np.array(train), np.array(val), np.array(c_test), np.array(l_test), np.array(t_test)\n\n # using numpy arrays\n train_data, train_drug, train_labels = train[:, :-3], train[:, -3:-1], train[:, -1]\n val_data, val_drug, val_labels = val[:, :-3], val[:, -3:-1], val[:, -1]\n c_test_data, c_test_drug, c_test_labels = c_test[:, :-3], c_test[:, -3:-1], c_test[:, -1]\n l_test_data, l_test_drug, l_test_labels = l_test[:, :-3], l_test[:, -3:-1], l_test[:, -1]\n t_test_data, t_test_drug, t_test_labels = t_test[:, :-3], t_test[:, -3:-1], t_test[:, -1]\n\n callbacks = [\n # Interrupt training if `val_acc` stops improving for over K epochs\n keras.callbacks.EarlyStopping(patience=K, monitor='val_binary_accuracy'),\n ZeroWeights(t),\n ]\n model = make_base_model(t.shape[0], t.shape[1])\n model.fit({'gene_input': train_data, 'drug_input': train_drug}, train_labels, epochs=EPOCH, batch_size=BATCH_SIZE, callbacks=callbacks, verbose=0,\n validation_data=([val_data, val_drug], val_labels))\n\n test_data = [c_test_data, l_test_data, t_test_data, cl_test_data]\n test_drug = [c_test_drug, l_test_drug, t_test_drug, cl_test_drug]\n test_labels = [c_test_labels, l_test_labels, t_test_labels, cl_test_labels]\n\n for i in range(4):\n y_pred = model.predict([test_data[i], test_drug[i]]).flatten()\n\n pred = y_pred > 0.5\n truth = test_labels[i] > 0.5\n all_auc[pos[i]].append(roc_auc_score(test_labels[i].astype(np.float32), pred))\n\n fpr, tpr, thresholds = roc_curve(truth, y_pred)\n tprs[pos[i]].append(interp(mean_fpr, fpr, tpr))\n tprs[pos[i]][-1][0] = 0.0\n roc_auc = auc(fpr, tpr)\n aucs[pos[i]].append(roc_auc)\n acc[pos[i]] += accuracy_score(truth, pred)\n\n with open(\"noreg_top_multi_trast_out_NN.txt\", \"w\") as f:\n f.write(\"tprs\\n\")\n for arr in tprs['t']:\n for val in arr:\n f.write(str(val) + \"\\t\")\n f.write(\"\\n\")\n f.write(\"aucs\\n\")\n for val in aucs['t']:\n f.write(str(val) + \"\\t\")\n f.write(\"\\n\")\n\n with open(\"noreg_top_multi_combo_out_NN.txt\", \"w\") as f:\n f.write(\"tprs\\n\")\n for arr in tprs['c']:\n for val in arr:\n f.write(str(val) + \"\\t\")\n f.write(\"\\n\")\n f.write(\"aucs\\n\")\n for val in aucs['c']:\n f.write(str(val) + \"\\t\")\n f.write(\"\\n\")\n\n with open(\"noreg_top_multi_lap_out_NN.txt\", \"w\") as f:\n f.write(\"tprs\\n\")\n for arr in tprs['l']:\n for val in arr:\n f.write(str(val) + \"\\t\")\n f.write(\"\\n\")\n f.write(\"aucs\\n\")\n for val in aucs['l']:\n f.write(str(val) + \"\\t\")\n f.write(\"\\n\")\n\n with open(\"noreg_top_multi_cl_lap_NN.txt\", \"w\") as f:\n f.write(\"tprs\\n\")\n for arr in tprs['cl']:\n for val in arr:\n f.write(str(val) + \"\\t\")\n f.write(\"\\n\")\n f.write(\"aucs\\n\")\n for val in aucs['cl']:\n f.write(str(val) + \"\\t\")\n f.write(\"\\n\")\n\n for i in range(4):\n print(pos[i] + \" accuracy:\")\n print(acc[pos[i]]/15.)\n\nrun()","sub_path":"NeoALTTO/gene_ontology/top_sets.py","file_name":"top_sets.py","file_ext":"py","file_size_in_byte":7274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"242076849","text":"def estritamente_crescente(n):\n lista=[]\n lista0=[]\n b=0\n i=0\n a=1\n while b current_date - interval \"\n\t\t\t\t\t\t\"'30' AND account_id = :id;\")\n\t\telse:\n\t\t\tstmt = text(\"SELECT COUNT(DISTINCT date) FROM session WHERE date BETWEEN date('now', '-30 days') AND date(\"\n\t\t\t\t\t\"'now', 'localtime') AND account_id = :id;\")\n\n\t\tres = db.engine.execute(stmt, id=current_user.id)\n\t\tresult = []\n\t\tfor row in res:\n\t\t\tresult.append(row[0])\n\n\t\treturn result[0]\n\n\t@staticmethod\n\tdef count_sessions():\n\t\tstmt = text(\"SELECT COUNT(*) FROM session;\")\n\t\tres = db.engine.execute(stmt)\n\t\tresult = []\n\t\tfor row in res:\n\t\t\tresult.append(row[0])\n\n\t\treturn result[0]\n\n\nclass Result(db.Model):\n\tid = db.Column(db.Integer, primary_key=True)\n\tsession_id = db.Column(db.Integer, db.ForeignKey('session.id'))\n\nclass Conditioning(Result):\n\tid = db.Column(db.ForeignKey(\"result.id\"), primary_key=True)\n\tdistance = db.Column(db.Integer, nullable=False)\n\ttime = db.Column(db.Time, nullable=False)\n\tworkout_id = db.Column(db.Integer, db.ForeignKey('session.id'))\n\n\t@staticmethod\n\tdef find_personal_bests():\n\t\tstmt = text(\"SELECT max(date), distance, min(time) AS time FROM Conditioning \"\n\t\t\t\t\t\"JOIN result ON conditioning.id=result.id JOIN session ON session.id=session_id \"\n\t\t\t\t\t\"WHERE account_id = :id GROUP BY distance;\")\n\n\t\tres = db.engine.execute(stmt, id=current_user.id)\n\t\tresult = []\n\t\tfor row in res:\n\t\t\tresult.append(((row[0]),(row[1]), row[2]))\n\n\t\treturn result\n\nclass Strength(Result):\n\tid = db.Column(db.ForeignKey(\"result.id\"), primary_key=True)\n\treps = db.Column(db.Integer, nullable=False)\n\tweight = db.Column(db.Integer, nullable=False)\n\tworkout_id = db.Column(db.Integer, db.ForeignKey('workout.id'))\n\n\t@staticmethod\n\tdef find_personal_bests():\n\t\tstmt = text(\"SELECT max(date), workout.name, reps, max(weight) AS weight FROM Strength \"\n\t\t\t\t\t\"JOIN workout ON workout.id=strength.workout_id JOIN result ON strength.id=result.id \"\n\t\t\t\t\t\"JOIN session ON session.id=session_id \"\n\t\t\t\t\t\"WHERE account_id = :id GROUP BY workout.name, reps;\")\n\n\t\tres = db.engine.execute(stmt, id=current_user.id)\n\t\tresult = []\n\t\tfor row in res:\n\t\t\tresult.append(((row[0]), (row[1]), row[2], row[3]))\n\n\t\treturn result\n\nclass Workout(db.Model):\n\tid = db.Column(db.Integer, primary_key=True)\n\tname = db.Column(db.String(144), nullable=False)","sub_path":"application/result/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"194892047","text":"# Copyright (c) Vidar Tonaas Fauske.\n# Distributed under the terms of the Modified BSD License.\n\nimport os\nimport sys\n\nimport tornado.web\nfrom traitlets import HasTraits, Bool, Unicode, default\nfrom jupyter_core.paths import jupyter_config_path\nfrom jupyterlab.commands import (\n get_app_dir,\n get_app_info,\n get_user_settings_dir,\n get_workspaces_dir,\n)\nfrom jupyterlab_server.handlers import (\n is_url,\n LabConfig,\n LabHandler,\n ThemesHandler,\n)\nfrom jupyterlab_server.server import (\n FileFindHandler,\n url_path_join as ujoin,\n)\nfrom jupyterlab_server.workspaces_handler import WorkspacesHandler\nfrom jupyterlab_server.settings_handler import SettingsHandler\nfrom voila.paths import notebook_path_regex\n\nfrom ._version import __version__\n\nHERE = os.path.dirname(__file__)\n\n\ndef load_config(nbapp):\n config = LabConfig(\n app_url='/phoila',\n tree_url='/voila/tree'\n )\n app_dir = getattr(nbapp, 'app_dir', get_app_dir())\n info = get_app_info(app_dir)\n static_url = info['staticUrl']\n user_settings_dir = getattr(\n nbapp, 'user_settings_dir', get_user_settings_dir()\n )\n workspaces_dir = getattr(nbapp, 'workspaces_dir', get_workspaces_dir())\n\n config.app_dir = app_dir\n config.app_name = 'Phoila'\n config.app_namespace = 'phoila'\n config.app_settings_dir = os.path.join(app_dir, 'settings')\n config.cache_files = True\n config.schemas_dir = os.path.join(app_dir, 'schemas')\n config.templates_dir = os.path.join(app_dir, 'static')\n config.themes_dir = os.path.join(app_dir, 'themes')\n config.user_settings_dir = user_settings_dir\n config.workspaces_dir = os.path.join(app_dir, 'workspaces')\n\n if getattr(nbapp, 'override_static_url', ''):\n static_url = nbapp.override_static_url\n if getattr(nbapp, 'override_theme_url', ''):\n config.themes_url = nbapp.override_theme_url\n config.themes_dir = ''\n\n if static_url:\n config.static_url = static_url\n else:\n config.static_dir = os.path.join(app_dir, 'static')\n\n return config\n\ndef _load_jupyter_server_extension(nb_server_app):\n if 'JUPYTERLAB_DIR' not in os.environ:\n os.environ['JUPYTERLAB_DIR'] = os.path.join(\n sys.prefix, 'share', 'jupyter', 'phoila')\n if 'JUPYTERLAB_SETTINGS_DIR' not in os.environ:\n os.environ['JUPYTERLAB_SETTINGS_DIR'] = os.path.join(\n jupyter_config_path()[0], 'phoila', 'settings'\n )\n if 'JUPYTERLAB_WORKSPACES_DIR' not in os.environ:\n os.environ['JUPYTERLAB_WORKSPACES_DIR'] = os.path.join(\n jupyter_config_path()[0], 'phoila', 'workspaces'\n )\n config = load_config(nb_server_app)\n return add_handlers(nb_server_app.web_app, config)\n\n\ndef add_handlers(web_app, config):\n \"\"\"Add the appropriate handlers to the web app.\n \"\"\"\n # Normalize directories.\n for name in config.trait_names():\n if not name.endswith('_dir'):\n continue\n value = getattr(config, name)\n setattr(config, name, value.replace(os.sep, '/'))\n\n # Normalize urls\n # Local urls should have a leading slash but no trailing slash\n for name in config.trait_names():\n if not name.endswith('_url'):\n continue\n value = getattr(config, name)\n if is_url(value):\n continue\n if not value.startswith('/'):\n value = '/' + value\n if value.endswith('/'):\n value = value[:-1]\n setattr(config, name, value)\n\n # Set up the main page handler and tree handler.\n base_url = web_app.settings.get('base_url', '/')\n app_path = ujoin(base_url, config.app_url)\n handlers = [\n (app_path, LabHandler, {'lab_config': config}),\n # + notebook_path_regex + '?'\n ]\n\n # Cache all or none of the files depending on the `cache_files` setting.\n no_cache_paths = [] if config.cache_files else ['/']\n\n # Handle local static assets.\n if config.static_dir:\n static_path = ujoin(base_url, config.static_url, '(.*)')\n handlers.append((static_path, FileFindHandler, {\n 'path': config.static_dir,\n 'no_cache_paths': no_cache_paths\n }))\n\n # Handle local settings.\n if config.schemas_dir:\n settings_config = {\n 'app_settings_dir': config.app_settings_dir,\n 'schemas_dir': config.schemas_dir,\n 'settings_dir': config.user_settings_dir\n }\n\n # Handle requests for the list of settings. Make slash optional.\n settings_path = ujoin(base_url, config.settings_url, '?')\n handlers.append((settings_path, SettingsHandler, settings_config))\n\n # Handle requests for an individual set of settings.\n setting_path = ujoin(\n base_url, config.settings_url, '(?P.+)')\n handlers.append((setting_path, SettingsHandler, settings_config))\n\n # Handle saved workspaces.\n if config.workspaces_dir:\n # Handle JupyterLab client URLs that include workspaces.\n workspaces_path = ujoin(base_url, config.workspaces_url, r'.+')\n handlers.append((workspaces_path, LabHandler, {'lab_config': config}))\n\n workspaces_config = {\n 'workspaces_url': config.workspaces_url,\n 'path': config.workspaces_dir\n }\n\n # Handle requests for the list of workspaces. Make slash optional.\n workspaces_api_path = ujoin(base_url, config.workspaces_api_url, '?')\n handlers.append((\n workspaces_api_path, WorkspacesHandler, workspaces_config))\n\n # Handle requests for an individually named workspace.\n workspace_api_path = ujoin(\n base_url, config.workspaces_api_url, '(?P.+)')\n handlers.append((\n workspace_api_path, WorkspacesHandler, workspaces_config))\n\n # Handle local themes.\n if config.themes_dir:\n themes_url = ujoin(base_url, config.themes_url)\n themes_path = ujoin(themes_url, '(.*)')\n handlers.append((\n themes_path,\n ThemesHandler,\n {\n 'themes_url': themes_url,\n 'path': config.themes_dir,\n 'no_cache_paths': no_cache_paths\n }\n ))\n\n web_app.add_handlers('.*$', handlers)\n","sub_path":"phoila/server_extension.py","file_name":"server_extension.py","file_ext":"py","file_size_in_byte":6273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"450486558","text":"\"\"\"Helpers for Kamereon models.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Any\nfrom typing import Dict\n\nfrom . import models\n\nDAYS_OF_WEEK = [\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n \"sunday\",\n]\n\n\ndef update_schedule(schedule: models.ChargeSchedule, settings: Dict[str, Any]) -> None:\n \"\"\"Update schedule.\"\"\"\n for day in DAYS_OF_WEEK:\n if day in settings.keys():\n day_settings = settings[day]\n\n if day_settings: # pragma: no branch\n start_time = day_settings[\"startTime\"]\n duration = day_settings[\"duration\"]\n\n setattr(\n schedule,\n day,\n models.ChargeDaySchedule(day_settings, start_time, duration),\n )\n\n\ndef create_schedule(\n settings: Dict[str, Any]\n) -> models.ChargeSchedule: # pragma: no cover\n \"\"\"Update schedule.\"\"\"\n raise NotImplementedError\n","sub_path":"src/renault_api/kamereon/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"654428046","text":"# exercise-06.py\n\nimport random\n\n# exo 6.1\n# Créez une liste nommée `my_list` contenant un nombre entier, un nombre à virgule flottante, une chaîne de caractères et un booléen\n\n# réponse 6.1\n\n# exo 6.2\n# Affichez l'élément qui se trouve à la troisième position de la liste\nmy_list = ['foo', 'bar', 'baz', 'lorem', 'ipsum']\n\n# réponse 6.2\n\n# exo 6.3\n# Ajoutez une chaîne de caractères à la fin de la liste `my_list` (sans modfier le code d'initialisation) et affichez le résultat\nmy_list = ['foo', 'bar', 'baz', 'lorem', 'ipsum']\n\n# réponse 6.3\n\n# exo 6.4\n# Supprimez l'élément qui se trouve en deuxièm position de la liste et affichez le résultat\nmy_list = ['foo', 'bar', 'baz', 'lorem', 'ipsum']\n\n# réponse 6.4\n\n# exo 6.5\n# Remplacez l'élément qui se trouve en deuxièm position de la liste par un nombre entier et affichez le résultat\nmy_list = ['foo', 'bar', 'baz', 'lorem', 'ipsum']\n\n# réponse 6.5\n\n# exo 6.6\n# Affichez la taille de la liste\nmy_list = ['foo', 'bar', 'baz', 'lorem', 'ipsum']\n\n# réponse 6.6\n\n# exo 6.7\n# Inversez la position des valeurs `bar` et `lorem` puis affichez le résultat\nmy_list = ['foo', 'bar', 'baz', 'lorem', 'ipsum']\n\n# réponse 6.7\n\n# Remarque : les exercices suivants nécessitent l'utilisation d'une boucle `for`\n\n# exo 6.8\n# Calculez la somme des nombres de la liste et affichez le résultat\nmy_list = [2.71, 42]\n\n# réponse 6.8\n\n# exo 6.9\n# Calculez la somme des nombres de la liste et affichez le résultat\nmy_list = [2.71, 42, 123, 2, 3.14, 1.61]\n\n# réponse 6.9\n\n# exo 6.10\n# Calculez la moyenne des nombres de la liste et affichez le résultat\nmy_list = [2.71, 42, 123, 2, 3.14, 1.61]\n\n# réponse 6.10\n\n# exo 6.11\n# Trouvez l'index de la valeur `3.14` dans la liste et affichez le résultat\nmy_list = [2.71, 42, 123, 2, 3.14, 1.61]\n\n# réponse 6.11\n\n# exo 6.12\n# Comptez les nombres plus petits ou égaux à 10 dans la liste et affichez le résultat\nmy_list = [2.71, 42, 123, 2, 3.14, 1.61]\n\n# réponse 6.12\n\n# exo 6.13\n# Multipliez chacun des nombres dans la liste par 100, réaffactez le résultat à la place de la valeur originelle puis affichez le résultat\nmy_list = [2.71, 42, 123, 2, 3.14, 1.61]\n\n# réponse 6.13\n\n# exo 6.14\n# Créez une deuxième liste ne contenant que les nombre entiers de la liste\nmy_list = [2.71, 42, 123, 2, 3.14, 1.61]\n\n# réponse 6.14\n\n# exo 6.15\n# Ici le but est d'intervertir les éléments de la liste deux à deux\n# Liste initiale :\n#\n# my_list = [2.71, 42, 123, 2, 3.14, 1.61]\n#\n# Résultat attendu :\n#\n# my_list = [42, 2.71, 2, 123, 1.61, 3.14]\nmy_list = [2.71, 42, 123, 2, 3.14, 1.61]\n\n# réponse 6.15\n\n# exo 6.16\n# Triez la liste en utilisant l'algorithme du tri bulle puis affichez la liste\nmy_list = [2.71, 42, 123, 2, 3.14, 1.61]\n\n# réponse 6.16\n\n# code 6.1\n# Lire la valeur de la ligne `m` et de la colonne `n` d'un tableau en 2 dimensions\n# print(matrix[m][n])\n#\n# Exemple avec la ligne 2 (index 1) et la colonne 3 (index 2)\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n]\n# Cette ligne affiche `6`\nprint(matrix[1][2])\n\n# exo 6.17\n# Affichez la valeur qui se trouve à la colonne 4, ligne 3\n# Attention : il faut faire `- 1` pour obtenir les index correspondant\nsize = 5\nmatrix = []\n\nfor _ in range(0, size):\n row = [random.randint(40, 100) for _ in range(0, size)]\n matrix.append(row)\n\nprint(matrix)\n\n# réponse 6.17\n\n# code 6.2\n# Pour afficher toutes les combinaisons possibles de deux nombres de 0 à n inclus vous pouvez utiliser deux boucles `for` imbriquées\n#\n# Exemple de toutes les combinaisons possibles de deux nombres de 0 à 2 inclus\nfor i in range(0, 3):\n for j in range(0, 3):\n print(i, j)\n\n# exo 6.18\n# Avec le même tableau en 2 dimensions, affichez toutes les valeurs plus petites ou égales à 50 ainsi que leur cordoonnées (ligne et colonne)\n\n# réponse 6.18\n\n","sub_path":"exercise-06.py","file_name":"exercise-06.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"192480414","text":"from neighbors import neighbors\ndef frequent_words_with_mismatches(text, k, d):\n '''\n Finds most frequent k-mers within the text with at most d mismatches. Does so by sliding a\n k-sized window down the text to find a pattern, generates the likely d-neighborhood for that\n pattern, and stores the frequency of those neighbors in a map. Then, the patterns with the\n max frequency are returned. Runs in O(n * k^2) time, where n is the length of the text and\n k is the length of the pattern.\n\n Parameters:\n text (str): Sequence in which k-mers are being searched for\n k (int): size of k-mer\n d (int): maximum Hamming Distance between k-mer and neighbors\n\n Returns:\n patterns (str(list)): all k-mers with frequence == max\n '''\n patterns = []\n frequency_map = {}\n for i in range(len(text) + 1 - k):\n pattern = text[i: i + k]\n neighborhood = neighbors(pattern, d)\n for neighbor in neighborhood:\n if neighbor in frequency_map:\n frequency_map[neighbor] += 1\n else:\n frequency_map[neighbor] = 1\n max_val = frequency_map[max(frequency_map, key = frequency_map.get)]\n for pattern in frequency_map:\n if frequency_map[pattern] == max_val:\n patterns.append(pattern)\n return patterns\n\ndef read_file(file):\n #parses text file from Rosalind to obtain sequence, k-mer size, and max Hamming Distance and\n #trims output for submission\n lines = [line.rstrip() for line in open(file)]\n nums = lines.pop().split(\" \")\n k, d = int(nums[0]), int(nums[1])\n seq = lines[0]\n print(\" \".join(frequent_words_with_mismatches(seq, k, d)))\n\n","sub_path":"Chapter_1/frequent_words_with_mismatches.py","file_name":"frequent_words_with_mismatches.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"611790343","text":"import pandas as pd\nimport numpy as np\nimport datetime\n\ndef m2_over_rate():\n data = pd.read_excel(\"扣罚数据输入/M2M3逾期明细.xlsx\", dtype={'贷款编号': 'O', 'SA工号': 'O'})\n m2 = data[data[\"首次M2\"] == 1]\n m2_over_count = pd.pivot_table(m2, index=['SA工号'], values=['贷款编号'], aggfunc=[len])\n m2_zc = pd.read_excel(\"扣罚数据输入/首次M2注册数.xlsx\", dtype={'SA工号': 'O'})\n m2_over_rate = pd.merge(m2_zc, m2_over_count, on=\"SA工号\", how=\"left\")\n for i in range(len(m2_over_rate)):\n m2_over_rate.loc[i, '首次M2逾期率'] = (m2_over_rate.iloc[i, 3] / m2_over_rate.iloc[i, 2]) * 100\n # 得到首次M2逾期率\n m2_over_rate = m2_over_rate[['SA工号', '首次M2逾期率']]\n return m2_over_rate\n\n\ndef m2_plus(m2_over_rate):\n data2 = pd.read_excel(\"扣罚数据输入/M2+逾期明细.xlsx\", dtype={'贷款编号': 'O', 'SA工号': 'O'})\n # M2已经扣的剔除\n def yikou():\n # 汇总首次M2和M2+的已经扣罚和退还的\n data11 = pd.read_excel(\"扣罚汇总/M2+扣罚汇总.xlsx\", dtype={'贷款编号': 'O', 'SA工号': 'O'})\n data22 = pd.read_excel(\"扣罚汇总/首次M2扣罚汇总.xlsx\", dtype={'贷款编号': 'O', 'SA工号': 'O'})\n yikou = pd.concat([data11, data22])\n return yikou\n\n yikou = yikou()\n yikou = yikou[['贷款编号', '扣押月份', '退还月份']]\n data_m2_plus = pd.merge(data2, yikou, on=\"贷款编号\", how=\"left\")\n\n for i in range(len(data_m2_plus)):\n if np.isnan(data_m2_plus.loc[i, \"扣押月份\"]) == False and np.isnan(data_m2_plus.loc[i, \"退还月份\"]) == True:\n data_m2_plus.drop([i], inplace=True)\n else:\n pass\n\n data_m2_plus = data_m2_plus.reset_index(drop=True) # 对索引重置\n data_m2_plus = data_m2_plus[['SA工号', 'SA姓名']]\n # 提取首次M2的数据\n data_first_m2 = pd.read_excel(\"扣罚数据输入/M2M3逾期明细.xlsx\", dtype={'贷款编号': 'O', 'SA工号': 'O'})\n data_first_m2 = data_first_m2[data_first_m2[\"首次M2\"] == 1]\n data_first_m2 = data_first_m2[['SA工号', 'SA姓名']]\n data_all = pd.concat([data_first_m2, data_m2_plus]).drop_duplicates(['SA工号']) # 去重\n data_all = data_all.reset_index(drop=True)\n #导入M3逾期率\n overdue_rate_m3 = pd.read_excel(\"扣罚数据输入/M3+逾期率.xlsx\",dtype={'SA工号':'O'})\n overdue_rate_m3 = overdue_rate_m3[['SA工号','M3+逾期率(%)']]\n people_list = pd.read_excel(\"扣罚数据输入/销售人员清单.xlsx\",dtype={'SA工号':'O','入岗日期转换':np.datetime64})\n people_list = people_list[['SA工号','姓名','在岗状态','入岗日期转换','结算日期','在职天数']]\n data_all = pd.merge(data_all,people_list, on=\"SA工号\",how=\"left\",)\n data_all = pd.merge(data_all,m2_over_rate,on=\"SA工号\",how=\"left\")\n data_all = pd.merge(data_all,overdue_rate_m3,on=\"SA工号\",how=\"left\")\n #将NA的换成0\n for i in range(len(data_all)):\n if np.isnan(data_all.loc[i,\"首次M2逾期率\"]):\n data_all.loc[i,\"首次M2逾期率\"] = 0\n else:\n pass\n\n for i in range(len(data_all)):\n if np.isnan(data_all.loc[i,\"M3+逾期率(%)\"]):\n data_all.loc[i,\"M3+逾期率(%)\"] = 0\n else:\n pass\n return data_all\n\n\ndef is_mianchu(data_all):\n for i in range(len(data_all)):\n if data_all.loc[i, \"在职天数\"] >= 90:\n if data_all.loc[i, \"首次M2逾期率\"] < 5.0:\n if data_all.loc[i, \"M3+逾期率(%)\"] < 7.0:\n data_all.loc[i, \"是否免除扣罚\"] = \"免\"\n else:\n data_all.loc[i, \"是否免除扣罚\"] = \"不\"\n else:\n data_all.loc[i, \"是否免除扣罚\"] = \"不\"\n else:\n if data_all.loc[i, \"首次M2逾期率\"] < 4.0:\n data_all.loc[i, '是否免除扣罚'] = \"免\"\n else:\n data_all.loc[i, \"是否免除扣罚\"] = \"不\"\n return data_all\n\ndef save(data_all):\n print(\"正在保存SA扣罚标准数据\")\n data_all = data_all[[\"SA工号\", \"SA姓名\", \"在岗状态\", \"入岗日期转换\", \"结算日期\", \"在职天数\", \"M3+逾期率(%)\", \"首次M2逾期率\", \"是否免除扣罚\"]]\n data_all.to_excel('数据输出/SA扣罚标准.xlsx',index=False)\n\n\n#SA首次M2单笔扣罚\n\ndef m2_first():\n print('开始计算SA的首次M2单笔扣罚')\n zmd = pd.read_excel('扣罚数据输入/主门店汇总.xlsx', dtype={'贷款编号': 'O'})\n m2 = pd.read_excel(\"扣罚数据输入/M2M3逾期明细.xlsx\", dtype={'贷款编号': 'O', 'SA工号': 'O'})\n m2 = m2[m2[\"首次M2\"] == 1]\n m2 = m2[['贷款编号', '贷款金额', '产品名称', '商户', '门店', 'SA工号', 'SA姓名']]\n m2 = pd.merge(m2, zmd, on=\"贷款编号\", how=\"left\")#加上主门店的扣款\n\n for i in range(len(m2)):\n if m2.loc[i, '产品名称'] == '一般产品' or m2.loc[i, '产品名称'] == '优惠产品' or m2.loc[i, '产品名称'] == '优惠产品A' or m2.loc[\n i, '产品名称'] == '优惠产品B':\n if m2.loc[i, '贷款金额'] >= 1500:\n m2.loc[i, '扣罚'] = 180\n else:\n m2.loc[i, '扣罚'] = 90\n elif m2.loc[i, '产品名称'] == '003产品':\n m2.loc[i, '扣罚'] = 60\n elif m2.loc[i, '产品名称'] == \"U客购\":\n m2.loc[i, '扣罚'] = 300\n else:\n if m2.loc[i, '贷款金额'] >= 2300:\n m2.loc[i, '扣罚'] = 120\n elif 1800 <= m2.loc[i, '贷款金额'] < 2300:\n m2.loc[i, '扣罚'] = 80\n else:\n m2.loc[i, '扣罚'] = 40\n\n for i in range(len(m2)):\n if np.isnan(m2.loc[i, '每日提成金额']):\n m2.loc[i, '最终扣罚'] = m2.loc[i, '扣罚']\n else:\n m2.loc[i, '最终扣罚'] = m2.loc[i, '每日提成金额']\n\n #判断是否免除扣罚\n m2_mianchu = pd.read_excel(\"数据输出/SA扣罚标准.xlsx\",dtype={'SA工号':'O'})\n m2_mianchu = m2_mianchu[['SA工号','是否免除扣罚']]\n m2 = pd.merge(m2,m2_mianchu,on=\"SA工号\",how=\"left\")\n\n for i in range(len(m2)):\n if m2.loc[i, '是否免除扣罚'] == '免':\n m2.loc[i, 'SA最终扣罚'] = 0\n elif m2.loc[i, '是否免除扣罚'] == '不':\n m2.loc[i, 'SA最终扣罚'] = m2.loc[i, '最终扣罚']\n else:\n print(\"免除扣罚出现问题,请核实!\")\n\n m2['逾期等级'] = '首次M2'\n m2 = m2[['贷款编号', '贷款金额', '产品名称', '商户', '门店', 'SA工号', 'SA姓名', '逾期等级','最终扣罚', '是否免除扣罚', 'SA最终扣罚']]\n return m2\n\n#M2+逾期明细\n\ndef m2_plus_koufa():\n print('开始计算SA的M2+单笔扣罚')\n def yikou():\n # 汇总首次M2和M2+的已经扣罚和退还的\n data1 = pd.read_excel(\"扣罚汇总/M2+扣罚汇总.xlsx\", dtype={'贷���编号': 'O', 'SA姓名': 'O'})\n data2 = pd.read_excel(\"扣罚汇总/首次M2扣罚汇总.xlsx\", dtype={'贷款编号': 'O', 'SA姓名': 'O'})\n yikou = pd.concat([data1, data2])\n return yikou\n yikou = yikou()\n yikou = yikou[['贷款编号', '扣押月份', '退还月份']]\n\n m2_plus = pd.read_excel('扣罚数据输入/M2+逾期明细.xlsx', dtype={'贷款编号': 'O', 'SA工号': 'O'})\n m2_plus = m2_plus[['贷款编号', '贷款金额', '商户', '门店', '产品名称', 'SA工号', 'SA姓名']]\n m2_plus = pd.merge(m2_plus, yikou, on=\"贷款编号\", how=\"left\")\n\n for i in range(len(m2_plus)):\n if np.isnan(m2_plus.loc[i, \"扣押月份\"]) == False and np.isnan(m2_plus.loc[i, \"退还月份\"]) == True:\n m2_plus.drop([i], inplace=True)\n else:\n pass\n\n m2_plus = m2_plus.reset_index(drop=True)\n\n m2_plus = m2_plus[['贷款编号', '贷款金额', '产品名称', '商户', '门店', 'SA工号', 'SA姓名']]\n zmd = pd.read_excel('扣罚数据输入/主门店汇总.xlsx', dtype={'贷款编号': 'O'})\n\n m2_plus = pd.merge(m2_plus, zmd, on=\"贷款编号\", how=\"left\")\n\n for i in range(len(m2_plus)):\n if m2_plus.loc[i, '产品名称'] == '一般产品' or m2_plus.loc[i, '产品名称'] == '优惠产品' or m2_plus.loc[i, '产品名称'] == '广州服务类产品' or m2_plus.loc[i, '产品名称'] == '优惠产品A' or m2_plus.loc[i, '产品名称'] == '优惠产品B':\n if m2_plus.loc[i, '贷款金额'] >= 1500:\n m2_plus.loc[i, '扣罚'] = 100\n else:\n m2_plus.loc[i, '扣罚'] = 50\n elif m2_plus.loc[i, '产品名称'] == '003产品':\n m2_plus.loc[i, '扣罚'] = 30\n elif m2_plus.loc[i, '产品名称'] == \"U客购\":\n m2_plus.loc[i, \"扣罚\"] = 180\n else:\n if m2_plus.loc[i, '贷款金额'] >= 2300:\n m2_plus.loc[i, '扣罚'] = 66\n elif 1800 <= m2_plus.loc[i, '贷款金额'] < 2300:\n m2_plus.loc[i, '扣罚'] = 44\n else:\n m2_plus.loc[i, '扣罚'] = 22\n\n m2_plus[\"最终扣罚\"] = 0\n for i in range(len(m2_plus)):\n if np.isnan(m2_plus.loc[i, '每日提成金额']):\n m2_plus.loc[i, '最终扣罚'] = m2_plus.loc[i, '扣罚']\n else:\n m2_plus.loc[i, '最终扣罚'] = m2_plus.loc[i, '每日提成金额']\n\n m2_plus_mianchu = pd.read_excel(\"数据输出/SA扣罚标准.xlsx\",dtype={'SA工号':'O'})\n m2_plus_mianchu = m2_plus_mianchu[['SA工号','是否免除扣罚']]\n m2_plus = pd.merge(m2_plus,m2_plus_mianchu,on=\"SA工号\",how=\"left\")\n\n for i in range(len(m2_plus)):\n if m2_plus.loc[i, '是否免除扣罚'] == \"免\":\n m2_plus.loc[i, 'SA最终扣罚'] = 0\n elif m2_plus.loc[i, '是否免除扣罚'] == \"不\":\n m2_plus.loc[i, 'SA最终扣罚'] = m2_plus.loc[i, '最终扣罚']\n else:\n print(\"免除扣罚出现问题,请核实!\")\n\n m2_plus['逾期等级'] = 'M2+'\n m2_plus = m2_plus[['贷款编号', '贷款金额', '产品名称', '商户', '门店', 'SA工号', 'SA姓名', '逾期等级', '最终扣罚', '是否免除扣罚', 'SA最终扣罚']]\n return m2_plus\n\ndef hebing(m2,m2_plus):\n data = pd.concat([m2,m2_plus])\n data.to_excel(\"数据输出/SA单笔扣罚.xlsx\",index=False)\n print(\"计算完成,good luck!\")\n\nif __name__ == '__main__':\n starttime = datetime.datetime.now()\n m2_over_rate = m2_over_rate() #计算首次M2逾期率\n data_all = m2_plus(m2_over_rate) #\n data_all_1=is_mianchu(data_all) #计算扣罚免除\n save(data_all_1) #保存扣罚免除数据\n m2 = m2_first() #SA首次M2单笔扣罚\n m2_plus =m2_plus_koufa() #SA的M2+单笔扣罚\n hebing(m2,m2_plus) #合并并保存\n endtime = datetime.datetime.now()\n print(\"用时:%d秒\" % (endtime - starttime).seconds)\n","sub_path":"SA扣罚标准函数版本.py","file_name":"SA扣罚标准函数版本.py","file_ext":"py","file_size_in_byte":10978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"106870069","text":"import time\nimport threading\n\n\nclass AsyncScheduler(object):\n def __init__(self):\n self._lock = threading.Lock()\n self._queue = []\n self._event_q = []\n self._last_event = 0\n self._th = threading.Thread(target=self.run)\n self._th.start()\n self.running = False\n\n def enter(self, period, task, args=(), kwargs={}):\n t = (period, task, args, kwargs)\n with self._lock:\n event = self._last_event\n self._queue.append(t)\n self._event_q.append(event)\n self._last_event += 1\n\n return event\n\n def run(self):\n while True:\n while not self._queue:\n time.sleep(1)\n\n with self._lock:\n t = self._queue[0]\n period, task, args, kwargs = t\n task(*args, **kwargs)\n with self._lock:\n self._queue.pop(0)\n self._event_q.pop(0)\n\n time.sleep(period)\n\n def kill(self):\n pass\n\n @property\n def queue(self):\n with self._lock:\n events = self._event_q[:]\n return events\n\n def empty(self):\n events = self.queue\n return len(events) == 0\n\n\nclass TaskQueues(object):\n def __init__(self):\n self._queues = {}\n\n def add_queue(self, idx):\n self._queues[idx] = AsyncScheduler()\n\n def get_empty_queue(self):\n for idx, q in self._queues.items():\n if q.empty():\n return (idx, q)\n\n return (None, None)\n\n def kill(self):\n pass\n","sub_path":"tasks/computer-vision/tf/code/remote_runner/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"253944504","text":"from datetime import datetime, timedelta\n\nfrom otree.views.admin import AdminReport\n\nfrom ._builtin import Page, WaitPage\n\n\nclass MyPage(Page):\n form_model = 'player'\n\n\nclass ResultsWaitPage(WaitPage):\n pass\n\n\nclass SessionBase(object):\n\n def post(self, *args, **kwargs):\n session_payoff = 4000\n percentage_saved = self.player.percentage_saved\n saved = 0\n if self.player.money_decision == 0:\n disbursement = 4000\n elif self.player.money_decision == 1:\n saved = (percentage_saved / 100) * session_payoff\n disbursement = session_payoff - saved\n else:\n saved = session_payoff\n disbursement = 0\n if saved:\n money = 50 if self.player.intermedio_actual == 1 else 25\n saved += int((saved / 100) * money)\n self.player.payoff = self.player.payoff + saved\n self.player.disbursement = self.player.disbursement + disbursement\n self.player.save()\n return super(SessionBase, self).post(*args, **kwargs)\n\n\nclass EncuestaSocioEconomica(Page):\n template_name = 'experimiento_1/encuesta_economica.html'\n form_model = 'player'\n form_fields = ['survey']\n\n\nclass Session1(SessionBase, Page):\n template_name = 'experimiento_1/session_1.html'\n form_model = 'player'\n form_fields = ['file_session_1']\n document = 'experimento_1/session_1.pdf'\n text_info = \"Las siguientes páginas hacen parte del libro El crimen como oficio: ensayos sobre economía del crimen en Colombia (2007), y es necesario para nosotros transcribir la información contenida en el documento. El tiempo aproximado del siguiente trabajo es de 15 min, por favor transcriba la información en el espacio disponible. \"\n\n def get_context_data(self, *args, **kwargs):\n context = super(Session1, self).get_context_data(*args, **kwargs)\n context['text_info'] = self.text_info\n context['document_url'] = self.document\n return context\n\n\nclass Session2(SessionBase, Page):\n template_name = 'experimiento_1/session_1.html'\n form_model = 'player'\n form_fields = ['file_session_2']\n document = 'experimento_1/session_2.pdf'\n\n text_info = \"Las siguientes páginas hacen parte del libro Informe de la desigualdad global (2018), y es necesario para nosotros transcribir la información contenida en el documento. El tiempo aproximado del siguiente trabajo es de 15 min, por favor transcriba la información en el espacio disponible. \"\n\n def get_context_data(self, *args, **kwargs):\n context = super(Session2, self).get_context_data(*args, **kwargs)\n context['text_info'] = self.text_info\n context['document_url'] = self.document\n return context\n\n\nclass Session3(SessionBase, Page):\n template_name = 'experimiento_1/session_1.html'\n form_model = 'player'\n form_fields = ['file_session_3']\n document = 'experimento_1/session_3.pdf'\n text_info = \"Las siguientes páginas hacen parte del libro Informe de la desigualdad global (2018), y es necesario para nosotros transcribir la información contenida en el documento. El tiempo aproximado del siguiente trabajo es de 15 min, por favor transcriba la información en el espacio disponible. \"\n\n def get_context_data(self, *args, **kwargs):\n context = super(Session3, self).get_context_data(*args, **kwargs)\n context['text_info'] = self.text_info\n context['document_url'] = self.document\n return context\n\n\nclass Session4(Page):\n template_name = 'experimiento_1/session_2.html'\n form_model = 'player'\n form_fields = ['monto_session_2']\n\n\nclass IntermedioSession(Page):\n template_name = 'experimiento_1/intermedio.html'\n form_model = 'player'\n form_fields = ['money_decision', 'percentage_saved']\n\n def get_context_data(self, *args, **kwargs):\n context = super(IntermedioSession, self).get_context_data(*args, **kwargs)\n return context\n\n def get_form(self, *args, **kwargs):\n form = super(IntermedioSession, self).get_form(*args, **kwargs)\n new_decisions = []\n money = 50 if self.player.intermedio_actual == 1 else 25\n for field in form.fields['money_decision'].choices:\n new_decisions.append((field[0], field[1].format(price_session=money)))\n form.fields['money_decision'].choices = new_decisions\n return form\n\n def post(self, *args, **kwargs):\n money_decision = self.request.POST.get('money_decision')\n percentage_saved = self.request.POST.get('percentage_saved')\n\n self.player.intermedio = self.player.intermedio + 1\n self.player.save()\n return super(IntermedioSession, self).post(*args, **kwargs)\n\n\nclass SevenDaysWaitPage(Page):\n template_name = 'experimiento_1/wait_page.html'\n\n def get_context_data(self, *args, **kwargs):\n day_available = self.player.updated_at.replace(hour=0, tzinfo=None) + timedelta(days=7)\n today = datetime.now()\n context = super(SevenDaysWaitPage, self).get_context_data(*args, **kwargs)\n context['day_available'] = day_available\n context['can_access'] = today > day_available\n return context\n\n\nclass Consent(Page):\n form_model = 'player' # Le dice que es un jugador\n form_fields = ['num_temporal', 'accepts_terms']\n\n\npage_sequence = [\n Consent,\n MyPage,\n IntermedioSession,\n Session1,\n IntermedioSession,\n # SevenDaysWaitPage,\n Session2,\n # SevenDaysWaitPage,\n Session3,\n EncuestaSocioEconomica,\n Session4,\n]\n","sub_path":"experimiento_1/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"370314863","text":"#!/usr/bin/python3\n\nimport gi\nimport os\nimport re\nimport sys\nimport threading\nimport subprocess\nimport setproctitle\n\ngi.require_version('Gtk', '3.0')\ngi.require_version('GLib', '2.0')\ngi.require_version('Keybinder', '3.0')\nfrom gi.repository import Gtk, Gdk, Pango, Gio, GLib, Keybinder\n\nsetproctitle.setproctitle('unam-menu')\n\n# Files\nhome = os.getenv(\"HOME\") + '/'\napplications = '/usr/share/applications/'\nlog_file = home + '.config/unam/unam-menu/log'\n\ndef check_files():\n global_conf = home + '.config/unam'\n local_conf = home + '.config/unam/unam-menu'\n\n if not os.path.isdir(global_conf):\n print('Creating config folder')\n os.makedirs(global_conf)\n \n if not os.path.isdir(local_conf):\n print('Setting up config')\n os.makedirs(local_conf)\n\ncheck_files()\n\ngapps = Gio.File.new_for_path(applications)\ndir_changed = gapps.monitor_directory(Gio.FileMonitorFlags.NONE, None)\n\ndef get_screen_size(x, y):\n display = subprocess.Popen('xrandr | grep \"\\*\" | cut -d\" \" -f4',shell=True,stdout=subprocess.PIPE).communicate()[0]\n display = str(display.rstrip())[2:-1]\n display = display.split('x')\n \n if x == True and y == True:\n return display\n elif x == True and y == False:\n return display[0]\n elif x == False and y == True:\n return display[1]\n elif x == False and y == False:\n return display[0] + 'x' + display[1]\n\ndef log(message):\n with open(log_file, \"a+\") as logfile:\n logfile.write(message + '\\n')\n\nclass spacer():\n def __init__(self):\n self.box = Gtk.Box()\n self.label = Gtk.Label('')\n self.box.add(self.label)\n #self.box.set_sensitive(False)\n \n def get_box(self):\n return self.box\n \nclass appbutton():\n def __init__(self):\n self.button = Gtk.Button()\n self.label = Gtk.Label()\n self.icon = Gtk.Image()\n self.layoutbox = Gtk.VBox()\n self.command = ''\n \n self.build()\n \n def build(self):\n self.flat()\n self.label.set_alignment(0.5,0.5)\n self.button.set_hexpand(True)\n self.layoutbox.add(self.icon)\n self.layoutbox.add(self.label)\n self.button.add(self.layoutbox)\n \n def construct(self, icon_name, label_text, tooltip_text, command):\n self.set_icon(icon_name, Gtk.IconSize.DIALOG)\n self.set_label(label_text)\n self.set_tooltip(tooltip_text)\n self.set_command(command)\n \n def flat(self):\n classes = self.button.get_style_context()\n classes.add_class('flat')\n \n def on_click(self, button, cmd):\n os.system(cmd + ' &')\n log('App launched: ' + cmd)\n menu.invisible(None, None)\n \n def set_icon(self, icon_name, icon_size):\n self.icon.set_from_icon_name(icon_name, icon_size)\n \n def get_icon(self):\n return self.icon.get_from_icon_name()\n \n def set_label(self, text):\n self.label.set_text(text)\n \n def get_label(self):\n return self.label.get_text()\n \n def set_tooltip(self, text):\n self.button.set_tooltip_text(text)\n \n def get_tooltip(self):\n return self.button.get_tooltip_text()\n \n def set_command(self, cmd):\n self.command = cmd\n self.button.connect('clicked', self.on_click, cmd)\n \n def get_command(self):\n return self.command\n \n def get_button(self):\n return self.button\n \n def get_info(self):\n return self.get_label(), self.get_command(), self.get_tooltip() #, self.get_icon()\n\nclass unam_menu(Gtk.Window):\n\n _current_accel_name = None\n\n def __init__(self):\n log('Initialized new instance')\n Gtk.Window.__init__(self, title=\"Unam Menu\")\n \n self.icon = Gtk.Image()\n self.icon.set_from_icon_name('app-launcher', Gtk.IconSize.MENU)\n \n self.drawer_mode = False\n self.visible = False\n self.no_search = True\n self.update = dir_changed\n\n # keyboard shortcuts\n accel = Gtk.AccelGroup()\n accel.connect(Gdk.keyval_from_name('Q'), Gdk.ModifierType.CONTROL_MASK, 0, Gtk.main_quit)\n self.add_accel_group(accel)\n self.bind_hotkey()\n\n self.connect(\"delete-event\", Gtk.main_quit)\n self.connect('focus-in-event', self.on_focus_in)\n self.connect('focus-out-event', self.on_focus_out)\n self.connect('key_press_event', self.on_key_press)\n self.update.connect('changed', self.update_list)\n\n self.semaphore = threading.Semaphore(4)\n self.wrapper = Gtk.VBox()\n self.scrollbox = Gtk.ScrolledWindow()\n self.scrollframe = Gtk.Viewport()\n self.box = Gtk.Box(spacing=6) \n self.spacer_left = Gtk.Box()\n self.spacer_right = Gtk.Box()\n self.controlbox = Gtk.HBox(spacing=2)\n self.searchbox = Gtk.Box(spacing=20)\n self.app_grid = Gtk.Grid()\n self.search_entry = Gtk.Entry()\n \n self.add(self.wrapper)\n self.controlbox.pack_start(self.spacer_left, True, True, 0)\n self.controlbox.pack_start(self.search_entry, True, True, 0)\n self.controlbox.pack_start(self.spacer_right, True, True, 0)\n self.wrapper.pack_start(self.controlbox, False, False, 0)\n self.wrapper.pack_start(self.scrollbox, True, True, 0)\n self.scrollbox.add(self.scrollframe)\n self.scrollframe.add(self.box)\n self.box.add(self.app_grid)\n\n self.spacer_right.set_halign(Gtk.Align.END)\n self.search_entry.set_icon_from_icon_name(1, 'search')\n self.search_entry.set_icon_tooltip_text(1, 'Search for Applications')\n self.search_entry.connect('changed', self.search)\n self.search_entry.connect('activate', self.launch)\n\n self.app_list = []\n \n # Drawer mode\n if len(sys.argv) > 1:\n if sys.argv[1] == '-d' or '--drawer':\n print('Set to drawer mode')\n log('Initialized in drawer mode. Configuring...')\n self.drawer_mode = True\n self.conf_drawer()\n\n self.load_apps()\n self.assemble()\n self.configure()\n \n self.show_all()\n self.set_focus()\n \n def conf_drawer(self):\n self.btn_quit = Gtk.Button()\n self.btn_quit.icon = Gtk.Image()\n\n self.btn_quit.add(self.btn_quit.icon)\n self.spacer_right.add(self.btn_quit)\n self.btn_quit.icon.set_from_icon_name('gtk-close', Gtk.IconSize.MENU)\n\n classes = self.btn_quit.get_style_context()\n classes.add_class('flat')\n \n def bind_hotkey(self): # thanks ulauncher\n Keybinder.init()\n accel_name = \"Q\" # \n \n # bind in the main thread\n GLib.idle_add(self.set_hotkey, accel_name)\n\n def unbind(self, accel_name):\n Keybinder.unbind(accel_name)\n\n def set_hotkey(self, accel_name):\n if self._current_accel_name:\n Keybinder.unbind(self._current_accel_name)\n self._current_accel_name = None\n \n Keybinder.bind(accel_name, self.on_hotkey_press)\n self._current_accel_name = accel_name\n #self.notify_hotkey_change(accel_name)\n \n def update_list(self, m, f, o, event):\n if event == Gio.FileMonitorEvent.CHANGES_DONE_HINT:\n print('Updating app list')\n self.app_list = []\n\n self.load_apps()\n self.clear()\n self.assemble()\n #self.show_all()\n \n def load_apps(self):\n app_count = 0\n \n apps = os.listdir(applications)\n apps = sorted(apps)\n\n #for file in os.listdir(applications):\n for app in apps:\n if os.path.isfile(os.path.join(applications, app)):\n buffer = open(applications + '/' + app, \"r\")\n\n name = \"void\"\n icon = \"void\"\n desc = \"void\"\n cmd = \"void\"\n\n for line in buffer:\n if line.startswith(\"Icon=\"):\n icon = line[5:].rstrip()\n if line.startswith(\"Name=\"):\n name = line[5:].rstrip()\n if line.startswith(\"Comment=\"):\n desc = line[8:].rstrip()\n if line.startswith(\"Exec=\"):\n cmd = line[5:].rstrip().lower()\n cmd = cmd.replace(\"%u\",\"\")\n cmd = cmd.replace(\"%f\",\"\")\n\n if icon is not \"void\" and name is not \"void\" and cmd is not \"void\" and desc is not \"void\":\n btn_app = appbutton()\n btn_app.construct(icon, name, desc, cmd)\n\n self.app_list.append(btn_app)\n app_count += 1\n\n icon = \"void\"\n name = \"void\"\n desc = \"void\"\n cmd = \"void\"\n \n def assemble(self):\n column = 1\n row = 1\n print(len(self.app_list))\n for item in range(0, len(self.app_list)):\n self.app_grid.attach(self.app_list[item].get_button(), column, row, 1, 1)\n if column == 3:\n column = 0\n row += 1\n column += 1\n\n def on_hotkey_press(self, event):\n if self.visible:\n self.invisible(None, None)\n else:\n self.set_visible(None, None)\n \n def set_focus(self):\n self.present()\n self.set_modal(True)\n self.set_keep_above(True)\n \n def set_visible(self, object, event):\n self.show_all()\n self.set_focus()\n self.search_entry.grab_focus()\n self.visible = True\n print('toggle visible')\n\n def invisible(self, object, event):\n self.hide()\n self.search_entry.set_text('')\n self.no_search = True\n self.visible = False\n print('toggle invisible')\n \n def configure(self):\n self.set_decorated(False)\n self.resize(660,600)\n self.set_skip_pager_hint(True)\n self.set_skip_taskbar_hint(True)\n #self.set_size_request(350,5)\n \n if self.drawer_mode:\n self.set_position(Gtk.WindowPosition.CENTER_ALWAYS)\n self.set_gravity(Gdk.Gravity.CENTER)\n else:\n self.move(0, int(get_screen_size(False, True)))\n \n def on_key_press(self, widget, event):\n key = Gdk.keyval_name(event.keyval)\n if 'Escape' in key:\n print(str(key))\n self.invisible(None, None)\n\n def on_focus_in(self, widget, event):\n self.visible = True\n\n def on_focus_out(self, widget, event):\n t = threading.Timer(0.07, lambda: not self.visible or self.invisible(None, None))\n t.start()\n\n def search(self, entry):\n if self.search_entry.get_text() != '':\n if self.no_search == True:\n self.no_search = False\n self.found = False\n self.clear()\n self.populate()\n self.show_all()\n else:\n self.clear()\n self.assemble()\n self.show_all()\n \n def clear(self):\n for widget in self.app_grid:\n self.app_grid.remove(widget)\n\n def populate(self):\n apps = 0\n row = 1\n column = 1\n query = self.search_entry.get_text()\n if query != \"\":\n for item in range(0, len(self.app_list)):\n if query in str(self.app_list[item].get_info()):\n self.app_grid.attach(self.app_list[item].get_button(), column, row, 1,1)\n apps += 1\n self.found = True\n if column == 3:\n row += 1\n column = 0\n column += 1\n \n if apps == 0:\n label = Gtk.Label('No items found')\n label.set_hexpand(True)\n label.set_alignment(0.5,0)\n self.found = False\n self.app_grid.attach(label, 0, 0, 1,1)\n\n def launch(self, *data):\n if (self.found):\n child = self.app_grid.get_children()\n print(len(child))\n child[len(child) - 1].grab_focus()\n self.activate_focus()\n else:\n self.invisible(None, None)\n \nmenu = unam_menu()\nmenu.invisible(None, None)\nGtk.main()\n","sub_path":"unam-menu.py","file_name":"unam-menu.py","file_ext":"py","file_size_in_byte":12551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"279508355","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 24 12:30:41 2017\r\n\r\n@author: Y40\r\n\"\"\"\r\nimport csv\r\nimport pandas as pd\r\nimport datetime\r\n\r\ndef date_calculate(start_date,date,mode):\r\n if mode == 'str':\r\n year1,month1,day1 = start_date.split('-')\r\n year1 = year1.split(' ')[-1]\r\n year2,month2,day2 = date.split('-')\r\n year2 = year2.split(' ')[-1]\r\n interval = (datetime.datetime(int(year2), int(month2), int(day2))-datetime.datetime(int(year1), int(month1), int(day1))).days\r\n \r\n if mode == 'list':\r\n year1 = start_date[0]\r\n month1 = start_date[1]\r\n day1 = start_date[2]\r\n year2 = date[0]\r\n month2 = date[1]\r\n day2 = date[3]\r\n interval = (datetime.datetime(int(year2), int(month2), int(day2))-datetime.datetime(int(year1), int(month1), int(day1))).days\r\n print(year1,month1,day1)\r\n print(year2,month2,day2)\r\n return interval\r\n \r\ndef date_add_sort(TotalList,date):\r\n TotalList.append(date)\r\n TotalList.sort(key=lambda x: x.split('-'))\r\n return TotalList\r\n \r\nif __name__=='__main__':\r\n user_data = pd.read_csv(\"D:\\\\Desktop\\\\Material\\\\STAT 154\\\\Kaggle\\\\ShrinkedData\\\\yelp_academic_dataset_review_train.csv\")\r\n datee = user_data.loc[[1]].date.values[0]\r\n datee2 = user_data.loc[[2]].date.values[0]\r\n datee3 = user_data.loc[[3]].date.values[0]\r\n print(datee,datee2,datee3)\r\n interval = date_calculate(datee,datee2,'str')\r\n print(interval)\r\n dateList = [datee,datee2,datee3]\r\n dateList.sort(key=lambda x: x.split('-')) \r\n print(dateList)","sub_path":"Date_calculate.py","file_name":"Date_calculate.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"340417191","text":"import cocotb\nfrom cocotb.clock import Clock\nimport cocotb.triggers as triggers\nfrom cocotb.triggers import Timer\nfrom trit_to_bit_model import trit_to_bit_model\nimport bit_handle\n\nreport = open('report.txt','w')\n\n@cocotb.test()\nasync def test_mod3(dut):\n \"\"\"Try accessing the design.\"\"\"\n\n cocotb.fork(Clock(dut.clk, 1, units=\"ns\").start())\n dut._log.info(\"Running test...\")\n fail = 0\n trits = [[0,0], [0,1], [1,1]]\n dut.rst1 <= 0\n dut.rst2 <= 0\n await Timer(0.5, units = \"ns\")\n for i1 in trits:\n for i2 in trits:\n for i3 in trits:\n for i4 in trits:\n for i5 in trits:\n i = i1 + i2 + i3 + i4 + i5\n inp = bit_handle.arr_to_str(i)\n dut.rst1 <= 1\n dut.a <= int.from_bytes(inp, \"big\")\n await triggers.RisingEdge(dut.clk)\n await Timer(0.5, units = \"ns\")\n dut.rst1 <= 0\n dut.rst2 <= 1\n await Timer(1, units = \"ns\")\n dut.rst2 <= 0\n await Timer(4, units = \"ns\")\n\n v = []\n for j in [i5,i4,i3,i2,i1]:\n if j == [0,1]: v.append(1)\n elif j == [0,0]: v.append(0)\n elif j == [1,1]: v.append(-1)\n else: raise(\"Error in transform to the integer trit of\", j);\n b = trit_to_bit_model(v)\n expect = int.from_bytes(bit_handle.arr_to_str(b), \"big\")\n try:\n if dut.out.value != expect:\n fail = 1\n report.write(\"When in = %s, out = %d, but I expect it = %d\\n\" %(bin(dut.a.value),int(dut.out.value),expect))\n except:\n fail = 1\n report.write(\"When in = %s, I expect it = %d\\n\" %(bin(dut.a.value),expect))\n\n if fail == 0: report.write(\"------VERIFICATION SUCCEED------\\n\")\n else: report.write(\"------VERIFICATION FAIL------\\n\")\n dut._log.info(\"Running test...done\")\n report.close()\n","sub_path":"Draft_Phuong/trit5_to_bit8_ver2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"597093370","text":"# Copyright 2016-2020 Blue Marble Analytics LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis operational type describes transmission lines whose flows are simulated\nusing a linear transport model, i.e. transmission flow is constrained to be\nless than or equal to the line capacity. Line capacity can be defined for\nboth transmission flow directions. The user can define losses as a fraction\nof line flow.\n\n\"\"\"\n\nimport os\nimport pandas as pd\nfrom pyomo.environ import Set, Param, Var, Constraint, NonNegativeReals, \\\n Reals, PercentFraction\n\n\ndef add_model_components(\n m, d, scenario_directory, subproblem, stage\n):\n \"\"\"\n The following Pyomo model components are defined in this module:\n\n +-------------------------------------------------------------------------+\n | Sets |\n +=========================================================================+\n | | :code:`TX_SIMPLE` |\n | |\n | The set of transmission lines of the :code:`tx_simple` operational |\n | type. |\n +-------------------------------------------------------------------------+\n | | :code:`TX_SIMPLE_OPR_TMPS` |\n | |\n | Two-dimensional set with transmission lines of the :code:`tx_simple` |\n | operational type and their operational timepoints. |\n +-------------------------------------------------------------------------+\n\n +-------------------------------------------------------------------------+\n | Params |\n +=========================================================================+\n | | :code:`tx_simple_loss_factor` |\n | | *Defined over*: :code:`TX_SIMPLE` |\n | | *Within*: :code:`PercentFraction` |\n | | *Default*: :code:`0` |\n | |\n | The fraction of power that is lost when transmitted over this line. |\n +-------------------------------------------------------------------------+\n\n\n |\n\n +-------------------------------------------------------------------------+\n | Variables |\n +=========================================================================+\n | | :code:`TxSimple_Transmit_Power_MW` |\n | | *Defined over*: :code:`TX_SIMPLE_OPR_TMPS` |\n | | *Within*: :code:`Reals` |\n | |\n | The transmission line's power flow in each timepoint in which the line |\n | is operational. Negative power means the power flow goes in the |\n | opposite direction of the line's defined direction. |\n +-------------------------------------------------------------------------+\n | | :code:`TxSimple_Losses_LZ_From_MW` |\n | | *Defined over*: :code:`TX_SIMPLE_OPR_TMPS` |\n | | *Within*: :code:`NonNegativeReals` |\n | |\n | Losses on the transmission line in each timepoint, which we'll account |\n | for in the \"from\" origin load zone's load balance, i.e. losses incurred |\n | when power is flowing to the \"from\" zone. |\n +-------------------------------------------------------------------------+\n | | :code:`TxSimple_Losses_LZ_To_MW` |\n | | *Defined over*: :code:`TX_SIMPLE_OPR_TMPS` |\n | | *Within*: :code:`NonNegativeReals` |\n | |\n | Losses on the transmission line in each timepoint, which we'll account |\n | for in the \"to\" origin load zone's load balance, i.e. losses incurred |\n | when power is flowing to the \"to\" zone. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Constraints |\n +=========================================================================+\n | | :code:`TxSimple_Min_Transmit_Constraint` |\n | | *Defined over*: :code:`TX_SIMPLE_OPR_TMPS` |\n | |\n | Transmitted power should exceed the transmission line's minimum power |\n | flow for in every operational timepoint. |\n +-------------------------------------------------------------------------+\n | | :code:`TxSimple_Max_Transmit_Constraint` |\n | | *Defined over*: :code:`TX_SIMPLE_OPR_TMPS` |\n | |\n | Transmitted power cannot exceed the transmission line's maximum power |\n | flow in every operational timepoint. |\n +-------------------------------------------------------------------------+\n | | :code:`TxSimple_Losses_LZ_From_Constraint` |\n | | *Defined over*: :code:`TX_SIMPLE_OPR_TMPS` |\n | |\n | Losses to be accounted for in the \"from\" load zone's load balance are 0 |\n | when power flow on the line is positive (power flowing from the \"from\" |\n | to the \"to\" load zone) and must be greater than or equal to the flow |\n | times the loss factor otherwise (power flowing to the \"from\" load zone).|\n +-------------------------------------------------------------------------+\n | | :code:`TxSimple_Losses_LZ_To_Constraint` |\n | | *Defined over*: :code:`TX_SIMPLE_OPR_TMPS` |\n | |\n | Losses to be accounted for in the \"to\" load zone's load balance are 0 |\n | when power flow on the line is negative (power flowing from the \"to\" |\n | to the \"from\" load zone) and must be greater than or equal to the flow |\n | times the loss factor otherwise (power flowing to the \"to\" load zone). |\n +-------------------------------------------------------------------------+\n | | :code:`TxSimple_Max_Losses_From_Constraint` |\n | | *Defined over*: :code:`TX_SIMPLE_OPR_TMPS` |\n | |\n | Losses cannot exceed the maximum transmission flow capacity times the |\n | loss factor in each operational timepoint. Provides upper bound on |\n | losses. |\n +-------------------------------------------------------------------------+\n | | :code:`TxSimple_Max_Losses_To_Constraint` |\n | | *Defined over*: :code:`TX_SIMPLE_OPR_TMPS` |\n | |\n | Losses cannot exceed the maximum transmission flow capacity times the |\n | loss factor in each operational timepoint. Provides upper bound on |\n | losses. |\n +-------------------------------------------------------------------------+\n\n \"\"\"\n\n # Sets\n ###########################################################################\n\n m.TX_SIMPLE = Set(\n within=m.TX_LINES,\n initialize=lambda mod: list(\n set(l for l in mod.TX_LINES\n if mod.tx_operational_type[l] == \"tx_simple\")\n )\n )\n\n m.TX_SIMPLE_OPR_TMPS = Set(\n dimen=2, within=m.TX_OPR_TMPS,\n initialize=lambda mod: list(\n set((l, tmp) for (l, tmp) in mod.TX_OPR_TMPS\n if l in mod.TX_SIMPLE)\n )\n )\n\n # Params\n ###########################################################################\n m.tx_simple_loss_factor = Param(\n m.TX_SIMPLE, within=PercentFraction, default=0\n )\n\n # Variables\n ###########################################################################\n\n m.TxSimple_Transmit_Power_MW = Var(\n m.TX_SIMPLE_OPR_TMPS,\n within=Reals\n )\n\n m.TxSimple_Losses_LZ_From_MW = Var(\n m.TX_SIMPLE_OPR_TMPS,\n within=NonNegativeReals\n )\n\n m.TxSimple_Losses_LZ_To_MW = Var(\n m.TX_SIMPLE_OPR_TMPS,\n within=NonNegativeReals\n )\n\n # Constraints\n ###########################################################################\n\n m.TxSimple_Min_Transmit_Constraint = Constraint(\n m.TX_SIMPLE_OPR_TMPS,\n rule=min_transmit_rule\n )\n\n m.TxSimple_Max_Transmit_Constraint = Constraint(\n m.TX_SIMPLE_OPR_TMPS,\n rule=max_transmit_rule\n )\n\n m.TxSimple_Losses_LZ_From_Constraint = Constraint(\n m.TX_SIMPLE_OPR_TMPS,\n rule=losses_lz_from_rule\n )\n\n m.TxSimple_Losses_LZ_To_Constraint = Constraint(\n m.TX_SIMPLE_OPR_TMPS,\n rule=losses_lz_to_rule\n )\n\n m.TxSimple_Max_Losses_From_Constraint = Constraint(\n m.TX_SIMPLE_OPR_TMPS,\n rule=max_losses_from_rule\n )\n\n m.TxSimple_Max_Losses_To_Constraint = Constraint(\n m.TX_SIMPLE_OPR_TMPS,\n rule=max_losses_to_rule\n )\n\n\n# Constraint Formulation Rules\n###############################################################################\n\n# TODO: should these move to operations.py since all transmission op_types\n# have this constraint?\ndef min_transmit_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxSimple_Min_Transmit_Constraint\n **Enforced Over**: TX_SIMPLE_OPR_TMPS\n\n Transmitted power should exceed the minimum transmission flow capacity in\n each operational timepoint.\n \"\"\"\n return mod.TxSimple_Transmit_Power_MW[l, tmp] \\\n >= mod.Tx_Min_Capacity_MW[l, mod.period[tmp]]\n\n\ndef max_transmit_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxSimple_Max_Transmit_Constraint\n **Enforced Over**: TX_SIMPLE_OPR_TMPS\n\n Transmitted power cannot exceed the maximum transmission flow capacity in\n each operational timepoint.\n \"\"\"\n return mod.TxSimple_Transmit_Power_MW[l, tmp] \\\n <= mod.Tx_Max_Capacity_MW[l, mod.period[tmp]]\n\n\ndef losses_lz_from_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxSimple_Losses_LZ_From_Constraint\n **Enforced Over**: TX_SIMPLE_OPR_TMPS\n\n Losses for the 'from' load zone of this transmission line (non-negative\n variable) must be greater than or equal to the negative of the flow times\n the loss factor. When the flow on the line is negative, power is flowing\n to the 'from', so losses are positive. When the flow on the line is\n positive (i.e. power flowing from the 'from' load zone), losses can be set\n to zero.\n If the tx_simple_loss_factor is 0, losses are set to 0.\n WARNING: since we have a greater than or equal constraint here, whenever\n tx_simple_loss_factor is not 0, the model can incur line losses that are\n not actually real.\n \"\"\"\n if mod.tx_simple_loss_factor[l] == 0:\n return mod.TxSimple_Losses_LZ_From_MW[l, tmp] == 0\n else:\n return mod.TxSimple_Losses_LZ_From_MW[l, tmp] >= \\\n - mod.TxSimple_Transmit_Power_MW[l, tmp] * \\\n mod.tx_simple_loss_factor[l]\n\n\ndef losses_lz_to_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxSimple_Losses_LZ_To_Constraint\n **Enforced Over**: TX_SIMPLE_OPR_TMPS\n\n Losses for the 'to' load zone of this transmission line (non-negative\n variable) must be greater than or equal to the flow times the loss\n factor. When the flow on the line is positive, power is flowing to the\n 'to' LZ, so losses are positive. When the flow on the line is negative\n (i.e. power flowing from the 'to' load zone), losses can be set to zero.\n If the tx_simple_loss_factor is 0, losses are set to 0.\n WARNING: since we have a greater than or equal constraint here, whenever\n tx_simple_loss_factor is not 0, the model can incur line losses that are\n not actually real.\n \"\"\"\n if mod.tx_simple_loss_factor[l] == 0:\n return mod.TxSimple_Losses_LZ_To_MW[l, tmp] == 0\n else:\n return mod.TxSimple_Losses_LZ_To_MW[l, tmp] >= \\\n mod.TxSimple_Transmit_Power_MW[l, tmp] * \\\n mod.tx_simple_loss_factor[l]\n\n\ndef max_losses_from_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxSimple_Max_Losses_From_Constraint\n **Enforced Over**: TX_SIMPLE_OPR_TMPS\n\n Losses cannot exceed the maximum transmission flow capacity times the\n loss factor in each operational timepoint. Provides upper bound on losses.\n \"\"\"\n if mod.tx_simple_loss_factor[l] == 0:\n return mod.TxSimple_Losses_LZ_From_MW[l, tmp] == 0\n else:\n return mod.TxSimple_Losses_LZ_From_MW[l, tmp] \\\n <= mod.Tx_Max_Capacity_MW[l, mod.period[tmp]] \\\n * mod.tx_simple_loss_factor[l]\n\n\ndef max_losses_to_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxSimple_Max_Losses_To_Constraint\n **Enforced Over**: TX_SIMPLE_OPR_TMPS\n\n Losses cannot exceed the maximum transmission flow capacity times the\n loss factor in each operational timepoint. Provides upper bound on losses.\n \"\"\"\n if mod.tx_simple_loss_factor[l] == 0:\n return mod.TxSimple_Losses_LZ_To_MW[l, tmp] == 0\n else:\n return mod.TxSimple_Losses_LZ_To_MW[l, tmp] \\\n <= mod.Tx_Max_Capacity_MW[l, mod.period[tmp]] \\\n * mod.tx_simple_loss_factor[l]\n\n# Transmission Operational Type Methods\n###############################################################################\n\ndef transmit_power_rule(mod, line, tmp):\n \"\"\"\n The power flow on this transmission line before accounting for losses.\n \"\"\"\n return mod.TxSimple_Transmit_Power_MW[line, tmp]\n\n\ndef transmit_power_losses_lz_from_rule(mod, line, tmp):\n \"\"\"\n Transmission losses that we'll account for in the origin \n load zone (load_zone_from) of this transmission line. These are zero\n when the flow is positive (power flowing from the origin load zone) and\n can be more than 0 when the flow is negative (power flowing to the\n origin load zone).\n \"\"\"\n return mod.TxSimple_Losses_LZ_From_MW[line, tmp]\n\n\ndef transmit_power_losses_lz_to_rule(mod, line, tmp):\n \"\"\"\n Transmission losses that we'll account for in the destination\n load zone (load_zone_to) of this transmission line. These are zero\n when the flow is negative (power flowing from the destination load zone)\n and can be more than 0 when the flow is positive (power flowing to the\n destination load zone).\n \"\"\"\n return mod.TxSimple_Losses_LZ_To_MW[line, tmp]\n\n\n# Input-Output\n###############################################################################\n\ndef load_model_data(m, d, data_portal, scenario_directory,\n subproblem, stage):\n \"\"\"\n\n :param m:\n :param data_portal:\n :param scenario_directory:\n :param subproblem:\n :param stage:\n :return:\n \"\"\"\n\n # Get the simple transport model lines\n df = pd.read_csv(\n os.path.join(scenario_directory, str(subproblem), str(stage), \"inputs\",\n \"transmission_lines.tab\"),\n sep=\"\\t\",\n usecols=[\"TRANSMISSION_LINES\", \"tx_operational_type\",\n \"tx_simple_loss_factor\"]\n )\n df = df[df[\"tx_operational_type\"] == \"tx_simple\"]\n\n # Dict of loss factor by tx_simple line based on raw data\n loss_factor_raw = dict(zip(\n df[\"TRANSMISSION_LINES\"],\n df[\"tx_simple_loss_factor\"]\n ))\n\n # Convert loss factors to float and remove any missing data (will\n # default to 0 in the model)\n loss_factor = {\n line: float(loss_factor_raw[line])\n for line in loss_factor_raw\n if loss_factor_raw[line] != \".\"\n }\n\n # Load data\n data_portal.data()[\"tx_simple_loss_factor\"] = loss_factor\n","sub_path":"gridpath/transmission/operations/operational_types/tx_simple.py","file_name":"tx_simple.py","file_ext":"py","file_size_in_byte":17403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"60383379","text":"\"\"\"Coding Dojo - Python Fundamentals - Assignment: Names\n\nCreated: 09/03/2017\nAuthor: Frank J Genova\n\nPart I\nGiven the following list:\nstudents = [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'},\n {'first_name' : 'Mark', 'last_name' : 'Guillen'},\n {'first_name' : 'KB', 'last_name' : 'Tonel'}\n]\nCreate a program that outputs:\nMichael Jordan\nJohn Rosales\nMark Guillen\nKB Tonel\n\nPart II\nNow, given the following dictionary:\nusers = {\n 'Students': [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'},\n {'first_name' : 'Mark', 'last_name' : 'Guillen'},\n {'first_name' : 'KB', 'last_name' : 'Tonel'}\n ],\n 'Instructors': [\n {'first_name' : 'Michael', 'last_name' : 'Choi'},\n {'first_name' : 'Martin', 'last_name' : 'Puryear'}\n ]\n }\nCreate a program that prints the following format\n(including number of characters in each combined name):\nStudents\n1 - MICHAEL JORDAN - 13\n2 - JOHN ROSALES - 11\n3 - MARK GUILLEN - 11\n4 - KB TONEL - 7\nInstructors\n1 - MICHAEL CHOI - 11\n2 - MARTIN PURYEAR - 13\n\n\"\"\"\n\n\n\ndef main():\n \"\"\"Print students\"\"\"\n\n students = [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'},\n {'first_name' : 'Mark', 'last_name' : 'Guillen'},\n {'first_name' : 'KB', 'last_name' : 'Tonel'}\n ]\n\n print(\"=\"*80)\n for student in students:\n first_name = student['first_name']\n last_name = student['last_name']\n print(\"{} {}\".format(first_name, last_name))\n print(\"=\"*80)\n\n users = {\n 'Students': [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'},\n {'first_name' : 'Mark', 'last_name' : 'Guillen'},\n {'first_name' : 'KB', 'last_name' : 'Tonel'}\n ],\n 'Instructors': [\n {'first_name' : 'Michael', 'last_name' : 'Choi'},\n {'first_name' : 'Martin', 'last_name' : 'Puryear'}\n ]\n }\n\n print(\"=\"*80)\n for kind in users:\n print(kind)\n count = 0\n character_count = 0\n for each in users[kind]:\n count += 1\n first_name = each['first_name']\n character_count = len(first_name)\n last_name = each['last_name']\n character_count += len(last_name)\n print(\"{} - {} {} - {}\".format(count, first_name, last_name, character_count))\n print(\"=\"*80)\n\nif __name__ == '__main__':\n main()\n ","sub_path":"Week1/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"99566115","text":"def naiveNearestSum(nums, N): # O(n^2)\n currSum = 0\n res = [0,0,abs(N-currSum)] # deviation of sum from N\n for i in range(len(nums)):\n currSum = 0 # clear it for every starting point i \n for j in range(i,len(nums)):\n currSum += nums[j]\n currDiff = abs(N-currSum)\n\n if currDiff < res[2]:\n res = [i,j,currDiff]\n\n if currDiff == 0:\n return res\n \n return res\n\nprint(naiveNearestSum([3,4,5,6,7],14)) # expect [1,3,1]\n\n\ndef posNearestSum(nums, K): # O(n)\n '''\n this method only takes non-negative array of nums\n it utilizes non-neg numbers s.t. if sum[i:j] > K,\n it means we (maybe) add too much (加爆),\n then we need to substract the sum[i:j] by i = i + 1\n '''\n currSum = 0\n res = [0,0, abs(K-currSum)]\n resTemp = [0,0, abs(K-currSum)] # don't let resTemp = res, very easy to get things wrong\n i = j = 0\n currDiff = prevDiff = 0\n # we only need to constrain j < len(nums)\n # because say sum[i:j] = sum[1:4], and 4 is the last position\n # if we still need to increase j (second else condition below)\n # it means the currSum is too small \n # moving i to the right will no longer be helpful\n while i <= j and j < len(nums): \n currSum += nums[j]\n\n prevDiff = currDiff\n\n currDiff = K - currSum\n \n if currDiff <= 0: # we need to move i right\n if abs(currDiff) < abs(prevDiff): # currDiff is better\n resTemp = [i,j,abs(currDiff)]\n \n # substracting nums[i] because we're shifting i+=1\n # substraing nums[j] because we will add it back in next iteration\n currSum -= (nums[i]+nums[j]) \n i += 1\n \n else: # move j\n resTemp = [i,j,abs(currDiff)]\n j += 1\n \n if resTemp[2] < res[2]: # resTemp is just for making this if condition written separately here\n res = resTemp\n \n return res\n\nprint(posNearestSum([3,4,5,6,7],14)) # expect [1,3,1]\n","sub_path":"leetcode/akuna/17_nearest_sum.py","file_name":"17_nearest_sum.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"111647163","text":"N,M,X=map(int,input().split())\nCA=[list(map(int,input().split())) for i in range(N)]\nmin_cost=float(\"inf\")\nfor bit in range(1<>digit)&1:\n cost+=CA[digit][0]\n for m in range(M):\n understand[m]+=CA[digit][m+1]\n if all(understand[m]>=X for m in range(M)):\n min_cost=min(min_cost,cost)\nprint(min_cost if min_cost!=float(\"inf\") else -1)","sub_path":"code/abc167_c_01.py","file_name":"abc167_c_01.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"35219964","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2014 SWIPO Project\n#\n# Authors (this file):\n# Stefan Schinkel \n\"\"\"\nWeave tests to check that python and weave implementations give the same\nresults\n\"\"\"\n\nfrom pyunicorn import ResNetwork\n\n\nres = ResNetwork.SmallTestNetwork()\nresC = ResNetwork.SmallComplexNetwork()\n\n\ndef testVCFB():\n for i in range(5):\n res.flagWeave = False\n vcfbPython = res.vertex_current_flow_betweenness(i)\n res.flagWeave = True\n vcfbWeave = res.vertex_current_flow_betweenness(i)\n assert vcfbPython == vcfbWeave\n\n\ndef testECFB():\n res.flagWeave = False\n ecfbPython = res.edge_current_flow_betweenness()\n res.flagWeave = True\n ecfbWeave = res.edge_current_flow_betweenness()\n l = len(ecfbPython)\n for i in range(l):\n for j in range(l):\n assert ecfbPython[i][j] == ecfbWeave[i][j]\n","sub_path":"tests/test_core/TestResitiveNetwork-weave.py","file_name":"TestResitiveNetwork-weave.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"641301242","text":"import os\nimport json\nimport uuid\nimport boto3\nfrom multiprocessing import Process, Pipe\nimport requests\nfrom exif import Image\n\n\nbucket = '6225-photo-manager'\n\ngoogle_maps_api_key = 'AIzaSyA1E0Q07cNt3jorqCmtiWGNZ_sVpDR2ZNs'\n\ns3_client = boto3.client('s3')\n\ndef lambda_handler(event, context):\n response_body = 'a'\n try:\n filenames = [key['Key'] for key in s3_client.list_objects(Bucket=bucket)['Contents']]\n\n # create a list to keep all processes\n processes = []\n # create a list to keep connections\n parent_connections = []\n\n # create a process per instance\n for filename in filenames:\n # create a pipe for communication\n parent_connection, child_connection = Pipe()\n parent_connections.append(parent_connection)\n\n # create the process, pass instance and connection\n process = Process(target=get_info, args=(filename, child_connection))\n processes.append(process)\n\n # start all processes\n for process in processes:\n process.start()\n\n # make sure that all processes have finished\n for process in processes:\n process.join()\n\n response_body = [parent_connection.recv()[0] for parent_connection in parent_connections]\n except Exception as e:\n response_body = str(e)\n\n return {\n 'statusCode': 200,\n 'body': json.dumps(response_body)\n }\n\n\ndef get_info(filename, connection):\n url = 'https://{bucket}.s3.us-east-2.amazonaws.com/{filename}'.format(bucket = bucket, filename = filename)\n\n # Download file to tmp\n filepath = '/tmp/{uuid}-{filename}'.format(uuid = uuid.uuid4(), filename = filename)\n s3_client.download_file(bucket, filename, filepath)\n\n # Get metadata\n info = get_metadata(filepath)\n info['url'] = url\n info['User File'] = filename\n connection.send([info])\n connection.close()\n\n\ndef get_location(latitude, longitude):\n base = 'https://maps.googleapis.com/maps/api/geocode/json'\n key = 'key={google_maps_api_key}'.format(google_maps_api_key = google_maps_api_key)\n parameters = 'latlng={latitude},{longitude}&sensor={sensor}'.format(\n latitude = latitude,\n longitude = longitude,\n # Fake sensor\n sensor = 'true'\n )\n url = '{base}?{key}&{parameters}'.format(base = base, key = key, parameters = parameters)\n # First result should be precise enough\n return json.loads(requests.get(url).text)['results'][0]['formatted_address']\n\n\ndef get_decimal_from_dms(dms, ref):\n degrees = dms[0]\n minutes = dms[1] / 60.0\n seconds = dms[2] / 3600.0\n\n if ref in ['S', 'W']:\n degrees = -degrees\n minutes = -minutes\n seconds = -seconds\n\n return degrees + minutes + seconds\n\n\ndef get_metadata(filepath):\n metadata = {}\n # read the image data using exif\n with open(filepath, \"rb\") as image_file:\n image = Image(image_file)\n\n metadata = {\n 'Date Taken': image.get('datetime_digitized'),\n 'Device Used': image.get('model'),\n 'Location': get_location(\n get_decimal_from_dms(image.get('gps_latitude'), image.get('gps_latitude_ref')),\n get_decimal_from_dms(image.get('gps_longitude'), image.get('gps_longitude_ref')),\n )\n }\n\n return metadata","sub_path":"Assignment4/DownloadPhotos.py","file_name":"DownloadPhotos.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"624765062","text":"from __future__ import unicode_literals\n\nimport re\n\nSKIP_PATTERNS = (\n re.compile(r\"^:?image:\", flags=re.I),\n re.compile(r\"^:?file:\", flags=re.I),\n re.compile(r\"^:?TimedText:\", flags=re.I),\n re.compile(r\"^:?wikipedia:\", flags=re.I),\n re.compile(r\"^:?wiktionary:\", flags=re.I),\n re.compile(r\"^:?meta:\", flags=re.I),\n re.compile(r\"^:?category:\", flags=re.I),\n re.compile(r\"^:?portal:\", flags=re.I),\n re.compile(r\"^:?help:\", flags=re.I),\n re.compile(r\"^:?user:\", flags=re.I),\n re.compile(r\"^:?talk:\", flags=re.I),\n re.compile(r\"^:?media:\", flags=re.I),\n re.compile(r\"^:?mediawiki:\", flags=re.I),\n re.compile(r\"^:?template:\", flags=re.I),\n re.compile(r\"^:?book:\", flags=re.I),\n re.compile(r\"^:?List of\", flags=re.I),\n re.compile(r\"^:?Lists of\", flags=re.I),\n)\n\nIGNORE_PATTERNS = SKIP_PATTERNS + (\n re.compile(r\"^:?Arbitration in \", flags=re.I),\n re.compile(r\"^:?Communications in \", flags=re.I),\n re.compile(r\"^:?Constitutional history of \", flags=re.I),\n re.compile(r\"^:?Economy of \", flags=re.I),\n re.compile(r\"^:?Demographics of \", flags=re.I),\n re.compile(r\"^:?Foreign relations of \", flags=re.I),\n re.compile(r\"^:?Geography of \", flags=re.I),\n re.compile(r\"^:?History of \", flags=re.I),\n re.compile(r\"^:?Military of \", flags=re.I),\n re.compile(r\"^:?Politics of \", flags=re.I),\n re.compile(r\"^:?Transport in \", flags=re.I),\n re.compile(r\"^:?Transportation in \", flags=re.I),\n re.compile(r\"^:?Outline of \", flags=re.I),\n re.compile(r\" in \\d\\d\\d\\d$\", flags=re.I),\n re.compile(r\"^\\d\\d\\d\\d in \", flags=re.I),\n re.compile(r\"\\(disamb\", flags=re.I),\n re.compile(r\"\\(diamb\", flags=re.I),\n re.compile(r\"\\{+\", flags=re.I),\n re.compile(r\"\\}+\", flags=re.I),\n)\n\n\ndef should_skip(title):\n for p in SKIP_PATTERNS:\n if re.search(p, title):\n return True\n return False\n\n\ndef is_good_title(title):\n for p in IGNORE_PATTERNS:\n if re.search(p, title):\n return False\n return True\n\n\ndef chop_leading_determiners(title):\n \"\"\"\n Remove leading determiners from title (the, a, an)\n \"\"\"\n\n # Note: no regexp is perfect. The one used here considers 'the'\n # followed by any non-word character to be bad. This rules out\n # 'The-underdogs' and 'The.scene', which turn into 'the underdogs' and\n # 'the scene' after put-symbols, respectively. However, 'a'\n # at the beginning is only considered bad if the next character is a\n # space. This is meant to keep things like 'A. H. Robbins', which is\n # converted into 'a h robbins' by put-symbols.\n pattern = re.compile(r\"^\\W*(the\\W|an\\W|a )\", flags=re.I)\n\n m = re.match(pattern, title)\n while m is not None:\n title = title[len(m.group(0)):]\n m = re.match(pattern, title)\n\n return title\n\n\ndef reverse_comma(synonym):\n \"\"\"\n Reverse synonyms with a comma\n \"\"\"\n\n # For now, we are only able to reverse synonyms that end in\n # [Tt]he|[Aa]n?, not all synonyms with a comma because of the case\n # when a comma is properly used, e.g.\n # \"11th/28th Battalion, the Royal Western Australia Regiment\"\n # \"Tenzin Gyatso, the 14th Dalai Lama\"\n # By only flipping synonyms that have an article at the end, we are\n # still able to correct:\n # \"Congo, Democratic Republic Of The\"\n # \"Martyrs, Acts of the\"\n # \"Golden ratio, the\"\n # The following are incorrectly reversed:\n # \"a\" could be the letter \"a\" as in \"Class A\"\n # e.g. \"Scavenger receptors, class a\"\n # \"a\" could be a preposition in French or Italian\n # e.g. \"Bernadine a Piconio\": \"Piconio, Bernadine a\"\n # In addition, \"an\" and \"the\" could be used in another language, such\n # as the French word for tea, \"the\" (with a lost accent on the e).\n\n m = re.search(r', (.* )?([Tt]he|[Aa]n?)$', synonym)\n if m:\n split = synonym.split(',')\n if len(split) == 2:\n split = map(lambda s: s.strip(), split)\n synonym = split[1] + \" \" + split[0]\n return synonym\n\n\ndef clean_synonym(title):\n title = title.strip()\n\n try:\n last_s = title.rindex(\"'s\")\n if last_s == len(title) - 2:\n title = title[:-2]\n except ValueError:\n pass\n\n title = title.replace(\"\\\\\\\\\", \"\\\\ \")\n title = title.replace(\"''\", \"'\")\n\n title = reverse_comma(title)\n title = chop_leading_determiners(title)\n\n # replace multiple spaces (including nbsp) with a single space\n title = re.sub(r'\\s+', ' ', title, flags=re.U)\n\n return title\n\n\ndef get_synonyms(symbol):\n synonyms = [symbol]\n\n without_parens = re.sub(r'\\(.*?\\)', '', symbol)\n if without_parens != symbol:\n synonyms.append(without_parens)\n\n synonyms = map(clean_synonym, synonyms)\n\n # delete synonyms with no word characters\n synonyms = filter(lambda s: re.match(r'^\\W*$', s) is None, synonyms)\n\n return synonyms\n","sub_path":"wikipediabase/symbols.py","file_name":"symbols.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"540353066","text":"# 365. Count 1 in Binary\n# Count how many 1 in binary representation of a 32-bit integer.\n#\n# Example\n# Given 32, return 1\n#\n# Given 5, return 2\n#\n# Given 1023, return 9\n#\n# Challenge\n# If the integer is n bits with m 1 bits. Can you do it in O(m) time?\n\nclass Solution:\n \"\"\"\n @param: num: An integer\n @return: An integer\n \"\"\"\n def countOnes(self, num):\n # write your code here\n\n # 5 0b101, we got 2\n # 7 0b111, we got 3\n \"how many 1's in n, depends on how many 1's in n-1\"\n \" if n -1 is even, then n has 1 more 1, it will have 1s of (n-1)//2 + 1 or 1s of (n-1) + 1 \"\n \"if n is even, it will have 1s of (n-1)//2\"\n \"but this is log(n)\"\n\n \"let's consider this way: 10 - 1 = 01 11 -1 = 10 100 -1 = 011, num & (num-1) = ? each time we do this, it will keep higher digits while eleminate last 1 \"\n\n \"how about negatives?\"\n \"-x is 1 with 31 digits of ~(x-1)\"\n\n count = 0\n\n if num < 0 :\n\n num1 = -num - 1\n else:\n num1 = num\n\n while num1 != 0 :\n num1 = num1 & (num1 - 1)\n count += 1\n\n if num < 0 :\n count = 1 + (31- count )\n\n return count\n\n","sub_path":"Algorithm/Python/BitOperation/Count1InBinary.py","file_name":"Count1InBinary.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"128864291","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom open3d import *\nimport tensorflow as tf\nimport random\nimport tf_util\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.visible_device_list = '0'\nconfig.gpu_options.allow_growth = True\n\nDATA_ROOT = \"trainning_data/\"\nNUM_POINT = 500 # Number of point\nCLASS_SIZE = 3 # Class size\nBATCH_SIZE = 5 * CLASS_SIZE # Batch size\nITERS = 60000 # How many generator iterations to train for\n\nLearning_Rate_Tran = 5e-4 \ndecay_rate_tran = 0.85 \ndecay_steps_tran = 3000\n\nLearning_Rate_Rot = 5e-4 \ndecay_rate_rot = 0.85 \ndecay_steps_rot = 3000\n\ndef get_real_data():\n\n\treal_point_cloud = []\n\treal_robot_trajectory = []\n\treal_robot_rot = []\n\treal_class_number = [] \n\n\tfor i in range(BATCH_SIZE):\n\t\tbatch = random.randint(1, 49)\n\t\t\n\t\tif batch <= 12: \n\t\t\tclass_number = 0.\n\t\telif batch <= 26:\n\t\t\tclass_number = 1.\n\t\telse:\n\t\t\tclass_number = 2.\n\n\t\tif (batch < 10):\n\t\t\tbatch = \"{}{}\".format(\"0\", batch)\n\t\telse:\n\t\t\tbatch = \"{}\".format(batch)\n\n\t\tpcd = read_point_cloud(DATA_ROOT + batch + '.pcd')\n\t\tpoint_cloud = np.asarray(pcd.points)\n\t\treal_point_cloud_temp = np.asarray(random.sample(list(point_cloud), NUM_POINT), dtype='float32')\n\n\t\tData_Points = open(DATA_ROOT + batch + '.txt', 'r')\n\t\trobot_trajectory = np.zeros([6], dtype='float32')\n\t\trobot_rot = np.zeros([2], dtype='float32')\n\t\tc = 0\n\t\tfor line in Data_Points:\n\t\t\trobot_trajectory[c] = line\n\t\t\tc += 1\n\t\tData_Points.close()\n\t\treal_robot_trajectory_temp = np.asarray(robot_trajectory, dtype='float32')\n\n\t\tif real_robot_trajectory_temp[-1] < 0:\n\t\t\trobot_rot[1] = 1.\n\t\telse:\n\t\t\trobot_rot[0] = 1.\n\n\t\treal_robot_trajectory_temp[-1] = np.abs(real_robot_trajectory_temp[-1])\n\n\t\treal_point_cloud.append(real_point_cloud_temp)\n\t\treal_robot_trajectory.append(real_robot_trajectory_temp)\n\t\treal_robot_rot.append(robot_rot)\n\t\treal_class_number.append(class_number)\n\n\treturn real_point_cloud, real_robot_trajectory, real_robot_rot, real_class_number\n\ndef point_net_model(point_cloud, is_training, bn_decay=None):\n\t\"\"\" Classification PointNet, input is BxNx3, output Bx40 \"\"\"\n\tbatch_size = point_cloud.get_shape()[0].value\n\tnum_point = point_cloud.get_shape()[1].value\n\tfeature_dim = point_cloud.get_shape()[2].value\n\tinput_image = tf.expand_dims(point_cloud, -1)\n\n\t# Point functions (MLP implemented as conv2d)\n\tnet = tf_util.conv2d(input_image, 64, [1, feature_dim],\n\t\t\t\t\t\tpadding='VALID', stride=[1, 1],\n\t\t\t\t\t\tis_training=is_training,\n\t\t\t\t\t\tscope='conv1', bn_decay=bn_decay)\n\n\tnet = tf_util.conv2d(net, 64, [1, 1],\n\t\t\t\t\t\tpadding='VALID', stride=[1, 1],\n\t\t\t\t\t\tis_training=is_training,\n\t\t\t\t\t\tscope='conv2', bn_decay=bn_decay)\n\n\tnet = tf_util.conv2d(net, 64, [1, 1],\n\t\t\t\t\t\tpadding='VALID', stride=[1, 1],\n\t\t\t\t\t\tis_training=is_training,\n\t\t\t\t\t\tscope='conv3', bn_decay=bn_decay)\n\n\tnet = tf_util.conv2d(net, 128, [1, 1],\n\t\t\t\t\t\tpadding='VALID', stride=[1, 1],\n\t\t\t\t\t\tis_training=is_training,\n\t\t\t\t\t\tscope='conv4', bn_decay=bn_decay)\n\n\tnet = tf_util.conv2d(net, 1024, [1, 1],\n\t\t\t\t\t\tpadding='VALID', stride=[1, 1],\n\t\t\t\t\t\tis_training=is_training,\n\t\t\t\t\t\tscope='conv5', bn_decay=bn_decay) # check the maximum along point dimension\n\n\tnet = tf_util.max_pool2d(net, [num_point, 1],\n\t\t\t\t\t\t\tpadding='VALID', scope='maxpool')\n\n\t# MLP on global point cloud vector\n\tnet = tf.reshape(net, [batch_size, -1])\n\tnet, _, _ = tf_util.fully_connected(net, 512, is_training=is_training,\n\t\t\t\t\t\t\t\t\t\tscope='fc1', bn_decay=bn_decay)\n\tnet, _, _ = tf_util.fully_connected(net, 256, is_training=is_training,\n\t\t\t\t\t\t\t\t\t\tscope='fc2', bn_decay=bn_decay)\n\treturn net\n\ndef Generator_Trans_Mean(point_cloud, class_number, is_training=tf.cast(True, tf.bool), bn_decay=None):\n\t\n\telement_mean = tf.reduce_mean(point_cloud, axis=1)\n\tcls_gt_onehot = tf.one_hot(indices=class_number, depth=CLASS_SIZE)\n\t\n\twith tf.variable_scope('Generator_Trans_Mean', reuse=tf.AUTO_REUSE):\n\t\telement_mean, _, _ = tf_util.fully_connected(tf.concat([element_mean, cls_gt_onehot], 1), 6, is_training=is_training, activation_fn=None, scope='output1')\n\t\telement_mean, _, _ = tf_util.fully_connected(element_mean, 3, is_training=is_training, activation_fn=None, scope='output2')\n\n\treturn element_mean\n\ndef Generator_Trans(point_cloud, class_number, is_training=tf.cast(True, tf.bool), bn_decay=None):\n\n\telement_mean = tf.reduce_mean(point_cloud, axis=1)\n\tpoint_cloud_normalized = point_cloud - tf.expand_dims(element_mean, 1)\n\tpoint_cloud_normalized = point_cloud_normalized/1000.0\n\t\n\tcls_gt_onehot = tf.one_hot(indices=class_number, depth=CLASS_SIZE)\n\tcls_gt_onehot_expand = tf.expand_dims(cls_gt_onehot, axis=1)\n\tcls_gt_onehot_tile = tf.tile(cls_gt_onehot_expand, [1, NUM_POINT, 1])\n\n\twith tf.variable_scope('Generator_Trans'):\n\t\ttrans_pred_res = point_net_model(tf.concat([point_cloud_normalized, cls_gt_onehot_tile], 2), \n\t\t\t\t\t\t\t\t\t\tis_training, bn_decay=bn_decay)\n\n\t\ttrans_pred_res, _, _ = tf_util.fully_connected(trans_pred_res, 3, is_training=is_training, activation_fn=None, scope='output')\n\n\treturn trans_pred_res\n\ndef Generator_Rot(point_cloud, class_number, is_training=tf.cast(True, tf.bool), bn_decay=None):\n\n\telement_mean = tf.reduce_mean(point_cloud, axis=1)\n\tpoint_cloud_normalized = point_cloud - tf.expand_dims(element_mean, 1)\n\tpoint_cloud_normalized = point_cloud_normalized/1000.0\n\n\t\n\tcls_gt_onehot = tf.one_hot(indices=class_number, depth=CLASS_SIZE)\n\tcls_gt_onehot_expand = tf.expand_dims(cls_gt_onehot, axis=1)\n\tcls_gt_onehot_tile = tf.tile(cls_gt_onehot_expand, [1, NUM_POINT, 1])\n\n\twith tf.variable_scope('Generator_Rot'):\n\t\t\n\t\trot_net = point_net_model(tf.concat([point_cloud_normalized, cls_gt_onehot_tile], 2), \n\t\t\t\t\t\t\t\t\tis_training, bn_decay=bn_decay)\n\n\t\tnet1, _, _ = tf_util.fully_connected(rot_net, 2, activation_fn=tf.tanh, scope='output1_rot')\n\t\tnet2, _, _ = tf_util.fully_connected(rot_net, 1, activation_fn=tf.sigmoid, scope='output2_rot')\n\t\n\t\trot_pred = tf.concat([net1 * 90.0 * 1.05, net2 * 180.0 * 1.05], 1)\n\n\treturn rot_pred\n\ndef Generator_Rot_Plus(point_cloud, class_number, is_training=tf.cast(True, tf.bool), bn_decay=None):\n\n\telement_mean = tf.reduce_mean(point_cloud, axis=1)\n\tpoint_cloud_normalized = point_cloud - tf.expand_dims(element_mean, 1)\n\tpoint_cloud_normalized = point_cloud_normalized/1000.0\n\n\t\n\tcls_gt_onehot = tf.one_hot(indices=class_number, depth=CLASS_SIZE)\n\tcls_gt_onehot_expand = tf.expand_dims(cls_gt_onehot, axis=1)\n\tcls_gt_onehot_tile = tf.tile(cls_gt_onehot_expand, [1, NUM_POINT, 1])\n\n\twith tf.variable_scope('Generator_Rot_Plus'):\n\t\t\n\t\trot_plus_net = point_net_model(tf.concat([point_cloud_normalized, cls_gt_onehot_tile], 2), \n\t\t\t\t\t\t\t\t\t\tis_training, bn_decay=bn_decay)\n\n\t\trot_plus_pred, _, _ = tf_util.fully_connected(rot_plus_net, 2, activation_fn=tf.nn.softmax, scope='output_rot_plus')\n\n\treturn rot_plus_pred\n\ndef save():\n\tsaver = tf.train.Saver()\n\tsaver.save(session, 'params/params.ckpt', write_meta_graph=False)\n\ndef restore():\n\tsaver = tf.train.Saver()\n\tsaver.restore(session, 'params/params.ckpt')\n\ndef get_trans_loss(robot_trajectory, robot_trans):\n\ttrans_loss = tf.sqrt(tf.reduce_sum(tf.square(robot_trajectory - robot_trans), axis=1))\n\treturn tf.reduce_mean(trans_loss)\n\ndef get_rot_loss(robot_trajectory, robot_rot):\n\toutput = robot_trajectory - robot_rot\n\toutput = tf.square(output)\n\trot_loss = tf.sqrt(tf.reduce_sum(output, axis=1))\n\n\treturn tf.reduce_mean(rot_loss)\n\npoint_cloud = tf.placeholder(tf.float32, shape=(BATCH_SIZE, NUM_POINT, 3))\nrobot_trajectory = tf.placeholder(tf.float32, shape=(BATCH_SIZE, 6))\nrobot_trajectory_rot = tf.placeholder(tf.float32, shape=(BATCH_SIZE, 2))\nclass_number = tf.placeholder(tf.int32, shape=BATCH_SIZE)\n\ngen_robot_trans_res = Generator_Trans(point_cloud, class_number)\ngen_robot_trans_mean = Generator_Trans_Mean(point_cloud, class_number)\n\ngen_robot_trans = gen_robot_trans_res*1000 + gen_robot_trans_mean\ngen_robot_rot = Generator_Rot(point_cloud, class_number)\ngen_robot_rot_plus = Generator_Rot_Plus(point_cloud, class_number)\n\ntrans_mean_loss = get_trans_loss(robot_trajectory[:, :3], gen_robot_trans_mean)\ntrans_loss = get_trans_loss(robot_trajectory[:, :3], gen_robot_trans)\nrot_loss = get_rot_loss(robot_trajectory[:, 3:], gen_robot_rot)\nrot_plus_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(\n\t\t\t\t\t\t\t\tlogits=gen_robot_rot_plus, labels=robot_trajectory_rot))\n\nglobal_step_tran = tf.Variable(tf.constant(0))\nlearning_rate_tran = tf.train.exponential_decay(Learning_Rate_Tran, global_step_tran, decay_steps_tran, decay_rate_tran, staircase=False)\n\nglobal_step_rot = tf.Variable(tf.constant(0))\nlearning_rate_rot = tf.train.exponential_decay(Learning_Rate_Rot, global_step_rot, decay_steps_rot, decay_rate_rot, staircase=False)\n\ngen_trans_mean_train_op = tf.train.AdamOptimizer(learning_rate=5e-4, beta1=0., beta2=0.9).minimize(trans_mean_loss)\ngen_trans_train_op = tf.train.AdamOptimizer(learning_rate=learning_rate_tran, beta1=0., beta2=0.9).minimize(trans_loss, global_step=global_step_tran)\ngen_rot_train_op = tf.train.AdamOptimizer(learning_rate=learning_rate_rot, beta1=0., beta2=0.9).minimize(rot_loss, global_step=global_step_rot)\ngen_rot_plus_train_op = tf.train.AdamOptimizer(learning_rate=learning_rate_rot, beta1=0., beta2=0.9).minimize(rot_plus_loss, global_step=global_step_rot)\n\n# Train loop\nwith tf.Session(config=config) as session:\n\tsession.run(tf.global_variables_initializer())\n\t#restore()\n\n\tfor iteration in range(5000):\n\t\t_rpc, _rrt, _rrr, _rcn = get_real_data()\n\t\tsession.run([gen_trans_mean_train_op], \n\t\t\t\t\tfeed_dict={point_cloud: _rpc, robot_trajectory: _rrt, class_number:_rcn})\n\t\t\n\t\tif iteration % 1000 == 999:\n\t\t\tprint('iteration = {}'.format(iteration))\n\n\tfor iteration in range(ITERS):\n\t\t_rpc, _rrt, _rrr, _rcn = get_real_data()\n\t\tsession.run([gen_trans_train_op, gen_rot_train_op, gen_rot_plus_train_op], \n\t\t\t\t\tfeed_dict={point_cloud: _rpc, robot_trajectory: _rrt, robot_trajectory_rot: _rrr, class_number:_rcn})\n\t\t\n\t\tif iteration % 1000 == 999:\n\t\t\tsave()\n\t\t\tprint('iteration = {}'.format(iteration))","sub_path":"robot grasping pose estimation unit/train_6d_pose.py","file_name":"train_6d_pose.py","file_ext":"py","file_size_in_byte":9883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"594778511","text":"txt = 'Hello My Name is Vishnu and I am 26 years old'\n\nwords = list(txt.split())\nlst = list()\n\nfor word in words:\n lst.append((len(word), word))\n\nlst.sort(reverse=True)\nresult = list()\n\nfor length, word in lst:\n result.append(word)\nprint(result)","sub_path":"tuples_sort_words_in_length.py","file_name":"tuples_sort_words_in_length.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"450052592","text":"\n# Selenium to Check whether logo exist or not in Homepage thesparksfoundationsingapore.org\n\nfrom selenium import webdriver\nimport time\nfrom selenium.webdriver.common.keys import Keys\nPATH = \"/home/amal/GRIP_Internship/chromedriver_linux64/chromedriver\"\ndriver = webdriver.Chrome(PATH)\n\ndriver.get(\"https://www.thesparksfoundationsingapore.org/\")\nelem = bool\nelem=driver.find_element_by_xpath(\"/html/body/div[1]/div/div[1]/h1/a/img\")\nif elem:\n print(\"Logo Exist in Homepage\")\nelse:\n print(\"Logo Missing from Homepage\")\n\ntime.sleep(2)\ndriver.quit()\nprint (\"The test is completed\")\n\n\n","sub_path":"CheckLogoHome.py","file_name":"CheckLogoHome.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"534969033","text":"import glob\nimport shutil\nimport os \nimport numpy as np\nimport json\n\nspecies_list = set()\nspecies_map = {}\n\n### Loop over files and get a list of unique species\nfor file in glob.glob('all/wav_old/*.wav'):\n\tfilename = os.path.basename(file).replace('.wav','')\n\tspecies_name = ''\n\tsong_number = ''\n\tfor c in filename: \n\t\tif c.isalpha():\n\t\t\tspecies_name += c\n\t\telse:\n\t\t\tsong_number += c\n\tspecies_list.add(species_name)\n\tspecies_map[species_name] = np.abs(hash(species_name))\n\tnew_filename = str(np.abs(hash(species_name))[:2])+'_'+song_number+'.wav'\n\tshutil.copy(file, os.path.join('all/wav/',new_filename))\n \nspecies_map = {k: int(v) for k,v in species_map.items()}\n\nwith open('bird_map.json', 'w') as f:\n\tjson.dump(species_map, f)","sub_path":"data/xeno-canto-dataset/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"475521130","text":"# iotest7.py Test fast_io PR\n# https://github.com/micropython/micropython-lib/pull/287\n\n# Test the case where runq is empty\n\n# The MyIO class supports .readline() which updates a call counter and clears the\n# .ready_rd flag. This is set by a timer (emulating the arrival of data from\n# some hardware device).\n\n\nimport io\nimport pyb\nimport utime\nimport uasyncio as asyncio\nimport micropython\nmicropython.alloc_emergency_exception_buf(100)\n\nMP_STREAM_POLL_RD = const(1)\nMP_STREAM_POLL_WR = const(4)\nMP_STREAM_POLL = const(3)\nMP_STREAM_ERROR = const(-1)\n\nclass MyIO(io.IOBase):\n def __init__(self, read=False, write=False):\n self.read_count = 0\n self.dummy_count = 0\n self.ready_rd = False\n pyb.Timer(4, freq = 100, callback = self.do_input)\n\n # Read callback: emulate asynchronous input from hardware.\n def do_input(self, t):\n self.ready_rd = True # Data is ready to read\n\n def ioctl(self, req, arg):\n ret = MP_STREAM_ERROR\n if req == MP_STREAM_POLL:\n ret = 0\n if arg & MP_STREAM_POLL_RD:\n if self.ready_rd:\n ret |= MP_STREAM_POLL_RD\n return ret\n\n def readline(self):\n self.read_count += 1\n self.ready_rd = False\n return b'a\\n'\n\n async def dummy(self):\n while True:\n await asyncio.sleep_ms(50)\n self.dummy_count += 1\n\n async def killer(self):\n print('Test runs for 5s')\n await asyncio.sleep(5)\n print('I/O count {} Dummy count {}'.format(self.read_count, self.dummy_count))\n\nasync def receiver(myior):\n sreader = asyncio.StreamReader(myior)\n while True:\n await sreader.readline()\n\ndef test(fast_io=False):\n loop = asyncio.get_event_loop(ioq_len = 6 if fast_io else 0)\n myior = MyIO()\n loop.create_task(receiver(myior))\n loop.create_task(myior.dummy())\n loop.run_until_complete(myior.killer())\n\nprint('Test case of empty runq: the fast_io option has no effect.')\nprint('I/O and dummy run at expected rates (around 500 and 99 counts respectively.')\nprint('Run test() to check normal I/O, test(True) for fast I/O')\n","sub_path":"uasyncio_iostream/tests/iotest7.py","file_name":"iotest7.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"70022067","text":"import numpy as np\nimport scipy.stats as st\nimport csv\nimport pandas as pd\nfrom math import sin,radians,cos,asin,sqrt\nimport matplotlib.pyplot as plt\nimport datetime\nimport parameter\n\n############################################################\n# This script is used to calculate the annual occurrence rate\n# gaoyy 201724\n############################################################\nprint(\"start program : \",datetime.datetime.now())\n\n# Parameter Setting\nprint(\"getting parameter\")\nparameter = parameter.SiteInfo()\nbegYear = parameter.begYear()\nendYear = parameter.endYear()\ntotalYear = endYear-begYear+1\nsiteName = parameter.name\n\n# Read data\ninputFileName = siteName+str(begYear)+\"-\"+str(endYear)+\".csv\"\nprint(\"reading data from file :\",inputFileName)\ndataset = pd.read_csv(inputFileName,header=None,sep=',')\ndataset = np.array(dataset)\nm ,n = np.shape(dataset)\ntcNum = dataset[:,0]\n\n# stats how many typhooon influence the station duiring 1970-2018\nprint(\"calculate annual occurrence rate Lambda\")\ntcNumNew = []\nfor element in tcNum :\n if(element not in tcNumNew):\n tcNumNew.append(element)\n element0 = str(int(element))\n element0 = element0.zfill(4)\n # print(\"typhoon numbering :\",element0)\ntotalNum = np.shape(tcNumNew)\n\nLambda = totalNum[0]/totalYear\nprint(\"total year during 1970-2018 :\",totalYear)\nprint(totalNum[0],\" typhoons influence the station during 1970-2018\")\nprint(\"annual occurrence rate Lambda : \",Lambda)\n\nprint(\"end program : \", datetime.datetime.now())\n\n","sub_path":"typhoonRiskV4p0/scripts_stats/statsLambda.py","file_name":"statsLambda.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"226702464","text":"#!/usr/bin/env python-mr\n\nfrom collections import defaultdict\nfrom queue import PriorityQueue\nfrom _.data.formatting.blocks import Block\n\nclass Grid:\n @staticmethod\n def parse(string):\n g = {}\n for row, line in enumerate(string):\n for col, v in enumerate(line):\n p = (row, col)\n g[p] = int(v)\n\n m = (row + 1, col + 1)\n return Grid(g, m)\n\n def __init__(self, pos, maximum):\n self._pos = pos\n self._max = maximum\n\n def neighbours(self, p):\n row, col = p\n yield (row - 1, col)\n yield (row + 1, col)\n yield (row, col - 1)\n yield (row, col + 1)\n\n def size(self):\n return self._max\n\n def __contains__(self, key):\n return key in self._pos\n\n def __getitem__(self, key):\n return self._pos[key]\n\n def __iter__(self):\n return iter(self._pos)\n\n def __str__(self):\n out = []\n height, width = self.size()\n for row in range(height):\n l = []\n for col in range(width):\n p = (row, col)\n if p not in self:\n l.append(\".\")\n else:\n l.append(str(self[p]))\n out.append(\"\".join(l))\n\n return \"\\n\".join(out)\n\n\nclass BiggerGrid:\n def __init__(self, grid, multiple):\n self._g = grid\n self._multiple = multiple\n\n def __str__(self):\n out = []\n height, width = self.size()\n for row in range(height):\n l = []\n for col in range(width):\n p = (row, col)\n if p not in self:\n l.append(\".\")\n else:\n l.append(str(self[p]))\n out.append(\"\".join(l))\n\n return \"\\n\".join(out)\n\n def get(self, key, default):\n row, col = key\n\n if row < 0 or col < 0:\n return default\n\n height, width = self._g.size()\n orow, ocol = row % height, col % width\n crow, ccol = row // height, col // width\n\n if crow >= self._multiple or ccol >= self._multiple:\n return default\n\n c = self._g[(orow, ocol)] + crow + ccol\n return (c - 1) % 9 + 1\n\n def __contains__(self, key):\n return self.get(key, None) is not None\n\n def __getitem__(self, key):\n val = self.get(key, None)\n if val is None:\n raise Exception()\n return val\n\n def size(self):\n height, width = self._g.size()\n return (height * self._multiple, width * self._multiple)\n\n def neighbours(self, p):\n row, col = p\n yield (row - 1, col)\n yield (row + 1, col)\n yield (row, col - 1)\n yield (row, col + 1)\n\n\n\ndef bfs(grid, start):\n costs = { start: 0 }\n visiting = set([])\n visit = PriorityQueue()\n for n in grid.neighbours(start):\n if n in grid:\n visit.put((grid[n], n))\n visiting.add(n)\n seen = set([start])\n\n while not visit.empty():\n priority, now = visit.get()\n visiting.discard(now)\n if now in seen:\n continue\n seen.add(now)\n\n cs = [costs[n] for n in grid.neighbours(now) if n in costs]\n costs[now] = grid[now] + min(cs)\n\n for n in grid.neighbours(now):\n if n in grid and n not in seen:\n visit.put((costs[now] + grid[n], n))\n visiting.add(n)\n\n return costs\n\n\nLOAD = \"content\"\ndef REWRITE(lines):\n return Grid.parse(lines)\n\n\ndef PART1(inputs):\n print(inputs)\n print(inputs.size())\n costs = bfs(inputs, (0,0))\n r, c = inputs.size()\n return costs[(r - 1, c - 1)]\n\n\ndef PART2(inputs):\n bigger = BiggerGrid(inputs, 5)\n print(bigger)\n print(bigger.size())\n costs = bfs(bigger, (0,0))\n r, c = bigger.size()\n return costs[(r - 1, c - 1)]\n\n","sub_path":"2021/day-15/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"507925035","text":"import torch\nimport numpy as np\nimport inferno.utils.python_utils as pyu\nfrom inferno.extensions.metrics.arand import ArandError\nfrom scipy.ndimage.measurements import label\n\n\nclass ArandErrorWithConnectedComponentsOnAffinities(ArandError):\n NP_DTYPE = 'float32'\n\n def __init__(self, thresholds=0.5, invert_probabilities=False,\n normalize_probabilities=False):\n super(ArandErrorWithConnectedComponentsOnAffinities, self).__init__()\n self.thresholds = pyu.to_iterable(thresholds)\n self.invert_probabilities = invert_probabilities\n self.normalize_probabilities = normalize_probabilities\n\n def affinity_to_segmentation(self, affinity_batch):\n assert affinity_batch.dim() in [4, 5], \\\n \"`affinity_batch` must be a 4D batch of 2D images or a 5D batch of 3D volumes.\"\n affinity_batch = affinity_batch.cpu().numpy()\n # probability_batch.shape = (N, z, y, x) or (N, y, x)\n probability_batch = affinity_batch.mean(axis=1)\n if self.invert_probabilities:\n probability_batch = 1. - probability_batch\n if self.normalize_probabilities:\n probability_batch = probability_batch / probability_batch.max()\n # Threshold\n thresholded_batches = [(probability_batch > threshold).astype(self.NP_DTYPE)\n for threshold in self.thresholds]\n # Run CC once for every threshold\n connected_components_batches = []\n # Run connected components on the thresholded batches\n for thresholded_batch in thresholded_batches:\n # The following also has the shape (N, y, x) (wlog 3D)\n connected_components = np.array([label(1. - volume_or_slice)[0]\n for volume_or_slice in thresholded_batch])\n # We reshape it to (N, 1, y, x) and convert to a torch tensor\n connected_component_tensor = torch.from_numpy(connected_components[:, None, ...])\n connected_components_batches.append(connected_component_tensor)\n return connected_components_batches\n\n def forward(self, prediction, target):\n # Threshold and convert to connected components\n connected_component_batches = self.affinity_to_segmentation(prediction)\n # Compute the arand once for ever threshold. Note that the threshold is global with\n # respect to the batches, which is intended.\n arand_errors = [super(ArandErrorWithConnectedComponentsOnAffinities, self).forward(batch,\n target)\n for batch in connected_component_batches]\n # Select the best arand error\n return min(arand_errors)\n","sub_path":"neurofire/metrics/arand.py","file_name":"arand.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"221200393","text":"#coding:utf8\nfrom django.shortcuts import render,HttpResponse,HttpResponseRedirect,reverse\nfrom django.http import JsonResponse\nfrom django import views\nfrom django.contrib.auth.backends import ModelBackend\nfrom django.contrib.auth import authenticate,login,logout\nfrom .models import User,TagModel,ArticleModel\nfrom .forms import LoginForm,AddTagForm,ArticleForm,EditProfileForm\nfrom utils import restful\n# Create your views here.\nfrom pure_pagination import Paginator, EmptyPage, PageNotAnInteger\nfrom django.conf import settings\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.db.models import Q\nONE_PAGE_COUNT = 15\n\nclass IndexView(views.View):\n def get(self,request):\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n articles = ArticleModel.objects.order_by('-create_time').all()\n p = Paginator(articles, ONE_PAGE_COUNT, request=request)\n articles = p.page(page)\n tags = TagModel.objects.all()\n user = User.objects.first()\n read_sort_articles = ArticleModel.objects.order_by('-readcount')[:5]\n return render(request,'index.html',{'articles':articles,'tags':tags,'this_page':page,'user':user,\n 'read_sort_articles':read_sort_articles})\n\n\nclass AboutView(views.View):\n def get(self,request):\n keyword = request.GET.get('keyword')\n user = User.objects.first()\n if keyword:\n articles = ArticleModel.objects.filter((Q(title__contains=keyword)|Q(content__contains=keyword)),\n author=user).all()\n else:\n articles = ArticleModel.objects.order_by('-readcount').filter(author=user).all()\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n p = Paginator(articles, ONE_PAGE_COUNT, request=request)\n articles = p.page(page)\n return render(request,'about.html',{'articles':articles})\n\nclass EditProfileView(views.View,LoginRequiredMixin):\n login_url = '/login/'\n redirect_field_name = 'next'\n def post(self,request):\n user = request.user\n if user:\n form = EditProfileForm(request.POST)\n if form.is_valid():\n nickname = form.cleaned_data.get('nickname')\n desc = form.cleaned_data.get('desc')\n card = form.cleaned_data.get('card')\n place = form.cleaned_data.get('place')\n user.nickname = nickname\n user.desc = desc\n user.card = card\n user.address = place\n user.save()\n return restful.ok()\n else:\n return restful.params_error(message=form.get_errors())\n else:\n return restful.unauth(message='未登录')\n\n\nclass LoginView(views.View):\n def get(self,request):\n redirect_url = request.GET.get('next', '')\n return render(request,'login.html',{'redirect_url':redirect_url})\n def post(self,request):\n user_name = request.POST.get(\"username\", \"\")\n pass_word = request.POST.get(\"password\", \"\")\n user = authenticate(request,email=user_name,password=pass_word)\n if user:\n login(request,user)\n redirect_url = request.POST.get('redirect_url', '')\n print(redirect_url)\n if redirect_url:\n return HttpResponseRedirect(redirect_url)\n # 跳转到首页 user request会被带回到首页\n return HttpResponseRedirect(reverse(\"blog:index\"))\n else:\n return render(request, 'login.html',{'error':'账号或密码错误'})\n\nclass CustomBackend(ModelBackend):\n def authenticate(self, email=None, password=None, **kwargs):\n try:\n # 不希望用户存在两个,get只能有一个。两个是get失败的一种原因 Q为使用并集查询\n user = User.objects.get(email=email)\n # django的后台中密码加密:所以不能password==password\n # UserProfile继承的AbstractUser中有def check_password(self,\n # raw_password):\n if user.check_password(password):\n return user\n except Exception as e:\n return None\n\nclass LogoutView(views.View):\n def get(self, request):\n # django自带的logout\n logout(request)\n # 重定向到首页,\n return HttpResponseRedirect(reverse(\"blog:index\"))\n\n\nclass AddArticleView(LoginRequiredMixin,views.View):\n login_url = '/login/'\n redirect_field_name = 'next'\n def get(self,request):\n tags = TagModel.objects.all()\n return render(request,'add_article.html',{'tags':tags})\n def post(self,request):\n tags = request.POST.get('tags')\n form = ArticleForm(request.POST)\n if form.is_valid():\n title = form.cleaned_data.get('title')\n content = form.cleaned_data.get('content')\n tags = tags.split(',')\n if tags[0]=='':\n ArticleModel.objects.create(title=title, content=content, author=request.user)\n else:\n all_tags = TagModel.objects.all()\n all_tagnames = [tag.name for tag in all_tags]\n article = ArticleModel.objects.create(title=title,content=content,author=request.user)\n for tag in tags:\n if tag in all_tagnames:\n ta = TagModel.objects.filter(name=tag).first()\n else:\n ta = TagModel(name=tag)\n ta.save()\n article.tags.add(ta)\n article.save()\n return restful.ok()\n else:\n print(form.errors)\n return restful.params_error(form.errors)\n\nclass ArticleDetailView(views.View):\n def get(self,request,article_id):\n article = ArticleModel.objects.get(pk=article_id)\n article.readcount+=1\n article.save()\n read_sort_articles = ArticleModel.objects.order_by('-readcount')[:5]\n tags = TagModel.objects.all()\n return render(request,'article_detail.html',{\"article\":article,'tags':tags,'read_sort_articles':read_sort_articles})\n\nclass AddTagView(views.View,LoginRequiredMixin):\n login_url = '/login/'\n redirect_field_name = 'next'\n\n def post(self,request):\n form = AddTagForm(request.POST)\n if form.is_valid():\n tag_name = form.cleaned_data.get('tag_name')\n tag_obj = TagModel.objects.filter(name=tag_name).first()\n if tag_obj:\n return restful.params_error('标签存在~')\n else:\n TagModel(name=tag_name).save()\n return restful.ok()\n else:\n print(form.errors)\n return restful.params_error('标签最长15个字符~')\n#文件上传\nfrom utils.upload import UploadFun\nclass Fileupload(views.View):\n def post(self,request):\n file = request.FILES.get('file')\n url = UploadFun(file)\n return restful.ok(data=url)\n\nclass ChangAvaterView(views.View,LoginRequiredMixin):\n login_url = '/login/'\n redirect_field_name = 'next'\n def post(self,request):\n file = request.FILES.get('file')\n url = UploadFun(file)\n user = request.user\n user.avatar = url\n user.save()\n return restful.ok()\n","sub_path":"apps/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"72148191","text":"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# 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 under\n# the License.\n# ==============================================================================\n\"\"\"Tests for read_parquet and ParquetDataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport numpy as np\n\nimport tensorflow as tf\nif not (hasattr(tf, \"version\") and tf.version.VERSION.startswith(\"2.\")):\n tf.compat.v1.enable_eager_execution()\nimport tensorflow_io.parquet as parquet_io # pylint: disable=wrong-import-position\n\n# Note: The sample file is generated from:\n# `parquet-cpp/examples/low-level-api/reader_writer`\n# This test extracts columns of [0, 1, 2, 4, 5]\n# with column data types of [bool, int32, int64, float, double].\n# Please check `parquet-cpp/examples/low-level-api/reader-writer.cc`\n# to find details of how records are generated:\n# Column 0 (bool): True for even rows and False otherwise.\n# Column 1 (int32): Equal to row_index.\n# Column 2 (int64): Equal to row_index * 1000 * 1000 * 1000 * 1000.\n# Column 4 (float): Equal to row_index * 1.1.\n# Column 5 (double): Equal to row_index * 1.1111111.\ndef test_parquet():\n \"\"\"Test case for read_parquet.\n\n \"\"\"\n filename = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n \"test_parquet\",\n \"parquet_cpp_example.parquet\")\n filename = \"file://\" + filename\n\n specs = parquet_io.list_parquet_columns(filename)\n columns = [\n 'boolean_field',\n 'int32_field',\n 'int64_field',\n 'float_field',\n 'double_field']\n p0 = parquet_io.read_parquet(filename, specs['boolean_field'])\n p1 = parquet_io.read_parquet(filename, specs['int32_field'])\n p2 = parquet_io.read_parquet(filename, specs['int64_field'])\n p4 = parquet_io.read_parquet(filename, specs['float_field'])\n p5 = parquet_io.read_parquet(filename, specs['double_field'])\n\n for i in range(500): # 500 rows.\n v0 = ((i % 2) == 0)\n v1 = i\n v2 = i * 1000 * 1000 * 1000 * 1000\n v4 = 1.1 * i\n v5 = 1.1111111 * i\n assert v0 == p0[i].numpy()\n assert v1 == p1[i].numpy()\n assert v2 == p2[i].numpy()\n assert np.isclose(v4, p4[i].numpy())\n assert np.isclose(v5, p5[i].numpy())\n\n dataset = tf.compat.v2.data.Dataset.zip(\n tuple(\n [parquet_io.ParquetDataset(filename, column) for column in columns])\n ).apply(tf.data.experimental.unbatch())\n i = 0\n for p in dataset:\n v0 = ((i % 2) == 0)\n v1 = i\n v2 = i * 1000 * 1000 * 1000 * 1000\n v4 = 1.1 * i\n v5 = 1.1111111 * i\n p0, p1, p2, p4, p5 = p\n assert v0 == p0.numpy()\n assert v1 == p1.numpy()\n assert v2 == p2.numpy()\n assert np.isclose(v4, p4.numpy())\n assert np.isclose(v5, p5.numpy())\n i += 1\n\nif __name__ == \"__main__\":\n test.main()\n","sub_path":"tests/test_parquet_eager.py","file_name":"test_parquet_eager.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"128532793","text":"import os\nimport sys\n\ninp = os.path.join(f\"{sys.argv[1]}.cov\")\n\n\ndef total_entries_count(in_file):\n count = 0\n with open(in_file) as f:\n for line in f:\n count += 1\n return count\n\n\ndef no_coverage_count(in_file):\n count = 0\n with open(in_file) as f:\n for line in f:\n if line.strip().split()[1] == \"0\":\n count += 1\n return count\n\n\ndef no_coverage_regions(in_file):\n with open(in_file) as f:\n ln_cov = \"\"\n first_coord = \"\"\n second_coord = \"\"\n set_flag = False\n set_print = False\n for line in f:\n if ln_cov == \"0\" and ln_cov == line.strip().split()[1] and not set_flag:\n first_coord = ln.strip().split()[0]\n second_coord = line.strip().split()[0]\n set_flag = True\n set_print = True\n elif ln_cov == \"0\" and ln_cov == line.strip().split()[1] and set_flag:\n second_coord = line.strip().split()[0]\n else:\n if set_print:\n print(f\"{first_coord}-{second_coord}\")\n set_print = False\n set_flag = False\n ln = line\n ln_cov = line.strip().split()[1]\n\n\ndef main():\n no_cov = no_coverage_count(inp)\n tot = total_entries_count(inp)\n print(no_cov)\n print(tot)\n print(no_cov/tot*100)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"zero_cov.py","file_name":"zero_cov.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"606680466","text":"from matplotlib import pyplot as plt\n\nexp_vals = [1400,600,300,410,250]\nexp_labels = ['Home Rent','Food','Phone / Internet Bill','Car','Other Utilities']\n\n#plt.axis('equal')\nplt.pie(exp_vals,labels=exp_labels,radius=1.5,autopct='%0.2f%%',explode=[0,0.3,0,0,0],shadow=True,startangle=45)\nplt.tight_layout()\n#plt.show()\nplt.savefig(\"abcd.pdf\",transparent=True)","sub_path":"Matplotlib/pie_save1.py","file_name":"pie_save1.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"93987278","text":"import random, math, time, struct, os, pygame, threading\r\npygame.init()\r\n\r\ndisplayWidth = 500\r\ndisplayHeight = 500\r\n\r\ngameDisplay = pygame.display.set_mode((displayWidth,displayHeight))\r\nmyfont = pygame.font.SysFont(None, int(displayWidth/20))\r\nclock = pygame.time.Clock()\r\noriginalTime = time.time()\r\nplayerSpriteImage = pygame.image.load(\"UFOSprite.png\").convert_alpha()\r\n\r\nclass Enemy():\r\n\r\n def __init__(self,speed):\r\n enemyLocationVar = enemyLocation() # Statically save the returned result of function\r\n XYStartEnemy = enemyLocationVar[0]\r\n XYEndEnemy = enemyLocationVar[1]\r\n self.XEnemy = enemyLocationVar[0][0] # Enemies X position and Y\r\n self.YEnemy = enemyLocationVar[0][1]\r\n self.speedEnemy = 1\r\n self.XIncrementEnemy = float(((XYStartEnemy[0] - XYEndEnemy[0])/1000) * speed) # Moves the enemy incrementally across the display\r\n self.YIncrementEnemy = float(((XYStartEnemy[1] - XYEndEnemy[1])/1000) * speed)\r\n\r\nclass Player():\r\n\r\n def __init__(self):\r\n self.XPlayer = (displayWidth/2)\r\n self.YPlayer = (displayHeight/2)\r\n self.XVelPlayer = 3\r\n self.YVelPlayer = 3\r\n self.spritePlayer = playerSpriteImage#(centre = [self.XPlayer,self.YPlayer])\r\n \r\ndef enemyLocation():\r\n r = random.randint(1,4)\r\n if r == 1 :\r\n XYStart = ((random.uniform(0,displayWidth)),0)\r\n XYEnd = ((random.uniform(0,displayWidth)),displayHeight) ###find perimeter randomly and on other parrallel side\r\n if r == 2 :\r\n XYStart = (displayWidth,(random.uniform(0,displayHeight)))\r\n XYEnd = (0,(random.uniform(0,displayHeight)))\r\n if r == 3 :\r\n XYStart = ((random.uniform(0,displayWidth)),displayHeight)\r\n XYEnd = (random.uniform(0,displayWidth),0)\r\n if r == 4 :\r\n XYStart = (0,(random.uniform(0,displayHeight)))\r\n XYEnd = (displayWidth,(random.uniform(0,displayHeight)))\r\n \r\n return [list(XYStart),list(XYEnd)]\r\n\r\ndef enemyCreateOften(speed, often): # Creating an enemy, if called, change the values of 'often' and 'speed'\r\n speed += 0.02\r\n if often > 0.05:\r\n often -= 0.003\r\n threading.Timer(often, enemyCreateOften).start()\r\n enemies.append(Enemy(speed)) # Creating a enemy\r\n return (speed,often)\r\n\r\ndef displaySetup(): # Timer, score etc\r\n \r\n gameDisplay.fill((255,255,255))\r\n timeScore = str(round(time.time()- originalTime,1))\r\n score = myfont.render(\"Your score: \" + timeScore, False, (255, 0, 0))\r\n gameDisplay.blit(score,(10,10))\r\n \r\ndef keyPress(event): # When the user presses a keyboard key to control player\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT: # Passed parameter 'key' should be 'event.type'\r\n player.Y -= player.YVelPlayer\r\n if event.key == pygame.K_RIGHT:\r\n player.Y += player.YVelPlayer\r\n if event.key == pygame.K_UP:\r\n player.X += player.XVelPlayer\r\n if event.key == pygame.K_DOWN:\r\n player.X += player.XVelPlayer\r\n if event.key == pygame.K_ESCAPE:\r\n pass # Make the pause display\r\n\r\nenemies = []\r\nplayer = Player()\r\n\r\nwhile True:\r\n \r\n displaySetup()\r\n gameDisplay.blit(player.spritePlayer,[100,100])\r\n pygame.display.update()\r\n clock.tick(60)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n","sub_path":"Alevel comp sci project.py","file_name":"Alevel comp sci project.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"638544157","text":"from math import sqrt\nimport re\nimport sys\n\n\n##------------------------------------------------------------##\n# \tThis function determines if a player is the ball owner. #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\tbx, by: ball's position on the X and Y axes.\t\t #\n#\t\tpx, py: player's position on the X and Y axes. \t #\n#\t\tradious\t\t\t\t\t\t\t\t\t\t\t\t #\n##------------------------------------------------------------## \t\t\t\t\t\t\t\t\t\t\t\t\ndef isOwner(bx, by, px, py, radious):\n\tdistance = sqrt(pow(bx - px, 2) + pow(by - py, 2))/10\n\treturn distance < radious\n\n##------------------------------------------------------------##\n#\tFunction used to extract some info about the ball from\t #\n#\tthe logfile. \t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\tinfo: string that indicates the required info. \t\t #\n#\t\tline: (show) line from the logfile. \t\t\t\t #\n##------------------------------------------------------------##\ndef extractBallInfo(info, line):\n\ti = 0\n\n\t##---- Move through the line until the 'b' char is found ----##\n\twhile (i < len(line)):\n\t\tif (line[i]==\"((b)\"):\n\t\t\tbreak\n\t\ti = i + 1\n\n\t##---- Extract the info required ----##\n\tif (info == \"ballpos.x\"):\n\t\treturn float(line[i+1])\n\telif (info == \"ballpos.y\"):\n\t\treturn float(line[i+2])\n\telif (info == \"ballvel.x\"):\n\t\treturn float(line[i+3])\n\telif (info == \"ballvel.y\"):\n\t\ttmp = re.sub(r'[()]', '', line[i+4]) # Remove \")\"\n\t\treturn float(tmp)\n\n##------------------------------------------------------------##\n#\tFunction used to extract the type of a certain player from #\n#\tthe logfile. \t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\tside: side of the field where his team is playing \t #\n#\t\t\t (l or r). \t\t\t\t\t\t\t\t #\n#\t\tunum: player number. \t\t\t\t\t\t #\n#\t\tline: (show) line from the logfile. \t\t\t\t #\n##------------------------------------------------------------##\ndef extractTypeInfo(side, unum, line):\n\ti = 0\n\n\t##---- Move through the line until the player is found ----##\n\twhile (i < len(line) - 2):\n\t\tif ((line[i] == \"((\" + side) and (line[i+1] == unum + \")\")):\n\t\t\ti = i + 2 \t\t# Move to the first value of the selected player\n\t\t\tbreak\n\t\ti = i + 1\n\n\treturn int(line[i])\n\n\n##------------------------------------------------------------##\n#\tFunction used to extract the position of a certain player #\n# from the logfile. \t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\tside: side of the field where his team is playing \t #\n#\t\t\t (l or r). \t\t\t\t\t\t\t\t #\n#\t\tunum: player number. \t\t\t\t\t\t #\n#\t\tinfo: string that indicates the required info. \t\t #\n#\t\tline: (show) line from the logfile. \t\t\t\t #\n##------------------------------------------------------------##\ndef extractPosInfo(side, unum, info, line):\n\ti = 0\n\n\t##---- Move through the line until the player is found ----##\n\twhile (i < len(line) - 1):\n\t\tif ((line[i] == \"((\" + side) and (line[i+1] == unum + \")\")):\n\t\t\ti = i + 4 \t\t# Move to the first value of the selected player\n\t\t\tbreak\n\t\ti = i + 1\n\n\tif (info == \"pos.x\"):\n\t\treturn float(line[i])\n\telif (info == \"pos.y\"):\n\t\treturn float(line[i+1])\n\telif (info == \"vel.x\"):\n\t\treturn float(line[i+2])\n\telif (info == \"vel.y\"):\n\t\treturn float(line[i+3])\n\telif (info == \"body\"):\n\t\treturn float(line[i+4])\n\telif (info == \"neck\"):\n\t\treturn float(line[i+5])\n\n\n##------------------------------------------------------------##\n#\tFunction used to extract the kick_rand value of a certain #\n#\ttype of player from the logfile. \t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\tline: (show) line from the logfile. \t\t\t\t #\n##------------------------------------------------------------##\ndef extractKickTypeInfo(line):\n\ti = 0\n\tnewLine = []\n\n\t##---- Remove parenthesis and separates\tfields ----##\n\tfor elem in line:\n\t\ttmp = re.sub(r'[()]', ' ', elem) \n\t\tnewLine += tmp.split()\n\n\t##---- Move through the line until the kick_rand is found ----##\n\twhile (i < len(newLine) - 1):\n\t\tif (newLine[i] == \"kick_rand\"):\n\t\t\treturn float(newLine[i+1])\n\t\ti = i + 1\n\n##------------------------------------------------------------##\n#\tThis function determines the ball owner. \t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\tball_posX, ball_posY: ball's position on the X and #\n#\t\t\t\t\t\t\t Y axes.\t\t \t\t\t\t #\n#\t\tleft_pPosX, left_pPosY: positions of the left team. #\n#\t\tright_pPosX, right_pPosY: positions of the right team. #\n#\t\tline: (show) line from the logfile. \t\t\t\t #\n#\t\tkick_rand: random value given for the server.\t\t #\n##------------------------------------------------------------##\ndef ownerPlayer(ball_posX, ball_posY, left_pPosX, left_pPosY, right_pPosX, right_pPosY, line, kick_rand):\n\tradious = 0.05\n\towner = \"\"\n\tminDist = 1000\n\townerX = 0\n\townerY = 0\n\n\tfor i in range(11):\n\t\tif (pow(ball_posX - left_pPosX[i], 2) + pow(ball_posY - left_pPosY[i], 2) < minDist):\n\t\t\townerX = left_pPosX[i]\n\t\t\townerY = left_pPosY[i]\n\t\t\towner = \"l \" + str(i+1)\n\t\t\tminDist = pow(ball_posX - left_pPosX[i], 2) + pow(ball_posY - left_pPosY[i], 2)\n\n\t\tif (pow(ball_posX - right_pPosX[i], 2) + pow(ball_posY - right_pPosY[i], 2) < minDist):\n\t\t\townerX = right_pPosX[i]\n\t\t\townerY = right_pPosY[i]\n\t\t\towner = \"r \" + str(i+1)\n\t\t\tminDist = pow(ball_posX - right_pPosX[i], 2) + pow(ball_posY - right_pPosY[i], 2)\n\n\tauxOwner = owner.split() \t# Convert into a list for extracting info\n\tif (owner != \"\"):\n\t\ttypePlayer = extractTypeInfo(auxOwner[0], auxOwner[1], line)\n\t\tif (isOwner(ball_posX, ball_posY, ownerX, ownerY, radious + kick_rand[typePlayer])):\n\t\t\treturn owner\n\treturn \"\"\n\n##------------------------------------------------------------##\n#\tThis function classifies the actions that have occurred #\n# during the match. \t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\tball_posX, ball_posY: ball's position on the X and #\n#\t\t\t\t\t\t\t Y axes.\t\t \t\t\t\t #\n#\t\tball_velXNew,ball_velYNew: ball's velocity on the X #\n#\t\t\t\t\t\t\t\t and Y axes for the #\n#\t\t\t\t\t\t\t\t current cycle.\t\t \t #\n#\t\tball_velXOld,ball_velYOld: ball's velocity on the X #\n#\t\t\t\t\t\t\t\t and Y axes for the #\n#\t\t\t\t\t\t\t\t last cycle.\t\t \t #\n#\t\townerNew: current owner of the ball. #\n#\t\townerOld: owner of the ball for the last cycle. #\n# oldOwner_X, oldOwner_Y: Position of the old owner in #\n# the X and Y axes. #\n# \t\towner : \t\t\t\tReal owner of the ball in #\n#\t\t\t\t\t\t\t\tthe current cycle. #\n##------------------------------------------------------------##\ndef actionClassifier(ball_posX, ball_posY,ball_velXNew,ball_velYNew,ball_velXOld,ball_velYOld,ownerNew,ownerOld,oldOwner_X,oldOwner_Y,owner):\n\t# -- Checking how many digits the owner's ids have -- #\n\townerO = \"\"\n\townerN = \"\"\n\tif (len(ownerOld) == 4) :\n\t\townerO = ownerOld[2]+ownerOld[3]\n\telif (len(ownerOld) == 3) :\n\t\townerO = ownerOld[2]\n\n\tif (len(ownerNew) == 4) :\n\t\townerN = ownerNew[2]+ownerNew[3]\n\telif (len(ownerNew) == 3) :\n\t\townerN = ownerNew[2]\n\n\t# If the ball velocity has changed it means it has moved\n\tif ((ball_velXNew != ball_velXOld) or (ball_velYNew != ball_velYOld)) :\n\t\tif (ownerNew != ownerOld) and (ownerNew != \"\") and (ownerOld != \"\") :\n\t\t\tif (ownerNew[0] == ownerOld[0]) : \t\t\t\t\t# If the ball stayed in the same team\n\t\t\t\tif (ownerN != ownerO) : \t\t\t\t\t\t# If the ball changed owners\n\t\t\t\t\treturn \"PASS\"\n\t\t\telif (ownerNew[0] != ownerOld[0]) :\t\t\t\t # If the ball changed teams\n\t\t\t\tif (ownerOld[0] == \"l\") :\t\t\t\t\t\t# Check for unsuccessful shots to the goal\n\t\t\t\t\tif (ball_posX >= 42.5) and (ball_posY > -10) and (ball_posY < 10) and (ball_velXOld > 0):\n\t\t\t\t\t\treturn \"UNSUCCESSFULSHOOT\"\n\t\t\t\telif (ownerOld[0] == \"r\") :\n\t\t\t\t\tif (ball_posX <= -42.5) and (ball_posY > -10) and (ball_posY < 10) and (ball_velXOld < 0):\n\t\t\t\t\t\treturn \"UNSUCCESSFULSHOOT\"\n\t\t\t\tdistance = sqrt(pow(ball_posX - oldOwner_X, 2) + pow(ball_posY - oldOwner_Y, 2))\n\t\t\t\tif (distance < 5) : \t\t\t\t\t\t\t# If the ball was lost near the old owner\n\t\t\t\t\treturn \"UNSUCCESSFULDRIBBLE\"\n\t\t\t\telse :\n\t\t\t\t\treturn \"UNSUCCESSFULPASS\"\n\t\telif (ownerNew == ownerOld) and (ownerNew != \"\") and (ownerOld != \"\") and (owner != \"\") :\n\t\t\tdistance = sqrt(pow(ball_posX - oldOwner_X, 2) + pow(ball_posY - oldOwner_Y, 2))\n\t\t\tif (distance > 0.5) : # If the ball and the owner have moved\n\t\t\t\treturn \"DRIBBLE\"\n\t\n\treturn \"\"\n\n\n##------------------------------------------------------------##\n#\tThis function returns the teammates involved in the action.#\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\towner: the owner of the ball.\t\t \t\t\t\t #\n#\t\tteam_posX, team_posY: positions of the team that owns #\n#\t\t\t\t\t\t\t the ball. \t\t\t\t\t #\n#\t\tbx, by: ball position. \t\t\t\t\t\t\t\t #\n##------------------------------------------------------------##\ndef chooseTeammates(owner, team_posX, team_posY, bx, by):\n\tauxOwner = owner.split()\n\townerX = team_posX[int(auxOwner[1]) - 1]\n\townerY = team_posY[int(auxOwner[1]) - 1]\n\tselected = [int(auxOwner[1]) - 1] # List with the players that are already selected\n\n\tteammates = [[ownerX, ownerY]] # Add the info about the owner\n\n\t##---- The second teammate correspond to the player who is closer to the owner ----##\n\tminDist = 10000\n\n\tfor i in range(0,11):\n\t\tif not(i in selected): \t#Discard the selected players\n\t\t\tactualDist = sqrt(pow(ownerX - team_posX[i], 2) + pow(ownerY - team_posY[i], 2))\n\t\t\tif (minDist > actualDist):\n\t\t\t\tminDist = actualDist\n\t\t\t\tminPlayer = i\n\tselected.append(minPlayer)\n\tteammates.append([team_posX[minPlayer], team_posY[minPlayer]]) \t# Add the info about the second teammate\n\t\n\t##---- The third teammate correspond to the player who is closer to the ball's trajectory ----##\n\tminDist = 10000\n\n\tfor i in range(0,11):\n\t\tif not(i in selected): \t#Discard the selected players\n\t\t\tactualDist = sqrt(pow(bx - team_posX[i], 2) + pow(by - team_posY[i], 2))\n\t\t\tif (minDist > actualDist):\n\t\t\t\tminDist = actualDist\n\t\t\t\tminPlayer = i\n\n\tteammates.append([team_posX[minPlayer], team_posY[minPlayer]]) \t\t# Add the info about the third teammate\n\n\treturn teammates\n\n##------------------------------------------------------------##\n#\tThis function returns the opponents involved in the action.#\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\townerX, ownerY: owner's position.\t \t\t\t\t #\n#\t\tteam_posX, team_posY: positions of the opponent team. #\n#\t\tbx, by: ball position. \t\t\t\t\t\t\t\t #\n#\t\told_bx, old_by: position of the ball at the start of #\n#\t\t\t\t\t\tthe action.\t\t\t\t\t\t\t #\n##------------------------------------------------------------##\ndef chooseOpponents(ownerX, ownerY, team_posX, team_posY, bx, by, old_bx, old_by):\n\topponents = []\n\tselected = [] # List with the players that are already selected\n\n\t##---- The first opponent correspond to the player who is closer to the owner ----##\n\tminDist = sqrt(pow(ownerX - team_posX[0], 2) + pow(ownerY - team_posY[0], 2))\n\tminPlayer = 0\n\n\tfor i in range(1,11):\n\t\tactualDist = sqrt(pow(ownerX - team_posX[i], 2) + pow(ownerY - team_posY[i], 2))\n\t\tif (minDist > actualDist):\n\t\t\tminDist = actualDist\n\t\t\tminPlayer = i\n\tselected.append(minPlayer)\n\topponents.append([team_posX[minPlayer], team_posY[minPlayer]]) \t\t# Add the info about the first opponent\n\n\t##---- The second opponent correspond to the player who is closer to last position of the ball ----##\n\tminDist = 10000\n\t\n\tfor i in range(0,11):\n\t\tif not(i in selected): \t#Discard the selected players\n\t\t\tactualDist = sqrt(pow(bx - team_posX[i], 2) + pow(by - team_posY[i], 2))\n\t\t\tif (minDist > actualDist):\n\t\t\t\tminDist = actualDist\n\t\t\t\tminPlayer = i\n\tselected.append(minPlayer)\n\topponents.append([team_posX[minPlayer], team_posY[minPlayer]])\t# Add the info about the second opponent\n\n\t##---- The third and the fourth opponents corresponds to the players near to the center of action path ----##\n\tmiddlePoint = [(bx + old_bx)/2, (by + old_by)/2]\n\t\n\tfor j in range(0,2):\n\t\tminDist = 10000\n\t\tfor i in range(0,11):\n\t\t\tif not(i in selected):\n\t\t\t\tactualDist = sqrt(pow(middlePoint[0] - team_posX[i], 2) + pow(middlePoint[1] - team_posY[i], 2))\n\t\t\t\tif (minDist > actualDist):\n\t\t\t\t\tminDist = actualDist\n\t\t\t\t\tminPlayer = i\n\t\tselected.append(minPlayer)\n\t\topponents.append([team_posX[minPlayer], team_posY[minPlayer]])\n\n\treturn opponents\n\n\n##------------------------------------------------------------##\n#\tThis function returns the nearest teammate \t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\tpx,py: player's position.\t \t\t\t\t \t\t #\n#\t\tteammates: position of all teammates.\t\t\t\t #\n##------------------------------------------------------------##\ndef nearestTeammate(px, py, teammates):\n\tminDist = sqrt(pow(px - teammates[0][0], 2) + pow(py - teammates[0][1], 2))\n\tindex = 0\n\tfor i in range(1,3):\n\t\tdist = sqrt(pow(px - teammates[i][0], 2) + pow(py - teammates[i][1], 2))\n\t\tif (minDist > dist):\n\t\t\tminDist = dist\n\t\t\tindex = i\n\n\treturn minDist\n\ndef distFromLine(x0,y0,x1,y1,x2,y2):\n\n\tif (x0!=x1):\n\t\ta = -(y1-y0)/(x1-x0)\n\t\tc = (((y1-y0)*x0)/(x1-x0)) - y0\n\t\tb = 1\n\telse:\n\t\ta = 1\n\t\tc = x0\n\t\tb = 0\n\n\tnum = abs(a*x2 + y2 + c)\n\tdenom = sqrt(pow(a,2) + b)\n\n\treturn num/denom\n\n\n##------------------------------------------------------------##\n#\tThis function generate the files for the second \t\t #\n#\tpreprocessing described by Maryam.\t\t\t\t\t\t #\n#\tParam:\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\tpx,py: player's position.\t \t\t\t\t \t\t #\n#\t\tteammates: position of all teammates.\t\t\t\t #\n##------------------------------------------------------------##\ndef generateNormalizedLogs(logFile):\n\t##---- Outputs files ----##\n\tshotFile = open(\"shotFile.dat\", \"a\") \n\tdribbleFile = open(\"dribbleFile.dat\", \"a\")\t\n\tpassFile = open(\"passFile.dat\", \"a\")\n\t#opponentFile = open(\"opponentFile.dat\", \"a\")\n\n\twith open(logFile) as file:\n\t\tcont = 0\n\t\tfor line in file:\n\t\t\tcont += 1\n\t\t\tteammates = []\n\t\t\tteammatesPass = []\n\t\t\topponents = []\n\t\t\topponentsPass = []\n\t\t\toriginalDist = []\n\n\t\t\tline = line.split()\t\t\t\t\t\t# Split into a list\n\n\t\t\t##---- Normalize ball's position ----##\n\n\t\t\tfirst_bx = float(line[0])\n\t\t\tfirst_by = float(line[1])\n\t\t\tlast_bx = float(line[2])\n\t\t\tlast_by = float(line[3])\n\n\t\t\ti = 4\n\t\t\twhile (i <= 24):\n\t\t\t\tdist = distFromLine(first_bx,first_by,last_bx,last_by,float(line[i]),float(line[i+1]))\n\t\t\t\tteammates.append(dist)\n\t\t\t\ti = i + 2\n\t\t\twhile (i <= 46):\n\t\t\t\tnearestPlayer = distFromLine(first_bx,first_by,last_bx,last_by,float(line[i]),float(line[i+1]))\n\t\t\t\topponents.append(nearestPlayer)\n\t\t\t\ti = i + 2\n\n\t\t\tball_velX = float(line[i])\n\t\t\tball_velY = float(line[i+1])\n\n\t\t\ti = i + 2\n\n\t\t\t##---- Actions ----##\n\t\t\tif (line[i] == \"GOAL\"):\n\t\t\t\tshotFile.write(str(first_bx/5) + \",\" + str(first_by/5) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tshotFile.write(str(teammates[j]) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tshotFile.write(str(opponents[j]) + \",\")\n\n\t\t\t\tshotFile.write(\"1\" + \"\\n\")\n\n\t\t\telif (line[i] == \"PASS\"):\n\t\t\t\tpassFile.write(str(first_bx/5) + \",\" + str(first_by/5) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tpassFile.write(str(teammates[j]) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tpassFile.write(str(opponents[j]) + \",\")\n\n\t\t\t\tpassFile.write(\"1\" + \"\\n\")\n\n\t\t\telif (line[i] == \"DRIBBLE\"):\n\t\t\t\tdribbleFile.write(str(first_bx/5) + \",\" + str(first_by/5) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tdribbleFile.write(str(teammates[j]) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tdribbleFile.write(str(opponents[j]) + \",\")\n\n\t\t\t\tdribbleFile.write(\"1\" + \"\\n\")\n\n\t\t\telif (line[i] == \"UNSUCCESSFULSHOOT\"):\n\t\t\t\tshotFile.write(str(first_bx/5) + \",\" + str(first_by/5) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tshotFile.write(str(teammates[j]) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tshotFile.write(str(opponents[j]) + \",\")\n\n\t\t\t\tshotFile.write(\"-1\" + \"\\n\")\n\n\t\t\telif (line[i] == \"UNSUCCESSFULDRIBBLE\"):\n\t\t\t\tdribbleFile.write(str(first_bx/5) + \",\" + str(first_by/5) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tdribbleFile.write(str(teammates[j]) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tdribbleFile.write(str(opponents[j]) + \",\")\n\n\t\t\t\tdribbleFile.write(\"-1\" + \"\\n\")\n\n\t\t\telif (line[i] == \"UNSUCCESSFULPASS\"):\n\t\t\t\tpassFile.write(str(first_bx/5) + \",\" + str(first_by/5) + \",\")\n\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tpassFile.write(str(teammates[j]) + \",\")\n\t\t\t\tfor j in range(0,11):\n\t\t\t\t\tpassFile.write(str(opponents[j]) + \",\")\n\n\t\t\t\tpassFile.write(\"-1\" + \"\\n\")\n\n\t\tfile.close()\n\t\n\tshotFile.close()\n\tpassFile.close()\n\tdribbleFile.close()\n\t#opponentFile.close()\n\n##---- Main function ----##\nif __name__ == \"__main__\":\n\n\tball_velXOld = 0\n\tball_velYOld = 0\n\tball_velXNew = 0\n\tball_velYNew = 0\n\tball_posXOld = 0\n\tball_posYOld = 0\n\tfirstVel = [0,0]\n\tisInitialPos = True\n\tourSide = \"\"\n\townerOld = \"\"\n\townerNew = \"\"\n\tkick_rand = []\n\toutputFile = open(sys.argv[2],\"w\") # Output file\n\tleft_pPosX0, left_pPosY0, right_pPosX0, right_pPosY0 = [], [], [], []\n\n\tcycle = 1\n\twith open(sys.argv[1]) as file:\n\t\tfor line in file:\n\t\t\tline = line.split()\t\t\t\t\t\t# Split into a list\n\t\n\t\t\tif ((line[0] == \"(show\")):\t# Is a (show) line\n\t\t\t\tleft_pPosX, left_pPosY = [], []\n\t\t\t\tright_pPosX, right_pPosY = [], []\n\n\t\t\t\t##---- Extract ball info ----##\n\t\t\t\tball_posX = extractBallInfo(\"ballpos.x\", line)\n\t\t\t\tball_posY = extractBallInfo(\"ballpos.y\", line)\n\n\t\t\t\t##---- Extract the current ball velocity ----##\n\t\t\t\tball_velXNew = extractBallInfo(\"ballvel.x\",line)\n\t\t\t\tball_velYNew = extractBallInfo(\"ballvel.y\",line)\n\n\t\t\t\tfor i in range(11):\n\t\t\t\t\tunum = str(i+1) \t\t\t\t# Uniform number\n\n\t\t\t\t\t##---- Extract player's position (Left Team) ----##\n\t\t\t\t\tleft_pPosX.append(extractPosInfo(\"l\", unum, \"pos.x\", line))\n\t\t\t\t\tleft_pPosY.append(extractPosInfo(\"l\", unum, \"pos.y\", line))\n\n\t\t\t\t\t##---- Extract player's position (Right Team) ----##\n\t\t\t\t\tright_pPosX.append(extractPosInfo(\"r\", unum, \"pos.x\", line))\n\t\t\t\t\tright_pPosY.append(extractPosInfo(\"r\", unum, \"pos.y\", line))\n\n\t\t\t\tif (isInitialPos): \t\t\t# First line of the action\n\t\t\t\t\tball_posXOld = ball_posX\n\t\t\t\t\tball_posYOld = ball_posY\n\t\t\t\t\tfirstVel[0] = ball_velXNew\n\t\t\t\t\tfirstVel[1] = ball_velYNew\n\n\t\t\t\t\t# Keep the player's position at the begining of the action\n\t\t\t\t\tleft_pPosX0 = left_pPosX \t\n\t\t\t\t\tleft_pPosY0 = left_pPosY\n\t\t\t\t\tright_pPosX0 = right_pPosX\n\t\t\t\t\tright_pPosY0 = right_pPosY\n\n\t\t\t\t\tisInitialPos = False\n\n\t\t\t\t#---- Obtaining the current owner of the ball ----##\n\t\t\t\towner = ownerPlayer(ball_posX,ball_posY,left_pPosX,left_pPosY,right_pPosX,right_pPosY,line,kick_rand)\n\t\t\t\t\n\t\t\t\tif (owner != \"\") :\n\t\t\t\t\t##---- If there is an owner, store it in ownerNew ----##\n\t\t\t\t\townerNew = owner\n\n\t\t\t\t##---- Extract the old owner's position ----##\n\t\t\t\toldOwner_X = None\n\t\t\t\toldOwner_Y = None\n\t\t\t\tif (ownerOld != \"\"):\n\t\t\t\t\tif (len(ownerOld) == 4) :\n\t\t\t\t\t\townerONum = ownerOld[2]+ownerOld[3]\n\t\t\t\t\telse :\n\t\t\t\t\t\townerONum = ownerOld[2]\n\n\t\t\t\t\toldOwner_X = extractPosInfo(ownerOld[0], ownerONum, \"pos.x\", line)\n\t\t\t\t\toldOwner_Y = extractPosInfo(ownerOld[0], ownerONum, \"pos.y\", line)\n\n\t\t\t\taction = actionClassifier(ball_posX,ball_posY,ball_velXNew,ball_velYNew,ball_velXOld,ball_velYOld,ownerNew,ownerOld,oldOwner_X,oldOwner_Y,owner)\n\t\n\t\t\t\tif (action != \"\"):\n\t\t\t\t\t##---- Add the action and the values to the output file ----##\n\t\t\t\t\tauxOwner = ownerOld.split()\n\n\t\t\t\t\tif (auxOwner[0] == ourSide):\n\t\t\t\t\t\townerX = oldOwner_X\n\t\t\t\t\t\townerY = oldOwner_Y\n\n\t\t\t\t\t\tif (auxOwner[0] == \"l\"):\n\t\t\t\t\t\t\tteammates = list(zip(left_pPosX0,left_pPosY0))\n\t\t\t\t\t\t\topponents = list(zip(right_pPosX0,right_pPosY0))\n\t\t\t\t\t\t\t\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tteammates = list(zip(right_pPosX0, right_pPosY0))\n\t\t\t\t\t\t\topponents = list(zip(left_pPosX0, left_pPosY0))\n\n\t\t\t\t\t\toutputFile.write(str(ball_posXOld) + \" \" + str(ball_posYOld) + \" \") # First ball position\n\t\t\t\t\t\toutputFile.write(str(ball_posX) + \" \" + str(ball_posY) + \" \") # Last ball position\n\n\t\t\t\t\t\tfor player in teammates:\n\t\t\t\t\t\t\toutputFile.write(str(player[0]) + \" \" + str(player[1]) + \" \") # X,Y position of the teammate\n\n\t\t\t\t\t\tfor player in opponents:\n\t\t\t\t\t\t\toutputFile.write(str(player[0]) + \" \" + str(player[1]) + \" \")\n\n\t\t\t\t\t\toutputFile.write(str(firstVel[0]) + \" \" + str(firstVel[1]) + \" \")\n\t\t\t\t\t\toutputFile.write(action + \"\\n\")\n\n\t\t\t\t\tisInitialPos = True\t\t# Restart the init values of the next action\n\n\t\t\t\t##---- Assign the Old Ball Velocity and Owner ----##\n\t\t\t\tball_velXOld = ball_velXNew\n\t\t\t\tball_velYOld = ball_velYNew\n\t\t\t\townerOld = ownerNew\n\n\t\t\t\tcycle = cycle+1\n\n\t\t\telif (line[0] == \"(player_type\"):\n\t\t\t\tkick_rand.append(extractKickTypeInfo(line))\n\t\t\n\t\t\telif (line[0] == \"(playmode\" and (line[2] == \"goal_l)\" or line[2]==\"goal_r)\") and (ourSide == line[2][5])) : # Check if a goal happened\n\t\t\t#elif (line[0] == \"(playmode\" and (line[2] == \"goal_l)\" or line[2]==\"goal_r)\")) : # Check if a goal happened\n\t\t\t\t##---- Add the action and the values to the output file ----##\n\t\t\t\tauxOwner = ownerOld.split()\n\n\t\t\t\tif (auxOwner[0] == \"l\"):\n\t\t\t\t\tteammates = list(zip(left_pPosX0,left_pPosY0))\n\t\t\t\t\topponents = list(zip(right_pPosX0,right_pPosY0))\n\n\t\t\t\telif (auxOwner[0] == \"r\"):\n\t\t\t\t\tteammates = list(zip(right_pPosX0, right_pPosY0))\n\t\t\t\t\topponents = list(zip(left_pPosX0, left_pPosY0))\n\n\t\t\t\toutputFile.write(str(ball_posXOld) + \" \" + str(ball_posYOld) + \" \") # First ball position\n\t\t\t\toutputFile.write(str(ball_posX) + \" \" + str(ball_posY) + \" \") # Last ball position\n\n\t\t\t\tfor player in teammates:\n\t\t\t\t\toutputFile.write(str(player[0]) + \" \" + str(player[1]) + \" \") # X,Y position of the teammate\n\n\t\t\t\tfor player in opponents:\n\t\t\t\t\toutputFile.write(str(player[0]) + \" \" + str(player[1]) + \" \")\n\n\t\t\t\toutputFile.write(str(firstVel[0]) + \" \" + str(firstVel[1]) + \" \")\n\t\t\t\toutputFile.write(\"GOAL\" + \"\\n\")\n\n\t\t\t\tisInitialPos = True\t\t# Restart the init values of the next action\n\n\t\t\telif ((line[0] == \"(team\") and (line[1] == \"1\")):\n\t\t\t\tif ((line[2] == \"JEMV\") or (line[2] == \"HELIOS_BASE\") or (line[2] == \"HELIOS_base\")):\n\t\t\t\t\tourSide = \"l\"\n\t\t\t\telse:\n\t\t\t\t\tourSide = \"r\"\n\n\t\tfile.close()\n\t\t\t\n\n\toutputFile.close()\n\tgenerateNormalizedLogs(sys.argv[2])\n\n\n\t\t\t\n\n\n","sub_path":"logs/preprocessingLogs.py","file_name":"preprocessingLogs.py","file_ext":"py","file_size_in_byte":21583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"6387119","text":"from datetime import date\n\nfrom tddspry.django import DatabaseTestCase, HttpTestCase\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpRequest\nfrom django.template import Template, Context, TemplateSyntaxError\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom test_tim.show_yourself.models import Person, Contacts, Request, ModelsLog\nfrom test_tim.show_yourself.middleware import CatchRequestMiddleware\nfrom test_tim.show_yourself.context_processors import settings_context\n\n\nTEST_FIRST_NAME = 'first name'\nNEW_FIRST_NAME = 'new first name'\nTEST_LAST_NAME = 'last name'\nTEST_BIRTH_DATE = date(1991, 12, 4)\nTEST_BIO = ''\n\nTEST_EMAIL = 'email@example.com'\nNEW_EMAIL = 'newemail@example.com'\nTEST_JABBER = 'jabber@jabber.org'\nTEST_SKYPE = 'myskypeid'\nTEST_OTHER = 'some other contacts'\nTEST_FK_PERSON_ID = 1\n\n\nclass TestPerson(DatabaseTestCase):\n\n def test_create(self):\n self.assert_create(Person, first_name=TEST_FIRST_NAME,\n last_name=TEST_LAST_NAME,\n birth_date=TEST_BIRTH_DATE,\n bio=TEST_BIO)\n\n def test_delete(self):\n person = self.assert_create(Person, first_name=TEST_FIRST_NAME,\n last_name=TEST_LAST_NAME,\n birth_date=TEST_BIRTH_DATE,\n bio=TEST_BIO)\n self.assert_delete(person)\n\n def test_read(self):\n self.assert_create(Person, first_name=TEST_FIRST_NAME,\n last_name=TEST_LAST_NAME,\n birth_date=TEST_BIRTH_DATE,\n bio=TEST_BIO)\n self.assert_read(Person, first_name=TEST_FIRST_NAME)\n\n def test_update(self):\n person = self.assert_create(Person, first_name=TEST_FIRST_NAME,\n last_name=TEST_LAST_NAME,\n birth_date=TEST_BIRTH_DATE,\n bio=TEST_BIO)\n self.assert_update(person, first_name=NEW_FIRST_NAME)\n\n\nclass TestContacts(DatabaseTestCase):\n\n def test_create(self):\n self.assert_create(Contacts, person_id=TEST_FK_PERSON_ID,\n email=TEST_EMAIL,\n jabber=TEST_JABBER,\n skype=TEST_SKYPE,\n other=TEST_OTHER)\n\n def test_delete(self):\n contacts = self.assert_create(Contacts, person_id=TEST_FK_PERSON_ID,\n email=TEST_EMAIL,\n jabber=TEST_JABBER,\n skype=TEST_SKYPE,\n other=TEST_OTHER)\n self.assert_delete(contacts)\n\n def test_read(self):\n self.assert_create(Contacts, person_id=TEST_FK_PERSON_ID,\n email=TEST_EMAIL,\n jabber=TEST_JABBER,\n skype=TEST_SKYPE,\n other=TEST_OTHER)\n self.assert_read(Contacts, email=TEST_EMAIL)\n\n def test_update(self):\n contacts = self.assert_create(Contacts, person_id=TEST_FK_PERSON_ID,\n email=TEST_EMAIL,\n jabber=TEST_JABBER,\n skype=TEST_SKYPE,\n other=TEST_OTHER)\n self.assert_update(contacts, email=NEW_EMAIL)\n\nTEST_PATH = '/music/bands/the_beatles/'\nNEW_PATH = '/music/bands/korn'\nTEST_METHOD = 'GET'\nTEST_IP = '127.0.0.1'\nTEST_USER_AGENT = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows 95)'\nTEST_PRIORITY = 1\n\n\nclass TestRequest(DatabaseTestCase):\n\n def test_create(self):\n self.assert_create(Request, path=TEST_PATH,\n method=TEST_METHOD,\n ip=TEST_IP,\n user_agent=TEST_USER_AGENT,\n priority=TEST_PRIORITY)\n\n def test_delete(self):\n request = self.assert_create(Request, path=TEST_PATH,\n method=TEST_METHOD,\n ip=TEST_IP,\n user_agent=TEST_USER_AGENT,\n priority=TEST_PRIORITY)\n self.assert_delete(request)\n\n def test_read(self):\n self.assert_create(Request, path=TEST_PATH,\n method=TEST_METHOD,\n ip=TEST_IP,\n user_agent=TEST_USER_AGENT,\n priority=TEST_PRIORITY)\n self.assert_read(Request, path=TEST_PATH)\n\n def test_update(self):\n request = self.assert_create(Request, path=TEST_PATH,\n method=TEST_METHOD,\n ip=TEST_IP,\n user_agent=TEST_USER_AGENT,\n priority=TEST_PRIORITY)\n self.assert_update(request, path=NEW_PATH)\n\n\nclass TestIndexPage(HttpTestCase):\n\n def test_index_url(self):\n self.go200('/show_yourself/')\n self.find('First name')\n self.find('Contacts')\n\n def test_homepage_bug(self):\n self.go200('/show_yourself/')\n p2 = Person(first_name='name', last_name='last',\n birth_date='1990-12-12')\n p2.save()\n p1 = Person.objects.get(pk=1)\n p1.delete()\n self.go200('/show_yourself/')\n\n def test_editpage_bug(self):\n self.helper('create_user', TEST_USERNAME, TEST_PASSWD)\n self.login(TEST_USERNAME, TEST_PASSWD)\n self.go200('/show_yourself/edit/')\n p2 = Person(first_name='name', last_name='last',\n birth_date='1990-12-12')\n p2.save()\n p1 = Person.objects.get(pk=1)\n p1.delete()\n self.go200('/show_yourself/edit/')\n\n\nclass TestEditPage(HttpTestCase):\n\n def test_good(self):\n # Ensure only authenticated users have acces to edit page.\n self.helper('create_user', TEST_USERNAME, TEST_PASSWD)\n self.login(TEST_USERNAME, TEST_PASSWD)\n self.go200('/show_yourself/edit/')\n\n # Test GET: Is forms are sent to the client?\n resp = self.client.get(reverse('edit'))\n self.assertEqual(resp.status_code, 200)\n self.assertTrue('person_form' in resp.context)\n self.assertTrue('contacts_form' in resp.context)\n\n # Test good POST.\n resp = self.client.post(reverse('edit'), {\n 'first_name': TEST_FIRST_NAME,\n 'last_name': TEST_LAST_NAME,\n 'birth_date': TEST_BIRTH_DATE,\n 'bio': TEST_BIO,\n 'email': TEST_EMAIL,\n 'jabber': TEST_JABBER,\n 'skype': TEST_SKYPE,\n 'other': TEST_OTHER,\n })\n self.assertEqual(resp.status_code, 302)\n person = Person.objects.all()[0]\n contacts = Contacts.objects.get(person=person)\n self.assertEqual(person.first_name, TEST_FIRST_NAME)\n self.assertEqual(contacts.email, TEST_EMAIL)\n\n # Not authenticated users havent acess to edit page.\n self.logout()\n self.go('/show_yourself/edit/')\n self.url(r'/accounts/login/\\?next=/show_yourself/edit/')\n\nTEST_USERNAME = 'testusername'\nTEST_PASSWD = 'testpassword'\n\n\nclass TestLogin(HttpTestCase):\n\n def test_login(self):\n self.helper('create_user', TEST_USERNAME, TEST_PASSWD)\n self.login(TEST_USERNAME, TEST_PASSWD)\n self.url('/show_yourself/')\n\n def test_logout(self):\n self.helper('create_user', TEST_USERNAME, TEST_PASSWD)\n self.login(TEST_USERNAME, TEST_PASSWD)\n self.logout()\n self.url(r'/show_yourself/')\n\n\nclass TestUrls(HttpTestCase):\n\n def testIndexUrl(self):\n self.go('/show_yourself/')\n\n def test_root_url(self):\n self.client.get('/')\n self.url('/show_yourself/')\n\nTEST_MIDDLEWARE_PATH = '/show_yourself/'\nTEST_MIDDLEWARE_IP = '127.0.0.1'\nTEST_MIDDLEWARE_METHOD = 'GET'\nTEST_MIDDLEWARE_USER_AGENT = 'TEST USER AGENT'\n\n\nclass TestMiddleware(HttpTestCase):\n\n def test_catch_rquest(self):\n self.go200(TEST_MIDDLEWARE_PATH)\n request = Request.objects.order_by('-time')[0]\n self.assertEqual(request.path, TEST_MIDDLEWARE_PATH)\n self.assertEqual(request.ip, TEST_MIDDLEWARE_IP)\n self.assertEqual(request.method, TEST_MIDDLEWARE_METHOD)\n\n http_request = HttpRequest()\n http_request.path = TEST_MIDDLEWARE_PATH\n http_request.method = TEST_MIDDLEWARE_METHOD\n http_request.META['REMOTE_ADDR'] = TEST_MIDDLEWARE_IP\n http_request.META['HTTP_USER_AGENT'] = TEST_MIDDLEWARE_USER_AGENT\n\n middleware = CatchRequestMiddleware()\n middleware.process_request(http_request)\n\n request = Request.objects.order_by('-time')[0]\n self.assertEqual(request.path, TEST_MIDDLEWARE_PATH)\n self.assertEqual(request.ip, TEST_MIDDLEWARE_IP)\n self.assertEqual(request.method, TEST_MIDDLEWARE_METHOD)\n self.assertEqual(request.user_agent, TEST_MIDDLEWARE_USER_AGENT)\n\n self.go('/show_yourself/requests')\n self.find(r'(?s)%s.*%s.*%s.*%s' %\n (TEST_MIDDLEWARE_PATH, TEST_MIDDLEWARE_IP,\n TEST_MIDDLEWARE_METHOD, TEST_MIDDLEWARE_USER_AGENT))\n\n\nclass TestContextProcessors(HttpTestCase):\n\n def test_settings_processor(self):\n context = settings_context(HttpRequest())\n self.assertEqual(context['MEDIA_URL'], settings.MEDIA_URL)\n self.assertEqual(context['STATIC_ROOT'], settings.STATIC_ROOT)\n self.assertEqual(context['ROOT_URLCONF'], settings.ROOT_URLCONF)\n\n resp = self.client.get(reverse('index'))\n self.assertEqual(resp.context['STATIC_URL'], settings.STATIC_URL)\n self.assertEqual(resp.context['ROOT_URLCONF'], settings.ROOT_URLCONF)\n\n\nclass TestTemplateTags(HttpTestCase):\n\n def setUp(self):\n self.user = User.objects.create_user('testuser',\n 'test@example.com', 's3krit')\n self.person = Person.objects.create(first_name=TEST_FIRST_NAME,\n last_name=TEST_LAST_NAME, birth_date=TEST_BIRTH_DATE,\n bio=TEST_BIO)\n\n def test_edit_link_tag_with_user(self):\n out = Template(\n \"{% load tags %}\"\n \"{% edit_link user %}\"\n ).render(Context({\n 'user': self.user,\n }))\n self.assertEqual(out, \"/admin/auth/user/%d/\" % self.user.id)\n\n def test_edit_link_tag_with_person(self):\n out = Template(\n \"{% load tags %}\"\n \"{% edit_link person %}\"\n ).render(Context({\n 'person': self.person,\n }))\n self.assertEqual(out,\n \"/admin/show_yourself/person/%d/\" % self.person.id)\n\n def test_edit_link_tag_parsing_errors(self):\n render = lambda t: Template(t).render(Context())\n\n self.assertRaises(TemplateSyntaxError, render,\n \"{% load tags %}{% edit_link %}\")\n\n self.assertRaises(TemplateSyntaxError, render,\n \"{% load tags %}{% edit_link \\\"text\\\" %}\")\n\n self.assertRaises(TemplateSyntaxError, render,\n \"{% load tags7 %}{% edit_link arg1 arg2 %}\")\n\n\nclass TestSignalsReceivers(DatabaseTestCase):\n\n def test_creation(self):\n p = self.assert_create(Person, first_name=TEST_FIRST_NAME,\n last_name=TEST_LAST_NAME,\n birth_date=TEST_BIRTH_DATE,\n bio=TEST_BIO)\n self.assert_read(ModelsLog,\n content_type=ContentType.objects.get_for_model(p),\n action='create',\n object_id=p.id)\n\n def test_editing(self):\n p = self.assert_create(Person, first_name=TEST_FIRST_NAME,\n last_name=TEST_LAST_NAME,\n birth_date=TEST_BIRTH_DATE,\n bio=TEST_BIO)\n self.assert_update(p, first_name=NEW_FIRST_NAME)\n self.assert_read(ModelsLog,\n content_type=ContentType.objects.get_for_model(p),\n action='edit',\n object_id=p.id)\n\n def test_deletion(self):\n p = self.assert_create(Person, first_name=TEST_FIRST_NAME,\n last_name=TEST_LAST_NAME,\n birth_date=TEST_BIRTH_DATE,\n bio=TEST_BIO)\n p_id = p.id\n self.assert_delete(p)\n self.assert_read(ModelsLog,\n content_type=ContentType.objects.get_for_model(p),\n action='delete',\n object_id=p_id)\n","sub_path":"test_tim/show_yourself/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":11614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"399862477","text":"import argparse\nimport os\nimport random\n\nclass PreprocessNP():\n\n #def __init__(self):\n #self.path_in = path_in\n #self.proportion_to_train = proportion_to_train\n\n def split_in_proportion(self, path_in, proportion_to_train=0.75):\n path_train = []\n path_val = [] \n num_class, path_class = self.get_dirs_inside(path_in)\n for _class in range(num_class):\n num_files, path_files = self.get_files_inside(path_class[_class])\n dataset_name = self.get_dataset_name(path_files)\n id_proportion_to_train = round(proportion_to_train*num_files)\n dataset = dataset_name[id_proportion_to_train-1]\n for i in range(id_proportion_to_train, len(path_files)):\n if dataset_name[i] == dataset:\n dataset = dataset_name[i]\n else:\n id_proportion_to_train = i\n break\n path_train = path_train + path_files[0:id_proportion_to_train]\n path_val = path_val + path_files[id_proportion_to_train:]\n\n return path_train, path_val\n\n @staticmethod\n def get_dirs_inside(path):\n path_dirs = []\n num_dirs = 0\n for root, dirs, files in os.walk(path):\n for _dir in dirs:\n path_dir = os.path.join(root, _dir)\n path_dirs.append(path_dir)\n num_dirs = num_dirs + 1\n return num_dirs, path_dirs\n\n @staticmethod\n def get_files_inside(path):\n path_files = []\n num_files = 0\n for root, dirs, files in os.walk(path):\n for _file in files:\n path_file = os.path.join(root, _file) \n path_files.append(path_file) \n num_files = num_files + 1\n return num_files, path_files \n \n @staticmethod\n def get_dataset_name(files):\n #dataset_name = [(os.path.basename(_file).split('_')[0] + '_' + os.path.basename(_file).split('_')[1]\n # + '_' + os.path.basename(_file).split('_')[2]) for _file in files]\n dataset_name = []\n for _file in files:\n try:\n temp = (os.path.basename(_file).split('_')[0] + '_' + os.path.basename(_file).split('_')[1]\n + '_' + os.path.basename(_file).split('_')[2])\n dataset_name.append(temp)\n except:\n print(_file)\n return dataset_name","sub_path":"components/unusable_model/preprocess_np_data.py","file_name":"preprocess_np_data.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"350169695","text":"from django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nimport requests\nfrom forms import CreateImageForm\nimport json\nfrom auth.decorators import require_auth\nfrom jaeweb.settings import BASE_URL\nimport os\nimport logging\n\nlogger=logging.getLogger(__name__)\n\n# Create your views here.\n@require_auth\ndef index(request):\n project_id = request.GET.get('project_id')\n url='{}/images?project_id={}'.format(BASE_URL,project_id)\n headers={'Content-Type':'application/json'}\n rs = requests.get(url,headers=headers)\n image_list=rs.json()\n\n return HttpResponse(json.dumps(image_list))\n\n@require_auth\ndef show(request):\n image_id=request.GET['id']\n url='{}/images/{}'.format(BASE_URL,image_id)\n headers={'Content-Type':'application/json'}\n rs = requests.get(url,headers=headers)\n return HttpResponse(json.dumps(rs.json())) \n\n\n@require_auth\ndef create(request):\n if request.method == \"POST\":\n form = CreateImageForm(request.POST)\n if form.is_valid():\n cleaned_data=form.cleaned_data\n project_id=cleaned_data.get('project_id')\n repo_path=cleaned_data.get('repo_path')\n repo_branch=cleaned_data.get('repo_branch')\n image_desc=cleaned_data.get('image_desc')\n user_name=request.session.get('user_id')\n #image_name=os.path.basename(repo_path)\n image_name= os.path.basename(repo_path) + '-' + repo_branch\n url=\"{}/images\".format(BASE_URL)\n headers={'Content-Type':'application/json'}\n data = {\n 'image_name':image_name,\n 'project_id':project_id,\n 'repo_path':repo_path,\n 'repo_branch':repo_branch,\n 'image_desc':image_desc,\n 'user_name':user_name,\n }\n rs = requests.post(url,headers=headers,data=json.dumps(data))\n logger.debug(rs.json())\n else:\n logger.debug('form is invalid')\n return HttpResponse(json.dumps(rs.json())) \n\n@require_auth\ndef delete(request):\n image_id=request.GET['id']\n f_id=request.GET['f']\n url = '{}/images/{}?force={}'.format(BASE_URL,image_id,f_id)\n headers={'Content-Type':'application/json'}\n rs = requests.delete(url,headers=headers)\n return HttpResponse(\"succeed\")\n\n@require_auth\ndef update(request):\n project_id = request.GET.get('project_id')\n url='{}/images?project_id={}'.format(BASE_URL,project_id)\n headers={'Content-Type':'application/json'}\n rs = requests.get(url,headers=headers)\n image_list=rs.json()\n logger.debug(image_list)\n\n url='{}/projects/{}'.format(BASE_URL,project_id)\n headers={'Content-Type':'application/json'}\n rs = requests.get(url,headers=headers)\n project_info = rs.json() \n role = 'normal'\n if request.session.get('user_id',None) == project_info['admin']:\n role = 'admin'\n\n return render_to_response('image-table-replace.html',{'image_list':image_list,'role':role})\n\n@require_auth\ndef edit(request):\n img_id = request.GET['id']\n url = '{}/images/edit?id={}'.format(BASE_URL,img_id)\n headers={'Content-Type':'application/json'}\n rs = requests.post(url,headers=headers)\n return HttpResponse(json.dumps(rs.json()))\n\n@require_auth\ndef commit(request):\n repo=request.GET.get('repo')\n tag=request.GET.get('tag')\n ctn=request.GET.get('ctn')\n id=request.GET.get('id')\n url=\"{}/images/commit?repo={}&tag={}&ctn={}&id={}\".format(BASE_URL,repo,tag,ctn,id)\n headers={'Content-Type':'application/json'}\n rs = requests.post(url,headers=headers)\n return HttpResponse(json.dumps(rs.json()))\n \n\t\n","sub_path":"images/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"231522215","text":"from Input import Input\nimport os,time,re,multiprocessing\nfrom grader import grader\nfrom sys import exit,stdout\nfrom math import log\nfrom copy import deepcopy\nfrom generatorReac1 import generatorReac \nfrom mater import *\nfrom outExtractor import extractor\n\n\n#from Gauss_connector import Gaussian_connector\ninCounter=0\n#random.seed(3) #Should be commented in the final version\n\n\ngener=False #gener will run the self.filename in Gaussian & will generated a new dict gener is instance of generatorReac1\npopulationSizeOfEachGeneration=14\nmaxGenerations=50\n\n#OLD:\nINIT_FILES=2\n\n\ndef handleFile0(filename):\n print (str(filename)+'\\n')\n basename = \".\".join(filename.split('/')[-1].split('.')[:-1])\n inp = Input(filename, basename, inCounter) # Initializing an object of Input module\n rvalues = inp.modify();del inp\n #return structure: ([name of new file(filename),basename,template of file, dictionary of this file])\n return ([rvalues[1],basename,rvalues[2],rvalues[0]])\n\ndef rmsd(dic1,dic2):\n summ=0\n cout=0\n for atom in dic1:\n for attrNum in range(len(dic1[atom])):\n nums=dic1[atom][attrNum][1].split(',')\n for indx in range(len(nums)):\n if '.' in nums[indx]:\n summ+=abs(float(num[indx])-float(dic2[atom][attrNum][1].split(',')[indx]))\n cout+=1\n return summ/float(cout)\n\ndef inputProcessor(listOfTraitsForEachFile,listOfFiles,firstRunFlag,dictToImplement):\n for attr in listOfTraitsForEachFile: # This part will generate input files for reactants and products\n filename=attr[0]\n template=attr[2]\n basename=attr[1]\n \n \n # =(self.filename, self.basename, inCounter, self.template, newDict)\n \n ## newDict is the dictionary we want to implement.\n ## self.template is a string of the lines of the user input file untill the first **** line.\n if firstRunFlag:\n listOfFiles.append(filename)\n else:\n inp = Input(filename, basename, inCounter, template, dictToImplement)\n rvalues = inp.modify()\n \"\"\" This meathod creates a new input file and return a list of 3 or 2 organs:\n 1) The dictionary that pulled to the new file.\n 2) The name of the new file.\n 3) String of the lines of the user input file untill the first **** line.\n * If it is not the first run, organ 3 dissmissed.\n \"\"\"\n listOfFiles.append(rvalues[1])\n return (inp)\n \n\n\ndef generate(CONST_reactants,CONST_products,globalDict):\n ###########################################################################\n ####### Here is the main method for the best set of parameters search:#######\n global inCounter, gener, DIST\n #inCounter is the main file number that added to the file. Gener must be global too so that this function can use its methods before instantiation \n #2/5/16: for each file, products and reactants contains a list of: filename, basename, template of the file and a dictionary inside\n\n reacInputs,prodInputs=[],[]\n inputProcessor(CONST_reactants,reacInputs,True,{}) #True means it is the first run\n inputProcessor(CONST_products,prodInputs,True,{})\n gener=generatorReac(reacInputs,prodInputs,globalDict)\n\n print ('\\nThis part is about to calculate the best set of parameters')\n\n dictsListOfThisGeneration=[globalDict]\n for generationNum in range(1,maxGenerations):\n dictListOfNextGeneration=[]\n #The lower the grade, the better\n gradesListOfThisGeneration=[] #[(dict,grade),...]\n print ('**************\\nThis is generation number: '+str(generationNum)+'\\n**************')\n #A loop in THIS generation, to measure the dicts:\n for dict in dictsListOfThisGeneration:\n reacInputs,prodInputs=[],[]\n inputProcessor(CONST_reactants,reacInputs,False,dict) #False mean it is not the first run\n inputProcessor(CONST_products,prodInputs,False,dict)\n gener=generatorReac(reacInputs,prodInputs,dict)\n reacOutputs=gener.getReacOutFilenames()\n prodOutputs=gener.getProdOutFilenames()\n errorHandler=grader()\n grade=errorHandler.getDictGrade(reacOutputs,prodOutputs)\n gradesListOfThisGeneration.append((dict,grade,inCounter)) \n inCounter += 1 \n def dictGradeReturner(tuppled):\n return (tuppled[1])\n #Putting the favorable dicts first:\n gradesListOfThisGeneration=sorted(gradesListOfThisGeneration,key=dictGradeReturner)\n print ('\\033[41m'+'TEST: inCounter:%s GradeList: %s'%(inCounter,[str(gradd[1])+' '+str(gradd[2]) for gradd in gradesListOfThisGeneration])+'\\033[0m') \n stdout.flush() \n numberOfDictsInNextGen=int(random.gauss(populationSizeOfEachGeneration,7)) #Edit! 2 is the mean of the gaussian distribution\n if numberOfDictsInNextGen == 0:\n numberOfDictsInNextGen=2\n elif numberOfDictsInNextGen < 0:\n numberOfDictsInNextGen=abs(numberOfDictsInNextGen)+1\n \n for numm in range(numberOfDictsInNextGen):\n #Matchmaker chooses the parents randomly from the list of dicts. Priority is higher for preciding dicts: \n matchmaker=mater(gradesListOfThisGeneration) \n matchmaker.makeCrossovers(generationNum)\n matchmaker.applyMutations(generationNum)\n dictListOfNextGeneration.append(matchmaker.getChild())\n dictsListOfThisGeneration=dictListOfNextGeneration\n\n \n \n #exit() \n #meanDeltaE=gener.getMeanDeltaE() #meanDeltaE is the float DeltaE that is inside \"temp\"\n #print ('\\nMeanDeltaE'+str(meanDeltaE))\n \n #temp=(-meanDeltaE/log(0.5)) # Temperature declaration\n #print (str(temp)+\" This is the temp\\n\")\n #print ('temp:',temp)\n print (gener) #Printing the results!!\n \n \ndef appendFiles(nameList,fileList):\n \"\"\"\n This function appends the nameList to the fileList:\n 1) Checks that the file is in the directory\n 2) if not, it tries to append the root directory\n 3) else, it prints an error massage\n \"\"\"\n for filename in nameList:\n filename=os.path.expanduser(filename)\n split=filename.split('/')\n if len (split)>1:\n if split[0]=='':\n \n if os.path.exists(filename): \n fileList.append(filename)\n else: # The full path is not correct\n print (\"\\nERROR: File does not exist in path: %s, aborting\" % filename)\n exit()\n else: # We got the full path without \"/\"\n abspath = \"\".join(['/', filename])\n if os.path.exists(abspath):\n fileList.append(abspath)\n else: \n abspath = \"\".join([os.getcwd(), '/', filename]) # Join the current path to filename\n if os.path.exists(abspath):\n fileList.append(abspath)\n else:\n print (\"\\nERROR: file does not exists in path or path is not correct: %s, aborting\" % filename)\n exit()\n else: # We got just the filename without any folder info\n abspath = \"\".join([os.getcwd(), '/', filename]) # Join the current path to filename\n if os.path.exists(abspath):\n fileList.append(abspath)\n else:\n print (\"ERROR: file does not exists in path: %s, aborting\" % abspath)\n exit()\n\n\nif __name__==\"__main__\":\n start_time = time.time()\n try:\n commands=open('PREFFERENCES.txt','rU')\n except:\n\n print ('ERROR: Cannot open: PREFFERENCES.txt file. Exiting!\\n')\n \n exit(0)\n lines=commands.readlines()\n countLine=0\n while not re.search(r'^Reactants:'.lower(), lines[countLine].lower()): countLine+=1 #Looking for 'Reactants'\n countLine+=1\n while not re.search(r'\\S', lines[countLine]): countLine+=1 #Empty lines between the reactants and the line: 'Reactants'\n reacStart=countLine #Start reactants\n while not re.search(r'^Products:'.lower(), lines[countLine].lower()): countLine+=1\n prodStart=countLine #contemporarry!\n countLine-=1\n while not re.search(r'\\S', lines[countLine]): countLine-=1 #Empty lines\n reacEnd=countLine+1\n countLine=prodStart+1 #Here may be an empty lines.\n while not re.search(r'\\S', lines[countLine]): countLine+=1 #Empty lines\n prodStart=countLine\n while re.search(r'\\S', lines[countLine]): countLine+=1 #Products lines\n prodEnd=countLine\n while not re.search(r'^Traits:'.lower(), lines[countLine].lower()): countLine+=1\n countLine+=1\n while not re.search(r'\\S', lines[countLine]): countLine+=1 #Empty lines\n traitsStart=countLine\n while countLinetcp套接字\n\n# 连接服务器\nserver_addr = ('127.0.0.1',8888) #服务端地址\nsockfd.connect(server_addr)\nfile_object = open(\"dict.txt\", 'rb+')\nwhile True:\n # 发送消息\n data =file_object.readline()\n if not data:\n break\n sockfd.send(data) # 转换为字节串再发送\n data = sockfd.recv(1024)\n print(\"Server:\",data.decode()) # 打印接收内容\n\n# 关闭套接字\nfile_object.close()\nsockfd.close()","sub_path":"PycharmProjects/python_file/month2/day06/tcp.client.py","file_name":"tcp.client.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"638752554","text":"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\n\ndata=pd.read_csv('Titanic.csv') #q1\nprint(data) #2, after examining the data target dependant variable is Survived\ndata.drop(data.columns[0], axis=1, inplace= True) #q3 dropping the passenger column as it is not necessary\nprint(data.isnull().sum()) #q4 no data is null\n\nfig=plt.figure()\nax1=fig.add_subplot(221)\nax1=sb.countplot(x=\"Class\", data=data)\nax1.set_title('Class Count')\nax2=fig.add_subplot(222)\nax2=sb.countplot(x=\"Sex\", data=data)\nax2.set_title('Sex Count')\nax3=fig.add_subplot(223)\nax3=sb.countplot(x=\"Age\", data=data)\nax3.set_title('Age Count')\nax4=fig.add_subplot(224)\nsb.countplot(x=\"Survived\", data=data)\nax4.set_title('Suvived Count')\nfig.suptitle('Lee_Maxwell_HW7') #q5 creating the count plots for each relevant column\n\ncatdata= pd.get_dummies(data, columns=['Class','Sex','Age','Survived']) #q6 getting dummy variables\nprint(catdata.columns)\n\nx=catdata.iloc[:,0:-2]\ny=catdata.iloc[:,-1] #preparing categorical data for the split. the y predictor will only the survived_yes column\n\n\nx_train, x_test, y_train, y_test =train_test_split(x,y, test_size=.3, random_state=0) #q7 splitting the data\nlogreg= LogisticRegression()\nlogreg.fit(x_train,y_train) #q8 fitting the data to logistic regression\n\ny_pred=logreg.predict(x_test) #using the test data to predict\ncnfmatrix= metrics.confusion_matrix(y_test, y_pred)\nprint(metrics.accuracy_score(y_test,y_pred)) #q9 printing the accuracy score\nprint(cnfmatrix) #q10 printing the confusion matrix\n\n\ntestpatient=np.array([0,0,1,0,0,1,1,0]).reshape(1,-1) #creating a sample data set with the desired categories of male, 3rd class, adult\n\ntestpatient_pred=logreg.predict(testpatient) #predicting the 3rd class male adult\nprint(testpatient_pred) #q11 printing the result, which is 0 meaning the 3rd class male adult is not predicted to survive\nplt.show()","sub_path":"Homeworks/Lee_Maxwell_HW7/Lee_Maxwell_HW7.py","file_name":"Lee_Maxwell_HW7.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"270570854","text":"'''\nRead through the users.txt, events.txt, and groups.txt files and use the\npartup api to fill up the database with test data.\n\nThe script takes a url as an optional command line argument. If the\nargument is included, the script will direct its api calls to that.\nOtherwise, the script will direct its api calls to the dev server.\n\nConsider modifying to take another command line argument that will\nlet you only do users, events, or groups.\n'''\nfrom __future__ import print_function\nfrom datetime import datetime, timedelta\nfrom random import random\nimport requests\nimport sys\n\nserver = \"http://52.4.3.6/api\"\ncookies = {}\n\n\ndef add_users():\n '''\n Reads an input file called 'users.txt' and adds the users defined in that\n file to the database. Each line in the file should be of the form:\n \"First_name Last_name email@address Password\". Lines starting with '#' will\n be ignored.\n '''\n f = open('users.txt', 'r')\n for l in f.readlines():\n line = l.strip('\\n').split()\n if line[0] == '#':\n # Ignore commented lines\n continue\n\n reg_data = {\n 'first_name': line[0],\n 'last_name': line[1],\n 'email': line[2],\n 'password': line[3]\n }\n\n r = requests.post(server + '/users/register/', data=reg_data)\n try:\n response = r.json()\n except (ValueError) as e:\n err = open('debug.html', 'w')\n err.write(r.text)\n err.close()\n raise e\n\n global cookies\n if (response['accepted'] is False and\n 'email is being used' not in response['error']):\n print('registration fail', l, response, file=sys.stderr)\n continue\n\n # Log in user and save the cookie\n login_data = {\n 'username': line[2],\n 'password': line[3]\n }\n r = requests.post(server + '/users/login/', data=login_data)\n response = r.json()\n if response['accepted'] is True:\n cookies[reg_data['email']] = r.cookies\n else:\n # Not clear what the error was so print to log file\n print('login fail', l, response, file=sys.stderr)\n\n f.close()\n\n\ndef _parse_time(displacement=0):\n '''\n Given an integer, displacement, return a string representing the\n date and time displacement days from now. The string returned will\n be of the \"YYYYMMDDhhmm\".\n '''\n time = datetime.now() + timedelta(days=displacement)\n info = (time.year, time.month, time.day, time.hour, time.minute)\n return '%4d%02d%02d%02d%02d' % info\n\n\ndef _random_name():\n '''\n Returns a random username from users.txt uniformly at random.\n '''\n name = ''\n counter = 0\n for l in open('users.txt', 'r').readlines():\n line = l.strip('\\n').split()\n if line[0] == '#':\n # ignore comments\n continue\n\n counter += 1\n if random() < (1.0 / float(counter)):\n name = line[2]\n return name\n\n\ndef _parse_invite_list(num_guests=0):\n '''\n Given an integer, num_guests, randomly select num_guests users from\n users.txt to invite to the event.\n '''\n return [_random_name() for i in range(num_guests)]\n\n\ndef add_events():\n '''\n Reads an input file called 'events.txt' and adds the events defined in that\n file to the database. Each line in the file should be of the form:\n \"username title time location_name public age_restriction price invite_guests\".\n username is the person to use when creating the event, time is the\n displacement (in days) from the current time, and invite_guest gives the\n number of people on the invite list. Those users are chosen at random from\n the users.txt file. Lines starting with '#' will be ignored.\n '''\n f = open('events.txt', 'r')\n for l in f.readlines():\n line = l.strip('\\n').split()\n if line[0] == '#':\n # Ignore commented lines\n continue\n\n # line[0] is the username\n global cookies\n cookie = cookies[line[0]]\n\n # Parse the rest of the line\n data = {\n 'title': line[1],\n 'time': _parse_time(int(line[2])),\n 'location_name': line[3],\n 'public': line[4],\n 'age_restrictions': line[5],\n 'price': line[6],\n 'invite_list': ','.join(_parse_invite_list(int(line[7])))\n }\n\n r = requests.post(server + '/events/create/', data=data,\n cookies=cookie)\n response = r.json()\n if response['accepted'] is False:\n print(l, response, file=sys.stderr)\n\n\ndef main(args):\n global server\n if len(args) > 1:\n server = args[1]\n add_users()\n add_events()\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"testdata/filldatabase.py","file_name":"filldatabase.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"646117652","text":"from django.conf.urls import url\nfrom ranking import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(\n r'^create/$',\n views.category_create,\n name='category_create'\n ),\n url(\n r'^(?P[\\d]+)/$',\n views.category_detail,\n name='category_detail'\n ),\n url(\n r'^(?P[\\d]+)/delete/$',\n views.category_delete,\n name='category_delete'\n ),\n url(\n r'^(?P[\\d]+)/update/$',\n views.category_update,\n name='category_update'\n ),\n url(\n r'^pages/$',\n views.PageListView.as_view(),\n name='page_list'\n ),\n url(\n r'^pages/create/$',\n views.PageCreateView.as_view(),\n name='page_create'\n ),\n url(\n r'^pages/(?P[\\d]+)/$',\n views.PageDetailView.as_view(),\n name='page_detail'\n ),\n url(\n r'^pages/(?P[\\d]+)/update/$',\n views.PageUpdateView.as_view(),\n name='page_update'\n ),\n url(\n r'^pages/(?P[\\d]+)/delete/$',\n views.PageDeleteView.as_view(),\n name='page_delete',\n ),\n url(\n r'^$',\n views.CategoryListView.as_view(),\n name='category_list'\n ),\n url(\n r'^create/$',\n views.CategoryCreateView.as_view(),\n name='category_create'\n ),\n url(\n r'^(?P[\\d]+)/$',\n views.CategoryDetailView.as_view(),\n name='category_detail'\n ),\n url(\n r'^(?P[\\d]+)/update/$',\n views.CategoryUpdateView.as_view(),\n name='category_update'\n ),\n url(\n r'^(?P[\\d]+)/delete/$',\n views.CategoryDeleteView.as_view(),\n name='category_delete',\n ),\n]\n","sub_path":"ranking/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"335116131","text":"#! /usr/bin/env python3\n\nimport re\n\ndef solve():\n r, c, k, candies = read()\n print(think(r, c, k, candies))\n\ndef read():\n r, c, k = list(map(int, re.split('\\W+', input().rstrip())))[ : 3]\n [n] = list(map(int, re.split('\\W+', input().rstrip())))[ : 1]\n candies = []\n for x in range(n):\n c_r, c_c = list(map(int, re.split('\\W+', input().rstrip())))[ : 2]\n candies.append([c_r, c_c])\n return r, c, k, candies\n\ndef think(r, c, k, candies):\n candies_in_row = get_candies_in_row(candies, r)\n candies_in_col = get_candies_in_col(candies, c)\n print(candies_in_row)\n print(candies_in_col)\n cells = 0\n return cells\n\ndef get_candies_in_row(candies, r):\n candies_in_row = []\n for row in range(r):\n candies_in_row.append(len(list(filter(lambda x: x[0] == row + 1, candies))))\n return candies_in_row\n\ndef get_candies_in_col(candies, c):\n candies_in_col = []\n for col in range(c):\n candies_in_col.append(len(list(filter(lambda x: x[1] == col + 1, candies))))\n return candies_in_col\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n solve()\n","sub_path":"atcoder/ABC/ABC023/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"544165737","text":"price = 49\ntxt = \"The price is {} dollars\"\nprint(txt.format(price))\ntxt = \"The price is {:.2f} dollars\"\nprint(txt.format(price))\nquantity = 3\nitemno = 567\nprice = 49\nmyorder = \"I want {} pieces of item number {} for {:.2f} dollars.\"\nprint(myorder.format(quantity, itemno, price))\nmyorder = \"I want {0} pieces of item number {1} for {2:.2f} dollars.\"\nprint(myorder.format(quantity, itemno, price))\nage = 36\nname = \"John\"\ntxt = \"His name is {1}. {1} is {0} years old.\"\nprint(txt.format(age, name))\nmyorder = \"I have a {carname}, it is a {model}.\"\nprint(myorder.format(carname = \"Ford\", model = \"Mustang\"))\nx=100\n\n\n#fstring use \"f\" or \"F\" in the bigining of the print statement.\nprint(f'Temp is {x}')\nprint(F'Temp is not {x**8:,}')\nimport math\nprint(f'{math.sqrt(9)}')\n\n\nimport time\nstart=time.perf_counter()\nprint(\"hi\")\nx=time.perf_counter()-start\nprint(x)\n","sub_path":"py_pgm/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"578373633","text":"from behave import *\r\nfrom selenium import webdriver\r\nfrom time import sleep\r\n\r\n@given('try to open webdriver \"Chrome\"')\r\ndef open(context):\r\n context.driver=webdriver.Chrome(\"C:\\\\Users\\\\sangeeth.kumar\\\\python selenium\\\\chromedriver_win32\\\\chromedriver.exe\")\r\n context.driver.get('https://www.google.com') \r\n@when('loading the google page')\r\ndef open(context): \r\n id=context.driver.find_element_by_id(\"lst-ib\")\r\n id.send_keys(\"calsoftinc.com\")\r\n@then('verify the title page')\r\ndef open(context):\r\n title = context.driver.title\r\n context.driver.close()\r\n if title != \"Google\":\r\n raise AssertionError\r\n\r\n","sub_path":"Assignment/steps/example_steps.py","file_name":"example_steps.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"600966544","text":"import hashlib\n\ndef get_hash(salt, index):\n md5 = hashlib.md5()\n message = (salt + str(index)).encode('utf-8')\n md5.update(message)\n return md5.hexdigest()\n\ndef get_triplet(key):\n for idx in range(len(key)-3):\n if key[idx] == key[idx+1] == key[idx+2]:\n return key[idx]\n return None\n\ndef has_five_in_row(key, char):\n for idx in range(len(key)-5):\n if key[idx] == char and key[idx] == key[idx+1] and\\\n key[idx+1] == key[idx+2] and key[idx+2] == key[idx+3] and\\\n key[idx+3] == key[idx+4]:\n return True\n return False\n\ndef check_next_1000_keys(salt, index, char):\n for idx in range(index+1, index+1000):\n hash = get_hash(salt, idx)\n if has_five_in_row(hash, char):\n print('5. char: {}, hash: {}'.format(char, hash))\n return True\n return False\n\ndef is_key(salt, key, index):\n triplet = get_triplet(key)\n\n if triplet is not None:\n if check_next_1000_keys(salt, index, triplet):\n print('3. char: {}, hash: {}'.format(triplet, key))\n return True\n return False\n\nif __name__ == '__main__':\n puzzle_input = 'cuanljph'\n otp_keys = []\n index = 0\n\n while len(otp_keys) < 64:\n key = get_hash(puzzle_input, index)\n\n if is_key(puzzle_input, key, index):\n otp_keys.append(key)\n print('Index for {}th key is {}'.format(len(otp_keys), index))\n index = index + 1\n\n print(otp_keys)\n","sub_path":"2016/days/14/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"635391443","text":"\"\"\"\nAuthor: Anurag Kumar\n\"\"\"\n\nimport os\nimport glob\nfrom shutil import copyfile\nimport pandas as pd\nfrom pydub import AudioSegment\nfrom pathlib import Path\nimport subprocess\nfrom tqdm import tqdm\nimport argparse\nfrom multiprocessing import Pool, Manager, Process, RLock\n\ndef convert_to_wav(fin, fout):\n \"\"\"\n Reads the file from fin and saves the file in wav format in fout\n \"\"\"\n temp = subprocess.run([\"ffmpeg\",\n \"-i\", \n fin, \n fout], \n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE)\n \n \ndef compress_segments(map_, wav_id, file_path, segments, outpath):\n \"\"\"\n Accepts the wav audio file and list of segment time stamps.\n Chunks the audio and calculates CR for each segment.\n \n file_path : path to wav file\n segments : list of segments time stamps\n outpath : path to save chunks\n \"\"\"\n try:\n audio = AudioSegment.from_wav(file_path)\n #print(\"\\nSegments:\", len(segments))\n for _, row in segments.iterrows():\n start = row[2] * 1000\n end = row[3] * 1000\n audio_chunk = audio[start:end]\n save_path = \"{}/{}_chunk_{}_{}.wav\".format(outpath, wav_id, start, end)\n audio_chunk.export(save_path, format='wav')\n compress_file(map_=map_, \n name=row[0],\n save_path=save_path)\n except Exception as e:\n print(\"ERR:\",e)\n print(\"Failed files:\", file_path)\n\ndef compress_file(map_, name, save_path):\n \"\"\"\n Compresses the file and calculates CR.\n\n map_: common map {uttid : CR} across processes\n name: utt_id\n save_path: temp path to store converted wavs/ compressed files.\n \"\"\"\n size = os.path.getsize(save_path)\n temp = subprocess.run([\"gzip\", \"-k\", save_path])\n cr_size = os.path.getsize(save_path+\".gz\")\n try:\n map_[name] = cr_size / size\n except Exception as e:\n print(f\"File: {save_path}, Ori:{size}, Compr:{cr_size}\")\n print(e)\n raise ZeroDivisionError\n temp = subprocess.run([\"rm\", save_path])\n temp = subprocess.run([\"rm\", save_path+\".gz\"])\n\n\ndef calc_CR_scp(pid, map_, file_, args, segments=None, start=None, end=None):\n \"\"\"\n Main function run by each process.\n\n pid : process_id\n map_ : common map {uttid : CR} across processes\n file_ : entire wav.scp to be read\n segments: segment file if exists\n start : start index for process\n end : end index for process\n \"\"\"\n tqdm_text = \"#\"+\"{}\".format(pid).zfill(3)\n data = file_[start:end]\n if segments:\n segments = pd.read_csv(segments, sep = ' ', header=None)\n with tqdm(total=end-start, desc=tqdm_text, position=pid+1) as pbar:\n for row in data:\n sep = ' ' if len(row.split(' ')) > 1 else '\\t'\n for val in row.split(sep):\n if val[:3] == '/db':\n fpath = val.strip()\n args.extn = val.strip().split('.')[-1]\n break\n wav_id = row.split(sep)[0]\n save_path = \"{}/{}.wav\".format(args.res_dir, wav_id) \n if args.extn == 'wav':\n convert_to_wav(fin=fpath, fout=save_path)\n else:\n copyfile(fpath, save_path)\n fpath = save_path\n if isinstance(segments, pd.DataFrame):\n segs = segments[segments[1] == wav_id]\n compress_segments(map_=map_, \n wav_id=wav_id,\n file_path=fpath,\n segments=segs, \n outpath=args.res_dir)\n else: \n compress_file(map_=map_, \n name=wav_id,\n save_path=save_path)\n pbar.update(1)\n\n\ndef save_file(map_, args):\n \"\"\"\n Saves the mapping of utt_id to cr in a file. \n map_ : mapping of utt_id to cr\n \"\"\" \n if args.segments:\n p = os.path.join(args.res_dir, 'compression_'+args.db+\"_seg\")\n else:\n p = os.path.join(args.res_dir, 'compression_'+args.db)\n with open(p, 'w') as f:\n for file in map_:\n f.write(\"{} {}\\n\".format(file, map_[file]))\n\ndef clean_dir(dir):\n \"\"\"\n Removes all files with certain pattern in the specified directory.\n \"\"\"\n files = glob.glob(dir)\n for file in files:\n os.remove(file)\n\ndef main(args):\n manager = Manager()\n map_ = manager.dict()\n files = ['wav.scp']\n sep = ' '\n if args.db == '6dial':\n sep = '\\t'\n for file_ in files: \n pool = Pool(processes=args.num_process, initargs=(RLock(), ), initializer=tqdm.set_lock)\n processes = []\n csv = open(args.wav_scp, 'r').readlines()\n if args.segments:\n segments = args.wav_scp[:-7] + 'segments'\n else:\n segments = None\n csv_len = len(csv)\n rows_per_process = int(csv_len/args.num_process) + 1\n print('\\n')\n print(f\"starting processes for file {file_} with {rows_per_process} rows\")\n for i in range(args.num_process):\n start = int(i*rows_per_process)\n end = int(min(start + rows_per_process, csv_len))\n processes.append(pool.apply_async(calc_CR_scp, args=(i,\n map_, \n csv, \n args, \n segments, \n start, \n end,)))\n pool.close()\n results = [job.get() for job in processes]\n \n for i in range(10):\n print('\\n')\n save_file(map_, args)\n print(\"compression ratio file created successfully...\")\n print(\"cleaning temporary files..\")\n clean_dir(dir=\"/shared/workspaces/anuragkumar95/compressions/*wav*\")\n\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--db\", type=str, required=True, help='Type of dataset, cv(commonvoice) or mls/ identifies for compression file')\n parser.add_argument(\"--num_process\", type=int, required=True)\n parser.add_argument('--wav_scp', type=str, required=True)\n parser.add_argument('--res_dir', type=str, required=True, help='Path to dir where the results will be stored.')\n parser.add_argument('--extn', type=str, required=False, help='default audio files extension, if not mentioned sets it internally.')\n parser.add_argument('--segments', action='store_true')\n args = parser.parse_args()\n main(args)\n\n\n ","sub_path":"espnet2/curriculum/compression_ratio.py","file_name":"compression_ratio.py","file_ext":"py","file_size_in_byte":6660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"477930839","text":"import logging\nfrom flask import (\n Blueprint,\n jsonify,\n request,\n abort,\n current_app\n)\n\nfrom onepiece.exceptions import (\n ComicbookException,\n NotFoundError,\n SiteNotSupport\n)\nfrom . import crawler\nfrom . import task\nfrom .const import ConfigKey\n\n\nlogger = logging.getLogger(__name__)\napp = Blueprint(\"api\", __name__, url_prefix='/api')\naggregate_app = Blueprint(\"aggregate\", __name__, url_prefix='/aggregate')\nmanage_app = Blueprint(\"task\", __name__, url_prefix='/manage')\n\n\ndef handle_404(error):\n if isinstance(error, NotFoundError):\n return jsonify(dict(message=str(error))), 404\n elif isinstance(error, SiteNotSupport):\n return jsonify(dict(message=str(error))), 400\n else:\n return jsonify(dict(message=str(error))), 500\n\n\napp.register_error_handler(ComicbookException, handle_404)\naggregate_app.register_error_handler(ComicbookException, handle_404)\nmanage_app.register_error_handler(ComicbookException, handle_404)\n\n\ndef check_manage_secret(request):\n secret = request.headers.get('API-Secret', '')\n right_secret = current_app.config.get(ConfigKey.MANAGE_SECRET)\n if right_secret:\n if secret != right_secret:\n abort(403)\n\n\n@app.route(\"//comic/\")\ndef get_comicbook_info(site, comicid):\n result = crawler.get_comicbook_info(site=site, comicid=comicid)\n return jsonify(result)\n\n\n@app.route(\"//comic//\")\ndef get_chapter_info(site, comicid, chapter_number):\n result = crawler.get_chapter_info(site=site, comicid=comicid, chapter_number=chapter_number)\n return jsonify(result)\n\n\n@app.route(\"//search\")\ndef search(site):\n name = request.args.get('name')\n page = request.args.get('page', default=1, type=int)\n if not name:\n abort(400)\n result = crawler.get_search_resuult(site=site, name=name, page=page)\n return jsonify(dict(search_result=result))\n\n\n@app.route(\"//tags\")\ndef tags(site):\n result = crawler.get_tags(site)\n return jsonify(dict(tags=result))\n\n\n@app.route(\"//list\")\ndef tag_list(site):\n tag = request.args.get('tag')\n page = request.args.get('page', default=1, type=int)\n result = crawler.get_tag_result(site=site, tag=tag, page=page)\n return jsonify(dict(list=result))\n\n\n@app.route(\"//latest\")\ndef latest(site):\n page = request.args.get('page', default=1, type=int)\n result = crawler.get_latest(site=site, page=page)\n return jsonify(dict(latest=result))\n\n\n@aggregate_app.route(\"/search\")\ndef aggregate_search():\n site = request.args.get('site')\n name = request.args.get('name')\n if not name:\n abort(400)\n result = crawler.aggregate_search(site=site, name=name)\n return jsonify(dict(list=result))\n\n\n@manage_app.route(\"/cookies/\", methods=['GET'])\ndef get_cookies(site):\n check_manage_secret(request)\n cookies = crawler.get_cookies(site=site)\n return jsonify(dict(cookies=cookies))\n\n\n@manage_app.route(\"/cookies/\", methods=['POST'])\ndef update_cookies(site):\n check_manage_secret(request)\n content = request.json or {}\n cookies = content.get('cookies')\n cover = content.get('cover', False)\n if not cookies or not isinstance(cookies, list):\n abort(400)\n ret = crawler.update_cookies(site=site, cookies=cookies, cover=cover)\n return jsonify(dict(cookies=ret))\n\n\n@manage_app.route(\"/task/add\")\ndef add_task():\n site = request.args.get('site')\n comicid = request.args.get('comicid')\n chapter = request.args.get('chapter', default='-1')\n send_mail = request.args.get('send_mail', default=0, type=int)\n gen_pdf = request.args.get('gen_pdf', default=0, type=int)\n receivers = request.args.get('receivers', default=\"\")\n is_all = 1 if request.args.get('is_all') == '1' else 0\n check_manage_secret(request)\n result = task.add_task(site=site,\n comicid=comicid,\n chapter=chapter,\n is_all=is_all,\n send_mail=send_mail,\n gen_pdf=gen_pdf,\n receivers=receivers)\n return jsonify(dict(data=result))\n\n\n@manage_app.route(\"/task/list\")\ndef list_task():\n page = request.args.get('page', default=1, type=int)\n check_manage_secret(request)\n size = 20\n result = task.list_task(page=page, size=size)\n return jsonify(dict(list=result))\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"6819661","text":"def pair_sum(arr, num):\r\n\tpairs = set()\r\n\tfor i in range(len(arr)):\r\n\t\tif arr[i] <= num:\r\n\t\t\tpairing_num = find_num(arr[i:], num - arr[i])\r\n\t\t\tif pairing_num != None:\r\n\t\t\t\tpairs.add((arr[i], pairing_num))\r\n\tprint('\\n'.join(map(str,list(pairs))))\r\n\r\ndef find_num(arr, num):\r\n\tfor n in arr:\r\n\t\tif n == num:\r\n\t\t\treturn n\r\n\treturn None\r\n\r\n# print(pair_sum([1,3,2,2], 4))\r\npair_sum([1,3,2,2], 4)\r\n\r\ndef anagramCheck(s1, s2):\r\n\t#returns true if s1 is anagram of s2\r\n\t#clint eastwood is anagram of old west action\r\n\ts1 = \"\".join(s1.lower().split())\r\n\ts2 = \"\".join(s2.lower().split())\r\n\tif len(s1) != len(s2):\r\n\t\treturn False\r\n\td = {}\r\n\tfor c in s2:\r\n\t\tif c not in d:\r\n\t\t\td[c] = 1\r\n\t\telse:\r\n\t\t\td[c] += 1\r\n\tfor c in s1:\r\n\t\tif c not in d:\r\n\t\t\treturn False\r\n\t\telse:\r\n\t\t\td[c] -= 1\r\n\tfor key in d:\r\n\t\tif d[key] != 0:\r\n\t\t\treturn False\r\n\treturn True\r\nprint(anagramCheck(\"dolg\",\"god\"))\r\n\r\ndef pair_sum(arr, k):\r\n\tl = []\r\n\tfor n in range(len(arr)):\r\n\t\tfor m in range(n+1, len(arr)):\r\n\t\t\tif arr[n] + arr[m] == k:\r\n\t\t\t\tl.append((arr[n], arr[m]))\r\n\treturn len(l)\r\nprint(pair_sum([1,6,3,2],4))\r\n\r\n# output = set() # {(1,3), (2,2)}\r\n\r\n# list(output) # [(1,3), (2,2)]\r\n\r\n# map(str,list(output)) # [\"(1,3)\",\"(2,2)\"]\r\n\r\n# print(\"\".join(map(str,list(output))))\r\n\r\n\r\n\r\ndef finder(arr1,arr2):\r\n\tmissing = []\r\n\r\n\tcount = dict()\r\n\r\n\tfor num in arr1:\r\n\t\tif num in count:\r\n\t\t\tcount[num] += 1\r\n\t\telse:\r\n\t\t\tcount[num] = 1\r\n\r\n\tfor num in arr2:\r\n\t\tif num in count:\r\n\t\t\tcount[num] -= 1\r\n\t\telse:\r\n\t\t\tpass # arr2 will always be 1 less\r\n\r\n\tfor k in count:\r\n\t\tif count[k] != 0:\r\n\t\t\tmissing.append(k)\r\n\r\n\treturn missing\r\n\r\n# O(N+N+N) => O(3N) => O(N)\r\nprint(finder([1,2,3,4,5,6,7], [3,7,2,1,4,6]))\r\n\r\n\r\ndef largest_cont_sum(arr):\r\n\tlargest = 0\r\n\tfor i in range(len(arr)):\r\n\t\tif arr[i] < 0:\r\n\t\t\tif largest + sumArr(arr[i:]) > largest:\r\n\t\t\t\tlargest += arr[i]\r\n\t\t\telse:\r\n\t\t\t\tpass\r\n\t\telse:\r\n\t\t\tlargest += arr[i]\r\n\r\n\treturn largest\r\ndef sumArr(arr):\r\n\ttotal = 0\r\n\tfor n in arr:\r\n\t\ttotal += n\r\n\treturn total\r\nprint(largest_cont_sum([1,2,-10,-10,30]))\r\n\r\n\r\ndef largest_cont_sum(arr):\r\n if len(arr) == 0:\r\n return 0\r\n\r\n max_sum = current_sum = arr[0] # 1\r\n\r\n for num in arr[1:]: #-10, 20\r\n current_sum = max(current_sum + num, num) # max(-9, -10) max (11, 20)\r\n max_sum = max(current_sum, max_sum) # max(-9, 1) =>1 (20, 1)\r\n\r\n return max_sum\r\n\r\ndef sentence_reversal(sentence):\r\n\tsentence_list = sentence.strip().split(' ')\r\n\tprint(sentence_list)\r\n\treturn_list = []\r\n\tlength = len(sentence_list)\r\n\tfor i in range(length):\r\n\t\treturn_list.append(sentence_list[length-1-i])\r\n\treturn ' '.join(return_list)\r\n\r\nprint(sentence_reversal(\" my dog ate my homework \"))\r\n\r\ndef compress(str1):\r\n\td = {}\r\n\tfor c in str1:\r\n\t\tif c in d:\r\n\t\t\td[c]+=1\r\n\t\telse:\r\n\t\t\td[c]=1\r\n\tstr_return=''\r\n\tfor key in d:\r\n\t\tstr_return += str(key) + str(d[key])\r\n\treturn str_return\r\nprint(compress('aabbbAA'))\r\n\r\ndef uni_char(s):\r\n\td = {}\r\n\tfor c in s:\r\n\t\tif c in d:\r\n\t\t\treturn False\r\n\t\telse:\r\n\t\t\td[c] = 1\r\n\treturn True\r\nprint(uni_char('abcdd'))","sub_path":"arrays.py","file_name":"arrays.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"485601414","text":"#--------------------------------------------------------------------------------------------\n# IMPORT STATEMENTS\n#--------------------------------------------------------------------------------------------\nimport math\nimport pygame\nimport random\n\n#--------------------------------------------------------------------------------------------\n# GLOBAL VARIABLES\n#--------------------------------------------------------------------------------------------\n# Change this variable to set the size of the grid\nn = 50\n# Screen Resolution\nWIDTH = 800\nHEIGHT = 800\n# Width of 1 cell in the maze grid\nw = WIDTH/n\n\n# Frames per second for pygame\nFPS = 30 \n\n# Colors\nWHITE = [255,255,255]\nBLACK = [0,0,0]\nBLUE = [2,5,64]\nGREEN = [124, 252, 0]\n\n# Determines the number of rows and columns in the grid\ncols = int(math.floor(WIDTH/w))\nrows = int(math.floor(HEIGHT/w))\n\n# Arrays\ngrid = []\nstack = []\n\n# Variable to track when the maze is done\nmazeComplete = False\n\n#--------------------------------------------------------------------------------------------\n# CELL CLASS\n#--------------------------------------------------------------------------------------------\nclass Cell:\n def __init__(self, i,j):\n # i.e the x coordinate\n self.i = i\n # i.e the y coordinate\n self.j = j\n # Boolean value to represent if there is a wall. True = wall. [Top, Right, Bottom, Left]\n self.walls = [True, True, True, True]\n # Variable to track if the cell was visited True = Visited\n self.visited = False\n\n#--------------------------------------------------------------------------------------------\n# FUNCTIONS - in alphabetical order\n#--------------------------------------------------------------------------------------------\ndef checkNeighbours(cell):\n neighbours = []\n \n i = cell.i\n j = cell.j\n\n # Finds the data for the cells surrounding the current cell\n top = grid[index(i,j-1)]\n right = grid[index(i+1,j)]\n bottom = grid[index(i,j+1)]\n left = grid[index(i-1,j)] \n\n # Adds the neighbours to the neighbours array if they have not been visited and that the index is valid\n if top.visited == False and index(i,j-1) >0:\n neighbours.append(top)\n if right.visited == False and index(i+1,j) >0:\n neighbours.append(right)\n if bottom.visited == False and index(i,j+1) >0:\n neighbours.append(bottom)\n if left.visited == False and index(i-1,j) >0:\n neighbours.append(left)\n\n # Randomly chooses a cell connected to the current cell\n if len(neighbours)>0:\n randomNum = random.randrange(0,len(neighbours))\n return neighbours[randomNum]\n else:\n return None\n \n\ndef createGrid(grid):\n for cell in grid:\n \n x = cell.i*w\n y = cell.j*w\n # Draws the top wall\n if cell.walls[0] == True:\n pygame.draw.line(screen, WHITE, [x, y],[x+w,y],1)\n else:\n pygame.draw.line(screen, BLUE, [x, y],[x+w,y],1)\n # Draws the right wall\n if cell.walls[1] == True:\n pygame.draw.line(screen, WHITE, [x+w, y],[x+w,y+w],1)\n else:\n pygame.draw.line(screen, BLUE, [x+w, y],[x+w,y+w],1)\n # Draws the bottom wall\n if cell.walls[2] == True:\n pygame.draw.line(screen, WHITE, [x, y+w],[x+w,y+w],1)\n else:\n pygame.draw.line(screen, BLUE, [x, y+w],[x+w,y+w],1)\n # Draws the left wall\n if cell.walls[3] == True:\n pygame.draw.line(screen, WHITE, [x, y],[x,y+w],1)\n else:\n pygame.draw.line(screen, BLUE, [x, y],[x,y+w],1)\n \n # Marks a cell as visited\n if cell.visited == True:\n markVisited(cell)\n\ndef currentHighlight(cell):\n pygame.draw.rect(screen, GREEN, [(cell.i)*w+1, (cell.j)*w+1, w-1, w-1]) # left top width heigh\n\ndef index(i,j):\n # Checks to make sure we are getting a valid index\n if (i<0 or j<0 or i>(cols-1) or j>(cols-1)):\n return -1\n \n # Converts the index of a 2D array into a 1D array\n index = i + j*cols\n return index\n\ndef markVisited(cell):\n pygame.draw.rect(screen, BLUE, [(cell.i)*w+1, (cell.j)*w+1, w-1, w-1]) # left top width heigh\n\ndef removeWalls(a, b):\n # Calculates the index of the given cells\n indexA = index(a.i, a.j)\n indexB = index(b.i, b.j)\n \n x = a.i - b.i\n if x == 1:\n # Removes the left wall of a\n grid[indexA].walls[3] = False\n # Removes the right wall of b\n grid[indexB].walls[1] = False\n elif x == -1:\n # Removes the right wall of a\n grid[indexA].walls[1] = False\n # Removes the left wall of b\n grid[indexB].walls[3] = False\n \n y = a.j - b.j\n if y == 1:\n # Removes the top wall of a\n grid[indexA].walls[0] = False\n # Removes the bottom wall of b\n grid[indexB].walls[2] = False\n elif y == -1:\n # Removes the bottom wall of a\n grid[indexA].walls[2] = False\n # Removes the top wall of b\n grid[indexB].walls[0] = False\n\n#--------------------------------------------------------------------------------------------\n# MAZE GENERATING CODE\n#--------------------------------------------------------------------------------------------\n# Creates the cell objects\nfor j in range(rows):\n for i in range(cols):\n cell = Cell(i,j)\n grid.append(cell)\n\n#--------------------------------------------------------------------------------------------\n# MAIN PYGAME CODE\n#--------------------------------------------------------------------------------------------\n# Initializes the pygame modules\npygame.init()\n# Initializes the module for sound loading and playback\npygame.mixer.init()\n# Creates the visual image surface on the monitor.\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\n# Adds a title of the display window\npygame.display.set_caption(\"Grid\")\n# Creates a clock object to track time\nclock = pygame.time.Clock()\n# Creates the black background on the screen\nscreen.fill(BLACK)\n# Sets the current cell to the first cell and marks it as visited\ncurrent = grid[0]\n# Labels the first cell as visited and highlights it in the maze\ngrid[0].visited = True\n# Adds the current cell to the stack\nstack.append(current)\npygame.display.update()\n \n\nrunning = True\nwhile running:\n # Keeps the game running at the right speed\n clock.tick(FPS) \n\n # Creates the grid for the maze\n createGrid(grid)\n\n # Randomly chooses the next cell in the maze\n if mazeComplete == False:\n # Finds a neighbouring cell to go to\n nextCell = checkNeighbours(current)\n # Pushes the current cell to the stack\n if nextCell != None:\n nextCell.visited = True\n grid[index(nextCell.i, nextCell.j)].visited = True\n removeWalls(current,nextCell)\n currentHighlight(current)\n stack.append(current)\n current = nextCell\n elif len(stack) > 0:\n # Pops a cell of the stack and makes it the current cell\n current = stack[len(stack)-1]\n del stack[len(stack)-1]\n currentHighlight(current)\n else:\n mazeComplete = True \n \n\n pygame.display.update()\n\n for event in pygame.event.get():\n # Checks for closing the window\n if event.type == pygame.QUIT:\n running = False","sub_path":"Maze.py","file_name":"Maze.py","file_ext":"py","file_size_in_byte":7372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"204037927","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n=========================================================================\n msproteomicstools -- Mass Spectrometry Proteomics Tools\n=========================================================================\n\nCopyright (c) 2013, ETH Zurich\nFor a full list of authors, refer to the file AUTHORS.\n\nThis software is released under a three-clause BSD license:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of any author or any participating institution\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n--------------------------------------------------------------------------\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\nINSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\nOR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\nOTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--------------------------------------------------------------------------\n$Maintainer: Hannes Roest $\n$Authors: Hannes Roest $\n--------------------------------------------------------------------------\n\"\"\"\nfrom __future__ import print_function\n\nimport pyopenms\nimport numpy as np\nimport sys\n\n# This program takes mass spectrometric data in ASCII format as produced by\n# Waters DataBridge program (V4.1) with the MassLynx to ASCII option and\n# convets it to mzML\n#\n# Input: ASCII data\n# Output: output in mzML format\n\nif len(sys.argv) < 3:\n print(\"Please use filename as the first argument and the outputname as the second argument\")\n exit()\n\nfname = sys.argv[1]\noutname = sys.argv[2]\nfh = open(fname)\noutexp = pyopenms.MSExperiment()\n\ndef handle_stack(stack, mslevel):\n # print \"Size\", len(stack), mslevel\n scan_nr_ = stack[0].split()\n assert(len(scan_nr_) == 2)\n scan_nr = int(scan_nr_[1])\n rt_ = stack[1].split()\n assert(len(rt_) == 3)\n rt = float(rt_[2])*60\n # Convert to mz/int pairs\n pairs = [it.split() for it in stack[3:] if len(it.strip()) > 0 and float(it.split()[1]) > 0.0]\n #mz = [float(it.split()[0]) for it in stack[3:] if len(it.strip()) > 0]\n #intensity = [float(it.split()[1]) for it in stack[3:] if len(it.strip()) > 0]\n try:\n mz = [float(it[0]) for it in pairs]\n intensity = [float(it[1]) for it in pairs]\n except ValueError:\n print(\"Could not convert\", len(stack), \"with pairs\" , len(pairs))\n return\n assert len(mz) == len(intensity)\n #\n print(\"Handle scan at rt\", rt)\n peaks = np.ndarray(shape=(len(mz), 2), dtype=np.float32)\n peaks[:,0] = mz\n peaks[:,1] = intensity\n s = pyopenms.MSSpectrum()\n s.set_peaks(peaks)\n s.setRT(rt)\n s.setMSLevel(1)\n outexp.addSpectrum(s)\n\nscan_cnt = 0\nstack = []\nstarted = False\nMSLevel = 0\nfor l in fh:\n if l.find(\"Scan\") != -1:\n if started:\n #break\n handle_stack(stack, MSLevel+1)\n MSLevel = (MSLevel+1)%2\n stack = []\n started = True\n stack.append(l)\n \npyopenms.MzMLFile().store(outname, outexp)\n\n\n","sub_path":"analysis/scripts/DIA/convertMassLynxTomzML.py","file_name":"convertMassLynxTomzML.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"310631947","text":"from sentence_transformers import SentenceTransformer\nfrom sklearn.preprocessing import normalize\nfrom config import MODEL_PATH\nimport gdown\nimport zipfile\nimport os\n\n\nclass SentenceModel:\n \"\"\"\n Say something about the ExampleCalass...\n\n Args:\n args_0 (`type`):\n ...\n \"\"\"\n\n def __init__(self):\n if not os.path.exists(MODEL_PATH):\n os.makedirs(MODEL_PATH)\n if not os.path.exists(\"./paraphrase-mpnet-base-v2.zip\"):\n url = 'https://public.ukp.informatik.tu-darmstadt.de/reimers/sentence-transformers/v0.2/paraphrase-mpnet-base-v2.zip'\n gdown.download(url)\n with zipfile.ZipFile('paraphrase-mpnet-base-v2.zip', 'r') as zip_ref:\n zip_ref.extractall(MODEL_PATH)\n self.model = SentenceTransformer(MODEL_PATH)\n\n def sentence_encode(self, data):\n embedding = self.model.encode(data)\n sentence_embeddings = normalize(embedding)\n return sentence_embeddings.tolist()\n","sub_path":"solutions/nlp/question_answering_system/quick_deploy/server/src/encode.py","file_name":"encode.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"173223315","text":"import cv2\nimport numpy as np\n\n\n\n# 1) Edges\ndef vector_image(img):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray = cv2.medianBlur(gray, 5)\n edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 3)\n\n # 2) Color\n color = cv2.bilateralFilter(img, 5, 200, 200)\n\n # 3) Cartoon\n cartoon = cv2.bitwise_and(color, color, mask=edges)\n\n return cartoon, color, edges, img\n\n# img = cv2.imread(\"/home/erwin/Desktop/test_ibuk2/1_670074_DST0163_08:59:27.176995.jpg\")\n\n# cartoon, color, edges, img = vector_image(img)\n\n# cv2.imshow(\"Image\", img)\n# cv2.imshow(\"Cartoon\", cartoon)\n# cv2.imshow(\"color\", color)\n# cv2.imshow(\"edges\", edges)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()","sub_path":"auto-adjustments(brightness and contrast)/face_recog/vector_image.py","file_name":"vector_image.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"284451918","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 8 05:33:49 2020\n\n@author: salman\n\"\"\"\nc = int(input(\"Number of copies: \"))\nif (c<=100):\n TC = 50*c\nelse:\n TC = 50*100+30*(c-100)\n \nprint(\"The Total cost of the copies: \",TC)\n \n \n\n","sub_path":"AI BRACU CLASS CODES/lab01_problem04.py","file_name":"lab01_problem04.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"612430926","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/insights/parsers/tests/test_sysconfig_network.py\n# Compiled at: 2019-05-16 13:41:33\nfrom insights.parsers.sysconfig import NetworkSysconfig\nfrom insights.tests import context_wrap\nNETWORK_SYSCONFIG = ('\\nNETWORKING=yes\\nHOSTNAME=rhel7-box\\nGATEWAY=172.31.0.1\\nNM_BOND_VLAN_ENABLED=no\\n').strip()\n\ndef test_sysconfig_network():\n result = NetworkSysconfig(context_wrap(NETWORK_SYSCONFIG))\n assert result['GATEWAY'] == '172.31.0.1'\n assert result.get('NETWORKING') == 'yes'\n assert result['NM_BOND_VLAN_ENABLED'] == 'no'","sub_path":"pycfiles/insights_core-3.0.162-py2.7/test_sysconfig_network.py","file_name":"test_sysconfig_network.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"140370660","text":"from engine.eager import EagerNet\nfrom models.dense import *\nfrom sklearn.datasets import load_digits\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\n\n\nclass example(tf.keras.Model):\n def __init__(self):\n super(example, self).__init__()\n self.dense_block = DenseBlock([10], kernel_initializer='glorot_normal', activations='relu')\n self.out = tf.layers.Dense(10)\n self.out2 = tf.layers.Dense(1)\n\n def call(self, x, training=True):\n x = self.dense_block(x)\n x1 = self.out(x)\n x2 = self.out2(x)\n return x1, x2\n\n\ntf.enable_eager_execution()\n\nprint(\"TensorFlow version: {}\".format(tf.VERSION))\nprint(\"Eager execution: {}\".format(tf.executing_eagerly()))\n\ncheckpoint_directory = 'checkpoints/'\n\ndata = load_digits()\n\nmodel = example() # Dense([10, 10], bn=True, dropout=0.2)\n\nx_train, x_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.33, stratify=data.target)\nimport numpy as np\nbatch_size = 64\ntraining_data = tf.data.Dataset.from_tensor_slices((x_train.astype(np.float32), (tf.cast(tf.one_hot(y_train, 10), tf.float32), y_train[:,None])))\neval_data = tf.data.Dataset.from_tensor_slices((x_test.astype(np.float32), (tf.cast(tf.one_hot(y_test, 10), tf.float32),y_test[:,None])))\n\n\nnet = EagerNet(model, 'mse', checkpoint_dir=checkpoint_directory)\nnet.set_seed(42)\nnet.model_name = 'aa'\nnet._model_name = 'bb'\nnet.fit(training_data, eval_data, train_from_scratch=False)\n\nnet.visualize_loss()\n\n# train = tf.dataset....shuffle(data_len).batch(batch_size)\n# val = tf.dataset.....batch(batch_size)\n# test = tf.dataset... or numpy (from tensor slices) or file or blalba first numpy only\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"131429220","text":"#Muestra el comando de 2 motores conectados a la salida 0-1 (pin 2 y 3)\n#y controlados por las flechas del cursor\n\nfrom msvcrt import getch\nimport os\nimport phi2.phi2 as phi2\n\n\ndef pantalla():\n os.system(\"cls\")\n print(\"***********************************\")\n print(\"Teclas en accion \")\n print(\"***********************************\")\n print(\"Use las flechas de cursor para manejar \")\n print(\"\")\n print(\"\")\n\npantalla()\n#conectamos a phi2\nphi2.set(\"com8\",\"9600\")\nphi2.open()\n\n\n\nwhile True:\n key = ord(getch())\n if (key == 80):\n print(\"Parar --> paran los dos motores\")\n phi2.write(0)\n if (key == 72):\n print(\"Adelante --> encienden los dos motores\")\n phi2.write(255)\n if (key == 77):\n print(\"Derecha --> Se detiene el de la derecha y se enciende el de la izquierda\")\n phi2.write(2)\n if (key == 75):\n print(\"Izquierda --> se detiene el de la izquierda y se enciende el de la derecrach\")\n phi2.write(1)","sub_path":"ejemplos/teclas.py","file_name":"teclas.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"282290290","text":"\nfrom __future__ import division\n\nimport time\nimport copy\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.utils.extmath import cartesian\n\nclass EMEstimate(object):\n \n def __init__(self, comparison_vectors, start_m, start_u, start_p):\n \n# Set comparison vectors \n self.comparison_vectors = comparison_vectors\n \n# Set first iteration\n self.m = start_m\n self.u = start_u\n self.p = start_p\n \n # Count the number of iterations\n self.iteration = 0\n\n self.comparison_space = pd.DataFrame({'count' : self.comparison_vectors.groupby(list(self.comparison_vectors)).size()}).reset_index()\n \n def estimate(self, max_iter=100, log=False):\n\n self.max_iter = max_iter\n \n while self.iteration < self.max_iter:\n \n # Compute expectation\n self.g = self._expectation(self.comparison_space[list(self.comparison_vectors)])\n \n # Maximize\n self.m, self.u, self.p = self._maximization(self.comparison_space[list(self.comparison_vectors)], self.comparison_space['count'], self.g)\n\n # Increment counter\n self.iteration = self.iteration+1\n \n \n def _maximizion(self):\n \n \"\"\" To be overwritten \"\"\"\n \n pass\n \n def _expectation(self):\n \n \"\"\" To be overwritten \"\"\"\n \n pass\n\n def m_prob(self, y):\n \n \"\"\" To be overwritten \"\"\"\n \n pass \n\n def u_prob(self, y):\n \n \"\"\" To be overwritten \"\"\"\n \n pass\n\n def weights(self, y):\n \n return np.log(np.divide(self.m_prob(y), self.u_prob(y)))\n \n def summary(self):\n \n summary = pd.merge(self.cartesian(), self.comparison_space, on=list(self.comparison_vectors), how='left').fillna(0)\n \n summary['m'] = self.m_prob(summary[list(self.comparison_vectors)])\n summary['u'] = self.u_prob(summary[list(self.comparison_vectors)])\n summary['w'] = self.weights(summary[list(self.comparison_vectors)])\n summary['g'] = self._expectation(summary[list(self.comparison_vectors)])\n \n summary.sort('w', ascending=True, inplace=True)\n summary['lambda'] = summary['m'].cumsum()\n\n summary.sort('w', ascending=False, inplace=True)\n summary['mu'] = summary['u'].cumsum()\n\n return summary\n \n def cartesian(self): # aanpassen max. Moet unique worden..\n \n # Cartesian product of all possible options\n \n max_tuple = []\n \n for col in list(self.comparison_vectors):\n \n max_tuple.append(self.comparison_vectors[col].unique())\n \n y_cart = pd.DataFrame(cartesian(max_tuple)) # ([0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1])\n y_cart.columns = list(self.comparison_vectors)\n\n return y_cart\n\nclass ECMEstimate(EMEstimate):\n \n def _maximization(self, y, f, g):\n \n for col in y.columns:\n \n for level in y[col].unique():\n \n # Maximization of m\n self.m[col][level] = sum((g*f)[y[col] == level])/sum(g*f)\n \n # Maximization of u\n self.u[col][level] = sum((((1-g)*f)[y[col] == level]))/sum((1-g)*f)\n \n # Maximization of p\n self.p = sum(g*f)/sum(f)\n \n return self.m, self.u, self.p\n \n def _expectation(self, y):\n \n return self.p*self.m_prob(y)/(self.p*self.m_prob(y)+(1-self.p)*self.u_prob(y)) \n \n def m_prob(self, y):\n \n return y.replace(self.m).prod(axis=1)\n \n def u_prob(self, y):\n \n return y.replace(self.u).prod(axis=1)\n\n\n \nclass EMSchurleEstimate(EMEstimate):\n \n\n def estimate(self):\n \n self.comparison_vectors_schurle = self.comparison_vectors[list(self.comparison_vectors)].copy()\n \n est = ECMFreqEstimate(self.comparison_vectors_schurle, self.start_m, self.start_u, self.start_p, max_iter = 0)\n cart_y = est.summary()\n\n for col in list(self.comparison_vectors)[1:]:\n\n cart_y['y_%s' % col] = cart_y[range(0,col)].apply(lambda x: \"\".join(map(str, list(x))), axis=1)\n\n cart_y['gm'] = cart_y['g']\n cart_y['gu'] = 1\n cart_y['gu'] = cart_y['gu'] - cart_y['gm']\n cart_y['gmf'] = cart_y['gm']*cart_y['count']\n cart_y['guf'] = cart_y['gu']*cart_y['count']\n\n self.cart_y = cart_y\n \n self.m_dict = {'1': self.start_m[0][1], '0':self.start_m[0][0]}\n\n for col in list(self.comparison_vectors)[1:]:\n\n comparison_space = self.cart_y.groupby([col, 'y_%s' % col]).sum()\n\n for index, value in comparison_space.iterrows():\n\n g_count_1 = float(comparison_space.loc[(1, index[1]), ['gmf']])\n g_count_0 = float(comparison_space.loc[(0, index[1]), ['gmf']])\n\n if index[0] == 1:\n g_count_index = float(comparison_space.loc[(index[0], index[1]), ['gmf']])\n elif index[0] == 0:\n g_count_index = float(comparison_space.loc[(index[0], index[1]), ['gmf']])\n else:\n raise RuntimeError\n\n key = str(index[1]) + str(index[0])\n \n if (g_count_1+g_count_0)> 0:\n self.m_dict[key] = g_count_index/(g_count_1+g_count_0)\n \n self.u_dict = {'1': self.start_u[0][1], '0':self.start_u[0][0]}\n\n for col in list(self.comparison_vectors)[1:]:\n\n comparison_space = self.cart_y.groupby([col, 'y_%s' % col]).sum()\n\n for index, value in comparison_space.iterrows():\n\n g_count_1 = float(comparison_space.loc[(1, index[1]), ['guf']])\n g_count_0 = float(comparison_space.loc[(0, index[1]), ['guf']])\n\n if index[0] == 1:\n g_count_index = float(comparison_space.loc[(index[0], index[1]), ['guf']])\n elif index[0] == 0:\n g_count_index = float(comparison_space.loc[(index[0], index[1]), ['guf']])\n else:\n raise RuntimeError\n\n key = str(index[1]) + str(index[0])\n \n if (g_count_1+g_count_0)> 0:\n self.u_dict[key] = g_count_index/(g_count_1+g_count_0)\n \n \n def _expectation(self, y):\n \n self.max_iter = 1\n \n return self.p*self.m_prob(y)/(self.p*self.m_prob(y)+(1-self.p)*self.u_prob(y)) \n \n def m_prob(self, y):\n \n y_m = self.cart_y[list(self.comparison_vectors)]\n\n for col in y_m.columns.tolist():\n\n y_m['m_%s' % col] = y_m[range(0,col+1)].apply(lambda x: \"\".join(map(str, list(x))), axis=1)\n y_m['m_%s' % col].replace(self.m_dict, inplace=True)\n\n return y_m[['m_0', 'm_1', 'm_2', 'm_3', 'm_4', 'm_5', 'm_6', 'm_7']].prod(axis=1)\n\n def u_prob(self, y):\n \n y_u = self.cart_y[list(self.comparison_vectors)]\n\n for col in y_u.columns.tolist():\n\n y_u['u_%s' % col] = y_u[range(0,col+1)].apply(lambda x: \"\".join(map(str, list(x))), axis=1)\n y_u['u_%s' % col].replace(self.u_dict, inplace=True)\n\n return y_u[['u_0', 'u_1', 'u_2', 'u_3', 'u_4', 'u_5', 'u_6', 'u_7']].prod(axis=1)\n\n\n","sub_path":"recordlinkage/estimation.py","file_name":"estimation.py","file_ext":"py","file_size_in_byte":7490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"5582369","text":"import sys\nsys.path.append(\"../src/\")\nimport LSTM_module2 as lstm\nimport modules as mod\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.io import wavfile\nimport sounddevice as sd\nfrom lstm_plotting import Plot\n\nimport ipdb\nimport lstm_functions as func\n\n\ndef mean_squared_error(x, y, name):\n return tf.square(x - y, name=name) \n\ndef log_loss(x, y, name):\n return tf.losses.log_loss(y, x)\n\ndef test_epoch(sess, epoch, sampFreq_test, save_name):\n error_total = np.array([])\n prediction_total = np.array([])\n save_name = save_name+\"lstm_test_{}\".format(epoch+1)\n feed_dict = {}\n feed_dict[inp.placeholder] = testX\n feed_dict[target.placeholder] = testY\n for t in range(testX.shape[0]//BATCH_SIZE - 1): # 2000\n error, prediction = sess.run([opt.outputs[TIME_DEPTH], out_prediction.outputs], feed_dict={inp.placeholder: testX[t*BATCH_SIZE : (t+1)*BATCH_SIZE], target.placeholder: testY[t*BATCH_SIZE : (t+1)*BATCH_SIZE]})\n error_total = np.append(error_total, error.ravel())\n prediction_total = np.append(prediction_total, prediction[1].ravel())\n \n if t%10 == 0:\n sys.stdout.write(\"\\r\" + \"epoch process{}%\".format((t*BATCH_SIZE / testX.shape[0])*100))\n sys.stdout.flush()\n \n plt.figure()\n myplot.plot_compare(testY[0:prediction_total.shape[0]], prediction_total, title=\"Prediction in test\", x=\"time\", y=\"amplitude\", save_name=save_name+\"_test.png\" )\n playback = func.data2int16(np.array(prediction_total))\n func.play_wav(playback, sampFreq_test)\n func.save_wav(playback, sampFreq_test, save_name+\"_test.wav\")\n \n\naudio_names_train = ['sp10.wav','sp11.wav', 'sp12.wav'] #'04_Chapter_1-4.wav' , ,\naudio_names_test = ['sp13.wav'] #'05_Chapter_1-5.wav'\ns_train, sampFreq0 = func.concat_audios(audio_names_train, ifnorm=True, save_name=\"10~12-ON-13-train_concat\", ifsave=False)\ns_test, sampFreq_test = func.concat_audios(audio_names_test, ifnorm=True, save_name=\"10~12-ON-13-test_concat\", ifsave=False)\n\ntrainX = s_train[0:-1].reshape(-1, 1)\ntrainY = s_train[1: ].reshape(-1, 1)\ntestX = s_test[0:-1].reshape(-1, 1)\ntestY = s_test[1: ].reshape(-1, 1)\n\nCELL_SIZE = 500\nTIME_DEPTH = 5\nBATCH_SIZE = 200\n\ninp = mod.ConstantPlaceholderModule(\"input\", shape=(BATCH_SIZE, 1))\ntarget = mod.ConstantPlaceholderModule(\"target\", shape=(BATCH_SIZE, 1))\ncell = lstm.LSTM_Cell(\"lstm_cell\", 1, CELL_SIZE)\nout_prediction = mod.FullyConnectedLayerModule(\"out_prediction\", tf.identity, CELL_SIZE, 1)\nerr = mod.ErrorModule(\"mse\", mean_squared_error)\n#err = mod.ErrorModule(\"logloss\", log_loss)\nopt = mod.OptimizerModule(\"adam\", tf.train.AdamOptimizer())\n\n# Connect input\ncell.add_input(inp)\nout_prediction.add_input(cell)\nerr.add_input(target)\nerr.add_input(out_prediction)\nopt.add_input(err)\nopt.create_output(TIME_DEPTH)\nout_prediction.create_output(1)\n\nmyplot = Plot()\n\ntrain_length = trainX.shape[0] #2000#\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(20):\n error_total = np.array([])\n prediction_total = np.array([])\n save_name = \"lstm_{}_epoch_batchsize_{}_10~12-ON-13_\".format(epoch+1, BATCH_SIZE)\n error = 0\n for t in range(train_length//BATCH_SIZE - 1):\n\n error += sess.run(opt.outputs[TIME_DEPTH], feed_dict={inp.placeholder: trainX[t*BATCH_SIZE : (t+1)*BATCH_SIZE], target.placeholder: trainY[t*BATCH_SIZE : (t+1)*BATCH_SIZE]})\n prediction = sess.run(out_prediction.outputs, feed_dict={inp.placeholder: trainX[t*BATCH_SIZE : (t+1)*BATCH_SIZE], target.placeholder: trainY[t*BATCH_SIZE : (t+1)*BATCH_SIZE]})\n prediction_total = np.append(prediction_total, prediction[1].ravel())\n if t == train_length//BATCH_SIZE - 2:\n sys.stdout.write(\"\\r\" + \"epoch process{}%\".format((t*BATCH_SIZE / train_length)*100))\n sys.stdout.flush()\n \n error_total = np.append(error_total, np.sum(error))\n plt.figure()\n myplot.plot_compare(np.ravel(trainY[0:prediction_total.shape[0]]), prediction_total, title=\"Prediction in train\", x=\"time\", y=\"amplitude\", save_name=save_name+\"_train.png\" )\n plt.close()\n\n playback = func.data2int16(np.array(prediction_total))\n func.play_wav(playback, sampFreq0)\n func.save_wav(playback, sampFreq0, save_name+\"_train.wav\")\n test_epoch(sess, epoch, sampFreq_test, save_name)\n print (\"Error:{}\".format(error_total))\n \nplt.figure()\nmyplot.plot_score(np.array(error_total), title=\"Score on training steps\", x=\"epochs\", y=\"MSE\", save_name=save_name+\"MSE in training steps.png\", ifsave=True)\n\n\n\n\n \n","sub_path":"examples/audio_lstm.py","file_name":"audio_lstm.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"148246006","text":"#%%\nimport random\nimport re\nimport time\nfrom personal.mysqldb import ToMysql\nfrom datetime import datetime\nimport requests\nfrom lxml import etree\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nkwargs = { 'host':'localhost',\n 'user':'root',\n 'passwd':'luoxue99',\n 'db':'china_land',\n 'charset':'utf8'}\n\nsql = ToMysql(kwargs)\n# option = webdriver.ChromeOptions()\n# option.add_argument('headless')\nbrowser = webdriver.Chrome(r'd:/code/policy/chromedriver.exe')\n# browser = webdriver.Ie(r'C:/Program Files/Internet Explorer/IEDriverServer.exe')\n# browser.maximize_window()\nbrowser.get('http://www.landchina.com/default.aspx?tabid=262') \n \n\n#%%\ndef page_parser(html, content, url):\n # html_s1 = html.xpath('//table[@id=\"Table2\"]//table')[0]\n # html_s2 = etree.tostring(html_s1, encoding='utf-8').decode('utf-8')\n pid = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())))\n title = html.xpath('//span[@id=\"lblTitle\"]/text()')\n date_out = html.xpath('//span[@id=\"lblCreateDate\"]/text()')\n loc_full = html.xpath('//span[@id=\"lblXzq\"]/text()')\n loc_full = loc_full[0] if loc_full else ''\n loc_list = loc_full.replace(' ', '').split('>') if '>' in loc_full else None\n province = city = xian = ''\n time_now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n open_during = html.xpath('//*[contains(text(), \"公示期\")]/u//text()')\n if loc_list:\n province = loc_list[0].replace('行政区:', '') if loc_list else ''\n city = loc_list[1] if len(loc_list)>1 else ''\n xian = loc_list[2] if len(loc_list)>2 else ''\n \n result_pub = {\n 'title': title[0] if title else '',\n 'pid': pid,\n 'region': loc_full,\n 'date_out': date_out[0].replace('发布时间:', '') if date_out else '',\n 'province': province,\n 'city': city,\n 'xian': xian,\n 'content': content,\n 'open_during': open_during[0] if open_during else '',\n 'url': url,\n 'update_time': time_now\n\n }\n sql.into('public', **result_pub)\n table_str = '//*[@id=\"tdContent\"]/table//table'\n table_num = html.xpath(table_str)\n insert_num = 0\n for i in range(1, len(table_num)+1):\n table_pre = table_str + str([i]) + '/tbody/tr'\n zongdi = html.xpath(table_pre + '/td[contains(text(), \"编号\")]/following-sibling::*[1]/text()')\n if zongdi != zongdi:\n spider_log = open(r'd:/code/spider_log.txt', 'w')\n print(date_out, ',', title, file=spider_log)\n address = html.xpath(table_pre + '/td[contains(text(), \"位置\")]/following-sibling::*[1]/text()')\n useness = html.xpath(table_pre + '/td[contains(text(), \"用途\")]/following-sibling::*[1]/text()')\n area = html.xpath(table_pre + '/td[contains(text(), \"面积\")]/following-sibling::*[1]/text()')\n project = html.xpath(table_pre + '/td[contains(text(), \"项目名称\")]/following-sibling::*[1]/text()')\n receiver = html.xpath(table_pre + '/td[contains(text(), \"受让单位\")]/following-sibling::*[1]/text()')\n years = html.xpath(table_pre + '/td[contains(text(), \"出让年限\")]/following-sibling::*[1]/text()')\n price = html.xpath(table_pre + '/td[contains(text(), \"成交价\")]/following-sibling::*[1]/text()')\n tiaojian = html.xpath(table_pre + '/td[contains(text(), \"出让条件\")]/following-sibling::*[1]/text()')\n result_zongdi = {\n 'pid': pid,\n 'date_out': date_out[0].replace('发布时间:', '') if date_out else '',\n 'zongdi': zongdi[0] if zongdi else '',\n 'region': loc_full,\n 'province': province,\n 'city': city,\n 'xian': xian,\n 'project': project[0] if project else '',\n 'address': address[0] if address else '',\n 'useness': useness[0] if useness else '',\n 'area': area[0] if area else '',\n 'years': years[0] if years else '',\n 'price': price[0] if price else '',\n 'receiver': receiver[0] if receiver else '',\n 'tiaojian': tiaojian[0] if tiaojian else '',\n 'update_time': time_now\n }\n \n sql.into('zongdi', **result_zongdi)\n insert_num = insert_num + 1\n\n# 开始执行\n\nbrowser.switch_to.window(browser.window_handles[0]) \nbrowser.implicitly_wait(30)\n# for i in range(8):\n# page_next = browser.find_element_by_link_text('下页')\n# if page_next:\n# page_next.click()\n# time.sleep(random.uniform(1))\n \npage_num_str = browser.find_element_by_xpath('//*[@id=\"mainModuleContainer_478_1112_1537_tdExtendProContainer\"]/table/tbody/tr[1]/td/table/tbody/tr[2]/td/div/table/tbody/tr/td[1]').text\npage_num_pa = re.findall(re.compile('共(\\d+)页'), page_num_str)\nif page_num_pa:\n page_num = page_num_pa[0]\n for i in range(int(page_num)+1):\n print('已插入页面:' + str(i+1))\n links = browser.find_elements_by_xpath('//table[@id=\"TAB_contentTable\"]//tr/td[3]/a')\n for link in links:\n link.click()\n browser.switch_to.window(browser.window_handles[-1])\n browser.implicitly_wait(30)\n url = browser.current_url\n content = browser.find_element_by_xpath('//table[@id=\"Table2\"]//table').text\n data = browser.page_source\n html = etree.HTML(data)\n page_parser(html, content, url)\n browser.close()\n browser.switch_to.window(browser.window_handles[0]) \n time.sleep(random.uniform(10,30)) \n page_next = browser.find_element_by_link_text('下页')\n if page_next:\n page_next.click()\n else:\n browser.refresh()\n browser.implicitly_wait(30)\n","sub_path":"policy/spider_china_land.py","file_name":"spider_china_land.py","file_ext":"py","file_size_in_byte":5824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"143445708","text":"\n\nfrom xai.brain.wordbase.nouns._launcher import _LAUNCHER\n\n#calss header\nclass _LAUNCHERS(_LAUNCHER, ):\n\tdef __init__(self,): \n\t\t_LAUNCHER.__init__(self)\n\t\tself.name = \"LAUNCHERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"launcher\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_launchers.py","file_name":"_launchers.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"505087956","text":"#!/usr/bin/python\n# -*- coding: utf8 -*-\n\n#主配置\n#######################################################################################\n#全局版本,debug为测试版,很多动作就是测试的样子\nimport collections\n\nfrom base_config import *\n\n#aes加密用串\ng_aeskey = 'Qfi#G&U6qGCafXgEA7rqnbrUWE*MGpMd'\n\n#cookie名称\ng_cookie_session_id = 'SSQ_XSESSION_ID'\ng_cookie_visit_session_id = 'SSQ_VISIT_XSESSION_ID_V3.0'\n\n\n#tornado安全cookie用加密串\ng_cookie_secret_str = 'dHARBeNR9CNk26wBG11s0V2g1CcdpYjlciTa8BUui0AOqb5fF6ivqotOD2dHW5b1'\n\n#后台进程是否用gevent跑\n#g_daemon_usegevent = True\n\n#缓存库使用模块\n#redis\n#memcache\ng_xcache_type = 'memcache'\n\n#全局xcache开关\ng_use_xcache = True\n\n#零时间设定\nzerotime = '1970-01-01 00:00:00'\n\n#搜索一秒请求一次限制\ng_one_sec_limit = False\n\n#数据库相关配置\n#######################################################################################\n#连接数分配方案:\n#计算程序见python AdminTools.py -n\n#本地开发用\nif g_version == 'debug':\n #pg配置\n g_db_user = 'postgres'\n g_db_password = '123kkk'\n g_db_host = '127.0.0.1'\n g_db_port = 5432\n g_db_database = 'postgres'\n g_db_async_maxconn = 33\n g_db_sync_maxconn = 10\n #xcache memcache连接\n g_memcache_server = '127.0.0.1:11111'\n g_local_memcache_server = '127.0.0.1:11111'\n\n # server_name配置\n g_cookie_domain = None\n\nelif g_version == 'test':\n # pg配置\n g_db_user = 'postgres'\n g_db_password = '123kkk'\n g_db_host = '127.0.0.1'\n g_db_port = 5432\n g_db_database = 'postgres'\n g_db_async_maxconn = 33\n g_db_sync_maxconn = 10\n # xcache memcache连接\n g_memcache_server = '127.0.0.1:11111'\n g_local_memcache_server = '127.0.0.1:11111'\n\n # server_name配置\n g_cookie_domain = None\n\n#生产环境用\nelse:\n #pg配置\n g_db_user = 'dbuser'\n g_db_password = 'XSS6AiBW'\n g_db_host = 'rds2jw6njb2clkj8ww57.pg.rds.aliyuncs.com'\n g_db_port = 3433\n g_db_database = 'sxsdb'\n g_db_async_maxconn = 10\n g_db_sync_maxconn = 10\n #xcache memcache连接\n g_memcache_server = 'b1f52310675d4935.m.cnhzaliqshpub001.ocs.aliyuncs.com:11211'\n g_local_memcache_server = '127.0.0.1:11211'\n\n g_cookie_domain = None\n # 阿里云MQ配置\ng_memcache_pool_minsize = 5\ng_memcache_pool_size = 20\n######################################################################################\n\n#当前域名\n#第一个是主域名,第二个是测试域名\nmydomains = ['admin.soulsu.com','toby.shixiseng.com']\n\n#图片服务器配置域名\n##############################################################################\n\n#阿里云oss配置\n\nif g_version == 'debug':\n\n if g_oss_source == 'aliyun':\n g_oss_endpoint = \"oss-cn-shanghai.aliyuncs.com\"\n g_oss_keyid = \"hTO9nvV5R56oJhOF\"\n g_oss_keysecret = \"nMVG92dg1twJ5k0o3YnGeCQBoVfKXZ\"\n g_opensearch_endpoint = 'http://opensearch-cn-hangzhou.aliyuncs.com'\n #不同项目的bucket不同\n g_oss_bucket = 'rpooss'\n g_opensearch_index_name = 'rpo'\n\n if g_oss_source == 'qcloud':\n # g_qcloud_appid = 1254081290 # 替换为用户的appid\n g_qcloud_secret_id = u'AKIDHTTJxPMjbHl2738RsBICuQkrnW3RZhWB' # 替换为用户的secret_id\n g_qcloud_secret_key = u'c3teEcWL0UmsY9ZpyDMK6h6jHg3LSSIy' # 替换为用户的secret_key\n g_qcloud_region = u\"ap-chengdu\" # # 替换为用户的region,目前可以为 shanghai/guangzhou\n # 不同项目的bucket不同\n g_qcloud_bucket = u'ssqimg-1254081290'\n\nelse:\n if g_oss_source == 'aliyun':\n g_oss_endpoint = \"oss-cn-shanghai-internal.aliyuncs.com\"\n g_oss_keyid = \"hTO9nvV5R56oJhOF\"\n g_oss_keysecret = \"nMVG92dg1twJ5k0o3YnGeCQBoVfKXZ\"\n g_opensearch_endpoint = 'http://opensearch-cn-hangzhou.aliyuncs.com'\n g_oss_bucket = 'rpooss'\n g_opensearch_index_name = 'rpo'\n\n if g_oss_source == 'qcloud':\n # g_qcloud_appid = 1254081290 # 替换为用户的appid\n g_qcloud_secret_id = 'AKIDHTTJxPMjbHl2738RsBICuQkrnW3RZhWB' # 替换为用户的secret_id\n g_qcloud_secret_key = 'c3teEcWL0UmsY9ZpyDMK6h6jHg3LSSIy' # 替换为用户的secret_key\n g_qcloud_region = 'ap-chengdu' # # 替换为用户的region,目前可以为 shanghai/guangzhou\n # 不同项目的bucket不同\n g_qcloud_bucket = 'ssqimg-1254081290'\n g_qcloud_tokoen = ''\n\n if g_oss_source == 'qiniu':\n pass\n\n# g_pic_server_host = 'rpoimg-1254365278.cossh.myqcloud.com'\ng_pic_server_host = 'ssqimg-1254081290.file.myqcloud.com'\n# g_pic_server_uri = 'http://rpoimg-1254365278.cossh.myqcloud.com/'\ng_pic_server_uri = 'https://ssqimg-1254081290.file.myqcloud.com/'\n# g_pic_server_host = 'ssqimg-1254081290.cos.ap-chengdu.myqcloud.com'\n# g_pic_server_uri = 'https://ssqimg-1254081290.cos.ap-chengdu.myqcloud.com/'\n\n\n#自建vsftpd的配置\n#g_uploader_ftp_user = 'newuser'\n#g_uploader_ftp_password = 'nwdm5&rAQi^6yBFn'\n\n#允许上传的文件类型\ng_uploader_allow_type = (\n 'application/pdf',\n 'text/plain',\n 'image/gif',\n 'application/msword',\n 'application/kswps',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'image/jpeg',\n 'application/x-jpe',\n 'image/jpg',\n 'application/x-jpg',\n 'image/png',\n 'application/x-png',\n 'application/vnd.ms-powerpoint',\n 'application/x-ppt',\n 'application/docx',\n 'application/octet-stream',\n 'application/vnd.ms-excel',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'text/html',\n)\n#需要原始状态保存的文件(图片一般要压缩,所以这里应该是pdf,doc这种,gif也是原始保存不压缩)\ng_uploader_original_save_type = (\n 'application/pdf',\n 'text/plain',\n 'image/gif',\n 'application/msword',\n 'application/kswps',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'application/vnd.ms-powerpoint',\n 'application/x-ppt',\n 'application/docx',\n 'application/octet-stream', # docx\n 'application/vnd.ms-excel',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'text/html',\n)\n# 最大允许5MB的图片\ng_uploader_maxsize = 5120\n#图片最大宽度px\ng_uploader_pic_max_width = 1920\n#图片预览图最大宽度px\ng_uploader_pic_thumb_max_width = 320\n\n\n#状态中文\ng_status_show = {\n 'normal':'正常',\n 'destroy':'已删',\n}\n\n\n#理员权限定义\ng_sxspermissions = {\n 'system_manager':'系统管理',\n}\n\ng_gender_option = {\n 1:'男',\n 2:'女',\n 3:'其他'\n}\n\n\ng_intention_option = {\n 1: '朋友',\n 2: '恋人',\n 0: '其他',\n}\n\ng_diet_option = {\n 1: '斋素',\n 2: '全素',\n 3: '蛋奶素',\n 4: '果素',\n 5: '半素',\n 6: '肉食',\n 0: '其他'\n}\ng_religion_option = {\n 1: '佛教',\n 2: '道教',\n 3: '儒教',\n 4: '伊斯兰教',\n 5: '基督教',\n 6: '天主教',\n 7: '印度教',\n 8: '犹太教',\n 9: '无神论',\n 0: '科学论',\n 1: '不可知论',\n 0: '其他',\n}\ng_alcohol_option = {\n 1: '不饮酒',\n 2: '偶尔饮酒',\n 3: '仅社交场合饮酒',\n 4: '经常饮酒',\n 5: '每天饮酒',\n 0: '其他',\n}\ng_cigarette_option = {\n 1: '不吸烟',\n 2: '偶尔吸烟',\n 3: '仅社交场合吸烟',\n 4: '经常吸烟',\n 5: '每天吸烟',\n 0: '其他',\n}\ng_marriage_option = {\n 1: '未婚',\n 2: '已婚',\n 3: '离异',\n 0: '其他',\n}\ng_children_option = {\n 1: '无,不想要',\n 2: '无,想要',\n 3: '无,可有可无',\n 4: '有,经常在家',\n 5: '有,偶尔在家',\n 6: '有,几乎不在家',\n 0: '其他',\n}\ng_education_option = {\n 1: '高中及以下',\n 2: '专科',\n 3: '本科',\n 4: '硕士',\n 5: '博士及以上',\n 0: '其他',\n}\ng_sports_option = {\n 1: '很少',\n 2: '每周',\n 3: '每天',\n 0: '其他',\n}\n\n\n\n\n\n# 理员权限定义,显示顺序为这个设置的顺序\n# 设置这个后,增加对应的handler即可在左侧显示出来\n# 每条的定义为[显示名称,uri,图标class定义]\ng_permissions = collections.OrderedDict()\n# g_permissions['media_manager'] = ['多媒体库', '/media/manager', 'fa fa-file-image-o']\ng_permissions['member_manager'] = ['用户管理', '/member/mamnager', 'fa fa-user-circle']\ng_permissions['menu_manager'] = ['菜谱管理', '/menu/mamnager', 'fa fa-book']\ng_permissions['cache_refresh'] = ['缓存刷新', '/cache/refresh', 'fa fa-refresh']\n# g_permissions['cheat_room'] = ['聊天室', '/cheat/room', 'fa fa-cogs']\ng_permissions['media_manager'] = ['多媒体库', '/media/manager2', 'fa fa-picture-o']\ng_permissions['system_manager'] = ['系统管理', '/adminuser/manager', 'fa fa-cogs']\n","sub_path":"utils/define.py","file_name":"define.py","file_ext":"py","file_size_in_byte":8687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"255265446","text":"#!/usr/bin/env python3\n\n\"\"\"\nupdate\n======\n\"\"\"\n\nimport datetime\nfrom functools import reduce\nimport logging\nfrom sqlalchemy import or_\nimport yaml\n\nimport database\nfrom database.models import Subject, Group, Incident, Location, Point\nfrom database.models import Operation, Outcome, Weather, Search\nfrom util import initialize_logging\nfrom weather import wsi\n\n\ndef remove_unreadable_incidents(session, limit=float('inf'), save_every=100):\n logger, count = logging.getLogger(), 0\n\n for incident_id, *empty in session.query(Incident.id):\n query = session.query(Incident).filter(Incident.id == incident_id)\n\n try:\n query.one()\n except ValueError:\n logger.info('Removing incident {} ... '.format(incident_id))\n\n for model in Group, Weather, Location, Operation, Outcome, Search:\n subquery = session.query(model)\n subquery = subquery.filter(model.incident_id == incident_id)\n\n instance = subquery.one_or_none()\n if instance is not None:\n session.delete(instance)\n\n query.delete()\n\n count += 1\n if count >= limit:\n break\n elif (count + 1)%save_every == 0:\n session.commit()\n\n session.commit()\n logger.info('Removed {} cases'.format(count))\n\n\ndef add_missing_instances(session):\n logger, count = logging.getLogger(), 0\n\n ...\n\n\ndef augment_weather_instance(weather, datetime_, ipp):\n start_date = datetime_.date()\n end_date = start_date + datetime.timedelta(1)\n fields = ['surfaceTemperatureCelsius', 'windSpeedKph',\n 'precipitationPreviousHourCentimeters', 'downwardSolarRadiation']\n\n history = wsi.fetch_history(lat=ipp.latitude, long=ipp.longitude,\n startDate=start_date, endDate=end_date,\n fields=fields)\n\n series = history['weatherData']['hourly']['hours']\n\n scrub = lambda sequence: filter(lambda item: item is not None, sequence)\n collect = lambda field: map(lambda hourly: hourly.get(field, None), series)\n\n temperatures = list(scrub(collect('surfaceTemperatureCelsius')))\n if len(temperatures) > 0:\n if weather.low_temp is None:\n weather.low_temp = min(temperatures)\n if weather.high_temp is None:\n weather.high_temp = max(temperatures)\n\n wind_speeds = list(scrub(collect('windSpeedKph')))\n if len(wind_speeds) > 0 and weather.wind_speed is None:\n weather.wind_speed = round(sum(wind_speeds)/len(wind_speeds), 3)\n\n solar_radiation = list(scrub(collect('downwardSolarRadiation')))\n if len(solar_radiation) > 0 and weather.solar_radiation is None:\n mean = sum(solar_radiation)/len(solar_radiation)\n weather.solar_radiation = round(mean, 3)\n\n snow, rain = 0, 0\n for hourly in series:\n temperature = hourly.get('surfaceTemperatureCelsius', None)\n prcp = hourly.get('precipitationPreviousHourCentimeters', None)\n\n if temperature is not None and prcp is not None:\n if temperature <= Weather.WATER_FREEZING_POINT:\n snow += prcp\n else:\n rain += prcp\n\n if weather.snow is None:\n weather.snow = round(snow, 3)\n if weather.rain is None:\n weather.rain = round(rain, 3)\n\n\ndef augment_weather_instances(session, limit=5000, save_every=50):\n logger = logging.getLogger()\n with open('../data/config.yaml') as config_file:\n config = yaml.load(config_file.read())\n\n wsi.DEFAULT_PARAMETERS['userKey'] = config['wsi']['key']\n logger.info('WSI key set to: {}'.format(wsi.DEFAULT_PARAMETERS['userKey']))\n\n query = session.query(Weather, Incident.datetime, Operation.ipp_id)\n query = query.join(Incident, Operation)\n query = query.filter(Incident.datetime, Operation.ipp_id)\n\n columns = Weather.high_temp, Weather.low_temp, Weather.wind_speed\n columns += Weather.snow, Weather.rain, Weather.solar_radiation\n criteria = map(lambda column: column == None, columns)\n query = query.filter(reduce(or_, criteria))\n\n count = 0\n for weather, datetime_, ipp_id in query:\n ipp = session.query(Point).get(ipp_id)\n\n if ipp.latitude is not None and ipp.longitude is not None:\n try:\n augment_weather_instance(weather, datetime_, ipp)\n logger.info('Updated {}'.format(weather))\n except ValueError as error:\n logger.error('Instance ID {}: {}'.format(weather.id, error))\n except error:\n logger.error(error)\n break\n\n count += 1\n if count >= limit:\n break\n elif (count + 1)%save_every == 0:\n session.commit()\n\n session.commit()\n logger.info('Updated {} weather instances'.format(count))\n\n\ndef execute():\n initialize_logging('../logs/update.log')\n logger = logging.getLogger()\n engine, session = database.initialize('sqlite:///../data/isrid-master.db')\n\n tasks = [augment_weather_instances]\n\n for task in tasks:\n try:\n task_name = task.__name__.replace('_', ' ')\n logger.info('Starting task: {}'.format(task_name))\n task(session)\n\n except KeyboardInterrupt:\n print()\n logger.info('Terminating update ... ')\n break\n\n except Exception as error:\n logger.error('{}: {}'.format(type(error).__name__, error))\n break\n\n logging.shutdown()\n database.terminate(engine, session)\n\n\nif __name__ == '__main__':\n execute()\n","sub_path":"src/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"435175208","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution(object):\n def inorderSuccessor(self, root, p):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :rtype: TreeNode\n \"\"\"\n # status: 0: p not found, 1: p found but successor not found, 2: successor found\n return self.traverse(root, p, [0])\n\n def traverse(self, node, p, status):\n if not node:\n return None\n if status[0] == 0:\n if node == p:\n status[0] = 1\n return self.traverse(node.right, p, status)\n ret = self.traverse(node.left, p, status)\n if status[0] == 0:\n return self.traverse(node.right, p, status)\n if status[0] == 1:\n status[0] = 2\n return node\n return ret # status: 2\n # status: 1\n ret = self.traverse(node.left, p, status)\n status[0] = 2\n # would not be status 2 here\n return ret if ret else node\n","sub_path":"src/inorder-successor-in-bst.py","file_name":"inorder-successor-in-bst.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"561098072","text":"from . import JarProvider\n\nclass Nukkit(JarProvider):\n base = 'http://www.nukkit-project.fr/downloads/'\n def work(self):\n self.add(('Nukkit', 'Stable'), (None, None), self.base + 'craftnukkit')\n self.add(('Nukkit', 'Beta'), (None, None), self.base + 'beta/craftnukkit')\n self.commit()\n\nref = Nukkit\n","sub_path":"mk2/servers/nukkit.py","file_name":"nukkit.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"327346322","text":"from setuptools import setup\nimport os\nimport versioneer\n\ntry:\n from Cython.Build import cythonize\nexcept ImportError:\n raise ImportError(\"Cython must be installed before pysqs can be installed.\")\n\ndef readme(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name='pysqs',\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n author='Brandon Bocklund',\n author_email='brandonbocklund@gmail.com',\n description='pysqs calculates simple quasirandom structures',\n packages=['pysqs'],\n ext_modules=cythonize(['pysqs/enumerate.pyx']),\n license='MIT',\n long_description=readme('README.rst'),\n url='https://brandonbockund.com/',\n install_requires=[],\n classifiers=[\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 1 - Planning',\n\n # Indicate who your project is intended for\n 'Intended Audience :: Science/Research',\n\n # Pick your license as you wish (should match \"license\" above)\n 'License :: OSI Approved :: MIT License',\n\n # Specify the Python versions you support here. In particular, ensure\n # that you indicate whether you support Python 2, Python 3 or both.\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n ],\n\n)\n","sub_path":"pypi_install_script/pysqs-0.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"242276576","text":"import random\nimport time\n\nimport dill as pickle\nimport pybullet as p\n\nfrom src.bot.SphereBot import SphereBot\nfrom src.bot.TurtleBot import TurtleBot\nfrom src.geom.Node import Node\n\n\nclass Obstacle:\n \"\"\"\n Obstacle in the pybullet simulation. Cube of 1x1x1 dimension with velocity, acceleration and/or random movement\n \"\"\"\n\n def __init__(self, start_pos: Node, start_orn: Node, velocity: Node, urdf_path: str, config, v_change=None, const_v=False,\n rand_acc=False):\n \"\"\"\n Initialises obstacle\n :param start_pos: start position\n :param start_orn: start orientation (in radians)\n :param velocity: start velocity\n :param urdf_path: filename of urdf file\n :param v_change: change in velocity per second\n :param const_v: maintain constant velocity magnitude (speed)\n :param rand_acc: randomly set acceleration\n \"\"\"\n self._config = config\n self.start_pos = start_pos\n self.start_orn = start_orn\n self.velocity = velocity\n self.v_change = v_change\n self.rand_acc = rand_acc\n self.const_velocity = const_v\n self.urdf_path = urdf_path\n self.p_id = -1\n self.last_update_time = None\n\n def instantiate(self):\n \"\"\"Instantiates the obstacle by loading its urdf file\"\"\"\n self.p_id = self._config.loadURDF(p, self.urdf_path, self.start_pos.as_list_3d(),\n p.getQuaternionFromEuler(self.start_orn.as_list_3d()))\n\n def update(self):\n \"\"\"\n called every turn. Allows obstacle to update its velocity/acceleration and use\n p.resetBaseVelocity() to set its current velocity\n \"\"\"\n new_time = time.time()\n if self.last_update_time is None:\n # first time its updated\n self.last_update_time = new_time\n return\n if self.v_change is not None:\n mag = self.velocity.mag()\n self.velocity = self.velocity + self.v_change * (new_time - self.last_update_time)\n if self.const_velocity:\n self.velocity = self.velocity.as_unit_vector() * mag\n if self.rand_acc:\n rand_v = Node.from_list([random.uniform(-1, 1), random.uniform(-1, 1)]).as_unit_vector() * 0.05\n self.v_change = (self.v_change + rand_v).as_unit_vector() * random.uniform(0, 0.1)\n if mag > 0.15:\n self.velocity = self.velocity.as_unit_vector() * 0.12\n (pos, orn) = p.getBasePositionAndOrientation(self.p_id)\n if pos[0] > 8.5 or pos[0] < 3 or pos[1] > 1 or pos[1] < -1:\n self.velocity = Node.from_list([6.5, 0]) - Node.from_tuple(pos).as_node_2d()\n self.velocity = self.velocity.as_unit_vector() * 0.1\n p.resetBaseVelocity(self.p_id, self.velocity.as_list_3d(), [0, 0, 0])\n\n self.last_update_time = new_time\n\n\nclass Scenario:\n \"\"\"\n A Pybullet obstacle course / scenario with start, goal positions, a robot model and an array of obstacles\n \"\"\"\n def __init__(self, start_pos: Node, start_orn: Node, goal_pos: Node, env_objects: [Obstacle], config):\n self.goal_pos = goal_pos\n self.config_ = config\n if config.ROB_MODEL == 0:\n # Turtlebot\n self.bot = TurtleBot(start_pos, p.getQuaternionFromEuler(start_orn.as_list_3d()), self.config_)\n elif config.ROB_MODEL >= 1:\n # Sphere\n self.bot = SphereBot(start_pos, p.getQuaternionFromEuler(start_orn.as_list_3d()), self.config_)\n self.env_objects = env_objects\n self.state = 0\n\n def instantiate(self):\n \"\"\"\n instantiate and connect to pybullet simulation\n \"\"\"\n if p.isConnected():\n p.connect(p.DIRECT)\n else:\n p.connect(p.GUI)\n p.configureDebugVisualizer(p.COV_ENABLE_GUI, True)\n p.configureDebugVisualizer(p.COV_ENABLE_DEPTH_BUFFER_PREVIEW, True)\n p.configureDebugVisualizer(p.COV_ENABLE_RGB_BUFFER_PREVIEW, True)\n p.configureDebugVisualizer(p.COV_ENABLE_SEGMENTATION_MARK_PREVIEW, False)\n\n p.resetSimulation()\n p.setGravity(0, 0, -10.)\n\n self.config_.loadURDF(p, self.config_.PLANE_URDF)\n self.bot.render()\n for o in self.env_objects:\n o.instantiate()\n\n p.addUserDebugLine(self.goal_pos.as_ndarray()+[-0.2, -0.2, 0.01],\n self.goal_pos.as_ndarray()+[0.2, 0.2, 0.01], [0, 0, 0], 4)\n p.addUserDebugLine(self.goal_pos.as_ndarray()+[0.2, -0.2, 0.01],\n self.goal_pos.as_ndarray()+[-0.2, 0.2, 0.01], [0, 0, 0], 4)\n\n p.addUserDebugLine(self.bot.pos.as_ndarray() + [-0.2, 0.2, 0.01],\n self.bot.pos.as_ndarray() + [0.2, 0.2, 0.01], [0, 0, 0], 4)\n p.addUserDebugLine(self.bot.pos.as_ndarray() + [0.2, 0.2, 0.01],\n self.bot.pos.as_ndarray() + [0.2, -0.2, 0.01], [0, 0, 0], 4)\n p.addUserDebugLine(self.bot.pos.as_ndarray() + [0.2, -0.2, 0.01],\n self.bot.pos.as_ndarray() + [-0.2, -0.2, 0.01], [0, 0, 0], 4)\n p.addUserDebugLine(self.bot.pos.as_ndarray() + [-0.2, -0.2, 0.01],\n self.bot.pos.as_ndarray() + [-0.2, 0.2, 0.01], [0, 0, 0], 4)\n\n # set view to look at the middle of the course\n p.resetDebugVisualizerCamera(cameraDistance=8.5, cameraYaw=-180, cameraPitch=-120,\n cameraTargetPosition=self.goal_pos.as_ndarray() / 2)\n\n def update(self):\n \"\"\"\n called every turn. Checks for collisions between the robot and obstacles and\n updates the robot and obstacles.\n \"\"\"\n p.setGravity(0, 0, -10.)\n if self.state == 0:\n for envO in self.env_objects:\n c_points = p.getClosestPoints(self.bot.p_id, envO.p_id, 0.001)\n if c_points is not None and len(c_points) > 0:\n self.state = 2\n print(\"CRASH\")\n if self.goal_pos.dist_2d(self.bot.pos) < self.config_.ROB_RADIUS * 1.5:\n print(\"GOAL\")\n self.state = 1\n self.bot.update()\n for o in self.env_objects:\n o.update()\n\n def set_path(self, path_points):\n \"\"\"\n Set a path for the robot to follow. If path_points is empty, then the robot stops\n :param path_points: list of next path points (very rough, no dubins path points here)\n \"\"\"\n if path_points is not None and len(path_points) > 0 and self.state == 0:\n self.bot.drive_along(path_points)\n else:\n # stop the robot since we are at the goal or crashed\n self.bot.drive_stop()\n\n def export_to_planner(self):\n \"\"\"\n pickles the current position, heading, goal position and future path (high resolution dubins path) to\n be sent to the sbPlanner module\n \"\"\"\n if self.state == 2:\n return pickle.dumps(\n (None, 0, self.goal_pos.as_list_2d(), self.bot.path_configurations_arr[:, :2]))\n else:\n pos_orn = self.bot.get_pos_orn()\n return pickle.dumps((pos_orn[:2], pos_orn[2], self.goal_pos.as_list_2d(), self.bot.path_configurations_arr[:,:2]))\n\n def export_to_gui(self):\n \"\"\"\n pickles the future path (high resolution dubins path), past path and current state to\n be sent to the sbGUI module\n \"\"\"\n if len(self.bot.path_configurations_arr[0]) > 0:\n to_send = (self.bot.path_configurations_arr[:, 0], self.bot.path_configurations_arr[:, 1],\n [x[0] for x in self.bot.past_path], [x[1] for x in self.bot.past_path],\n self.evaluate())\n else:\n to_send = ([], [],\n [x[0] for x in self.bot.past_path], [x[1] for x in self.bot.past_path],\n self.evaluate())\n return pickle.dumps(to_send)\n\n def evaluate(self):\n return self.state\n\n def delete(self):\n p.disconnect()\n\n# # # Scenario setup functions\n\n\ndef scen_0(config_):\n # Clear\n start_pos = Node.from_list(config_.P_START)\n goal_pos = Node.from_list([5, 0])\n start_orn = Node.from_list(config_.O_START)\n\n return Scenario(start_pos, start_orn, goal_pos, [], config_)\n\n\ndef scen_1(config_):\n # Static Simple\n start_pos = Node.from_list(config_.P_START)\n goal_pos = Node.from_list(config_.P_GOAL)\n start_orn = Node.from_list(config_.O_START)\n\n obj1 = Obstacle(Node.from_list([3.5, 0.5, 0.5]),\n Node.from_list([0, 0, 0.75]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n\n return Scenario(start_pos, start_orn, goal_pos, [obj1], config_)\n\n\ndef scen_2(config_):\n # Static Cluttered\n start_pos = Node.from_list(config_.P_START)\n goal_pos = Node.from_list(config_.P_GOAL)\n start_orn = Node.from_list(config_.O_START)\n\n obj1 = Obstacle(Node.from_list([2.2, 1.90, 0.5]),\n Node.from_list([0, 0, 0.75]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj2 = Obstacle(Node.from_list([5.8, 0.9, 0.5]),\n Node.from_list([0, 0, 0]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj3 = Obstacle(Node.from_list([2.3, -0.85, 0.5]),\n Node.from_list([0, 0, 0.1]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj4 = Obstacle(Node.from_list([6.5, -1.90, 0.5]),\n Node.from_list([0, 0, 0.75]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj5 = Obstacle(Node.from_list([10., 0.8, 0.5]),\n Node.from_list([0, 0, 0.]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n\n return Scenario(start_pos, start_orn, goal_pos, [obj1, obj2, obj3, obj4], config_)\n\n\ndef scen_3(config_):\n # Static C Shape\n start_pos = Node.from_list(config_.P_START)\n goal_pos = Node.from_list(config_.P_GOAL)\n start_orn = Node.from_list(config_.O_START)\n\n obj0 = Obstacle(Node.from_list([2.3, 2.7, 0.5]),\n Node.from_list([0, 0, 00]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj1 = Obstacle(Node.from_list([3.5, 2.20, 0.5]),\n Node.from_list([0, 0, 0.75]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj2 = Obstacle(Node.from_list([4, 1, 0.5]),\n Node.from_list([0, 0, 0]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj3 = Obstacle(Node.from_list([4.1, 0, 0.5]),\n Node.from_list([0, 0, 0]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj4 = Obstacle(Node.from_list([4, -1, 0.5]),\n Node.from_list([0, 0, 0]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj5 = Obstacle(Node.from_list([3.5, -2.20, 0.5]),\n Node.from_list([0, 0, 0.75]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n obj6 = Obstacle(Node.from_list([2.3, -2.7, 0.5]),\n Node.from_list([0, 0, 00]),\n Node.from_list([0, 0, 0]), config_.BLOCK_URDF, config_)\n\n return Scenario(start_pos, start_orn, goal_pos, [obj0, obj1, obj2, obj3, obj4, obj5, obj6], config_)\n\n\ndef scen_4(config_):\n # Dynamic Dodge-the-Bullet\n start_pos = Node.from_list(config_.P_START)\n goal_pos = Node.from_list(config_.P_GOAL)\n start_orn = Node.from_list(config_.O_START)\n\n obj1 = Obstacle(Node.from_list([7, 0.2, 0.5]),\n Node.from_list([0, 0, 0.7]),\n Node.from_list([-0.1, 0, 0.0]), config_.BLOCK_DYN_URDF, config_)\n\n return Scenario(start_pos, start_orn, goal_pos, [obj1], config_)\n\n\ndef scen_5(config_):\n # Dynamic Traffic-Lights\n start_pos = Node.from_list(config_.P_START)\n goal_pos = Node.from_list(config_.P_GOAL)\n start_orn = Node.from_list(config_.O_START)\n\n obj1 = Obstacle(Node.from_list([3, -1.5, 0.5]),\n Node.from_list([0, 0, 0.]),\n Node.from_list([0, 0.09, 0.0]), config_.BLOCK_DYN_URDF, config_)\n obj2 = Obstacle(Node.from_list([3, -4.5, 0.5]),\n Node.from_list([0, 0, 0.]),\n Node.from_list([0, 0.09, 0.0]), config_.BLOCK_DYN_URDF, config_)\n obj3 = Obstacle(Node.from_list([6, 4, 0.5]),\n Node.from_list([0, 0, 0.25]),\n Node.from_list([0, -0.09, 0.0]), config_.BLOCK_DYN_URDF, config_)\n\n return Scenario(start_pos, start_orn, goal_pos, [obj1, obj2, obj3], config_)\n\n\ndef scen_6(config_):\n # Dynamic At-the-Mall\n start_pos = Node.from_list(config_.P_START)\n goal_pos = Node.from_list(config_.P_GOAL)\n start_orn = Node.from_list(config_.O_START)\n\n obj1 = Obstacle(Node.from_list([6.5, 1, 0.5]),\n Node.from_list([0, 0, 0.]),\n Node.from_list([-0.1, -0.05, 0.0]).as_unit_vector()*0.1, config_.BLOCK_DYN_URDF, config_)\n obj2 = Obstacle(Node.from_list([9.5, -0.5, 0.5]),\n Node.from_list([0, 0, 0.]),\n Node.from_list([-0.05, 0., 0.0]), config_.BLOCK_DYN_URDF, config_)\n obj3 = Obstacle(Node.from_list([1.5, 1.5, 0.5]),\n Node.from_list([0, 0, 0.]),\n Node.from_list([0., 0.05, 0.0]), config_.BLOCK_DYN_URDF, config_)\n obj4 = Obstacle(Node.from_list([1.5, -1.5, 0.5]),\n Node.from_list([0, 0, 0.75]),\n Node.from_list([0., 0.05, 0.0]), config_.BLOCK_DYN_URDF, config_)\n\n return Scenario(start_pos, start_orn, goal_pos, [obj1, obj2, obj3, obj4], config_)\n\n\ndef scen_7(config_):\n # obstacle experiment; dependent on O_M config different velocity models are set\n start_pos = Node.from_list(config_.P_START)\n goal_pos = Node.from_list(config_.P_GOAL)\n start_orn = Node.from_list(config_.O_START)\n\n o_p_start = Node.from_list([6, 0.5, 0.5]) # start position\n o_o_start = Node.from_list([0, 0, 0.]) # start orientation\n o_v_start = Node.from_list([0., 0., 0.]) # start velocity\n o_v_change = None\n o_v_const = True\n o_v_rand = False\n if config_.OBSTACLE_MOVEMENT == 0:\n # static\n pass\n elif config_.OBSTACLE_MOVEMENT == 1:\n # fixed speed\n o_v_start = Node.from_list([-2.5, -0.5, 0.0]).as_unit_vector() * 0.1\n elif config_.OBSTACLE_MOVEMENT == 2:\n # fixed speed, changing velocity direction\n o_v_start = Node.from_list([.25, -.5, 0]).as_unit_vector() * 0.1\n o_v_change = Node.from_list([-0.25, 0.25, 0]).as_unit_vector() * (0.1/9.)\n elif config_.OBSTACLE_MOVEMENT == 3:\n # accelerating\n o_v_start = Node.from_list([-2.5, -0.5, 0]).as_unit_vector() * 0.1\n o_v_change = Node.from_list([-2.5, -0.5, 0]).as_unit_vector() * 0.008\n o_v_const = False\n pass\n elif config_.OBSTACLE_MOVEMENT == 4:\n # decelerating\n o_v_start = Node.from_list([-2.5, -0.5, 0]).as_unit_vector() * 0.15\n o_v_change = Node.from_list([-2.5, -0.5, 0]).as_unit_vector() * -0.005\n o_v_const = False\n else:\n # random motion\n o_v_start = Node.from_list([-2.5, -0.5, 0]).as_unit_vector() * 0.1\n o_v_change = Node.from_list([-0.25, 0.25, 0]).as_unit_vector() * (0.1/9.)\n o_v_const = False\n o_v_rand = True\n\n obj1 = Obstacle(o_p_start,\n o_o_start,\n o_v_start, config_.BLOCK_DYN_URDF,\n o_v_change, o_v_const, o_v_rand, config_)\n\n return Scenario(start_pos, start_orn, goal_pos, [obj1], config_)\n","sub_path":"src/bot/Environment.py","file_name":"Environment.py","file_ext":"py","file_size_in_byte":15801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"444764317","text":"from mock import patch, Mock\nimport pytest\nfrom pytest_mock import mocker\nfrom message.ping import Message\nfrom datetime import datetime\nfrom freezegun import freeze_time\nimport json\n\nclass TestPingMessage:\n def create_message(self):\n return Message()\n \n @freeze_time(\"2020-08-15\")\n def test_time_measurement(self):\n ping_msg = self.create_message()\n ping_msg.start()\n ping_msg.end()\n assert ping_msg.time() == 0\n\n def test_time_now_mock(self):\n freezer = freeze_time(\"2020-11-08 12:00:01\")\n freezer.start()\n start = datetime.now()\n assert datetime.now() == datetime(2020, 11, 8, 12, 0, 1)\n freezer.stop()\n freezer = freeze_time(\"2020-11-08 12:00:02\")\n freezer.start()\n stop = datetime.now()\n dt_ms = stop.timestamp()*1000 - start.timestamp()*1000\n assert dt_ms == 1000\n freezer.stop()\n\n def test_serialization(self):\n freezer = freeze_time(\"2020-11-08 12:00:00\")\n freezer.start()\n\n ping_msg = self.create_message()\n ping_msg.start()\n msg = ping_msg.json()\n server_msg = Message(json.loads(msg))\n freezer = freeze_time(\"2020-11-08 12:00:01\")\n freezer.start()\n server_msg.end()\n df = server_msg.time()\n assert server_msg.time() == 1.0\n\n\n\n ","sub_path":"tests/ref/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"603428860","text":"#!/usr/bin/python3\n\n\ndef divisible_by_2(my_list=[]):\n\n new = []\n if not my_list:\n return new\n for elem in my_list:\n if elem % 2 == 0:\n new.append(True)\n else:\n new.append(False)\n return new\n","sub_path":"0x03-python-data_structures/10-divisible_by_2.py","file_name":"10-divisible_by_2.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"450392074","text":"# Homework 1\n# problem 2 solution\n\n#\n# Do not distribute.\n#\n\nimport math\nimport pylab\n\na = float(input(\"Enter a: \"))\n\nif a == 0:\n # this is now a linear equation and we can't apply the given formula:\n print(\"Cannot proceed with a==0\")\n exit(1) # terminate program\n # no need for else\n \nb = float(input(\"Enter b: \"))\nc = float(input(\"Enter c: \"))\n\ndelta = b * b - 4 * a * c\n\nif delta < 0:\n print(\"no real solutions\")\nelif delta == 0:\n x = -b /(2 * a)\n print(\"one solutions\", x)\nelse:\n x1 = (-b - math.sqrt(delta)) / (2 * a)\n x2 = (-b + math.sqrt(delta)) / (2 * a)\n print(\"two solutions: x1 =\",x1,\"x2 =\",x2)\n\n\n# graph:\nxs = []\nys = []\n# prepare the domain for the function we graph\nx0 = -4.0 # lower bound\nx1 = +4.0 # upper bound\n\nn = 50 # n points\ndx = (x1 - x0) / n # delta between points\n\nx = x0\n\nwhile x <= x1:\n xs.append(x)\n y = a * x**2 + b * x + c\n \n ys.append(y)\n x += dx\n\n# after the loop:\npylab.plot(xs, ys, \"b.-\") # creates the graph figure, but does not show it yet\npylab.title(\"{}x^2 + {}x + {}\".format(a,b,c))\npylab.xlabel(\"x\")\npylab.ylabel(\"y\")\n\n# draw axes:\npylab.axhline(0, color='black')\npylab.axvline(0, color='black')\n\npylab.show() # what it says...\n\n# end\n\n","sub_path":"Module 1/python-h1-solutions/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"267825036","text":"# 你想创建一个内嵌变量的字符串,变量被它的值所表示的字符串替换掉。\n\nimport sys\n\ntext = \"The quick brown {fox} jumps over the lazy {dog}.\"\nprint(text)\n\n# format\nprint(text.format(fox=\"dog\", dog=\"fox\"))\n\n# format_map, var\nfox = \"dog\"\ndog = \"fox\"\nprint(text.format_map(vars()))\n\n# 对象实例\n\n\nclass Info:\n def __init__(self, fox, dog):\n self.fox = fox\n self.dog = dog\n\n\nname = Info(\"dog\", \"fox\")\nprint(text.format_map(vars(name)))\n\n# 可缺失变量\n\n\nclass safesub(dict):\n # 防止 key 找不到\n def __missing__(self, key):\n return \"{\" + key + \"}\"\n\n\ndel dog # 确保变量 dog 不存在\nprint(text.format_map(safesub(vars())))\n\n# 封装\n\n\ndef sub(text):\n return text.format_map(safesub(sys._getframe(1).f_locals))\n\n\nname = \"python\"\n\nprint(sub(\"Hello, {name}\"))\n","sub_path":"python3-cookbook/2.15.interpolating_variables_in_strings.py","file_name":"2.15.interpolating_variables_in_strings.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"467394767","text":"import requests\nfrom bs4 import BeautifulSoup\n#beautifulsoup4 bs4 파일안에 있고 beautifulsoup 이라는 기능 사용할 것!\n\nraw = requests.get(\"https://tv.naver.com/r/\")\n#print(raw)\n#print(raw.text)\n#print(raw.elapsed)\n\nhtml = BeautifulSoup(raw.text, 'html.parser')\n#print(html)\n\n# 1-3위 컨테이너: div.inner\n# 제목 : dt.title\n# 채널명 : dd.chn\n# 재생수 : span.hit\n# 좋아요수 : span.like\n\n#1. 컨테이너 수집\ncontainer = html.select(\"div.inner\")\n# print(container[0])\n\n#2. 영상데이터 수집\nfor cont in container :\n title = cont.select_one(\"dt.title\")\n chn = cont.select_one(\"dd.chn\")\n hit = cont.select_one(\"span.hit\")\n like = cont.select_one(\"span.like\")\n\n print(title.text.strip())\n print(chn.text.strip())\n print(hit.text.strip())\n print(like.text.strip())\n print(\"=\" * 50)\n\n#3. 반복하기\n\n# 4-100위 컨테이너: div.cds_type\n# 제목 : dt.title\n# 채널명 : dd.chn\n# 재생수 : span.hit\n# 좋아요수 : span.like\ncontainer2 = html.select(\"div.cds_type\")\n\nfor cont in container2 :\n title = cont.select_one(\"dt.title\")\n chn = cont.select_one(\"dd.chn\")\n hit = cont.select_one(\"span.hit\")\n like = cont.select_one(\"span.like\")\n\n print(title.text.strip())\n print(chn.text.strip())\n print(hit.text.strip())\n print(like.text.strip())\n print(\"=\" * 50)\n\n","sub_path":"week3/week3_1.py","file_name":"week3_1.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"52926814","text":"import ccxt\nimport time\nimport os\nimport pandas as pd\nimport datetime\nfrom pymongo import MongoClient\n\nmongo_client = MongoClient('localhost', 27017)\ndb = mongo_client.crypto_currency\ncollection = db['ohlcv']\n# symbol = 'BNB/BTC'\nsymbol = 'BTC/USDT'\nmarket = 'binance'\ntimewindow = '1m'\n\nmsec = 1000\nminute = 60 * msec\nhour = 60 * minute\nhold = 3 * minute\n\ndef get_file_contents(filename):\n try:\n with open(filename, 'r') as f:\n return f.read().strip()\n except FileNotFoundError:\n print(\"'%s' file not found\" % filename)\n\n\nbinance = ccxt.binance()\nhome_path = os.path.expanduser(\"~\")\nbinance.apiKey = get_file_contents(home_path + '/api_key/binance/pub')\nbinance.secret = get_file_contents(home_path + '/api_key/binance/private')\n\n# upon instantiation\nbinance = ccxt.binance({\n 'apiKey': binance.apiKey,\n 'secret': binance.secret,\n})\n\nexchange = ccxt.binance({\n # 'apiKey': binance.apiKey,\n # 'secret': binance.secret,\n 'timeout': 30000,\n 'rateLimit': 2000,\n 'enableRateLimit': True\n})\n\nfrom_datetime = '2018-03-28 00:00:00'\nfrom_timestamp = exchange.parse8601(from_datetime)\n\n\nnow = datetime.datetime.now()\nto_datetime = '{:%Y-%m-%d %H:%M:%S}'.format(now)\nto_timestamp = exchange.parse8601(to_datetime)\n\n# now = exchange.milliseconds()\n\nheader = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']\n\n\nwhile from_timestamp < to_timestamp:\n try:\n # print(exchange.milliseconds(), 'Fetching candles starting from', exchange.iso8601(from_timestamp))\n \n ohlcvs = exchange.fetch_ohlcv(symbol, timewindow, from_timestamp)\n\n while len(ohlcvs) == 0:\n print(\"waiting for incomming fetch\")\n time.sleep(hold)\n ohlcvs = exchange.fetch_ohlcv(symbol, timewindow, from_timestamp)\n\n # df_current = pd.DataFrame(list(ohlcvs), columns = header)\n df_current = pd.DataFrame(ohlcvs, columns = header)\n df_current['market'] = market\n df_current['symbol'] = symbol\n df_current['timewindow'] = timewindow\n # convert df to list of dict\n lst_dict = df_current.T.to_dict().values()\n\n collection.insert_many(lst_dict)\n\n print(exchange.milliseconds(), 'Fetched', len(ohlcvs), 'candles')\n if len(ohlcvs) > 0:\n first = ohlcvs[0][0]\n last = ohlcvs[-1][0]\n print('First candle epoch', first, exchange.iso8601(first))\n\n # from_timestamp += len(ohlcvs) * minute * 5 # very bad\n from_timestamp = ohlcvs[-1][0] + minute * 5 # good\n # from_timestamp = ohlcvs[-1][0] \n\n # v = ohlcvs[0][0]/ 1000\n # !date --date @{v} +\"%Y-%m-%d %H:%M\"\n print('Last candle epoch', last, exchange.iso8601(last))\n\n now = datetime.datetime.now()\n to_datetime = '{:%Y-%m-%d %H:%M:%S}'.format(now)\n to_timestamp = exchange.parse8601(to_datetime)\n\n except (ccxt.ExchangeError, ccxt.AuthenticationError, ccxt.ExchangeNotAvailable, ccxt.RequestTimeout) as error:\n print('Got an error', type(error).__name__, error.args, ', retrying in', hold, 'seconds...')\n time.sleep(hold)\n\n\n# dumping\n\n# !ipython\n# i = 0\n# v = ohlcvs[i][0] / 1000\n# !date --date @{v} +\"%Y-%m-%d %H:%M\"\n# ohlcvs[i][1] # High","sub_path":"src/crawl_data/houbi.py","file_name":"houbi.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"564874219","text":"def supermarket_checkout(a):\t\n\td = {'A':0,'B':0,'C':0,'D':0}\n\tfor x in a:\n\t\tif x not in d:\n\t\t\td[x] = 1\n\t\telse:\n\t\t\td[x] += 1\n\n\ta_bill = 0\n\tb_bill = 0\n\tc_bill = 0\n\td_bill = 0\n\tt = d.copy()\n\tfor x in d:\n\t\tif x == \"A\":\n\t\t\twhile d[x] !=0:\t\n\t\t\t\tif d[x] >= 3:\n\t\t\t\t\ta_bill += 130\n\t\t\t\t\td[x]-=3\n\t\t\t\telse:\n\t\t\t\t\ta_bill += 50\n\t\t\t\t\td[x] -= 1\t\n\t\telif x == \"B\":\n\t\t\twhile d[x] !=0:\t\n\t\t\t\tif d[x] >= 2:\n\t\t\t\t\tb_bill += 45\n\t\t\t\t\td[x]-=2\n\t\t\t\telse:\n\t\t\t\t\tb_bill += 30\n\t\t\t\t\td[x] -= 1\t\n\t\telif x == \"C\":\n\t\t\tc_bill += d[x]*20\n\t\telif x == \"D\":\n\t\t\td_bill += d[x]*15\t\n\tfa = a_bill+b_bill+c_bill+d_bill\n\treturn fa\n\nif __name__==\"__main__\":\n\titems = input(\"Enter Items : \").upper()\n\tfinal_price = supermarket_checkout(items)\n\tprint(final_price)","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"33125405","text":"from rest_framework import viewsets\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.contrib.auth import logout\nfrom django.core.paginator import Paginator\nimport requests\n\n\n\nfrom app import models, services\nfrom .serializers import TodoSerializer\n\n\nclass TodoViewset(viewsets.ModelViewSet):\n queryset = models.Todo.objects.all()\n serializer_class = TodoSerializer\n\n\ndef app_view (request, page):\n user = request.session['id']\n username = request.session['name']\n todos = services.get_todos(user, username)\n page_todo = Paginator(todos, 10)\n cant_pages = page_todo.num_pages\n\n selected_page = page_todo.page(page)\n\n next_page = 0\n prev_page = 0\n\n if (page < cant_pages):\n next_page = page + 1\n if (page >= 2):\n prev_page = page - 1\n\n ctx = {\n 'username': username,\n 'user_id': user,\n 'todos': selected_page.object_list,\n 'cant_pages': cant_pages,\n 'current_page': page,\n 'next_page': next_page,\n 'prev_page': prev_page\n }\n print(ctx)\n return render(request, 'main.html', ctx)\n\n\n## crea la pagina para hacer el posteo de datos.\ndef add_todo(request):\n if (request.method == 'POST'):\n title = request.POST['title']\n description = request.POST['description']\n is_done = False\n user = request.session['id']\n finish_time = request.POST['finish_time']\n\n services.add_todo(title, description, is_done, user, finish_time)\n \n\n\n return HttpResponseRedirect(\"/app/1\")\n return render (request, 'todo.html')\n\n#funcion para marcar como completada la task\ndef done (request, todo_id):\n services.done_todo(todo_id)\n return HttpResponseRedirect(\"/app/1\")\n\n#funcion para desloguearse\ndef log_out(request):\n logout(request)\n return HttpResponseRedirect(\"/\")","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"326801812","text":"'''\nYour function should take in a single parameter (a string `word`)\nYour function should return a count of how many occurences of ***\"th\"*** occur within `word`. Case matters.\nYour function must utilize recursion. It cannot contain any loops.\n'''\n \ndef count_th(word):\n # If the word has less than 2 letters then it can't match 'th'\n if len(word) < 2:\n return 0\n if word[0] =='t' and word[1] == 'h':\n # if there is still letters left to test\n if len(word) > 2:\n return 1 + count_th(word[2:]) # we know the next lette is 'h' and won't match 't', so we can skip\n else:\n return 1\n else: # no match, check the next substring\n if len(word) > 2: # there is still letters left to test\n return count_th(word[1:])\n else: # no match and not enough letters left to test\n return 0","sub_path":"recursive_count_th/count_th.py","file_name":"count_th.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"219252070","text":"import math\n\ndef fact(n):\n \"\"\"\n takes int n and returns an integer n factorial ( n! )\n \"\"\"\n total = 1\n for i in range(n):\n total *= i+1\n return total\n\ndef cos_power(x, iterations=20):\n \"\"\"\n the power series approximation of the cosine function\n takes float in radians and returns float between -1 and 1\n\n takes a keyword arg 'iterations' (default 20).\n higher iterations result in higher accuracy of the approximation\n (capped at 86 iterations to prevent it breaking)\n\n \"\"\"\n total = 1\n iterations = min(86, iterations)\n for n in range(1,iterations):\n total += ((-1)**n * x**(2*n))/fact(2*n)\n return total\n\ndef print_cos(height=24, width=12, offsetangle=0, char='#', use_math=True):\n \"\"\"\n Prints one full cycle on a cos graph\n\n options: (all are keyword args)\n height (default=24)\n the number of rows in the printout\n\n width (default=12)\n the number of columns in the printout\n\n offsetangle (default=0)\n an angle in radians to start the graph at\n\n char (default='#')\n the character to use for the printout\n\n use_math (default=True)\n use the cos function from the math module\n if False, use the cosine power series approximation\n\n maxeonyx@gmail.com\n\n \"\"\"\n if use_math:\n func = math.cos\n else:\n func = cos_power\n iterations = height//2\n amplitude = width//2\n for i in range(0, iterations*2 + 1):\n print(char*(amplitude+int(func(math.pi/iterations*i+offsetangle)*amplitude)))\n\nprint(cos_power(math.pi/4, iterations=86))\nprint_cos()\n","sub_path":"cos_power_series.py","file_name":"cos_power_series.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"114487213","text":"import sys, os\nfrom mrcnn.config import Config\nfrom mrcnn import visualize\nimport mrcnn.model as modellib\nimport skimage\nfrom skimage.measure import find_contours\nimport numpy as np\nimport cv2\nimport json\n\nclass MeleConfig(Config):\n # Give the configuration a recognizable name\n NAME = \"mele\"\n\n # Train on 1 GPU and 1 image per GPU. Batch size is 1 (GPUs * images/GPU).\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 1 # background + 1 (mele)\n\n # All of our training images are 512x512\n IMAGE_MIN_DIM = 512\n IMAGE_MAX_DIM = 1280\n\n # You can experiment with this number to see if it improves training\n STEPS_PER_EPOCH = 500\n\n # This is how often validation is run. If you are using too much hard drive space\n # on saved models (in the MODEL_DIR), try making this value larger.\n VALIDATION_STEPS = 5\n \n # Matterport originally used resnet101, but I downsized to fit it on my graphics card\n BACKBONE = 'resnet50'\n\n # To be honest, I haven't taken the time to figure out what these do\n RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128)\n TRAIN_ROIS_PER_IMAGE = 32\n MAX_GT_INSTANCES = 50 \n POST_NMS_ROIS_INFERENCE = 500 \n POST_NMS_ROIS_TRAINING = 1000 \n\nclass InferenceConfig(MeleConfig):\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n DETECTION_MIN_CONFIDENCE = 0.85\n\nif __name__ == \"__main__\":\n\n display = False\n\n if len(sys.argv) >= 4:\n model_directory = sys.argv[1]\n images_folder = sys.argv[2]\n output_folder = sys.argv[3]\n\n if len(sys.argv) == 5:\n display = sys.argv[4] == \"1\"\n\n inference_config = InferenceConfig()\n\n # Recreate the model in inference mode\n model = modellib.MaskRCNN(mode=\"inference\", config=inference_config, model_dir=model_directory) \n\n print(\"Loading weights...\")\n # model.load_weights(model.find_last(), by_name=True)\n model.load_weights(model.find_last(), by_name=True)\n\n image_paths = []\n\n segmentation = {}\n\n for filename in os.listdir(images_folder):\n\n if os.path.splitext(filename)[1].lower() in ['.png', '.jpg', '.jpeg']:\n \n image_path = os.path.join(images_folder, filename)\n\n img = skimage.io.imread(image_path)\n img_arr = np.array(img)\n results = model.detect([img_arr], verbose=1)\n r = results[0]\n \n # print(filename)\n\n masked_image = np.zeros(np.shape(img))\n #masked_image = img.astype(np.uint32).copy()\n\n regions = [] \n\n for roi in r['rois']:\n regions.append({\"roi\" : roi.tolist()})\n\n for i in range(len(r['rois'])):\n mask = r['masks'][:, :, i]\n for c in range(3):\n masked_image[:, :, c] = np.where(mask == 1,\n 255,\n masked_image[:, :, c])\n \n cv2.imwrite(os.path.join(output_folder, filename), masked_image.astype(np.uint8))\n \n print(display)\n if display:\n visualize.display_instances(img, r['rois'], r['masks'], r['class_ids'], ['BG', 'mela'], r['scores'], figsize=(5,5))\n\n segmentation[filename] = regions \n\n with open(os.path.join(output_folder, \"segmentation.json\"), 'w') as f:\n json.dump(segmentation, f, ensure_ascii=False)\n\n else:\n print(\"Usage: python detect.py \")\n","sub_path":"Apple3D_tool/detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"529009839","text":"\"\"\"\nlogging configuration\n\"\"\"\nimport logging\n\n\ndef get_logger():\n \"\"\"\n This function sets the logging configuration.\n :return: It returns a logger. Using this logger we can put the exceptions in the log file.\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.ERROR)\n # set the logging format\n formatter = logging.Formatter('%(asctime)s : %(name)s : ', datefmt='%m/%d/%Y %I:%M:%S %p')\n # adding a exception.log file\n file_handler = logging.FileHandler('exceptions.log')\n file_handler.setLevel(logging.ERROR)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n return logger\n","sub_path":"logging_configuration/logging_config.py","file_name":"logging_config.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"453475722","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cmath as cm\nj=cm.sqrt(-1)\nn=np.linspace(-200,200,400)\nx=np.sin(2*np.pi*10/50*n)\nN=len(x)\nw=np.linspace(-np.pi,np.pi,1000)\nX=[]\nY=[]\nZ=[]\nfor i in range(0,1000,1):\n\tsum=0\n\tfor k in range(0,N,1):\n\t\tsum=sum+(x[k]*(cm.exp(-1*j*w[i]*k)))\n\tX.append(sum)\n\tY.append(np.abs(sum))\n\tZ.append(np.angle(sum))\nplt.subplot(411)\nplt.plot(x)\na1=plt.subplot(412)\na1.plot(w,X)\nplt.subplot(413,sharex=a1)\nplt.plot(w,Y)\nplt.subplot(414,sharex=a1)\nplt.plot(w,Z)\nplt.show()\n","sub_path":"DTFT.py","file_name":"DTFT.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"131211421","text":"#!/usr/bin/env python\n\"\"\"\nCopyright 2017 ARC Centre of Excellence for Climate Systems Science\n\nauthor: Scott Wales \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom numpy.distutils.core import setup, Extension\n\noasisf = Extension('oasis.f', \n sources=['oasis/oasis.f90'], \n libraries=['psmile.MPI1', 'scrip', 'mct', 'mpeu'], \n extra_f90_compile_args=['-fPIC'])\n\nsetup(\n name = 'oasis',\n packages = ['oasis'],\n ext_modules = [oasisf],\n install_requires = ['numpy', 'mpi4py']\n )\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"543081076","text":"from collections import defaultdict\n\n\n# def bfs(graph, start, goal):\n# # keep track of explored nodes\n# explored = []\n# # keep track of all the paths to be checked\n# queue = [[start]]\n#\n# # return path if start is goal\n# if start == goal:\n# return \"That was easy! Start = goal\"\n#\n# # keeps looping until all possible paths have been checked\n# while queue:\n# # pop the first path from the queue\n# path = queue.pop(0)\n# # get the last node from the path\n# node = path[-1]\n# if node not in explored:\n# neighbours = graph[node]\n# # go through all neighbour nodes, construct a new path and\n# # push it into the queue\n# for neighbour in neighbours:\n# new_path = list(path)\n# new_path.append(neighbour)\n# queue.append(new_path)\n# # return path if neighbour is goal\n# if neighbour == goal:\n# return new_path\n#\n# # mark node as explored\n# explored.append(node)\n\ndef bfs(graph_to_search, start, end):\n queue = [[start]]\n visited = set()\n\n while queue:\n # Gets the first path in the queue\n path = queue.pop(0)\n\n # Gets the last node in the path\n vertex = path[-1]\n\n # Checks if we got to the end\n if vertex == end:\n return path\n # We check if the current node is already in the visited nodes set in order not to recheck it\n elif vertex not in visited:\n # enumerate all adjacent nodes, construct a new path and push it into the queue\n for current_neighbour in graph_to_search.get(vertex, []):\n new_path = list(path)\n new_path.append(current_neighbour)\n queue.append(new_path)\n\n # Mark the vertex as visited\n visited.add(vertex)\n\n\ndef get_depth(graph, start, list_final):\n shortest = []\n for final in list_final:\n temp = bfs(graph, start, final)\n if not shortest:\n shortest = temp\n elif temp is not None and len(temp) < len(shortest):\n shortest = temp\n return len(shortest)\n\n\nclass SimpleCycle:\n def __init__(self, graph):\n \"\"\"\n :type graph: dict\n \"\"\"\n self.graph = {v: set(adj_nodes) for (v, adj_nodes) in graph.items()}\n\n # def dfa_depth(self, start: str, final_nodes: list) -> list:\n # def bfs(graph, start, final) -> list:\n # queue = [[start]]\n # while queue:\n # path = queue.pop(0)\n # node = path[-1]\n # # path found\n # if node == final:\n # return path\n #\n # # visit neighbors && create path\n # for neighbor in graph.get(node, []):\n # new_path = list(path)\n # new_path.append(neighbor)\n # queue.append(new_path)\n # current_short = []\n # for final in final_nodes:\n # new_path = bfs(self.graph, start, final)\n # if current_short == [] or len(current_short) > len(new_path):\n # current_short = new_path\n # return len(current_short)\n\n def simple_cycles(self) -> list:\n \"\"\"\n Johnson's algorithm implementation for finding elementary cycles\n :return: A generator function for the cycles\n \"\"\"\n\n # helpers\n def _remove_node(graph: dict, target: str) -> dict:\n \"\"\"\n A helper function for obtaining a new graph with a node removed\n :param graph: An adjacency list representation of the graph\n :param target: The node to remove\n :return: An adjacency list representation of the new graph\n \"\"\"\n graph_copy = graph.copy()\n del graph_copy[target]\n for neighbors in graph_copy.values():\n neighbors.discard(target)\n return graph_copy\n\n def _sub_graph(graph, vertices):\n \"\"\"\n A helper function for obtaining the sub graph from a particular\n :param graph: An adjacency list representation of the graph\n :param vertices: The vertices of the graph\n :return: A generator of the new sub-graph\n \"\"\"\n return {v: graph[v] & vertices for v in vertices}\n\n def _unblock(unblock, blocked_nodes, b):\n \"\"\"\n A method for yielding every elementary cycle once and only once\n :param unblock: The node to unblock\n :param blocked_nodes: list of blocked nodes\n :param b: current result\n \"\"\"\n stack = {unblock}\n while stack:\n node = stack.pop()\n if node in blocked_nodes:\n blocked_nodes.remove(node)\n stack.update(b[node])\n b[node].clear()\n\n working_graph = self.graph.copy()\n components = strongly_connected_components(working_graph)\n while components:\n scc = components.pop()\n start_node = scc.pop()\n path = [start_node]\n blocked = set()\n closed = set()\n blocked.add(start_node)\n b = defaultdict(set)\n stack = [(start_node, list(working_graph[start_node]))]\n while stack:\n current_node, adjacent_node = stack[-1]\n if adjacent_node:\n next_node = adjacent_node.pop()\n if next_node == start_node:\n yield path[:]\n closed.update(path)\n elif next_node not in blocked:\n path.append(next_node)\n stack.append((next_node, list(working_graph[next_node])))\n closed.discard(next_node)\n blocked.add(next_node)\n continue\n if not adjacent_node:\n if current_node in closed:\n _unblock(current_node, blocked, b)\n else:\n for adjacent in working_graph[current_node]:\n if current_node not in b[adjacent]:\n b[adjacent].add(current_node)\n stack.pop()\n path.pop()\n working_graph = _remove_node(working_graph, start_node)\n components.extend(strongly_connected_components(_sub_graph(working_graph, set(scc))))\n\n\ndef strongly_connected_components(graph: dict) -> list:\n \"\"\"\n Tarjan's algorithm for finding scc\n :param graph: An adjacency list representation of the graph\n :return: A list of strongly connected components\n \"\"\"\n\n counter = [0]\n stack = []\n lowlink = {}\n index = {}\n result = []\n\n def _strong_connect(node):\n index[node] = counter[0]\n lowlink[node] = counter[0]\n counter[0] += 1\n stack.append(node)\n\n neighbors = graph[node]\n for neighbor in neighbors:\n if neighbor not in index:\n _strong_connect(neighbor)\n lowlink[node] = min(lowlink[node], lowlink[neighbor])\n elif neighbor in stack:\n lowlink[node] = min(lowlink[node], index[neighbor])\n\n if lowlink[node] == index[node]:\n connected_component = []\n\n while True:\n neighbor = stack.pop()\n connected_component.append(neighbor)\n if neighbor == node: break\n result.append(connected_component[:])\n\n for node in graph:\n if node not in index:\n _strong_connect(node)\n\n return result\n","sub_path":"src/cycles.py","file_name":"cycles.py","file_ext":"py","file_size_in_byte":7799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"291391962","text":"# HW 10\n\n# import packages\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom math import *\nfrom scipy import optimize\n\n# define 2D function\ndef func(z):\n x, y = z\n return (x-2)**2 + (y-2)**2 + 2\n\n# minimize\nresult = optimize.minimize(func, [3,10])\nminimum = result.x \ncalls = result.nfev\n\nprint(minimum)\nprint(\"The number of function calls used was %i\" %(calls))\n\n# plot\nx = np.arange(-2,7,1)\ny = np.arange(-2,7,1)\nX, Y = np.meshgrid(x,y)\nfunction = (X-2)**2 + (Y-2)**2 + 2\n\nfig = plt.figure()\nax = Axes3D(fig)\nax.plot_surface(X,Y,function)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"My Function to Minimize\")\nax.set_zlim(-5,20)\n\nplt.show()\n\n\n","sub_path":"minimize2D.py","file_name":"minimize2D.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"176153602","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport time\r\nfrom tensorflow.contrib.slim.nets import resnet_v2\r\nslim = tf.contrib.slim\r\nfrom l2_attack import CarliniL2\r\nimport os\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n\r\n\r\nclass Model():\r\n def __init__(self,image_size,num_channels,num_labels,recognizer):\r\n self.image_size = image_size\r\n self.num_channels = num_channels\r\n self.num_labels = num_labels\r\n self.recognizer = recognizer\r\n\r\n def predict(self,images):\r\n images=images+0.5\r\n #images = images - tf.constant([123.68, 116.779, 103.939])\r\n with slim.arg_scope(resnet_v2.resnet_arg_scope()):\r\n logit, end = self.recognizer(images, self.num_labels, is_training=False, reuse=True)\r\n logit = tf.reshape(logit, [-1, self.num_labels])\r\n return logit\r\n\r\nif __name__==\"__main__\":\r\n\r\n config = tf.ConfigProto()\r\n config.gpu_options.allow_growth = True\r\n\r\n images = np.load(\"../../../datas/1000-vggres-same-image.npy\")[:1000]\r\n print(images.shape)\r\n labels = np.load(\"../../../datas/results/1000-vggres-same-label.npy\")[:1000]\r\n print(\"ok,target label is finished.\\n\")\r\n labels=labels.astype(np.int64)\r\n print(labels.shape)\r\n labels.shape=(1000)\r\n model_file = \"./model/resnet_v2_152.ckpt\"\r\n total_size = images.shape[0]\r\n batch_size = 10\r\n image_class = 1001\r\n height, width = 224, 224\r\n\r\n images = images/255-0.5\r\n\r\n b = np.zeros((total_size, image_class))\r\n b[np.arange(total_size), labels+1] = 1.0\r\n labels = b\r\n print (labels.shape)\r\n\r\n X = tf.placeholder(tf.float32, [None, height, width, 3])\r\n lab = tf.placeholder(tf.float32, (None, image_class))\r\n\r\n model = resnet_v2.resnet_v2_152\r\n with slim.arg_scope(resnet_v2.resnet_arg_scope()):\r\n net,end = model(X,1001,is_training=False)\r\n\r\n model = Model(224, 3, 1001, model)\r\n net = model.predict(X)\r\n correct_prediction = tf.equal(tf.argmax(net, 1), tf.argmax(lab, 1))\r\n accurary = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n ks=[0]\r\n for k in ks:\r\n with tf.Session(config=config) as sess:\r\n init = tf.global_variables_initializer()\r\n sess.run(init)\r\n saver = tf.train.Saver(tf.global_variables())\r\n checkpoint_path = model_file\r\n saver.restore(sess, checkpoint_path)\r\n print(\"load success!\")\r\n CW = CarliniL2(sess, model, batch_size=batch_size, confidence=k, targeted=False, max_iterations=1000)\r\n \r\n start_time = time.time()\r\n epochs_num = total_size // batch_size\r\n adv_all = np.zeros(shape=(1000,224,224,3))\r\n count = 0\r\n count2 = 0\r\n for i in range(epochs_num):\r\n imgs_batch = images[i * batch_size:(i + 1) * batch_size]\r\n labs_batch = labels[i * batch_size:(i + 1) * batch_size]\r\n acc,logit= sess.run([accurary,net], feed_dict={X: imgs_batch,\r\n lab:labs_batch})\r\n print (acc)\r\n count += len(labs_batch)\r\n cur_accuracy = acc*100\r\n print('sec {:>6}/{:<6} {:>6.2f}%'.format(count, total_size, cur_accuracy))\r\n \r\n adv = CW.attack(imgs_batch,labs_batch)\r\n adv= np.reshape(adv,(batch_size,224,224,3))\r\n acc2,logit= sess.run([accurary,net], feed_dict={X: adv,\r\n lab:labs_batch})\r\n \r\n cur_accuracy2 = acc2*100\r\n print('sec {:>6}/{:<6} {:>6.2f}%'.format(count, total_size, cur_accuracy2))\r\n adv_all[i*batch_size:(i+1)*batch_size]=adv\r\n np.save(\"./results/CW-untarget-RES152-k0\",adv_all)\r\n duration = time.time() - start_time\r\n print('run time:', duration)","sub_path":"code/attacker/CW_attacker/CW-slim-untarget-RES152.py","file_name":"CW-slim-untarget-RES152.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"354205631","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sqlite3\nimport re\nimport glob\nfrom pprint import pprint\nimport yaml\nimport sys\nfrom tabulate import tabulate\n\ndef create_db(name, schema):\n db_filename = name\n schema_filename = schema\n db_exists = os.path.exists(db_filename)\n conn = sqlite3.connect(db_filename)\n\n if not db_exists:\n print('Creating schema...')\n with open(schema_filename, 'r') as f:\n schema = f.read()\n conn.executescript(schema)\n print('Done')\n else:\n print('Database exists.')\n\ndef add_data(db_file, filenames=''):\n query_write_into_dhcp_snooping_table = '''insert into dhcp (mac, ip, vlan, interface, switch, active, last_active) values (?, ?, ?, ?, ?, 1, datetime('now'))'''\n query_set_active_0_dhcp_snooping_table = '''update dhcp set active = 0'''\n query_write_into_switches_table = '''insert into switches (hostname, location) values (?, ?)'''\n delete_old_rows = '''DELETE FROM dhcp WHERE last_active <= date('now','-7 day') '''\n dhcp_snooping_files = glob.glob('*dhcp_snooping.txt')\n dhcp_snooping_files_new = glob.glob(os.path.join('new_data','*dhcp_snooping.txt'))\n db_filename = db_file\n regex = re.compile('(\\S+) +(\\S+) +\\d+ +\\S+ +(\\d+) +(\\S+)')\n\n result = []\n for filename in dhcp_snooping_files:\n switch_name = filename.split('_')[0]\n with open(filename) as data:\n for line in data:\n match = regex.search(line)\n if match:\n result.append(match.groups()+(switch_name,))\n\n\n result_new = []\n for filename in dhcp_snooping_files_new:\n switch_name = filename.split('\\\\')[1].split('_')[0]\n with open(filename) as data:\n for line in data:\n match = regex.search(line)\n if match:\n result_new.append(match.groups()+(switch_name,))\n\n result_yml = []\n with open('switches.yml') as f:\n templates = yaml.safe_load(f)\n for sw in templates['switches']:\n result_yml.append( (sw, templates['switches'][sw],) )\n\n\n print('Adding data into table switches...')\n write_list_to_database(db_filename, query_write_into_switches_table, result_yml)\n print('Adding data into table dhcp...')\n write_list_to_database(db_filename, query_write_into_dhcp_snooping_table, result)\n print('Update data in table dhcp...')\n print('set active = 0 in table dhcp...')\n write_list_to_database(db_filename, query_set_active_0_dhcp_snooping_table)\n print('Update data in table dhcp with new files...')\n write_list_to_database(db_filename, query_write_into_dhcp_snooping_table, result_new)\n print('Deleting rows, which older than 7 days...')\n write_list_to_database(db_filename, delete_old_rows )\n\ndef write_list_to_database(db_filename, query_line, list_of_tuples=[]):\n conn = sqlite3.connect(db_filename)\n if list_of_tuples != []:\n for row in list_of_tuples:\n try:\n with conn:\n conn.execute(query_line, row)\n conn.commit()\n except sqlite3.IntegrityError as e:\n print('During data insertion: '+str(row)+' Error occured: ', e)\n if len(row) > 2:\n print( 'Updating row '+str(row)+' in database dhcp')\n conn.execute(\"update dhcp set ip = '\"+row[1]+\"', vlan = \"+row[2]+\", interface = '\"+row[3]+\"', switch ='\"+row[4]+\"', active = 1, last_active = datetime('now') where mac = '\"+row[0]+\"'\")\n conn.commit() \n else:\n try:\n conn.execute(query_line)\n conn.commit()\n except sqlite3.IntegrityError as e:\n print('During data insertion: Error occured: ', e)\n conn.close()\n\n\ndef get_all_data(db_file):\n db_filename = db_file\n conn = sqlite3.connect(db_filename)\n query = 'select * from dhcp' + ' where active = 1'\n result = conn.execute(query)\n print('Active records: ')\n print(tabulate(result))\n query = 'select * from dhcp' + ' where active = 0'\n result = conn.execute(query)\n print('Inactive records: ')\n print(tabulate(result))\n\n\ndef get_data(db_file, key, value):\n db_filename = db_file\n if key !='' and value !='':\n keys = ['vlan', 'mac', 'ip', 'interface', 'switch']\n if not key in keys:\n print('Enter key from {}'.format(', '.join(keys)))\n else:\n conn = sqlite3.connect(db_filename)\n print('\\nDetailed information for host(s) with', key, value)\n query = \"select * from dhcp where active = 1 and \"+key+\" = '\"+value+\"' \"\n result = conn.execute(query)\n print('Active records: ')\n print(tabulate(result))\n query = \"select * from dhcp where active = 0 and \"+key+\" = '\"+value+\"' \"\n result = conn.execute(query)\n print('Inactive records: ')\n print(tabulate(result))\n\nif __name__ == '__main__':\n pass","sub_path":"exercises/18_db/task_18_6/parse_dhcp_snooping_functions.py","file_name":"parse_dhcp_snooping_functions.py","file_ext":"py","file_size_in_byte":5025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"394454941","text":"import urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\n\nimport xml.etree.ElementTree as ET\n\ntarget_url = 'http://py4e-data.dr-chuck.net/comments_148898.xml'\nhtml = urllib.request.urlopen(target_url).read()\nsoup = BeautifulSoup(html, 'html.parser')\n\nresult_sum = 0\n\nx = ET.fromstring(str(soup))\ncomments = x.findall('comments/comment')\nfor comment in comments:\n num = int(comment.find('count').text)\n result_sum += num\n\nprint(result_sum)","sub_path":"py4e/chapter13/chapter13-assignment.py","file_name":"chapter13-assignment.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"138415004","text":"import re\r\nimport sys\r\nfrom collections import Counter\r\n\r\n\r\ndef getList(filename, pattern, type):\r\n try:\r\n file = open(str(filename), \"r\")\r\n except IOError:\r\n print(\"File not found\")\r\n return \"\"\r\n line = file.readline()\r\n if type == \"v4\":\r\n ips = []\r\n while line:\r\n x = re.findall('[0-9][0-9]*[0-9]*\\.[0-9][0-9]*[0-9]*\\.[0-9][0-9]*[0-9]*\\.[0-9][0-9*]*[0-9]*', line)\r\n line = file.readline()\r\n if x:\r\n if len(x) > 1:\r\n for i in x:\r\n ips.append(i)\r\n else:\r\n ips.append(x[0])\r\n file.close()\r\n return ips\r\n if type == \"custom\":\r\n matches = []\r\n while line:\r\n x = re.findall(str(pattern), line)\r\n line = file.readline()\r\n if x:\r\n if len(x) > 1:\r\n for i in x:\r\n matches.append(i)\r\n else:\r\n matches.append(x[0])\r\n file.close()\r\n return matches\r\n\r\n\r\ndef getDictFromList(list):\r\n c = Counter(list)\r\n return c.most_common()\r\n\r\n\r\ndef printOrdered(list):\r\n for i in list:\r\n print(i)\r\n \r\ndef getByDelin(filename, delin1, delin2):\r\n try:\r\n file = open(str(filename), \"r\")\r\n except IOError:\r\n print(\"File not found\")\r\n return 0\r\n line1 = file.readline()\r\n while line1:\r\n line1 = line1.split(str(delin1))\r\n lineout = str(line1[1])\r\n line2 = lineout.split(str(delin2))\r\n sys.stdout.write('{}\\n'.format(line2[0]))\r\n line1 = file.readline()\r\n \r\ndef findDuplicates(list):\r\n unique_list = []\r\n count = 0\r\n for i in list:\r\n if i not in unique_list:\r\n unique_list.append(i)\r\n for x in unique_list:\r\n for z in list:\r\n if x == z:\r\n count += 1\r\n print(x, count)\r\n count = 0\r\n\r\ndef printHelp():\r\n print(\"\\n\\nWelcome to the Beartrap log analyzer. Beartrap requires a filepath to a text file, and it needs to know what you are searching for\\n\"\r\n \"\\nTo look for the contents in a log file, '-i' for IPv4 addresses or '-c' for a custom pattern.\\n\"\r\n \"\\nYou can also use regular expressions with -c, the documentation for regular expressions can be found at:\\n\"\r\n \"\\nhttps://docs.python.org/2/library/re.html\\n\"\r\n \"\\nIf you would like to recieve the list items sorted by occurance in the log, append '-i' or '-c' with an 'o'. As in '-io' or '-co'\"\r\n \"\\nFinally, enter the path to your log file as the last argument.\"\r\n \"\\n\\nArguments MUST be used in this order. You cannot use -i with -h, or use -c with -r.\\n\"\r\n \"\\nthe syntax is: search type [argument] file\\n--\")\r\n\r\n\r\nif __name__ == '__main__':\r\n arg = sys.argv\r\n if arg[1] == \"-i\":\r\n findDuplicates(getList(arg[2], \"\", \"v4\"))\r\n elif arg[1] == \"-io\":\r\n printOrdered(getDictFromList(getList(arg[2], \"\", \"v4\")))\r\n elif arg[1] == \"-c\":\r\n print(findDuplicates(getList(arg[3], arg[2], \"custom\")))\r\n elif arg[1] == \"-d\":\r\n getByDelin(arg[4], arg[2], arg[3])\r\n elif arg[1] == \"-h\":\r\n printHelp()\r\n elif arg[1] == \"-co\":\r\n printOrdered(getDictFromList(getList(arg[3], arg[2], \"custom\")))\r\n else:\r\n print(\"Invalid Input\")\r\n","sub_path":"Beartrap.py","file_name":"Beartrap.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"200000009","text":"import os\nimport csv\n#Set the path for the file\ncsvpath = os.path.join('/', 'Users', 'xllz', 'Desktop', 'GTbootcamp', 'Homeworks_XL', '03-python','PyPoll','Resources','election_data.csv')\nprint(csvpath)\n#Open csv file\nwith open(csvpath) as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\") \n#Skip the header\n next(csvreader) \n#Initialize the total vote\n Total_vote=0\n Candidate_list=[]\n Candidate=[]\n Count_Khan=0\n Count_Correy=0\n Count_Li=0\n Count_OTooley=0\n Winner_rate=[]\n#calculate number of total vote, complete list of candidates\n for row in csvreader:\n Total_vote+=1\n Candidate.append(row[2])\n if row[2] not in Candidate_list:\n Candidate_list.append(row[2])\n # count how many votes for each candiate and calculate percentage and formatting the final results \n for i in Candidate:\n if i==Candidate_list[0]:\n Count_Khan+=1\n Rate_Khan=round(Count_Khan/Total_vote,3)\n Rate_Khan_format= format(Rate_Khan, \".3%\")\n elif i==Candidate_list[1]:\n Count_Correy+=1\n Rate_Correy=round(Count_Correy/Total_vote,3)\n Rate_Correy_format= format(Rate_Correy, \".3%\")\n elif i==Candidate_list[2]:\n Count_Li+=1\n Rate_Li=round(Count_Li/Total_vote,3)\n Rate_Li_format= format(Rate_Li, \".3%\")\n elif i==Candidate_list[3]:\n Count_OTooley+=1\n Rate_OTooley=round(Count_OTooley/Total_vote,3)\n Rate_OTooley_format= format(Rate_OTooley, \".3%\")\n # To find the winner, generate a list of voting rates for each candidate \n Winner_rate= (Rate_Khan, Rate_Correy, Rate_Li, Rate_OTooley)\n# find the maximum voting rate\n Winner_maximum=max(Winner_rate)\n# find the index for the maximum voting rate in the list\n Winner_index=Winner_rate.index(Winner_maximum)\n# the index is the same as the order in the candidate list\n Winner=Candidate_list[Winner_index] \n# Analysis output\n print(\"Election Results\") \n print(\"-----------------------------------------\") \n print(f\"Total Votes: {Total_vote}\")\n print(\"-----------------------------------------\") \n print(f\"{Candidate_list[0]}: {Rate_Khan_format} ({Count_Khan})\")\n print(f\"{Candidate_list[1]}: {Rate_Correy_format} ({Count_Correy})\")\n print(f\"{Candidate_list[2]}: {Rate_Li_format} ({Count_Li})\")\n print(f\"{Candidate_list[3]}: {Rate_OTooley_format} ({Count_OTooley})\")\n print(\"-----------------------------------------\") \n print(f\"Winner: {Winner}\")\n print(\"-----------------------------------------\") \n# write output in a txt file\n Pypoll_output_file = os.path.join('/', 'Users', 'xllz', 'Desktop', 'GTbootcamp', 'Homeworks_XL', '03-python','python_challenge','PyPoll','Pypoll_output.txt')\n f=open(Pypoll_output_file, 'w')\n f.write(\"Election Results\\n\") \n f.write(\"-----------------------------------------\\n\") \n f.write(f\"Total Votes: {Total_vote}\\n\")\n f.write(\"-----------------------------------------\\n\") \n f.write(f\"{Candidate_list[0]}: {Rate_Khan_format} ({Count_Khan})\\n\")\n f.write(f\"{Candidate_list[1]}: {Rate_Correy_format} ({Count_Correy})\\n\")\n f.write(f\"{Candidate_list[2]}: {Rate_Li_format} ({Count_Li})\\n\")\n f.write(f\"{Candidate_list[3]}: {Rate_OTooley_format} ({Count_OTooley})\\n\")\n f.write(\"-----------------------------------------\\n\") \n f.write(f\"Winner: {Winner}\\n\")\n f.write(\"-----------------------------------------\\n\") ","sub_path":"03-python/python_challenge/PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"162898392","text":"from flask import Flask, render_template, request\nimport json\nimport email\nimport smtplib\nfrom os.path import basename\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.application import MIMEApplication\nfrom email.mime.text import MIMEText\nimport atexit\n\n\n\ndata = {}\ndata['people'] = []\napplication = Flask(__name__)\nisPresent = False\n\n@application.route('/')\ndef render():\n return render_template('index.html')\n\n @application.route('/css/newcss.css')\n def render():\n return render_template('index.html')\n\n@application.route('/result',methods = ['POST', 'GET'])\ndef result():\n global isPresent\n if request.method == 'POST':\n result = request.form\n for key, value in result.items():\n print(key+\":\"+value)\n with open('data.json') as json_file:\n data = json.load(json_file)\n for p in data['people']:\n if p[\"PhoneNumber\"]==result[\"PhoneNumber\"]:\n p['First Name']=result[\"first_name\"]\n p['Last Name']=result[\"last_name\"]\n p['PhoneNumber']=result[\"PhoneNumber\"]\n p['Guests']=result[\"Guests\"]\n p['Meal Preference']=result[\"Meal\"]\n p['Comments']=result[\"Comments\"]\n with open('data.json', 'w') as outfile:\n json.dump(data, outfile)\n isPresent = True\n sendEmail(p)\n if (not isPresent):\n data['people'].append({\n 'First Name': result[\"first_name\"],\n 'Last Name': result[\"last_name\"],\n 'PhoneNumber': result[\"PhoneNumber\"],\n 'Guests': result[\"Guests\"],\n 'Meal Preference': result[\"Meal\"],\n 'Comments': result[\"Comments\"]\n })\n with open('data.json', 'w') as outfile:\n json.dump(data, outfile)\n sendEmail(result)\n return render_template(\"result.html\",result = result)\n\n\ndef sendEmail(data):\n msg = MIMEMultipart('alternative')\n\n\n # Create the body of the message (a plain-text and an HTML version)\n html = \"\"\"\\\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
First NameLast NamePhone NumberGuestsMeal PreferenceComments
\"\"\"+data[\"First Name\"]+\"\"\"\"\"\"+data[\"Last Name\"]+\"\"\"\"\"\"+data[\"PhoneNumber\"]+\"\"\"\"\"\"+data[\"Guests\"]+\"\"\"\"\"\"+data[\"Meal Preference\"]+\"\"\"\"\"\"+data[\"Comments\"]+\"\"\"
\n \n \n \"\"\"\n\n with open(\"data.json\", \"rb\") as fil:\n part = MIMEApplication(\n fil.read(),\n Name=basename(\"data.json\")\n )\n # After the file is closed\n part['Content-Disposition'] = 'attachment; filename=data.json'\n msg.attach(part)\n part2 = MIMEText(html, 'html')\n msg.attach(part2)\n msg['From'] = \"viallifleur@outlook.com\"\n msg['To'] = \"vialli_kavoo@hotmail.com\"\n msg['Subject'] = \"New User has Just RSVP'ed \"+data[\"First Name\"]+\" \"+data[\"Last Name\"]\n s = smtplib.SMTP(\"smtp.live.com\",587)\n s.ehlo() # Hostname to send for this command defaults to the fully qualified domain name of the local host.\n s.starttls() #Puts connection to SMTP server in TLS mode\n s.ehlo()\n s.login('viallifleur@outlook.com', 'Vialli@1234')\n s.sendmail(\"viallifleur@outlook.com\", \"vialli_kavoo@hotmail.com\", msg.as_string())\n s.quit()\n print(\"Message Sent Successfully\")\n\n@atexit.register\ndef sendcrashReport():\n msg = MIMEText(\"The Application has crashed\")\n msg['From'] = \"viallifleur@outlook.com\"\n msg['To'] = \"vialli_kavoo@hotmail.com\"\n msg['Subject'] = \"Application has crashed \"\n s = smtplib.SMTP(\"smtp.live.com\",587)\n s.ehlo() # Hostname to send for this command defaults to the fully qualified domain name of the local host.\n s.starttls() #Puts connection to SMTP server in TLS mode\n s.ehlo()\n s.login('viallifleur@outlook.com', 'Vialli@1234')\n s.sendmail(\"viallifleur@outlook.com\", \"vialli_kavoo@hotmail.com\", msg.as_string())\n s.quit()\n print(\"Message Sent Successfully\")\n\nif __name__ == '__main__':\n application.run()\n","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"302227950","text":"from PIL import Image\nfrom PIL import ImageFilter\n\n\ndef apply_filter(image, filter):\n pixels = [filter(p) for p in image.getdata()]\n nim = Image.new(\"RGB\", image.size)\n nim.putdata(pixels)\n return nim\n\n\ndef open_image(filename):\n image = Image.open(filename)\n if image == None:\n print(\"Specified input file \" + filename + \" cannot be opened.\")\n return Image.new(\"RGB\", (400, 400))\n else:\n print(str(image.size) + \" = \" + str(len(image.getdata())) + \" total pixels.\")\n return image.convert(\"RGB\")\n\n\ndef restart():\n a = input(\"Would you like to do another operation?\")\n if a == 'Yes':\n choices()\n if a == 'No':\n quit()\n\n\ndef identity(pixel):\n r, g, b = pixel\n return(r, g, b)\n\n\ndef invert(pixel):\n r, g, b = pixel\n finished = (255 - r, 255 - g, 255 - b)\n return finished\n\n\ndef darken(pixels):\n r, g, b = pixels\n r = int(r * 0.25)\n g = int(g * 0.25)\n b = int(b * 0.25)\n return(r, g, b)\n pass\n\n\ndef brighten(pixel):\n r, g, b = pixel\n r = int(r * 1.25)\n g = int(g * 1.25)\n b = int(b * 1.25)\n return (r, g, b)\n pass\n\n\ndef gray_scale(pixel):\n r, g, b = pixel\n r = int((r + g + b)/3)\n g = int((r + g + b)/3)\n b = int((r + g + b)/3)\n return (r, g, b)\n pass\n\n\ndef posterize(pixel):\n r, g, b = pixel\n if 63 >= r >= 0:\n r = 50\n if 63 >= g >= 0:\n g = 50\n if 63 >= b >= 0:\n b = 50\n if 127 >= r >= 64:\n r = 100\n if 127 >= g >= 64:\n g = 100\n if 127 >= b >= 64:\n b = 100\n if 191 >= r >= 128:\n r = 150\n if 191 >= g >= 128:\n g = 150\n if 191 >= b >= 128:\n b = 150\n if 255 >= r >= 192:\n r = 200\n if 255 >= g >= 192:\n g = 200\n if 255 >= b >= 192:\n b = 200\n return (r, g, b)\n\n\ndef solarize(pixel):\n r, g, b = pixel\n if r < 128:\n r = 255 - r\n if g < 128:\n g = 255 - g\n if b < 128:\n b = 255 - b\n return (r, g, b)\n pass\n\n\ndef flip(imageX):\n type = input(\"Would you like to flip the image vertically or horizontally?\")\n if type == 'Vertically':\n img = Image.open(imageX).transpose(Image.FLIP_TOP_BOTTOM)\n if type == 'Horizontally':\n img = Image.open(imageX).transpose(Image.FLIP_LEFT_RIGHT)\n img.show()\n return img\n\n\ndef blur(imageX):\n r = int(input(\"What do you want the radius to be?\"))\n print(imageX)\n original_image = Image.open(imageX)\n blurred_image = original_image.filter(ImageFilter.GaussianBlur(radius=r))\n blurred_image.show()\n return blurred_image\n\n\ndef sharpen(imageX):\n inpt_radius = int(input(\"What would you like the radius to be?\"))\n inpt_percent = int(input(\"Enter sharpening percentage.\"))\n inpt_threshold = int(input(\"Enter a sharpening threshold.\"))\n sharper_image = Image.open(imageX)\n sharper_image = sharper_image.filter(ImageFilter.UnsharpMask(radius = inpt_radius, percent = inpt_percent, threshold = inpt_threshold))\n sharper_image.show()\n return sharper_image\n\n\ndef cropper(imageX):\n start_x = int(input(\"Enter a starting value for x.\"))\n start_y = int(input(\"Enter a starting value for y.\"))\n end_x = int(input(\"Enter an ending value for x.\"))\n end_y = int(input(\"Enter an ending value for y.\"))\n imgd = Image.open(imageX)\n area = (start_x, start_y, end_x, end_y)\n cropped_img = imgd.crop(area)\n cropped_img.show()\n return cropped_img\n\n\ndef load_and_go(fname, filterfunc):\n image = open_image(fname)\n nimage = apply_filter(image, filterfunc)\n image.show()\n nimage.show()\n a = input(\"What would you like to call this new image? Enter the file ending as well.\")\n nimage.save(a)\n\n\ndef choices():\n choice = input(\"Which operation would you like to do? You can 'Darken', 'Brighten', 'Invert', 'Grayscale',\"\n \"'Posterize', 'Solarize', 'Flip', 'Blur', 'Sharpen', or 'Crop'.\")\n input_file = input(\"Which photo would you like to change?\")\n if choice == 'Darken':\n load_and_go(input_file, darken)\n if choice == 'Brighten':\n load_and_go(input_file, brighten)\n if choice == 'Invert':\n load_and_go(input_file, invert)\n if choice == 'Grayscale':\n load_and_go(input_file, gray_scale)\n if choice == 'Posterize':\n load_and_go(input_file, posterize)\n if choice == 'Solarize':\n load_and_go(input_file, solarize)\n if choice == 'Flip':\n b = flip(input_file)\n a = input(\"What would you like to call this new image?\")\n b.save(a)\n if choice == 'Blur':\n c = blur(input_file)\n a = input(\"What would you like to call this new image?\")\n c.save(a)\n if choice == 'Sharpen':\n b = sharpen(input_file)\n a = input(\"What would you like to call this new image?\")\n b.save(a)\n if choice == 'Crop':\n b = cropper(input_file)\n a = input(\"What would you like to call this new image?\")\n b.save(a)\n\n\nif __name__ == \"__main__\":\n choices()\nwhile True:\n restart()\n\n","sub_path":"Day3/photoshop.py","file_name":"photoshop.py","file_ext":"py","file_size_in_byte":5025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"308922844","text":"# if statements\n\ncars = ['audi', 'bwm', 'subaru', 'toyota']\n\n\nfor car in cars:\n\n\t \n\tif car == 'bwm':\n\n\t print( car.upper())\n\nelse :\n\n\t print( car.title())\n\nif car != \" honda\":\n\n\tprint( \" i want to buy bmw. \".upper())\n\n","sub_path":"cars2.py","file_name":"cars2.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"619605436","text":"import requests\nimport json\npost_body = [\n {\"action\": \"searchapi.SearchPubsCommon\",\n \"parameters\": {\n \"offset\": 0,\n \"size\": 1000,\n \"searchType\": \"all\",\n \"switches\": [\"lang_zh\"],\n \"aggregation\":[\"year\", \"author_year\"],\n \"query\":\"Cyberspace security\",\n \"year_interval\":1\n },\n \"schema\":{\n \"publication\": [\"id\",\n \"year\",\n \"title\",\n \"title_zh\",\n \"abstract\",\n \"abstract_zh\",\n \"authors\",\n \"authors._id\",\n \"authors.name\",\n \"keywords\",\n \"authors.name_zh\",\n \"num_citation\",\n \"num_viewed\",\n \"num_starred\",\n \"num_upvoted\",\n \"is_starring\",\n \"is_upvoted\",\n \"is_downvoted\",\n \"venue.info.name\",\n \"venue.volume\",\n \"venue.info.name_zh\",\n \"venue.info.publisher\",\n \"venue.issue\",\n \"pages.start\",\n \"pages.end\",\n \"lang\",\n \"pdf\",\n \"ppt\",\n \"doi\",\n \"urls\",\n \"flags\",\n \"resources\"]}}]\n\n# https://www.aminer.cn/search/pub?q=Cyberspace%20security&t=b\nurl = 'https://apiv2.aminer.cn/n?a=SEARCH__searchapi.SearchPubsCommon___'\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66'\n}\n# data=json.dumps(post_body)\n# json=post_body\n# print(json.dumps(post_body), type(json.dumps(post_body)))\nresponse = requests.post(url=url, headers=headers, json=post_body)\nprint(response.status_code)\n\n# print(response.content.decode('utf-8'))\njson_str = response.content.decode('utf-8')\njson_str = json.loads(json_str)\njson_format = json.dumps(\n json_str, indent=4, sort_keys=True, ensure_ascii=False)\n# print(json_format)\n\nwith open('./paper_data.json', 'w', encoding='utf-8') as file:\n json.dump(json_str, file, indent=4, ensure_ascii=False)\n","sub_path":"知识图谱/主页面爬取.py","file_name":"主页面爬取.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"268405037","text":"'''\n@Author: ruoru\n@Date: 2020-05-19 11:54:33\n@LastEditors: ruoru\n@LastEditTime: 2020-05-19 13:41:24\n@Description: https://leetcode-cn.com/problems/permutations/\n'''\nfrom typing import List\n\n\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n result = []\n\n def backtrack(route, choices):\n if not choices:\n result.append(route.copy())\n return\n\n for i in range(len(choices)):\n route.append(choices[i])\n backtrack(route, [choices[j] for j in range(len(choices)) if j != i])\n del route[-1]\n backtrack([], nums)\n return result\n\n\ns = Solution()\nprint(s.permute([1, 2, 3]))\n","sub_path":"backtracking/permutations_again.py","file_name":"permutations_again.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"516496361","text":"import sublime\nimport sublime_plugin\nimport os\nimport re\n\nfrom FolderFiles.folder_files import(FolderFiles, open_file_or_folder_by_panel,\n open_folder_by_panel)\n\ntry:\n from FileList.file_list import open_file, get_short_path\n from QuickSearchEnhanced import quick_search\n from OpenPath.open_path import open_path\nexcept ImportError as error:\n sublime.error_message(\"Dependency import failed; please read readme for \" +\n \"FolderFiles plugin for installation instructions; to disable this \" +\n \"message remove this plugin; message: \" + str(error))\n raise error\n\nclass FolderFilesHelper(sublime_plugin.TextCommand):\n def _get_panels(self):\n panel = quick_search.panels.get_current()\n folder_files = panel and panel.get_caller('folder_files')\n return panel, folder_files\n\n def _get_file_list_panels(self):\n panel = quick_search.panels.get_current()\n folder_files = panel and panel.get_caller('file_list')\n return panel, folder_files\n\nclass OpenFolderInList(FolderFilesHelper):\n def run(self, edit):\n panel, _ = self._get_file_list_panels()\n if panel == None:\n return\n\n open_file_or_folder_by_panel(panel)\n\nclass OpenFileManagerForFolderInList(FolderFilesHelper):\n def run(self, edit):\n _, folder_files = self._get_panels()\n if folder_files == None:\n return\n\n open_path(folder_files.get_current_path())\n\nclass OpenExactFileInList(FolderFilesHelper):\n def run(self, edit):\n panel, folder_files = self._get_panels()\n if folder_files == None:\n return\n\n path = panel.get_current_text()\n if path[0:1] != '/':\n path = folder_files.get_current_path() + '/' + path\n\n open_file_or_folder_by_panel(panel, path)\n\nclass OpenFileInList(FolderFilesHelper):\n def run(self, edit):\n panel, folder_files = self._get_panels()\n if folder_files == None:\n return\n\n sublime.active_window().open_file(panel.get_current_value())\n\nclass PreviewFileInList(FolderFilesHelper):\n def run(self, edit):\n panel, folder_files = self._get_panels()\n if folder_files == None:\n return\n\n sublime.active_window().open_file(panel.get_current_value(),\n sublime.TRANSIENT)\n\nclass GotoFolderInList(FolderFilesHelper):\n def run(self, edit, path):\n _, folder_files = self._get_panels()\n if folder_files == None:\n return\n\n match = re.match(r'\\$(\\d)', path)\n if match != None:\n folder_files.goto(self.view.window().folders()[int(match.group(1))])\n elif path == '$ROOT':\n path = folder_files.get_current_path()\n for folder in self.view.window().folders():\n if folder == path[0:len(folder)]:\n folder_files.goto(folder)\n break\n elif path == '$UP':\n folder_files.goto_up()\n elif path == '$DOWN':\n folder_files.goto_down()\n else:\n folder_files.goto(os.path.expanduser(path))\n\nclass CreateFolderInList(FolderFilesHelper):\n def run(self, edit):\n panel = quick_search.panels.get_current()\n folder_files = panel and panel.get_caller('folder_files')\n if folder_files == None:\n return\n\n path = folder_files.get_path() + '/' +panel.get_current_text()\n os.mkdir(path)\n folder_files.goto(path)\n panel.set_text('')\n\nclass FindInCurrentFileFolder(FolderFilesHelper):\n def run(self, edit):\n panel, folder_files = self._get_panels()\n panel.close(False, None)\n sublime.active_window().focus_view(panel.get_opener())\n\n path, _ = get_short_path(folder_files.get_path())\n sublime.active_window().run_command('show_panel', {\"panel\": \"find_in_files\",\n \"where\": path + '/'})","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"189425927","text":"import streamlit as st \nimport pandas as pd\nimport joblib\n\nmodel = open(\"RandomForestStress.pkl\", \"rb\")\nrf=joblib.load(model)\n\nst.title(\"Propensão Aplicações em Períodos de Stress\")\n \nsegmento_list=['Private','Alta Renda','Varejo']\nsuitability_list=['Conservador','Moderado','Arrojado']\ngeracao_list=['Veterano','Baby Boomer','Geração X','Geração Y','Geração Z']\nsexo_list=['Masculino','Feminino']\nest_civil_list=['Solteiro','Casado','Divorciado','Viuvo']\nnacionalidade_list=['Brasileiro','Estrangeiro']\nescolaridade_list=['Ensino Fundamental','Ensino Medio','Superior Completo','Pós Graduação']\n\ncolumns_list=['saldo_inicio_periodo_stress',\n'tipo_cliente_ALTA_RENDA', \n'tipo_cliente_PRIVATE',\n'tipo_cliente_VAREJO', \n'suitability_Arrojado',\n'suitability_Conservador', \n'suitability_Moderado', \n'geracao_ALPHA',\n'geracao_BABY_BOOMERS', \n'geracao_GERACAO_X', \n'geracao_GERACAO_Y',\n'geracao_GERACAO_Z', \n'geracao_VETERANO', \n'sexo_FEMININO',\n'sexo_MASCULINO', \n'est_civil_CASADO', \n'est_civil_DIVORCIADO',\n'est_civil_SOLTEIRO', \n'est_civil_VIUVO', \n'nacionalidade_BRASILEIRO',\n'nacionalidade_ESTRANGEIRO', \n'escolaridade_ANALFABETO',\n'escolaridade_DOUTORADO', \n'escolaridade_ENSINO_FUNDAMENTAL',\n'escolaridade_ENSINO_MEDIO', \n'escolaridade_MESTRADO',\n'escolaridade_POS_GRADUADO', \n'escolaridade_SUPERIOR_COMPLETO',\n'escolaridade_SUPERIOR_EM_ANDAMENTO']\n\ninput_variables = pd.DataFrame([[0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], columns=columns_list)\n\nsegmento = st.selectbox('Segmento:', segmento_list)\nsuitability = st.selectbox('Perfil Suitability:', suitability_list)\ngeracao = st.selectbox('Geração:', geracao_list)\nsexo = st.selectbox('Sexo:', sexo_list)\nest_civil = st.selectbox('Estado Civil:', est_civil_list)\nnacionalidade = st.selectbox('Nacionalidade:', nacionalidade_list)\nescolaridade = st.selectbox('Escolaridade:', escolaridade_list)\ninvestimentos = st.slider(label='Saldo em Aplicações', key='Saldo em Aplicações',value=10.0, min_value=0.0, max_value=1000.0, step=5.0, format=\"%.1f mil\") * 1000\n\n\nst.write(\"Volume Total Investimentos do Cliente: \", '{:,.0f}'.format(investimentos))\n\ninput_variables.saldo_inicio_periodo_stress[0] = investimentos\n\nif segmento == 'Private':\n\tinput_variables.tipo_cliente_PRIVATE[0] = 1\nelif segmento == 'Alta Renda':\n\tinput_variables.tipo_cliente_ALTA_RENDA[0] = 1\nelif segmento == 'Varejo':\n\tinput_variables.tipo_cliente_VAREJO[0] = 1\t\n\nif suitability == 'Arrojado':\n\tinput_variables.suitability_Arrojado[0] = 1\nelif suitability == 'Conservador':\n\tinput_variables.suitability_Conservador[0] = 1\nelif suitability == 'Moderado':\n\tinput_variables.suitability_Moderado[0] = 1\n\nif geracao == 'Veterano':\n\tinput_variables.geracao_VETERANO[0] = 1\nelif geracao == 'Baby Boomer':\n\tinput_variables.geracao_BABY_BOOMERS[0] = 1\nelif geracao == 'Geração X':\n\tinput_variables.geracao_GERACAO_X[0] = 1\nelif geracao == 'Geração Y':\n\tinput_variables.geracao_GERACAO_Y[0] = 1\nelif geracao == 'Geração Z':\n\tinput_variables.geracao_GERACAO_Z[0] = 1\n\nif sexo == 'Masculino':\n\tinput_variables.sexo_MASCULINO[0] = 1\nelif sexo == 'Feminino':\n\tinput_variables.sexo_FEMININO[0] = 1\n\nif est_civil == 'Solteiro':\n\tinput_variables.est_civil_SOLTEIRO[0] = 1\nelif est_civil == 'Casado':\n\tinput_variables.est_civil_CASADO[0] = 1\nelif est_civil == 'Divorciado':\n\tinput_variables.est_civil_DIVORCIADO[0] = 1\nelif est_civil == 'Viuvo':\n\tinput_variables.est_civil_VIUVO[0] = 1\n\nif nacionalidade == 'Brasileiro':\n\tinput_variables.nacionalidade_BRASILEIRO[0] = 1\nelif nacionalidade == 'Estrangeiro':\n\tinput_variables.nacionalidade_ESTRANGEIRO[0] = 1\n\nif escolaridade == 'Ensino Fundamental':\n\tinput_variables.escolaridade_ENSINO_FUNDAMENTAL[0] = 1\nelif escolaridade == 'Ensino Medio':\n\tinput_variables.escolaridade_ENSINO_MEDIO[0] = 1\nelif escolaridade == 'Superior Completo':\n\tinput_variables.escolaridade_SUPERIOR_COMPLETO[0] = 1\nelif escolaridade == 'Pós Graduação':\n\tinput_variables.escolaridade_POS_GRADUADO[0] = 1\n\n\nprob = [row[1] for row in rf.predict_proba(input_variables)]\n\nst.write(\"Probalidade do cliente aplicar em períodos de Stress é: \", '{:,.1f}'.format(prob[0] * 100) , \"%\")\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"231270573","text":"import openpyxl\nfrom templates.article import ArticleWorkbook, ArticleSheet\n\nclass SpreadsheetIO:\n \"\"\"\n 試算表的操作封裝\n \"\"\"\n\n def __init__(self):\n self.file = None\n self.row_num = 0\n\n def load(self, xls_path):\n \"\"\"\n 讀取 Xlsx 檔案\n \n @param xls_path 試算表檔案位置\n \"\"\"\n self.file = ArticleWorkbook(xls_path)\n\n def get_data(self):\n \"\"\"\n 取得 excel 表中所紀錄的資料\n \"\"\"\n result = {}\n for item in self.file.data:\n key = item.tw_name\n result[key] = {\n 'eng_name': item.eng_name,\n 'x': item.x,\n 'y': item.y,\n 'width': item.width,\n 'height': item.height\n }\n return result\n\n def export_table(self, data_list, path, header='', desc=''):\n \"\"\"\n 透過樣板輸出資料表\n \"\"\"\n book = ArticleWorkbook()\n # 由於內容要求為 tuple ,因此轉換後再寫入。\n data_list = self.__dict_to_tuple(data_list)\n book.data.write(data_list, header, desc)\n book.save(path) \n\n def compare_data(self, data_list):\n \"\"\"\n 與現有資料進行比對,若有誤差則以傳入的資料為主。\n \"\"\"\n xls_data = self.get_data()\n for item in data_list:\n if item['tw_name'] in xls_data:\n key = item['tw_name']\n item['eng_name'] = xls_data[key]['eng_name']\n item['width'] = xls_data[key]['width']\n item['height'] = xls_data[key]['height'] \n return data_list\n\n def __dict_to_tuple(self, data_list):\n \"\"\"\n 將內容轉換為元組\n \"\"\"\n result = []\n for item in data_list:\n result.append(\n (self.row_num, item['tw_name'], item['eng_name'], item['x'], item['y'], item['width'], item['height'])\n )\n self.row_num = self.row_num + 1\n return result\n\n def list_to_dict(self, data_list):\n result = {}\n print(data_list)\n for item in data_list:\n key = item['tw_name']\n result[key] = {\n 'eng_name': item['eng_name'],\n 'x': item['x'],\n 'y': item['y'],\n 'width': item['width'],\n 'height': item['height']\n }\n return result","sub_path":"module/spreadsheet_io.py","file_name":"spreadsheet_io.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"308616308","text":"#LAND BATTLE SIMULATOR\n\nimport random\n\ndef score(t,tadv,tren,wag,wagc,mult,a,b,c,d,e,f,g,h,i,j,k,l,m,n):\n if t==1:\n scoreat=(mult*tadv*(wag*(a*5+b*15+c*8+e*25+f*12+g*20)+wagc*0.3*(h*5+i*15+j*8+l*25+m*12+n*20)))\n scoredef=(mult*tadv*tren*(wag*(a*2+b*15+c*10+d*6+e*6)+wagc*0.3*(h*2+i*15+j*10+k*6+l*6)))\n scoreairat=(mult*(wag*(d*15+f*12)+wagc*0.3*(k*15+m*12)))\n scoreairdef=(mult*(wag*(f*8+g*10)+wagc*0.3*(m*8+n*10)))\n if t==2:\n scoreat=(mult*(wag*(a*60+b*40+c*45+d*50+e*10+f*0.5+g*20*1.5)+wagc*0.3*(h*60+i*40+j*45+k*50+l*10+m*0.5+n*20*1.5)))\n scoredef=(mult*(wag*(a*60+b*30+c*45+d*30+e*30)+wagc*0.3*(h*60+i*30+j*45+k*30+l*30)))\n scoreairat=(mult*(wag*(b*40*0.25+c*45*0.25+e*10*0.5+f*12)+wagc*0.3*(i*40*0.25+j*45*0.25+l*10*0.5+m*12)))\n scoreairdef=(mult*(wag*(f*8+g*10)+wagc*0.3*(m*8+n*10)))\n return[scoreat,scoredef,scoreairat,scoreairdef]\ndef casualties(unit,scatW,scatL,scdefW,scdefL,status,casu,sn,mult,cons,typ,air):\n typm=typ-(typ/2)+air/2\n if air==1:\n if ((-scatL)+scdefW)<((-scatW)+scdefL):\n if status=='loser':\n status='winner'\n if status=='winner':\n status='loser'\n scat=[scatL,scatW]\n scdef=[scdefL,scdefW]\n scatL=scat[1]\n scatW=scat[0]\n scdefL=scdef[1]\n scdefW=scdef[0]\n w=(((scatL+scdefL)/(scatW+scdefW))*(1+((scatL+scdefL)/(scatW+scdefW))))/4\n d=(((scatL+scdefL)/(scatW+scdefW))*(1+((scatL+scdefL)/(scatW+scdefW))))/10\n if status=='winner':\n deaths=round(unit*d*typm,0)\n wounded=round((unit-deaths)*w*typm,0)\n remaining=unit-wounded-deaths\n if typ==1:\n casu[0]=casu[0]+wounded*mult\n casu[1]=casu[1]+deaths*mult\n if typ==2:\n woundedDeath=random.randint(0, 10)\n deathDeath=random.randint(50, 100)\n woundedWounded=woundedDeath+15\n woundedWounded=random.randint(0,woundedWounded)\n deathWounded=100-deathDeath\n deathWounded=random.randint(0,deathWounded)\n casu[0]=casu[0]+round(wounded*mult*woundedWounded/100+deaths*mult*deathWounded/100,0)\n casu[1]=casu[1]+round(deaths*mult*(deathDeath/100)+wounded*mult*(woundedDeath/100),0)\n print(remaining,'/',wounded,'/',deaths)\n if status=='loser':\n p=(((scatW+scdefW)/(scatL+scdefL))**2)/1.35\n ld=d*(1+(p/2))\n if ld>=0.95:\n ld=0.95\n lw=w*(1+(p/2))\n if lw>=1:\n lw=1\n deaths=round(unit*ld*typm,0)\n wounded=round((unit-deaths)*lw*typm,0)\n remaining=unit-wounded-deaths\n if typ==1:\n casu[0]=casu[0]+wounded*mult\n casu[1]=casu[1]+deaths*mult\n if typ==2:\n woundedDeath=random.randint(0, 10)\n deathDeath=random.randint(50, 100)\n woundedWounded=woundedDeath+15\n woundedWounded=random.randint(0,woundedWounded)\n deathWounded=100-deathDeath\n deathWounded=random.randint(0,deathWounded)\n casu[0]=casu[0]+round(wounded*mult*woundedWounded/100+deaths*mult*deathWounded/100,0)\n casu[1]=casu[1]+round(deaths*mult*(deathDeath/100)+wounded*mult*(woundedDeath/100),0)\n print(remaining,'/',wounded,'/',deaths)\n return()\n \n\n#DATA INPUT\n\ndef TEAM(n,sidesat,sidesdef,nsid,li,typ):\n teamname='Team'+str(n)\n print()\n globals()[teamname]= input(\"Name of the country : \")\n\n if typ==1:\n\n Inf='Inf'+str(n)\n globals()[Inf] = int(input(\"Infantrymen : \"))\n Tanks='Tanks'+str(n)\n globals()[Tanks] = int(input(\"Tanks : \"))\n AFV='AFV'+str(n)\n globals()[AFV] = int(input(\"AFVs :\"))\n AAA='AAA'+str(n)\n globals()[AAA] = int(input(\"AAA cannons : \"))\n FA='FA'+str(n)\n globals()[FA] = int(input(\"FA cannons : \"))\n Fighter='Fighter'+str(n)\n globals()[Fighter] = int(input(\"Fighters : \"))\n Bomber='Bomber'+str(n)\n globals()[Bomber] = int(input(\"Bombers : \"))\n\n cons='cons'+str(n)\n globals()[cons]=int(input(\"Conscripts ? [1]:yes [0]:no\"))\n\n if globals()[cons]==1:\n\n CInf='CInf'+str(n)\n globals()[CInf] = int(input(\"Conscript Infantrymen : \"))\n CTanks='CTanks'+str(n)\n globals()[CTanks] = int(input(\"Conscript Tanks : \"))\n CAFV='CAFV'+str(n)\n globals()[CAFV] = int(input(\"Conscript AFVs :\"))\n CAAA='CAAA'+str(n)\n globals()[CAAA] = int(input(\"Conscript AAA cannons : \"))\n CFA='CFA'+str(n)\n globals()[CFA] = int(input(\"Conscript FA cannons : \"))\n CFighter='CFighter'+str(n)\n globals()[CFighter] = int(input(\"Conscript Fighters : \"))\n CBomber='CBomber'+str(n)\n globals()[CBomber] = int(input(\"Conscript Bombers : \"))\n\n else :\n \n CInf='CInf'+str(n)\n globals()[CInf] = 0\n CTanks='CTanks'+str(n)\n globals()[CTanks] = 0\n CAFV='CAFV'+str(n)\n globals()[CAFV] = 0\n CAAA='CAAA'+str(n)\n globals()[CAAA] = 0\n CFA='CFA'+str(n)\n globals()[CFA] = 0\n CFighter='CFighter'+str(n)\n globals()[CFighter] = 0\n CBomber='CBomber'+str(n)\n globals()[CBomber] = 0\n\n if typ==2:\n\n Inf='Inf'+str(n)\n globals()[Inf] = 0\n Tanks='Tanks'+str(n)\n globals()[Tanks] = 0\n AFV='AFV'+str(n)\n globals()[AFV] = 0\n AAA='AAA'+str(n)\n globals()[AAA] = 0\n FA='FA'+str(n)\n globals()[FA] = 0\n CInf='CInf'+str(n)\n globals()[CInf] = 0\n CTanks='CTanks'+str(n)\n globals()[CTanks] = 0\n CAFV='CAFV'+str(n)\n globals()[CAFV] = 0\n CAAA='CAAA'+str(n)\n globals()[CAAA] = 0\n CFA='CFA'+str(n)\n globals()[CFA] = 0\n\n BattleS='BattleS'+str(n)\n globals()[BattleS] = int(input(\"Battleships : \"))\n Destroyer='Destroyers'+str(n)\n globals()[Destroyer] = int(input(\"Destroyers : \"))\n Cruisers='Cruisers'+str(n)\n globals()[Cruisers] = int(input(\"Cruisers :\"))\n Uboat='Uboat'+str(n)\n globals()[Uboat] = int(input(\"Uboats : \"))\n TroopS='TroopS'+str(n)\n globals()[TroopS] = int(input(\"Troopships : \"))\n\n coas=int(input(\"Coastal battle ? [1]:yes [0]:no\"))\n\n if coas==1:\n\n Fighter='Fighter'+str(n)\n globals()[Fighter] = int(input(\"Fighters : \"))\n Bomber='Bomber'+str(n)\n globals()[Bomber] = int(input(\"Bombers : \"))\n\n else :\n Fighter='Fighter'+str(n)\n globals()[Fighter] = 0\n Bomber='Bomber'+str(n)\n globals()[Bomber] = 0\n\n cons='cons'+str(n)\n globals()[cons]=int(input(\"Conscripts ? [1]:yes [0]:no\"))\n\n if globals()[cons]==1:\n\n CBattleS='CBattleS'+str(n)\n globals()[CBattleS] = int(input(\"Conscript Battleships : \"))\n CDestroyer='CDestroyers'+str(n)\n globals()[CDestroyer] = int(input(\"Conscript Destroyers : \"))\n CCruisers='CCruisers'+str(n)\n globals()[CCruisers] = int(input(\"Conscript Cruisers :\"))\n CUboat='CUboat'+str(n)\n globals()[CUboat] = int(input(\"Conscript Uboats : \"))\n CTroopS='CTroopS'+str(n)\n globals()[CTroopS] = int(input(\"Conscript Troopships : \"))\n\n if coas==1:\n\n CFighter='CFighter'+str(n)\n globals()[CFighter] = int(input(\"Conscript Fighters : \"))\n CBomber='CBomber'+str(n)\n globals()[CBomber] = int(input(\"Conscript Bombers : \"))\n\n else:\n\n CFighter='CFighter'+str(n)\n globals()[CFighter] = 0\n CBomber='CBomber'+str(n)\n globals()[CBomber] = 0\n else:\n \n CBattleS='CBattleS'+str(n)\n globals()[CBattleS] = 0\n CDestroyer='CDestroyers'+str(n)\n globals()[CDestroyer] = 0\n CCruisers='CCruisers'+str(n)\n globals()[CCruisers] = 0\n CUboat='CUboat'+str(n)\n globals()[CUboat] = 0\n CTroopS='CTroopS'+str(n)\n globals()[CTroopS] = 0\n CFighter='CFighter'+str(n)\n globals()[CFighter] = 0\n CBomber='CBomber'+str(n)\n globals()[CBomber] = 0\n tr='tr'+str(n)\n if (globals()[TroopS]+globals()[CTroopS])!=0:\n globals()[tr]=round(int(input(\"Number of soldiers transported by troopships\"))/(globals()[TroopS]+globals()[CTroopS]),0)\n else:\n globals()[tr]=0\n\n print(\"Country stats :\")\n\n Part='Part'+str(n)\n globals()[Part] = ((int(input(\"Military budget (without the $ and no commas) : \")))/100000000000)+1\n Rese='Rese'+str(n)\n globals()[Rese] = ((int(input(\"Research budget (without the $ and no commas) : \")))/100000000000)+1\n Wage='Wage'+str(n)\n globals()[Wage] = (((int(input(\"Wage level (1-4) : \")))-1)/10)+1\n CWage='CWage'+str(n)\n globals()[CWage] = (((int(input(\"Conscript Wage level (1-4) : \")))-1)/4)+1\n Tired='Tired'+str(n)\n globals()[Tired] = (1-(int(input(\"Recent Battles (one year) : \"))/20))\n Morale='Morale'+str(n)\n Mor = (10 - (int(input(\"Recent Battles lost (one year) : \"))))+(int(input(\"Recent Battles won (one year) : \")))\n if Mor > 10 :\n Mor = 10\n if Mor < 1 :\n Mor = 1\n else:\n Mor = Mor\n globals()[Morale] = 1+((-5+Mor)/20)\n \n if typ==1:\n\n Terrain='Terrain'+str(n)\n globals()[Terrain] = 1+((int(input(\"Terrain Knowledge (out of 5) : \"))-3)/20)\n Climate='Climate'+str(n)\n globals()[Climate] = 0.25+(float(input(\"Climate malus : \")))\n trench = 'trench'+str(n)\n globals()[trench] = (int(input(\"Entrenchement? [0] : no [1]: yes : \")))\n if globals()[trench]==1:\n Entrench='Entrench'+str(n)\n globals()[Entrench] = 1+((int(input(\"Entrenchement level : \")))**2)/30\n if globals()[trench]==0:\n Entrench='Entrench'+str(n)\n globals()[Entrench] = 1\n hill=int(input(\"Elevation advantage? [0] : no [1]: yes : \"))\n river=int(input(\"Defending a river? [0] : no [1]: yes : \"))\n city=int(input(\"Defending a city? [0] : no [1]: yes : \"))\n landing=int(input(\"Disembarkment ? [0] : no [1]: yes : \"))\n Tadv = 'Tadv'+str(n)\n globals()[Tadv]=1+(hill+river+city-landing)/2\n Supply='Supply'+str(n)\n globals()[Supply] = 1-(int(input(\"Supply line cut ? [0]:no [1]:yes\"))/3)\n\n else :\n\n Terrain='Terrain'+str(n)\n globals()[Terrain] = 1\n Climate='Climate'+str(n)\n globals()[Climate] = 1\n Entrench = 'Entrench'+str(n)\n globals()[Entrench] = 1\n Tadv = 'Tadv'+str(n)\n globals()[Tadv] = 1\n Supply='Supply'+str(n)\n globals()[Supply] = 1\n \n Luck = 'Luck'+str(n)\n globals()[Luck] = (random.randint(85, 112))/100\n GenDef = 'GenDef'+str(n)\n globals()[GenDef] = int(input(\"General's defense skills : \"))\n GenOff = 'GenOff'+str(n)\n globals()[GenOff] = int(input(\"General's attack skills : \"))\n TacticOff = 'TacticOff'+str(n)\n globals()[TacticOff] = float(input(\"Offensive Tactic bonus : \"))*(1+(globals()[GenOff])/20)\n TacticDef = 'TacticDef'+str(n)\n globals()[TacticDef] = float(input(\"Defensive Tactic bonus : \"))*(1+(globals()[GenDef])/20)\n Multi = 'Multi'+str(n) \n globals()[Multi] = globals()[Supply]*globals()[Rese]*globals()[Luck]*globals()[Climate]*globals()[Terrain]*globals()[Morale]*globals()[Tired]*globals()[Part]*globals()[TacticOff]*globals()[TacticDef]\n scoreteam=0\n if typ==1:\n scoreteam= score(1,globals()[Tadv],globals()[Entrench],globals()[Wage],globals()[CWage],globals()[Multi],globals()[Inf],globals()[Tanks],globals()[AFV],globals()[AAA],globals()[FA],globals()[Fighter],globals()[Bomber],globals()[CInf],globals()[CTanks],globals()[CAFV],globals()[CAAA],globals()[CFA],globals()[CFighter],globals()[CBomber])\n if typ==2:\n scoreteam= score(2,1,1,globals()[Wage],globals()[CWage],globals()[Multi],globals()[BattleS],globals()[Destroyer],globals()[Cruisers],globals()[Uboat],globals()[TroopS],globals()[Fighter],globals()[Bomber],globals()[CBattleS],globals()[CDestroyer],globals()[CCruisers],globals()[CUboat],globals()[CTroopS],globals()[CFighter],globals()[CBomber])\n scoreat = scoreteam[0]+scoreteam[2]\n scoredef = scoreteam[1]+scoreteam[3]\n scoreairat = scoreteam[2]\n scoreairdef = scoreteam[3]\n li.append([nsid,n])\n return [scoreat,scoredef,scoreairat,scoreairdef]\n\ndef casucount(a,b,c,d,e,f,g,i,s,tr,scatW,scatL,scdefW,scdefL,scatWair,scatLair,scdefWair,scdefLair,typ,pop):\n if a==Inf or a==CInf :\n am=1\n if a==CInf:\n namea=\"Conscripted Infantrymen\"\n Consa=1.5\n if a==Inf :\n namea=\"Infantrymen\"\n Consa=1\n else :\n am=850\n if a==CBattleS:\n namea=\"Conscript Battleships\"\n Consa=1.5\n if a==BattleS:\n namea=\"Battleships\"\n Consa=1\n \n if b==Tanks or b==CTanks :\n bm=5\n if b==CTanks :\n nameb=\"Conscript Tanks\"\n Consb=1.5\n if b==Tanks :\n nameb=\"Tanks\"\n Consb=1\n else :\n bm=450\n if b==CDestroyer:\n nameb=\"Conscript Destroyers\"\n Consb=1.5\n if b==Destroyer :\n nameb=\"Destroyers\"\n Consb=2\n \n if c==AFV or c==CAFV :\n cm=4\n if c==CAFV:\n namec=\"Conscript AFVs\"\n Consc=1.5\n if c==AFV :\n namec=\"AFVs\"\n Consc=1\n else :\n cm=600\n if c==CCruisers:\n namec=\"Conscript Cruisers\"\n Consc=1.5\n if c==Cruisers:\n namec=\"Cruisers\"\n Consc=1\n \n if d==AAA or d==CAAA:\n dm=3\n if d==CAAA:\n named=\"Conscript AAA cannons\"\n Consd=1.5\n if d==AAA :\n named=\"AAA cannons\"\n Consd=1\n else :\n dm=50\n if d==CUboat :\n named=\"Conscript Uboats\"\n Consd=3\n if d==Uboat :\n named=\"Uboats\"\n Consd=2\n \n if e==FA or e==CFA :\n em=3\n if e==CFA:\n namee=\"Conscript FA cannons\"\n Conse=1.5\n if e==FA :\n namee=\"FA cannons\"\n Conse=1\n else :\n em=6+(globals()[tr])\n if e==CTroopS:\n namee=\"Conscript Troopships\"\n Conse=1.5\n if e==TroopS :\n namee=\"Troopships\"\n Conse=1\n\n if f==CFighter:\n namef=\"Conscript Fighters\"\n Consf=3\n if f==Fighter:\n namef=\"Fighters\"\n Consf=2\n\n if g==CBomber:\n nameg=\"Conscript Bombers\"\n Consg=3\n if g==Bomber:\n nameg=\"Bombers\"\n Consg=2\n \n \n \n print(\"------------------------------------------------------------------------\")\n casualties1=[0,0]\n teamname='Team'+str(Listside[i][1])\n \n print(str(globals()[teamname]),\"'s\",namea,\" remaining / wounded(damaged if battleship) / dead(destroyed if battleship):\",end=' ')\n print(casualties(globals()[a],scatW,scatL,scdefW,scdefL,s,casualties1,sidenat1,am,Consa,typ,0))\n \n print(str(globals()[teamname]),\"'s\",nameb,\" remaining / damaged / destroyed:\",end=' ')\n print(casualties(globals()[b],scatW,scatL,scdefW,scdefL,s,casualties1,sidenat1,bm,Consb,typ,0))\n \n print(str(globals()[teamname]),\"'s\",namec,\" remaining / damaged / destroyed:\",end=' ')\n print(casualties(globals()[c],scatW,scatL,scdefW,scdefL,s,casualties1,sidenat1,cm,Consc,typ,0))\n \n print(str(globals()[teamname]),\"'s\",named,\" remaining / damaged / destroyed:\",end=' ')\n print(casualties(globals()[d],scatW,scatL,scdefW,scdefL,s,casualties1,sidenat1,dm,Consd,typ,0))\n \n print(str(globals()[teamname]),\"'s\",namee,\" remaining / damaged / destroyed:\",end=' ')\n print(casualties(globals()[e],scatW,scatL,scdefW,scdefL,s,casualties1,sidenat1,em,Conse,typ,0))\n\n if (s=='winner' and scdefWair!=0 and scatLair==0) or (s=='loser' and scdefLair!=0 and scatWair==0):\n \n print(str(globals()[teamname]),\"'s\",namef,\" remaining / damaged / destroyed:\",end=' ')\n print(globals()[f],'/ 0 / 0')\n print()\n \n print(str(globals()[teamname]),\"'s\",nameg,\" remaining / damaged / destroyed:\",end=' ')\n print(globals()[g],'/ 0 /0')\n print()\n \n if (s=='winner' and scdefWair!=0 and scatLair!=0) or (s=='loser' and scdefLair!=0 and scatWair!=0) :\n \n print(str(globals()[teamname]),\"'s\",namef,\" remaining / damaged / destroyed:\",end=' ')\n print(casualties(globals()[f],scatWair,scatLair,scdefWair,scdefLair,s,casualties1,sidenat1,1,Consf,1,1))\n \n print(str(globals()[teamname]),\"'s\",nameg,\" remaining / damaged / destroyed:\",end=' ')\n print(casualties(globals()[g],scatWair,scatLair,scdefWair,scdefLair,s,casualties1,sidenat1,3,Consg,1,1))\n \n print(\"Casualties (wounded/dead):\",casualties1)\n pop=round(pop*(((casualties1[0]+casualties1[1])/(pop+1))/10),0)\n print(\"------------------------------------------------------------------------\")\n return (pop)\n \nListside=[]\ntyp=int(input(\"Type of battle : [1]:land, [2]:sea\"))\nSide1=input('Name of the first side :')\nsidenat1=int(input('Nations fighting for this side :'))\nnumber=1\nSiden=1\nsidescoreat1=0\nsidescoreairat1=0\nsidescoreDef1=0\nsidescoreairDef1=0\nfor loop in range(sidenat1):\n teamfi=TEAM(number,sidescoreat1,sidescoreDef1,Siden,Listside,typ)\n number=number+1\n sidescoreat1=sidescoreat1+teamfi[0]\n sidescoreairat1=sidescoreairat1+teamfi[2]\n sidescoreDef1=sidescoreDef1+teamfi[1]\n sidescoreairDef1=sidescoreairDef1+teamfi[3]\nprint()\nSide2=input('Name of the second side :')\nsidenat2=int(input('Nations fighting for this side :'))\nsidescoreat2=0\nsidescoreairat2=0\nsidescoreDef2=0\nsidescoreairDef2=0\nSiden=2\nfor loop in range(sidenat2):\n teamse=TEAM(number,sidescoreat2,sidescoreDef2,Siden,Listside,typ)\n number=number+1\n sidescoreat2=sidescoreat2+teamse[0]\n sidescoreairat2=sidescoreairat2+teamse[2]\n sidescoreDef2=sidescoreDef2+teamse[1]\n sidescoreairDef2=sidescoreairDef2+teamse[3]\npopulationcity=int(input('nearby population'))/6000\nScoreside1 = sidescoreDef2-sidescoreat1\nScoreside2 = sidescoreDef1-sidescoreat2\n\ndef who_knows_what_this_even_does(side, win, loss):\n global populationcity\n global Inf\n global CInf\n global Tanks\n global CTanks\n global AFV\n global CAFV\n global AAA\n global CAAA\n global FA\n global CFA\n global Fighter\n global CFighter\n global Bomber\n global CBomber\n global BattleS\n global CBattleS\n print()\n print(str(side),\" won the battle!\")\n Listside.sort()\n for i in range (0,number-1):\n if Listside[i][0] == win:\n Inf='Inf'+str(Listside[i][1])\n Tanks='Tanks'+str(Listside[i][1])\n AFV='AFV'+str(Listside[i][1])\n AAA='AAA'+str(Listside[i][1])\n FA='FA'+str(Listside[i][1])\n Fighter='Fighter'+str(Listside[i][1])\n Bomber='Bomber'+str(Listside[i][1])\n CInf='CInf'+str(Listside[i][1])\n CTanks='CTanks'+str(Listside[i][1])\n CAFV='CAFV'+str(Listside[i][1])\n CAAA='CAAA'+str(Listside[i][1])\n CFA='CFA'+str(Listside[i][1])\n CFighter='CFighter'+str(Listside[i][1])\n CBomber='CBomber'+str(Listside[i][1])\n if typ==1:\n populationcity=populationcity+casucount(Inf,Tanks,AFV,AAA,FA,Fighter,Bomber,i,\"winner\",0,sidescoreat1,sidescoreat2,sidescoreDef1,sidescoreDef2,sidescoreairat1,sidescoreairat2,sidescoreairDef1,sidescoreairDef2,1,populationcity)\n cons='cons'+str(Listside[i][1])\n if globals()[cons]==1:\n populationcity=populationcity+casucount(CInf,CTanks,CAFV,CAAA,CFA,CFighter,CBomber,i,\"winner\",0,sidescoreat1,sidescoreat2,sidescoreDef1,sidescoreDef2,sidescoreairat1,sidescoreairat2,sidescoreairDef1,sidescoreairDef2,1,populationcity)\n if typ==2:\n tr='tr'+str(Listside[i][1])\n BattleS='BattleS'+str(Listside[i][1])\n Destroyer='Destroyers'+str(Listside[i][1])\n Cruisers='Cruisers'+str(Listside[i][1])\n Uboat='Uboat'+str(Listside[i][1])\n TroopS='TroopS'+str(Listside[i][1])\n CBattleS='BattleS'+str(Listside[i][1])\n CDestroyer='Destroyers'+str(Listside[i][1])\n CCruisers='Cruisers'+str(Listside[i][1])\n CUboat='Uboat'+str(Listside[i][1])\n CTroopS='TroopS'+str(Listside[i][1])\n populationcity=populationcity+casucount(BattleS,Destroyer,Cruisers,Uboat,TroopS,Fighter,Bomber,i,\"winner\",tr,sidescoreat1,sidescoreat2,sidescoreDef1,sidescoreDef2,sidescoreairat1,sidescoreairat2,sidescoreairDef1,sidescoreairDef2,2,populationcity)\n cons='cons'+str(Listside[i][1])\n if globals()[cons]==1:\n populationcity=populationcity+casucount(CBattleS,CDestroyer,CCruisers,CUboat,CTroopS,CFighter,CBomber,i,\"winner\",tr,sidescoreat1,sidescoreat2,sidescoreDef1,sidescoreDef2,sidescoreairat1,sidescoreairat2,sidescoreairDef1,sidescoreairDef2,2,populationcity)\n if Listside[i][0] == loss:\n Inf='Inf'+str(Listside[i][1])\n Tanks='Tanks'+str(Listside[i][1])\n AFV='AFV'+str(Listside[i][1])\n AAA='AAA'+str(Listside[i][1])\n FA='FA'+str(Listside[i][1])\n Fighter='Fighter'+str(Listside[i][1])\n Bomber='Bomber'+str(Listside[i][1])\n CInf='CInf'+str(Listside[i][1])\n CTanks='CTanks'+str(Listside[i][1])\n CAFV='CAFV'+str(Listside[i][1])\n CAAA='CAAA'+str(Listside[i][1])\n CFA='CFA'+str(Listside[i][1])\n CFighter='CFighter'+str(Listside[i][1])\n CBomber='CBomber'+str(Listside[i][1])\n if typ==1:\n populationcity=populationcity+casucount(Inf,Tanks,AFV,AAA,FA,Fighter,Bomber,i,\"loser\",0,sidescoreat1,sidescoreat2,sidescoreDef1,sidescoreDef2,sidescoreairat1,sidescoreairat2,sidescoreairDef1,sidescoreairDef2,1,populationcity)\n cons='cons'+str(Listside[i][1])\n if globals()[cons]==1:\n populationcity=populationcity+casucount(CInf,CTanks,CAFV,CAAA,CFA,CFighter,CBomber,i,\"loser\",0,sidescoreat1,sidescoreat2,sidescoreDef1,sidescoreDef2,sidescoreairat1,sidescoreairat2,sidescoreairDef1,sidescoreairDef2,1,populationcity)\n if typ==2:\n tr='tr'+str(Listside[i][1])\n BattleS='BattleS'+str(Listside[i][1])\n Destroyer='Destroyers'+str(Listside[i][1])\n Cruisers='Cruisers'+str(Listside[i][1])\n Uboat='Uboat'+str(Listside[i][1])\n TroopS='TroopS'+str(Listside[i][1])\n CBattleS='BattleS'+str(Listside[i][1])\n CDestroyer='Destroyers'+str(Listside[i][1])\n CCruisers='Cruisers'+str(Listside[i][1])\n CUboat='Uboat'+str(Listside[i][1])\n CTroopS='TroopS'+str(Listside[i][1])\n populationcity=populationcity+casucount(BattleS,Destroyer,Cruisers,Uboat,TroopS,Fighter,Bomber,i,\"loser\",tr,sidescoreat1,sidescoreat2,sidescoreDef1,sidescoreDef2,sidescoreairat1,sidescoreairat2,sidescoreairDef1,sidescoreairDef2,2,populationcity)\n cons='cons'+str(Listside[i][1])\n if globals()[cons]==1:\n populationcity=populationcity+casucount(CBattleS,CDestroyer,CCruisers,CUboat,CTroopS,CFighter,CBomber,i,\"loser\",tr,sidescoreat1,sidescoreat2,sidescoreDef1,sidescoreDef2,sidescoreairat1,sidescoreairat2,sidescoreairDef1,sidescoreairDef2,2,populationcity)\n \n populationcity=round(populationcity,0)\n print('Civil casualties:',populationcity)\n\n \nif Scoreside1 0:\n content = content + '该船有位置了!'\n sendemail(content)\n else:\n content = time_stamp + ' ' + content + ' 该船没有位置'\n print(content)\n except requests.exceptions.Timeout as e:\n print('请求超时:' + str(e.message))\n except requests.exceptions.HTTPError as e:\n print('http请求错误:' + str(e.message))\n\n\nif __name__ == '__main__':\n requests_info()\n","sub_path":"weizhoudao_ticket.py","file_name":"weizhoudao_ticket.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"288343227","text":"import subprocess\nimport logging\nimport requests\nimport json\nimport arrow\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\nclass KubeLog(object):\n \"\"\"\n Wrapper for kubernetes\n \"\"\"\n\n def __init__(self, service, namespace, token):\n self.service = service\n self.namespace = namespace\n self.token = token\n\n def get_replicas(self):\n \"\"\"Get the repilca names from namespace.\n\n Return a List containing the replicas names\n \"\"\"\n logger.warning(\"get_replicas\")\n cmd = (f'kubectl get pods -n {self.namespace} '\n f'| grep {self.service} '\n '| cut -d \" \" -f1')\n names = subprocess.check_output(cmd, shell=True)\n logger.warning(cmd)\n return names.decode().split()\n\n def get_replicas_logs(self, replica):\n \"\"\"Return Logs of a specific replica\"\"\"\n cmd = f'kubectl logs -n {self.namespace} {replica}'\n logs = subprocess.check_output(cmd, shell=True)\n logger.warning(\"Done with logs\")\n return logs.decode()\n\n def post_in_gist(self, logs, replica):\n now = arrow.now()\n now = now.timestamp\n title = f'{self.namespace}-{replica}-{now}.log'\n url = \"https://api.github.com/gists\"\n headers = {'authorization': f'Basic {self.token}'}\n payload = {\n \"description\": \"the description for this gist\",\n \"public\": False,\n \"files\": {\n title: {\n \"content\": logs\n }\n }\n }\n logger.warning(\"Posting in gist\")\n r = requests.post(url, data=json.dumps(payload), headers=headers)\n return r.json()\n","sub_path":"external/kubelogs.py","file_name":"kubelogs.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"530937917","text":"# /usr/bin/env python\n# -*- coding:utf-8 -*-\n\n# @Time : 2019/2/11 14:44\n# @Author : lemon\n\nimport json\n\n\ndef f1():\n '''\n 对python对象进行操作\n '''\n\n # json.dumps\n # 将 Python 对象编码成 JSON 字符串\n\n p_list = [\n {'lemon':True,'apple':6},\n {'pear':6,'banana':False}\n ]\n\n p_dict = {'python':1,'Java':2,'Hadoop':None}\n\n json_list = json.dumps(p_list)\n json_dict = json.dumps(p_dict)\n\n\n\n # json.loads\n # 将 已编码的 JSON 字符串解码为 Python 对象\n\n list1 = json.loads(json_list)\n dict1 = json.loads(json_dict)\n\n pass\n\n\ndef f2():\n '''\n 文件的读写\n '''\n\n # 写入JSON文件\n p_dict = '{\"python\": 1, \"Java\": 2, \"Hadoop\":null,\"lemon\":true,\"banana\":false}'\n\n with open('files/json_test.json','w',encoding='utf-8') as f:\n json.dump(p_dict,f)\n\n\n\n # 读取JSON文件\n\n with open('files/json_test.json','r',encoding='utf-8') as f:\n data = json.load(f)\n data1 = json.loads(data)\n print(data)\n print(data1)\n\n\n\n\n\nif __name__ == '__main__':\n f2()\n\n","sub_path":"Scattered/python/curriculum/python_2/第十一章/json_demo.py","file_name":"json_demo.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"319263344","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport codecs\nimport os\nimport shutil\nimport tempfile\nimport unittest\nimport uuid\n\nimport six\n\nfrom conans.client.cmd.export import _replace_scm_data_in_conanfile\nfrom conans.test.utils.tools import try_remove_readonly\nfrom conans.util.files import load\n\n\nclass ASTReplacementTest(unittest.TestCase):\n scm_data = {'type': 'git',\n 'url': 'this-is-the-url',\n 'revision': '42'}\n\n conanfile = six.u(\"\"\"{header}\nfrom conans import ConanFile\n\nclass LibConan(ConanFile):\n name = \"Lib\"\n author = \"{author}\"\n scm = {{\"type\": \"git\",\n \"url\": \"auto\",\n \"revision\": \"auto\"}}\n \"\"\")\n\n def run(self, *args, **kwargs):\n self._tmp_folder = tempfile.mkdtemp(suffix='_conans')\n try:\n super(ASTReplacementTest, self).run(*args, **kwargs)\n finally:\n shutil.rmtree(self._tmp_folder, ignore_errors=False, onerror=try_remove_readonly)\n\n def _get_conanfile(self, header='', author=\"jgsogo\", encoding=\"ascii\"):\n tmp = os.path.join(self._tmp_folder, str(uuid.uuid4()))\n with codecs.open(tmp, 'w', encoding=encoding) as f:\n f.write(self.conanfile.format(header=header, author=author))\n return tmp\n\n def _check_result(self, conanfile):\n content = load(conanfile)\n\n self.assertEqual(content.count(self.scm_data['url']), 1)\n self.assertEqual(content.count(self.scm_data['revision']), 1)\n self.assertIn(self.scm_data['url'], content)\n self.assertIn(self.scm_data['revision'], content)\n\n def test_base(self):\n conanfile = self._get_conanfile()\n _replace_scm_data_in_conanfile(conanfile, self.scm_data)\n self._check_result(conanfile)\n\n def test_author_non_ascii(self):\n conanfile = self._get_conanfile(author=six.u(\"¡ÑÁí!\"), encoding='utf-8')\n _replace_scm_data_in_conanfile(conanfile, self.scm_data)\n self._check_result(conanfile)\n\n def test_shebang_utf8(self):\n header = \"#!/usr/bin/env python2\\n# -*- coding: utf-8 -*-\"\n conanfile = self._get_conanfile(author=six.u(\"¡Ñandú!\"), header=header, encoding='utf-8')\n _replace_scm_data_in_conanfile(conanfile, self.scm_data)\n self._check_result(conanfile)\n\n def test_shebang_ascii(self):\n header = \"#!/usr/bin/env python3\\n# -*- coding: utf-8 -*-\"\n conanfile = self._get_conanfile(author=\"jgsogo\", header=header, encoding='ascii')\n _replace_scm_data_in_conanfile(conanfile, self.scm_data)\n self._check_result(conanfile)\n\n def test_shebang_several(self):\n header = \"#!/usr/bin/env python2\\n# -*- coding: utf-8 -*-\\n# -*- coding: utf-8 -*-\"\n conanfile = self._get_conanfile(author=six.u(\"¡Ñandú!\"), header=header, encoding='utf-8')\n _replace_scm_data_in_conanfile(conanfile, self.scm_data)\n self._check_result(conanfile)","sub_path":"conans/test/unittests/client/cmd/ast_replacement_scm_test.py","file_name":"ast_replacement_scm_test.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"491967019","text":"from _Helper import *\n\n# \n# Given an array of citations(each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: \"A scientist has index h if h of his/her N papers have at least h citations each, and the other N - h papers have no more than h citations each.\" For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. Note: If there are several possible values for h, the maximum one is taken as the h-index.\n# \n\n# \n# TIME: O(N)\n# SPACE: O(N)\n# \n\n# \n# Use a GREATER array to store counts of each index 0~N\n# Note the definition, other N-h <= h, not <. And the h-index can be a value not existed in the given array\n# \n\n# \n# Medium\n# \n\n\n# \nclass Solution(object):\n def hIndex(self, citations):\n \"\"\"\n :type citations: List[int]\n :rtype: int\n \"\"\"\n n = len(citations)\n GreaterCounts = [0] * (n + 1)\n for ci in citations:\n if ci > n:\n GreaterCounts[n] += 1\n else:\n GreaterCounts[ci] += 1\n for i in range(n, 0, -1):\n if GreaterCounts[i] >= i:\n return i\n GreaterCounts[i - 1] += GreaterCounts[i]\n return 0\n\n\n# \n\n# \nsolution = Solution()\nInput = [0]\nexpected = 0\nactual = solution.hIndex(Input)\nAreEqual(expected, actual, Input)\n# another pair\nInput = [3, 0, 6, 1, 5]\nexpected = 3\nactual = solution.hIndex(Input)\nAreEqual(expected, actual, Input)\n# another pair\nInput = [3, 4, 6, 1, 5]\nexpected = 3\nactual = solution.hIndex(Input)\nAreEqual(expected, actual, Input)\n# another pair\nInput = [2, 4, 6, 1, 5]\nexpected = 3\nactual = solution.hIndex(Input)\nAreEqual(expected, actual, Input)\n# ","sub_path":"274_H_Index.py","file_name":"274_H_Index.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"506818853","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\nimport re\nimport socket\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\n\n\nlogfile_name = 'dnsmasq.log'\nblacklist = 'blacklist.conf'\n\n\ndef sort_domains_by_fqn(domain_list, reverse=False):\n# \treverse the order of the qualified name\n\thosts = ['.'.join(host.split('.')[::-1]) for host in domain_list]\n\thosts.sort(reverse=reverse)\n\thosts = ['.'.join(host.split('.')[::-1]) for host in hosts]\n\treturn hosts\n\t\n\t\n\n# Logfile format:\n# \t\tdnsmasq: query[A] self.events.data.microsoft.com from 192.168.1.3\n# \t\tdnsmasq: config self.events.data.microsoft.com is 0.0.0.0\n# \t\tdnsmasq: query[A] pubads.g.doubleclick.net from 192.168.1.3\n\n\nquery_counts = {}\ncached_counts = {}\nblocked_counts = {}\nhosts_counts = {}\nreplies = {}\nhosts = {}\n\n# This is inexact as it allows illegal addresses, but \n# is sufficient for this case\nip_regex = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')\n\n\n\n\nwith open(logfile_name) as logfile:\n\tlast_reply_host = last_config_host = last_hosts_host = None\n\tfor line in logfile:\n\t\tif line.startswith('dnsmasq:'):\n\t\t\tfields = line.strip().lower().split()\n\t\t\tif len(fields) == 5:\n\t\t\t\tdnsmasq, action, host, direction, address = fields\n\t\t\t\tif action.startswith('query'):\n\t\t\t\t\tquery_counts[host] = query_counts.get(host, 0) + 1\n\t\t\t\telif (action == 'cached') and (address[0].isnumeric()):\n\t\t\t\t\tcached_counts[host] = query_counts.get(host, 0) + 1\n\t\t\t\telif action == 'reply':\n\t\t\t\t\t# A reply can contain multiple addresses\n\t\t\t\t\t# keep a track of last host and only count one per request\n\t\t\t\t\tif host != last_reply_host:\n\t\t\t\t\t\tlast_reply_host = host\n\t\t\t\t\t\t# Ignore ipv6\n\t\t\t\t\t\tif (':' not in host) and not ip_regex.match(host):\n\t\t\t\t\t\t\t# Ensure that it's an address and not a tag\n\t\t\t\t\t\t\tif address[0].isnumeric():\n\t\t\t\t\t\t\t\treply_addresses = replies.get(host, set())\n\t\t\t\t\t\t\t\treply_addresses.add(address)\n\t\t\t\t\t\t\t\treplies[host] = reply_addresses\n\t\t\t\t\t\t\n\t\t\t\telif action == 'config':\n\t\t\t\t\t# Only count one for multiple entries\n\t\t\t\t\tif host != last_config_host:\n\t\t\t\t\t\tlast_config_host = host\n\t\t\t\t\t\tif address in ('nodata-ipv4', '127.0.0.1', '0.0.0.0', '::'):\n\t\t\t\t\t\t\tblocked_counts[host] = blocked_counts.get(host, 0) + 1\n\t\t\t\t\n\t\t\t\telif action.startswith('/usr/local/etc/') and address[0].isnumeric():\n\t\t\t\t\t# Count one for multiple entries\n\t\t\t\t\tif host != last_hosts_host:\n\t\t\t\t\t\tlast_hosts_host = host\n\t\t\t\t\t\thosts_counts[host] = hosts_counts.get(host, 0) + 1\n\t\t\t\t\t\n\t\t\t\t\t\n# Create dictionary of hosts to addresses from hosts file\nwith open('hosts') as h:\n\tlinenum = 0\n\tfor line in h:\n\t\tlinenum += 1\n\t\tline = line.strip()\n\t\tif (len(line) > 10) and (line[0].isnumeric() or line[0] == ':'):\n\t\t\taddress, host = line.split()\n\t\t\thost_addresses = hosts.get(host, set())\n\t\t\thost_addresses.add(address)\n\t\t\thosts[host] = host_addresses\n\t\t\t\n\n# Merge data from hosts and replies\nnon_blocked_hosts = sort_domains_by_fqn(replies.keys())\nblocked_hosts = set()\n\nwith open('hosts', 'w') as h:\n\tfor host in non_blocked_hosts:\n\t\n\t\t# Ensure that the host is not now blocked (by change in blacklists)\n\t\tip_address = socket.getaddrinfo(host, 0)[-1][-1][0]\n\t\tif ip_address not in ['0.0.0.0', '::']:\n\t\t\thost_addresses = hosts.get(host, set())\n\t\t\n\t\t\t# merge with set union of hosts and replies\n\t\t\thost_addresses |= replies[host]\n\t\t\n\t\t\t# Write out hosts file, one ip address, one host per line\n\t\t\tfor address in host_addresses:\n\t\t\t\th.write(f'{address.ljust(30)} {host}\\n')\n\t\t\n\t\t# If null ip address we're blocked, don't save to hosts\n\t\t# Only write out each host once (not for every address)\n\t\telif host not in blocked_hosts:\n\t\t\tblocked_hosts.add(host)\n\t\t\tprint(f'Not putting {host} in to hosts as in block list')\n\t\t\t\nprint(\"Cleaned up hosts file\")\n\t\t\t\t\n# check for duplicates in conf files\nhere = Path('.')\nlongest_domain_path = 0\npaths = {}\nfor conffile in here.glob('*.conf'):\n\tlines = []\n\twith open(conffile, 'r') as conf:\n\t\tdomains = set()\n\t\tlinenum = 0\n\t\tfor line in conf:\n\t\t\tlinenum += 1\n\t\t\tif line.startswith('address'):\n\t\t\t\t_, domain, __ = line.split('/')\n\t\t\t\tif domain in domains:\n\t\t\t\t\tprint(f'{conffile}: removed duplicate domain {domain} at line {linenum}')\n\t\t\t\telse:\n\t\t\t\t\tdomains.add(domain)\n\t\t\t\t\tlines.append(line)\n\t\t\t\t\t\n\t\t\t\t# Find longest domain Path\n\t\t\t\tlongest_domain_path = max(longest_domain_path, len(domain.split('.')))\n\t\t\t\tpath_len = len(domain.split('.'))\n\t\t\t\tpath_entry = paths.get(path_len, [])\n\t\t\t\tpath_entry.append(domain)\n\t\t\t\tpaths[path_len] = path_entry\n\t\t\t\t\n\t\t\telse:\n\t\t\t\t# Keep comments and blank lines\n\t\t\t\tlines.append(line)\n\t\t\n\t# write out unique lines\n\twith open(conffile, 'w') as conf:\n\t\tconf.seek(0)\n\t\tfor line in lines:\n\t\t\tconf.write(line)\n\t\t\t\n# print(f'{longest_domain_path=}')\n# for k in sorted(paths):\n# \tprint(k)\n# \tfor domain in paths[k]:\n# \t\tprint(f'\\t{domain}')\n# \n\n# Check for sub-domains covered by higher domains\nsorted_paths = sorted(paths)\nfor i, k in enumerate(sorted_paths):\n\tif k != sorted_paths[-1]:\n\t\tfor domain in paths[k]:\n\t\t\tfor domain_len in sorted_paths[i+1:]:\n\t\t\t\tfor sub_domain in paths[domain_len]:\n\t\t\t\t\tif sub_domain.split('.')[-k:] == domain.split('.'):\n\t\t\t\t\t\tprint(f'Redundant {sub_domain} with {domain}')\n\n# check for duplicate address in hosts\nwith open('hosts') as h:\n\taddresses = {}\n\tdistinct_hosts = set()\n\ttotal_addresses = 0\n\tfor line in h:\n\t\tif line[0].isnumeric() or (line[0] == ':'):\n\t\t\ttotal_addresses += 1\n\t\t\taddress, host = line.strip().split()\n\t\t\thosts = addresses.get(address, [])\n\t\t\thosts.append(host)\n\t\t\taddresses[address] = hosts\n\t\t\tdistinct_hosts.add(host)\n\n\n\tdistinct_address = len(addresses.keys())\n\ttotal_hosts = 0\n\tfor address in addresses:\n\t\ttotal_hosts += len(addresses[address])\n\t\t\n\tprint(f'hosts total addresses: {total_addresses}')\n\tprint(f'hosts distinct addresses: {distinct_address}')\n\tprint(f'hosts distinct hosts: {len(distinct_hosts)}')\n\nwith open('allowed_hosts.txt', 'w') as f:\n\tfor host in non_blocked_hosts:\n\t\tf.write(f'{host}\\n')\n\t\t\t\nwith open('hosts_hosts.txt', 'w') as f:\n\tfor host in hosts:\n\t\tf.write(f'{host}\\n')\n\t\t\t\n\n\n\n#Plot some stats\n# top_count = 15\n# query_counts = {k: v for k, v in sorted(query_counts.items(), key=lambda item: item[1], reverse=True)}\n# top_sites = list(query_counts.keys())[:top_count]\n# top_counts = list(query_counts.values())[:top_count]\n# fig, ax = plt.subplots(figsize=(8,5))\n# ax.bar(top_sites, top_counts)\n# plt.xticks(rotation=90)\n# fig.subplots_adjust(bottom=0.5)\n# plt.title('Top queries')\n# plt.show()\n# plt.close()\n# \n# blocked_counts = {k: v for k, v in sorted(blocked_counts.items(), key=lambda item: item[1], reverse=True)}\n# top_sites = list(blocked_counts.keys())[:top_count]\n# top_counts = list(blocked_counts.values())[:top_count]\n# fig, ax = plt.subplots(figsize=(8,5))\n# ax.bar(top_sites, top_counts)\n# plt.xticks(rotation=90)\n# fig.subplots_adjust(bottom=0.5)\n# plt.title('Top blocks')\n# plt.show()\n# plt.close()\n# \n# cached_counts = {k: v for k, v in sorted(cached_counts.items(), key=lambda item: item[1], reverse=True)}\n# top_sites = list(cached_counts.keys())[:top_count]\n# top_counts = list(cached_counts.values())[:top_count]\n# fig, ax = plt.subplots(figsize=(8,5))\n# ax.bar(top_sites, top_counts)\n# plt.xticks(rotation=90)\n# fig.subplots_adjust(bottom=0.5)\n# plt.title('Top cache hits')\n# plt.show()\n# plt.close()\n# \n# hosts_counts = {k: v for k, v in sorted(hosts_counts.items(), key=lambda item: item[1], reverse=True)}\n# top_sites = list(hosts_counts.keys())[:top_count]\n# top_counts = list(hosts_counts.values())[:top_count]\n# fig, ax = plt.subplots(figsize=(8,5))\n# ax.bar(top_sites, top_counts)\n# plt.xticks(rotation=90)\n# fig.subplots_adjust(bottom=0.5)\n# plt.title('Top hosts hits')\n# plt.show()\n# plt.close()\n\n\n\t\t\n\t\n","sub_path":"update_conf_files.py","file_name":"update_conf_files.py","file_ext":"py","file_size_in_byte":7613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"310595050","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport redis\n\n\"\"\"\n使用redis操作,未使用连接池\nredis提供两个类Redis和StrictRedis用于实现Redis的命令,StrictRedis用于实现大部分官方的命令,\n并使用官方的语法和命令,Redis是StrictRedis的子类,用于向后兼容旧版本的redis-py。\n\nredis连接实例是线程安全的,可以直接将redis连接实例设置为一个全局变量,直接使用。\n如果需要另一个Redis实例(or Redis数据库)时,就需要重新创建redis连接实例来获取一个新的连接。\n同理,python的redis没有实现select命令。\n\n\"\"\"\nr = redis.Redis(host='localhost', port=6379, decode_responses=True)\nr.set('hello', 'niange')\nprint(r['hello'])\nprint(r.get('hello'))\nprint(type(r.get('hello')))\n\nuids = ['hello', 'hello1', 'hello2', 'nima']\nvalues_list = r.mget(uids)\nvalues = {}\nfor i in xrange(len(uids)):\n\tvalue = values_list[i]\n\tif value is not None:\n\t\tvalues[uids[i]] = value\nprint(values)\n","sub_path":"python_redis/python_redis_01.py","file_name":"python_redis_01.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"360580966","text":"\"\"\"\nSimple Barrier example\n\"\"\"\nimport threading\nimport time\n\n\ndef task_one(barrier):\n print(\"Task A\")\n print(\"Waiting for other threads to start & sync up\")\n barrier.wait()\n for x in range(1, 10):\n print(\"A--\", x)\n time.sleep(1)\n\n\ndef task_two(barrier):\n print(\"Task B\")\n time.sleep(3)\n barrier.wait()\n for x in range(1, 10):\n print(\"B--\", x)\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n barrier = threading.Barrier(2, timeout=10)\n t1 = threading.Thread(target=task_one, args=(barrier,))\n t2 = threading.Thread(target=task_two, args=(barrier,))\n\n t1.start()\n t2.start()\n\n t1.join()\n t2.join()\n","sub_path":"code/other/example14.py","file_name":"example14.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"492837537","text":"from sys import argv\nfrom Data import Data\nfrom Statistics import Statistics\nfrom AlgorithmRunner import AlgorithmRunner\nimport numpy as np\nimport os\nfrom CompetitiveData import CompetitiveData\n\n\"\"\"\nLoads data from given csv\n:param input_path: path to csv file\n:return:data - object of the data file\n data_features - the data after preprocess\n\"\"\"\ndef load_data():\n if len(argv) < 2:\n print('Not enough arguments provided. Please provide the path to the input file')\n exit(1)\n input_path = argv[1]\n\n if not os.path.exists(input_path):\n print('Input file does not exist')\n exit(1)\n data = Data(input_path)\n data_features = data.preprocess()\n return data, data_features\n\n\"\"\"\n calculates stastistics parameters for the required learning algorithm\n :param data - object of the data file\n data_features - the data after preprocess\n\"\"\"\ndef question_1(data,data_features):\n print(\"Question 1:\")\n knn_runner = AlgorithmRunner(\"KNN\")\n rocchio_runner = AlgorithmRunner(\"Rocchio\")\n stats = Statistics()\n\n #KNN calculations\n kfoldKNN = data.split_to_k_folds()\n sumPrecisionKNN = 0\n sumRecallKNN = 0\n sumAccuracyKNN = 0\n\n for trainKNN, testKNN in kfoldKNN:\n knn_runner.fit(data_features.loc[:, data_features.columns != 'imdb_score'].iloc[trainKNN], data_features['imdb_score'].iloc[trainKNN])\n pred = knn_runner.algorithm.predict(data_features.loc[:, data_features.columns != 'imdb_score'].iloc[testKNN])\n sumPrecisionKNN = stats.precision(labels = np.array(data_features['imdb_score'].iloc[testKNN]).T,predictions = pred) + sumPrecisionKNN\n sumRecallKNN = stats.recall(labels = np.array(data_features['imdb_score'].iloc[testKNN]),predictions=pred) +sumRecallKNN\n sumAccuracyKNN = stats.accuracy(labels = np.array(data_features['imdb_score'].iloc[testKNN]),predictions=pred) + sumAccuracyKNN\n print(\"KNN classifier: \",sumPrecisionKNN/5,\",\",sumRecallKNN/5, \",\",sumAccuracyKNN/5)\n\n #Rocchio calculations\n kfoldRocciho = data.split_to_k_folds()\n sumPrecisionRocchio = 0\n sumRecallRocchio = 0\n sumAccuracyRocchio = 0\n for trainRocciho, testRocciho in kfoldRocciho:\n rocchio_runner.fit(data_features.loc[:, data_features.columns != 'imdb_score'].iloc[trainRocciho], data_features['imdb_score'].iloc[trainRocciho])\n pred = rocchio_runner.algorithm.predict(data_features.loc[:, data_features.columns != 'imdb_score'].iloc[testRocciho])\n sumPrecisionRocchio = stats.precision(labels = np.array(data_features['imdb_score'].iloc[testRocciho]).T,predictions = pred) + sumPrecisionRocchio\n sumRecallRocchio = stats.recall(labels = np.array(data_features['imdb_score'].iloc[testRocciho]),predictions=pred) +sumRecallRocchio\n sumAccuracyRocchio = stats.accuracy(labels = np.array(data_features['imdb_score'].iloc[testRocciho]),predictions=pred) + sumAccuracyRocchio\n print(\"Rocchio classifier: \",sumPrecisionRocchio/5,\",\",sumRecallRocchio/5, \",\",sumAccuracyRocchio/5)\n print(\" \")\n\n\nif __name__ == '__main__':\n data, data_features = load_data()\n question_1(data,data_features)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"554260908","text":"import track\n\ndef calculate_curve(track, speed):\n curvedtrackdistence = ((track.lower()).count('b')) + ((track.lower()).count('e')) + ((track.lower()).count('n')) + ((track.lower()).count('d'))\n curvedtrackdistence = curvedtrackdistence*0.25\n curvetime = (((curvedtrackdistence/speed)*60)*60)\n return curvedtrackdistence, curvetime\ndef calculate_straight(track, speed):\n straighttrackdistence = ((track.lower()).count('s')) + ((track.lower()).count('r')) + ((track.lower()).count('a')) + ((track.lower()).count('i')) + ((track.lower()).count('g')) + ((track.lower()).count('h')) + ((track.lower()).count('t'))\n straighttrackdistence = straighttrackdistence*0.25\n straighttime = (((straighttrackdistence/speed)*60)*60)\n return straighttrackdistence, straighttime\n \n\ndef speed(averagespeed):\n if (averagespeed < 60):\n return ('Kind of slow.')\n elif (averagespeed >= 60) and (averagespeed < 120):\n return ('Getting there.')\n elif (averagespeed >= 120):\n return ('Wow, quite the car!')\n \n \ntracknumber = input('Select a track between 1 and {:d} => '.format(track.get_number_of_tracks()))\nprint(tracknumber)\nspeedcurve = input('Speed on curved segments (MPH) => ')\nprint(speedcurve)\nspeedstraight = input('Speed on straight segments (MPH) => ')\nprint(speedstraight)\n\nspeedcurve = float(speedcurve)\nspeedstraight = float(speedstraight)\n\ntrack = track.get_track(int(tracknumber))\n\ntimedistencecurve = calculate_curve(track,speedcurve)\ntimedistencesraight = calculate_straight(track,speedstraight)\ntotaltime = timedistencecurve[1] + timedistencesraight[1]\ntotaldistence = timedistencecurve[0] + timedistencesraight[0]\n\naveragespeed = (totaldistence / (totaltime/3600))\n\nspeedtest = speed(averagespeed)\n\nprint()\nprint('Track:')\nprint(track)\nprint('is {1:0.2f} miles long. You raced it in {0:0.2f} seconds at an average speed of {2:0.2f} MPH'.format(totaltime,totaldistence, averagespeed))\nprint(speedtest)\n","sub_path":"HW2/hw2_part2.py","file_name":"hw2_part2.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"482425630","text":"#!/user/bin/env pypy3\nimport sys\nfrom functools import reduce\n\n\ndef fast_input():\n return sys.stdin.readline()[:-1]\n\n\ndef digit_sum(num: int) -> int:\n str_num = str(num)\n return reduce(\n lambda acc, n: acc + int(n),\n list(str_num),\n 0\n )\n\n\ndef solve(n: int, a: int, b: int) -> int:\n num_sum = 0\n for num in range(1, n + 1):\n if a <= digit_sum(num) <= b:\n num_sum += num\n return num_sum\n\n\ndef main():\n [n, a, b] = list(map(int, fast_input().split()))\n result = solve(n, a, b)\n print(result)\n\n\nmain()\n","sub_path":"Python_codes/p03478/s027744094.py","file_name":"s027744094.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"557820099","text":"\r\n\r\nimport unittest\r\nimport os,sys,inspect\r\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\r\nparentdir = os.path.dirname(currentdir)\r\nsys.path.insert(0,parentdir) \r\n\r\nimport BinarySearchTree\r\nimport BinaryTree\r\nimport Calculator\r\nimport BookStore\r\nimport BinarySearchTreeWithDuplication\r\n\r\n\r\nclass BinarySearchTreeTest(unittest.TestCase) :\r\n \r\n def test_binarytree(self) :\r\n points = 0.5\r\n q = BinarySearchTree.BinarySearchTree()\r\n try:\r\n self.assertIsNone(q.find(2))\r\n self.assertAlmostEqual(q.remove(2), False)\r\n except:\r\n pass\r\n finally:\r\n points += 0.5\r\n \r\n try:\r\n q.add(3, \"third\")\r\n q.add(2, \"second\")\r\n q.add(1, \"first\")\r\n self.assertAlmostEqual(q.size(), 3)\r\n self.assertAlmostEqual(q.find(2.5), \"third\")\r\n q.remove(3)\r\n self.assertIsNone(q.find(3))\r\n self.assertAlmostEqual(q.size(), 2)\r\n q.add(3, \"third\")\r\n q.add(5, \"fifth\")\r\n q.add(4, \"fourth\")\r\n \r\n self.assertAlmostEqual(q.size(), 5)\r\n self.assertAlmostEqual(q.find(3.4), \"fourth\")\r\n print(\"In order\")\r\n q.in_order()\r\n print(\"Pre oder\")\r\n q.pre_order()\r\n print(\"Pos order\")\r\n q.pos_order()\r\n print(\"BF Traversal\")\r\n q.bf_traverse()\r\n self.assertAlmostEqual(q.height(), 4)\r\n points += 1\r\n except:\r\n print(\"BinarySearchTreeTest is not correct\")\r\n finally:\r\n \r\n print(f\"BinarySearchTreeTest: {points} Points\")\r\n \r\n def test_calculator(self) :\r\n points = 0.5\r\n s = Calculator.Calculator()\r\n try:\r\n self.assertAlmostEqual(s.evaluate(\"\"), \"\")\r\n except:\r\n print(\"Calculator is not correct\")\r\n finally:\r\n points += 0.5\r\n try:\r\n self.assertAlmostEqual(s.evaluate(\"((a*b)+(c*d))\"), 0)\r\n s.set_variable(\"a\", 1.3)\r\n s.set_variable(\"b\", 2.1)\r\n s.set_variable(\"c\", 2.2)\r\n s.set_variable(\"d\", 3.0)\r\n self.assertAlmostEqual(s.evaluate(\"((a*b)+(c*d))\"), 9.33)\r\n \r\n points += 1\r\n except:\r\n print(\"Calculator is aa not correct\")\r\n finally:\r\n print(f\"Calculator {points} Points\")\r\n \r\n def test_BookStore(self) :\r\n points = 0.5\r\n try:\r\n a = BookStore.BookStore()\r\n self.assertAlmostEqual(a.loadCatalog(\"../books.txt\"), 499813)\r\n points += 0.5\r\n a.addBookByPrefix(\"Tears of the S\")\r\n b = a.removeFromShoppingCart()\r\n self.assertAlmostEqual(b.title, \"Tears of the Sun\")\r\n a.addBookByPrefix(\"World of Po\")\r\n b = a.removeFromShoppingCart()\r\n self.assertAlmostEqual(b.title, \"World of Pop Hits of 70's\")\r\n \r\n points += 1\r\n except:\r\n print(\"BookStore is not correct\")\r\n finally:\r\n print(f\"BookStore: {points} Points\")\r\n\r\n \r\n def test_BinarySearchTreeWithDuplication(self) :\r\n points = 0\r\n a = BinarySearchTreeWithDuplication.BinarySearchTreeWithDuplication()\r\n try:\r\n a = BinarySearchTreeWithDuplication.BinarySearchTreeWithDuplication()\r\n a.add(1, \"a\")\r\n a.add(1, \"b\")\r\n a.add(1, \"c\")\r\n a.add(2, \"d\")\r\n a.add(3, \"e\")\r\n a.add(3, \"z\")\r\n self.assertAlmostEqual(1,1)\r\n self.assertAlmostEqual(a.find(1).__str__(), \"a,b,c\")\r\n self.assertAlmostEqual(a.find(2).__str__(), \"d\") \r\n self.assertAlmostEqual(a.find(3).__str__(), \"e,z\")\r\n points += 2\r\n except:\r\n pass\r\n finally:\r\n print(f\"BinarySearchTreeWithDuplication: {points} Points\")\r\n \r\n ","sub_path":"unit_test/unit_test_lab4.py","file_name":"unit_test_lab4.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"228645337","text":"from __future__ import print_function\nimport requests\nimport argparse\nimport json\nimport time\nimport base64\nimport logging\nfrom logging.config import fileConfig\n\nENDPOINTS = {\n 'auth': '/api/domoweb/auth/login',\n 'app': '/api/library/v1/apps/{}/details',\n 'appstore': '/api/library/v1/apps',\n 'icon': '/api/library/v1/images/v2'\n}\n\n\nclass App(object):\n \"\"\" Appstore App \"\"\"\n\n def __init__(self, **entries):\n \"\"\" Build from JSON \"\"\"\n\n self.__dict__.update(entries)\n self.images = self.appImageDependencies\n self.tags = self.appTags\n\n def update_tags(self, tags):\n \"\"\" Update tags from CSV list \"\"\"\n\n tag_array = [{'tag': x.strip()} for x in tags.split(',')]\n self.tags = tag_array\n\n def update_icons(self, images):\n \"\"\" Update image id references \"\"\"\n\n final_images = []\n for image in self.images:\n if image['type'] in images:\n imageId = images.get(image['type'])\n image['imageId'] = imageId\n image['fullImagePath'] = '/api/library/v1/images/full/{}'\\\n .format(imageId)\n image['base64ImagePath'] = '/api/library/v1/images/full/{}'\\\n .format(imageId)\n image['thumbnailImagePath'] = '/api/library/v1/images/full/{}'\\\n .format(imageId)\n\n final_images.append(image)\n self.images = final_images\n\n def update_description(self, description):\n \"\"\" Update app description \"\"\"\n\n self.description = description\n\n def is_featured(self, state):\n \"\"\" Update Is Featured flag \"\"\"\n\n if state:\n self.isFeatured = True\n self.featuredStart = int(round(time.time() * 1000))\n self.featuredEnd = 4118450400000\n else:\n self.isFeatured = False\n self.featuredStart = None\n self.featuredEnd = None\n\nclass Domo():\n \"\"\" Domo Helper Class \"\"\"\n\n def __init__(self, domain):\n \"\"\" Set domain \"\"\"\n\n self.domain = 'https://{}'.format(domain)\n self.session = requests.Session()\n\n def _build_url(self, var):\n \"\"\" Helper function to build url \"\"\"\n\n return '{}{}'.format(self.domain, ENDPOINTS.get(var))\n\n def login(self, usr, pwd):\n \"\"\" Authenticate \"\"\"\n\n payload = json.dumps({'username': usr, 'password': pwd})\n r = self.session.post(self._build_url('auth'), data=payload)\n\n auth = {'domo-domo-authentication': r.json().get('sid')}\n self.session.headers.update(auth)\n return r.status_code == 200\n\n def get_app(self, app_id):\n \"\"\" Return Appstore App by ID \"\"\"\n\n url = self._build_url('app').format(app_id)\n params = {'includeHistory': False, 'includeTemplates': False}\n r = self.session.get(url, params=params)\n return App(**r.json())\n\n def load_image(self, path, imageType):\n \"\"\" Load Base64 image into Appstore. Return dict of icon ids \"\"\"\n\n with open(path, 'rb') as image_file:\n img = base64.b64encode(image_file.read())\n base = 'data:image/png;base64,{}'.format(img.decode('utf-8'))\n\n params = {'base64EncodedImageDataUri': base, 'imageType': imageType}\n r = self.session.post(self._build_url('icon'), json=params)\n response = r.json()\n\n return dict(map(lambda x: (x['imageType'], x['id']), response))\n\n def update_app(self, app):\n \"\"\" Put update app in Appstore \"\"\"\n\n url = self._build_url('appstore')\n r = self.session.put(url, json=app.__dict__)\n return r.status_code\n\n\ndef build_args():\n \"\"\" Helper function \"\"\"\n\n parser = argparse.ArgumentParser(\"Cobra Commander v2.0.2\")\n parser.add_argument('-u', '--usr', required=True)\n parser.add_argument('-p', '--pwd', required=True)\n parser.add_argument('-d', '--domo', required=True, help=\"Domo Domain\")\n parser.add_argument('-a', '--app', required=True, help=\"App Id\")\n parser.add_argument('-i', '--icon', help=\"App Icon\")\n parser.add_argument('-t', '--tags', help=\"App Tags\")\n parser.add_argument('--desc', help=\"App Description\")\n parser.add_argument('--feature', dest=\"featured\", action=\"store_true\")\n parser.add_argument('--no-feature', dest=\"featured\", action=\"store_false\")\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n \"\"\" Main Script function \"\"\"\n\n fileConfig('log_config.ini')\n logger = logging.getLogger(__name__)\n\n args = build_args()\n domo = Domo(args.domo)\n\n # If successful login\n if domo.login(args.usr, args.pwd):\n app = domo.get_app(args.app)\n logger.info('App {} | App fetched'.format(app.id))\n\n if args.tags:\n logger.info('App {} | Updating tags \"{}\"'.format(app.id, args.tags))\n app.update_tags(args.tags)\n\n if args.icon:\n logger.info('App {} | Updating icon {}'.format(app.id, args.icon))\n images = domo.load_image(args.icon, 'icon')\n logger.debug('App {} | Icon loaded {}'.format(app.id, images))\n app.update_icons(images)\n\n if args.desc:\n logger.info('App {} | Updating description'.format(app.id))\n app.update_description(args.desc.decode('string_escape'))\n\n if 'featured' in args:\n logger.info('App {} | Updating \"is Featured\"'.format(app.id))\n app.is_featured(args.featured)\n\n status = domo.update_app(app)\n if status == 200:\n logger.info('APP {} | SUCCESS'.format(app.id))\n else:\n logger.warn('APP {} | FAILED: {}'.format(app.id, status))\n\n else:\n logger.error('Unauthorized. Check your credentials')\n","sub_path":"cobra_commander.py","file_name":"cobra_commander.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"323788301","text":"#coding:utf-8\r\nimport os\r\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\r\n# del temp files\r\ndef del_temp_files(path):\r\n ls = os.listdir(path)\r\n for i in ls:\r\n c_path = os.path.join(path, i)\r\n if os.path.isdir(c_path):\r\n del_file(c_path)\r\n else:\r\n try:\r\n os.remove(c_path)\r\n except:\r\n print(c_path)\r\ndef split_pdf(infn):\r\n # clear tempfile\r\n del_temp_files(\"temp\")\r\n\r\n # split pdf by pages\r\n pdf_input = PdfFileReader(open(infn, 'rb'))\r\n page_count = pdf_input.getNumPages()\r\n print(\"xxxxxx\",page_count)\r\n # read first-5th as the index\r\n pdf_output = PdfFileWriter()\r\n for i in range(0, 5):\r\n pdf_output.addPage(pdf_input.getPage(i))\r\n pdf_output.write(open(\"temp/%s\"%0 + \"_result.pdf\", \"wb\"))\r\n print('finishindex') \r\n # split pdf by page\r\n for i in range(5, page_count):\r\n pdf_output = PdfFileWriter()\r\n pdf_output.addPage(pdf_input.getPage(i))\r\n pdf_output.write(open(\"temp/%s\"%i + \"_result.pdf\", \"wb\"))\r\n\r\n\r\nif __name__ == '__main__':\r\n pdf_path = 'resource/ccc.pdf'\r\n split_pdf(pdf_path)","sub_path":"kernel/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"140446637","text":"\"\"\"\r\n检验代理可用\r\n\"\"\"\r\n\r\nfrom queue import Queue\r\n\r\nimport time\r\n\r\nfrom ProxyCheck import ProxyCheck\r\nfrom ProxyManager import ProxyManager\r\n\r\n\r\nclass ProxyValidSchedule(ProxyManager, object):\r\n def __init__(self):\r\n ProxyManager.__init__(self)\r\n self.queue = Queue()\r\n self.proxy_item = dict()\r\n\r\n def __validProxy(self, threads=10):\r\n \"\"\"\r\n 验证 useful_proxy 代理\r\n :param threads:\r\n :return:\r\n \"\"\"\r\n thread_list = list()\r\n for index in range(threads):\r\n thread_list.append(ProxyCheck(self.queue, self.proxy_item))\r\n\r\n for thread in thread_list:\r\n thread.start()\r\n\r\n for thread in thread_list:\r\n thread.join()\r\n\r\n\r\n def putQueue(self):\r\n self.db.change_table(self.useful_proxy_queue)\r\n self.proxy_item = self.db.get_all()\r\n for item in self.proxy_item:\r\n self.queue.put(item)\r\n\r\n def main(self):\r\n self.putQueue()\r\n while True:\r\n if not self.queue.empty():\r\n self.__validProxy()\r\n else:\r\n time.sleep(60 * 5)\r\n self.putQueue()\r\n\r\ndef run():\r\n p = ProxyValidSchedule()\r\n p.main()\r\n\r\nif __name__ == '__main__':\r\n p = ProxyValidSchedule()\r\n p.main()","sub_path":"proxyIpSpider/ProxyValidSchedule.py","file_name":"ProxyValidSchedule.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"398667604","text":"import cv2\nimport numpy as np\n\n# To find hsv range of a color\nred = np.uint8([[[0, 0, 255]]])\nres = cv2.cvtColor(red, cv2.COLOR_BGR2HSV)\nprint(res)\n\n# To find flags starting with COLOR_\nflags = [i for i in dir(cv2) if i.startswith('COLOR_')]\nprint(flags)\n\nimg1 = cv2.imread('photo-1557296387-5358ad7997bb.jfif')\nimg2 = cv2.imread('images (2).jfif')\nprint(img1.shape)\nprint(img2.shape)\nimg3 = cv2.resize(img2, None, fx= 1000/183, fy= 1271/275)\nprint(img3.shape)\n#cv2.imshow('img', img3)\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n","sub_path":"extra.py","file_name":"extra.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"210668510","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nfrom numpy import array\nfrom numpy import hstack\nfrom sklearn.metrics import roc_auc_score, confusion_matrix\nfrom torch.nn import functional as F\nimport random \n\nn_features = 24\nn_timesteps = 538\nepoch = 5\nbatch_size = 32\nX = np.load('X2.npy')\ny = np.load('y2.npy')\nr = random.sample(range(len(X)), k = int(.8 * len(X)))\n\n\nclass lstm(nn.Module):\n def __init__(self,n_features,seq_length):\n super(lstm, self).__init__()\n self.n_features = n_features\n self.seq_len = seq_length\n self.n_hidden = 40 # number of hidden states\n self.n_layers = 2# number of LSTM layers (stacked) \n self.l_lstm = torch.nn.LSTM(input_size = n_features, \n hidden_size = self.n_hidden,\n num_layers = self.n_layers, \n batch_first = True, dropout = .3)\n self.W_s1 = nn.Linear(self.n_hidden, 40)\n self.W_s2 = nn.Linear(40, 1)\n self.fc_layer = nn.Linear(self.n_hidden, 20)\n self.label = nn.Linear(20, 2)\n self.drop = nn.Dropout(p=.15)\n \n def init_hidden(self, batch_size):\n # even with batch_first = True this remains same as docs\n hidden_state = torch.zeros(self.n_layers,batch_size,self.n_hidden)\n cell_state = torch.zeros(self.n_layers,batch_size,self.n_hidden)\n self.hidden = (hidden_state, cell_state)\n \n def attention(self, lstm_out):\n print(\"lstm shape: \", lstm_out.shape)\n attn_weight_matrix = self.W_s1(lstm_out)\n attn_weight_matrix = torch.tanh(attn_weight_matrix)\n attn_weight_matrix = self.W_s2(attn_weight_matrix)\n attn_weight_matrix = attn_weight_matrix.permute(0, 2, 1)\n attn_weight_matrix = F.softmax(attn_weight_matrix, dim=2)\n print(\"attn matrix shape: \", attn_weight_matrix.shape)\n return attn_weight_matrix\n \n def forward(self, x): \n batch_size, seq_len, _ = x.size()\n x = self.drop(torch.Tensor(x))\n lstm_out, self.hidden = self.l_lstm(x,self.hidden)\n #lstm_out = lstm_out.permute(1, 0, 2)\n\t\t# output.size() = (batch_size, num_seq, 2*hidden_size)\n\t\t# h_n.size() = (1, batch_size, hidden_size)\n\t\t# c_n.size() = (1, batch_size, hidden_size)\n attn_weight_matrix = self.attention(lstm_out)\n\t\t# attn_weight_matrix.size() = (batch_size, r, num_seq)\n\t\t# output.size() = (batch_size, num_seq, 2*hidden_size)\n hidden_matrix = torch.bmm(attn_weight_matrix, lstm_out)\n print('hidden matrix shape: ', hidden_matrix.shape);\n\t\t# hidden_matrix.size() = (batch_size, r, 2*hidden_size)\n\t\t# Let's now concatenate the hidden_matrix and connect it to the fully connected layer.\n print(\"hidden matrix post: \", hidden_matrix.view(-1, hidden_matrix.size()[1]*hidden_matrix.size()[2]).shape)\n fc_out = self.fc_layer(hidden_matrix.view(-1, hidden_matrix.size()[1]*hidden_matrix.size()[2]))\n print(\"fc_out shape: \", fc_out.shape)\n logits = self.label(fc_out)\n\t\t# logits.size() = (batch_size, output_size)\n #print(\"logits shape: \", logits.shape)\n return logits\n\nmv_net = lstm(n_features,n_timesteps)\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(mv_net.parameters(), lr=1e-2, weight_decay=.0001)\n\ntraindata = X[r] #960\ntrainlabel = y[r]\ntestdata = X[np.delete(np.array(range(len(X))), r)] \ntestlabel = y[np.delete(np.array(range(len(X))), r)]\nmv_net.train()\nfor t in range(epoch):\n for b in range(0,len(traindata),batch_size):\n inpt = traindata[b:b+batch_size,:,:]\n target = trainlabel[b:b+batch_size] \n \n x_batch = torch.tensor(inpt,dtype=torch.float32) \n y_batch = torch.tensor(target,dtype=torch.long)\n \n mv_net.init_hidden(x_batch.size(0))\n output = mv_net(x_batch)\n #if target == [1]:\n #loss = criterion(output.view(-1), y_batch)\n # else:\n loss = criterion(output, y_batch) #.view(-1)\n loss.backward()\n optimizer.step() \n optimizer.zero_grad() \n print('step : ' , t , 'loss : ' , loss.item())\n\n\nguess = torch.tensor([])\nfor b in range(0, len(testdata), batch_size):\n inpt = testdata[b:b+batch_size,:,:]\n x_batch = torch.tensor(inpt,dtype=torch.float32)\n mv_net.init_hidden(x_batch.size(0))\n output = mv_net(x_batch)\n #print(output.shape)\n guess = torch.cat((guess, output.detach()))\nauc = roc_auc_score(testlabel, guess[:,[0]])\n#tn, fp, fn, tp = confusion_matrix(testlabel, guess).ravel()\n","sub_path":"LSTM_atn.py","file_name":"LSTM_atn.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"160605553","text":"import array\n\n# used to initialize sequences\n\n# generating a tuple\nsymbols = '$¢£¥€¤'\ntuple_values = tuple(ord(symbol) for symbol in symbols)\nprint(tuple_values)\n\n# generating an array\narray_values = array.array('I', (ord(symbol) for symbol in symbols))\nprint(array_values)\n\n# generator for cartesian product of shirts ordered by (color, size)\n# one item generated at a time, then discarded\n# saves space\ncolors = 'black white grey'.split()\nsizes = 'S M L'.split()\nfor shirt in ('%s %s' % (color, size) for color in colors for size in sizes):\n print(shirt)\n\n","sub_path":"Part II/Ch.2/GeneratorExpressions.py","file_name":"GeneratorExpressions.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"7560742","text":"a,b,c = 1,2,3\n\ndef change_values(a,c):\n global b\n print(a,b,c) #what gets printed?\n a,b,c = 0,0,0\n\ndef main():\n global a\n a=-1\n change_values(c,a)\n print(a,b,c) #what gets printed?\n\nmain()","sub_path":"py_intro/functions/Exercises/global_vs_local.py","file_name":"global_vs_local.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"613693278","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nfont_label = {'family' : 'Arial',\n 'color' : 'black',\n 'weight' : 'normal',\n 'size' : 12,\n }\n\nloss_file = '../checkpoints/Compare/underwater_pix2pix512_Res9Gmultibranch46D_selectDdcpL1a30lu5gan1_lsgan/loss_log.txt'\n\nG_GAN = []\nD_fake = []\nD_real = []\nG_underwater = []\nD_underwater = []\nstop_eopch = 65\nwith open(loss_file, 'r') as f:\n for line in f.readlines():\n part = line.split(' ')\n if part[0]== '(epoch:' and int(part[1][:-1])<=stop_eopch:\n G_GAN.append(float(part[9]))\n G_underwater.append(float(part[11]))\n D_real.append(float(part[13]))\n D_fake.append(float(part[15]))\n D_underwater.append(float(part[17]))\n\nD_GAN = (np.array(D_real) + np.array(D_fake))*0.5\nG_GAN_ave = G_GAN.copy()\nD_fake_ave = D_GAN.copy()\nG_UI_ave = G_underwater.copy()\nD_UI_ave = D_underwater.copy()\nfor i in range(0,len(G_GAN)):\n if i < 50:\n G_GAN_ave[i] = np.mean(G_GAN[0:i + 1])\n D_fake_ave[i] = np.mean(D_fake[0:i + 1])\n G_UI_ave[i] = np.mean(G_underwater[0:i + 1])\n D_UI_ave[i] = np.mean(D_underwater[0:i + 1])\n else:\n G_GAN_ave[i] = np.mean(G_GAN[i-50:i+1])\n D_fake_ave[i] = np.mean(D_fake[i - 50:i+1])\n G_UI_ave[i] = np.mean(G_underwater[i - 50:i+1])\n D_UI_ave[i] = np.mean(D_underwater[i - 50:i+1])\n\nlit = np.linspace(0, stop_eopch+1, len(G_GAN))\n\nax=plt.subplot(1,1,1)\nax.grid(True, which='both', alpha=0.2)\nplt.plot(lit, G_GAN, color='crimson',alpha=0.5)\nG_GAN_plt, =plt.plot(lit, G_GAN_ave, color='crimson', linewidth=2.0)\nplt.xlim(0,stop_eopch)\nplt.xlabel('epoch',)\nplt.ylabel('loss',fontdict=font_label)\n# plt.legend([G_GAN_plt], [r'$G$:$\\mathcal{L}_{lscGAN}$'], loc='upper right', fontsize=12)\n\n# ax=plt.subplot(4,1,2)\n# ax.grid(True, which='both', alpha=0.2)\nplt.plot(lit, D_fake,color='green',alpha=0.5)\nD_GAN_plt, = plt.plot(lit, D_fake_ave, color='green',linewidth=2.0)\nplt.xlim(0,stop_eopch)\nplt.xlabel('epoch',fontdict=font_label)\nplt.ylabel('loss',fontdict=font_label)\nplt.legend([G_GAN_plt, D_GAN_plt], ['G', 'D'], loc='upper right',fontsize=12)\n\nplt.figure()\nax=plt.subplot(1,1,1)\nax.grid(True, which='both', alpha=0.2)\nplt.plot(lit, G_underwater,color='blue',alpha=0.5)\nG_underwater_plt, = plt.plot(lit, G_UI_ave, color='blue',linewidth=2.0)\nplt.xlim(0,stop_eopch)\nplt.xlabel('epoch', fontdict=font_label)\nplt.ylabel('loss', fontdict=font_label)\n\nplt.plot(lit, D_underwater, color='m', alpha=0.5)\nD_underwater_plt, = plt.plot(lit, D_UI_ave, color='m',linewidth=2.0)\nplt.xlim(0,stop_eopch)\nplt.xlabel('epoch', fontdict=font_label)\nplt.ylabel('loss', fontdict=font_label)\nplt.legend([G_underwater_plt, D_underwater_plt], ['G', 'D'], loc='upper right',fontsize=12)\n\nplt.show()\n","sub_path":"exp/Multi_stage_loss.py","file_name":"Multi_stage_loss.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"517451244","text":"from time import time\nfrom hashlib import sha256\nfrom abc import ABCMeta, abstractmethod\n\n__version__ = \"0.0.5\"\n__author__ = \"Adrian Agnic\"\n\n\nclass Interface(metaclass=ABCMeta):\n\n def __init__(self, hardness):\n super().__init__()\n self.bc = Blockchain(hardness)\n self.commitlog = {}# NOTE wallet or tracker of index, hash\n\n @abstractmethod\n def save(self, data):\n self.bc.add(data)\n\n @abstractmethod\n def commit(self):\n self.bc.mine()\n\n\n\nclass Blockchain:\n\n def __init__(self, hardness):\n self.x = int(hardness)\n self.genesis()\n\n def add(self, data):\n self.buffer.append(Block(data))\n\n def mine(self):\n for block in self.buffer:\n latest = self.latest()\n b, l = block.body[\"meta\"], latest.body[\"meta\"]\n b[\"index\"], b[\"previous\"] = (l[\"index\"] + 1), l[\"hash\"]\n self.chain[str(b[\"index\"])] = self.work(block)\n self.validate()\n\n def latest(self):\n return self.chain[str((len(self.chain) - 1))]\n\n def genesis(self):\n self.buffer = []\n self.chain = {}\n gen_block = Block(\"genesis\")\n gen_block.body[\"meta\"][\"index\"], gen_block.body[\"meta\"][\"previous\"] = 0, \"0\" * 64\n self.chain[\"0\"] = self.work(gen_block)\n self.chain[\"0\"].__dict__.update({\n \"head\": {\n \"index\": self.chain[\"0\"].body[\"meta\"][\"index\"],\n \"hash\": self.chain[\"0\"].sha(True)\n }\n })\n\n def work(self, block):\n block.sha()\n while block.body[\"meta\"][\"hash\"][:self.x] != \"0\" * self.x:\n block.body[\"meta\"][\"nonce\"] += 1\n block.sha()\n return block\n\n def validate(self):\n for i in range(1, len(self.chain)):\n current = self.chain[str(i)]\n if current.body[\"meta\"][\"hash\"] == current.sha(True):\n current.__dict__.update({\n \"head\": {\n \"index\": current.body[\"meta\"][\"index\"],\n \"hash\": current.sha(True)\n }\n })\n return True\n self.genesis()\n return False\n\n\n\nclass Block:\n\n def __init__(self, data):\n self.__dict__.update({\n \"body\": {\n \"meta\": {\n \"index\": None,\n \"timestamp\": time(),\n \"previous\": None,\n \"hash\": None,\n \"nonce\": 0\n },\n \"data\": data\n }\n })\n\n def __repr__(self):\n return f\"index: {self.head['index']} || hash: {self.head['hash']}\\n\"\n\n def sha(self, ret=False):\n dct = self.body[\"meta\"]\n cat = f\"{dct['index']}{dct['timestamp']}{dct['previous']}{dct['nonce']}{self.body['data']}\"\n res = sha256(sha256(cat.encode()).hexdigest().encode()).hexdigest()\n if ret: return res\n dct[\"hash\"] = res\n","sub_path":"python/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"336025531","text":"import re\n\ndef str2set(cls):\n CL = re.compile(r'\\w+')\n clset = set()\n for match in CL.finditer(cls):\n cl = match.group()\n clset.add(cl)\n return clset\n\ndef set2str(clset):\n clstr = ''\n for cl in clset:\n clstr += str(cl)\n clstr += ','\n return clstr[:-1]\n\ndef check_cl(cl1, cl2):\n '''\n cl1 : ,로 구분된 cl list\n cl2 : ,로 구분된 cl list\n 동작 : cl1의 각 cl을 확인하여 cl2에 포함되어 있지 않은 cl을 list up함. \n 즉 cl1 - cl2\n return type : set\n '''\n CL = re.compile(r'\\w+')\n cl1set = str2set(cl1)\n cl2set = str2set(cl2)\n return cl1set - cl2set\n\n\ndef make_cl(eur_cls, add_cls='', sub_cls=''):\n '''\n return type : set\n '''\n eurclset = str2set(eur_cls)\n addclset = str2set(add_cls)\n subclset = str2set(sub_cls)\n #\n for cl in addclset:\n eurclset.add(cl)\n return eurclset - subclset\n\nCLLIST = 'cl_list.txt'\n\ndef update():\n \n with open(CLLIST, 'rt') as f:\n eur_partials = ['']\n kor_partials = ['']\n add_partials = ['']\n sub_partials = ['']\n eurclset = set()\n korclset = set()\n addclset = set()\n subclset = set()\n\n while(1):\n line = f.readline()\n if line == '' or line[:3] == 'EOD':\n pos = f.tell()\n break\n temp = []\n \n temp = re.findall('^eur_partials\\s*=\\s*([\\d,]*)', line)\n if temp != []:\n eur_partials = temp[:]\n eurclset = str2set(eur_partials[0])\n continue\n\n temp = re.findall('^kor_partials\\s*=\\s*([\\d,]*)', line)\n if temp != []:\n kor_partials = temp[:]\n korclset = str2set(kor_partials[0])\n continue\n\n temp = re.findall('^add_partials\\s*=\\s*([\\d,]*)', line)\n if temp != []:\n add_partials = temp[:]\n addclset = str2set(add_partials[0])\n continue\n\n temp = re.findall('^sub_partials\\s*=\\s*([\\d,]*)', line)\n if temp != []:\n sub_partials = temp[:]\n subclset = str2set(sub_partials[0])\n continue\n \n diff1 = eurclset - korclset - subclset\n diff2 = korclset - eurclset - subclset\n\n for cl in addclset:\n eurclset.add(cl)\n resultlist = list(eurclset - subclset)\n resultlist.sort()\n \n\n with open(CLLIST, 'wt+') as f:\n f.write('eur_partials = %s\\n' % eur_partials[0])\n f.write(\"\\n\")\n\n f.write('kor_partials = %s\\n' % kor_partials[0])\n f.write('\\n')\n\n f.write('add_partials = %s\\n' % add_partials[0])\n f.write('\\n')\n\n f.write('sub_partials = %s\\n' % sub_partials[0])\n \n f.write(\"------------------------------------------\\n\")\n\n f.write('1. EUR - KOR : \\n')\n f.write(set2str(diff1))\n f.write('\\n')\n f.write('2. KOR - EUR : \\n')\n f.write(set2str(diff2))\n f.write('\\n')\n f.write('\\n')\n f.write('3. New CL list : \\n')\n f.write(str([int(x) for x in resultlist]).replace(', ',',')[1:-1])\n f.write('\\n')\n\ndef main():\n update()\n\nif __name__ == '__main__':\n main()\n\n \n","sub_path":"cltool/cltool.py","file_name":"cltool.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"21513426","text":"\n# Project 5\n# Author: Luis Armendariz and Alex petrov\n# instructor: S.Einakian\n# CPE 101- 01\nimport sys\n\ndef get_file():\n file_input = sys.argv[1]\n valid_input = False\n\n while valid_input == False:\n try:\n open_file = open(file_input)\n print(\"Usage: python puzzle.py image_file.ppm\")\n valid_input = True\n\n except Exception as error:\n print(\"Unable to open <{}>\".format(file_input))\n exit()\n if valid_input == True:\n return file_input\n\n# makes the file into a list\ndef clean_file(file_input):\n\n filein = open(file_input, 'r')\n listin = [line.strip().split(' ') for line in filein.readlines()]\n return listin\n#[['P3'], ['500', '375'], ['255'], ['21'], ['85'], ['166'], ['21'], ['53'], ['111'], [$\n\ndef split_list_heading(file_input):\n heading = file_input[:3]\n return heading\n#[['P3'], ['500', '375'], ['255']]\n\ndef split_list_rgb(file_input):\n rgb = file_input[3:]\n return rgb\n#[['21'], ['85'], ['166'], ['21'], ['53'], ['111'], ['21'], ['3']]\n#return rgb list\n\ndef split_list_flat(rgb_list):\n flat_rgb = []\n for rgb in rgb_list:\n for i in rgb:\n flat_rgb.append(i)\n return flat_rgb\n# ['21', '85', '166', '21', '53', '111', '21', '3', '195']\n\ndef puzzle_solve(flat_rgb):\n listNew = []\n for x in range(0, len(flat_rgb), 3):\n mult = int(flat_rgb[x]) * 10\n if mult > 255:\n mult = 255\n flat_rgb[x + 1] = flat_rgb[x + 2] = mult\n listNew.append(mult)\n listNew.append(flat_rgb[x + 1])\n listNew.append(flat_rgb[x + 2])\n return listNew\n\ndef new_ppm(group_rgb, heading):\n with open(\"hidden.ppm\", \"w\") as hidden_file:\n hidden_file.write(\"P3\" + \"\\n\")\n hidden_file.write(\"500 375\" + \"\\n\")\n hidden_file.write(\"255\" + \"\\n\")\n for rgb in group_rgb:\n hidden_file.write(str(rgb) + \"\\n\")\n","sub_path":"Project5/puzzle (1).py","file_name":"puzzle (1).py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"396075456","text":"\"\"\"Binary Search\"\"\"\n\ndef bsearch(arr,key):\n l,r = 0,len(arr)-1\n\n while (l <= r):\n m = (l+r)//2\n if arr[m] == key:\n return m+1\n elif arr[m] < key:\n l = m+1\n else:\n r = m-1\n return -1\n\nn1 = int(input())\nn2 = int(input())\nvals = [int(x) for x in input().split()]\nkeys = [int(x) for x in input().split()]\n\nret_vals = []\nfor k in keys:\n ret_vals.append(str(bsearch(vals,k)))\n","sub_path":"rosalind/algorithmic_heights/problem_2.py","file_name":"problem_2.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"128423095","text":"from django.shortcuts import render, HttpResponseRedirect, get_object_or_404\nfrom mainapp.models import Product\nfrom basketapp.models import Basket\nfrom mainapp.views import get_basket\nfrom django.contrib.auth.decorators import login_required\nfrom django.template.loader import render_to_string\nfrom django.http import JsonResponse\nfrom django.urls import reverse\n\n\n@login_required\ndef index(request):\n context = {\n 'page_title': 'basket',\n 'basket': get_basket(request.user)\n }\n return render(request, 'basketapp/index.html', context)\n\n\n@login_required\ndef basket_add(request, pk):\n if 'login' in request.META.get('HTTP_REFERER'):\n return HttpResponseRedirect(reverse('main:product',\n kwargs={\n 'pk': pk,\n }))\n product = get_object_or_404(Product, pk=pk)\n basket_item = Basket.objects.filter(product=product, user=request.user).first()\n if basket_item:\n basket_item.quantity += 1\n basket_item.save()\n print(f'обновлен объект корзины')\n else:\n Basket.objects.create(product=product, user=request.user, quantity=1)\n print(f'создан новый объект корзины')\n return HttpResponseRedirect(request.META['HTTP_REFERER'])\n\n\n@login_required\ndef basket_edit(request, product_pk, quantity):\n if request.is_ajax():\n quantity = int(quantity)\n new_basket_item = Basket.objects.get(pk=int(product_pk))\n\n if quantity > 0:\n new_basket_item.quantity = quantity\n new_basket_item.save()\n else:\n new_basket_item.delete()\n\n context = {\n 'basket': get_basket(request.user),\n }\n result = render_to_string('basketapp/includes/inc__basket_list.html', context)\n\n return JsonResponse({\n 'result': result\n })\n\n\n@login_required\ndef basket_remove(request, pk):\n basket_record = get_object_or_404(Basket, pk=pk)\n basket_record.delete()\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n","sub_path":"geekshop/basketapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"113696566","text":"import random\n\ndef jogar():\n imprime_comeco()\n lista_palavras = ler_arquivo(\"c:/Users/f0fp559/Documents/alura/Python/jogos/palavras.txt\")\n palavra = define_palavra(lista_palavras)\n resolve_jogo(palavra)\n\ndef imprime_comeco():\n print(\"*********************************\")\n print(\"Bem vindo ao jogo da forca!\")\n print(\"*********************************\")\n\ndef ler_arquivo(caminho):\n lista_palavras = []\n with open(caminho) as arquivo:\n for linha in arquivo:\n lista_palavras.append(linha.strip().upper())\n return lista_palavras\n\ndef define_palavra(lista_palavras):\n return lista_palavras[random.randrange(0,len(lista_palavras) - 1)]\n\ndef retorna_chute():\n return input(\"\\nDigite uma letra: \").strip().upper()\n\ndef preenche_resultado(palavra):\n return [\"_\" for letra in palavra]\n\ndef imprime_palavra(resultado):\n for letra in resultado:\n print(letra, sep=\" \", end=\" \")\n print(\"\\n\")\n\ndef imprime_resultado(acertou, enforcou, palavra):\n if (acertou):\n print(\"Você ganhou!\")\n if (enforcou):\n print(\"Você perdeu! A palavra era{}\".format(palavra))\n\ndef verifica_acerto(chute, palavra, resultado):\n index = 0\n for letra in palavra:\n if (chute == letra):\n resultado[index] = letra\n index += 1\n return resultado\n\ndef verifica_erro(erros):\n erros += 1\n print(\"Você errou. Jogadas restantes:{}\".format(6 - erros))\n return erros\n\ndef resolve_jogo(palavra):\n enforcou = acertou = False\n erros = 0\n resultado = preenche_resultado(palavra)\n imprime_palavra(resultado)\n while (not enforcou and not acertou):\n chute = retorna_chute()\n if (chute in palavra):\n resultado = verifica_acerto(chute, palavra, resultado)\n else:\n erros = verifica_erro(erros)\n acertou = \"_\" not in resultado\n enforcou = erros == 6\n imprime_palavra(resultado)\n imprime_resultado(acertou, enforcou, palavra)\n\nif(__name__ == \"__main__\"):\n jogar()","sub_path":"Python/jogos/forca.py","file_name":"forca.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"48890574","text":"import os\nimport logging as logger\nfrom datetime import datetime\nfrom osbot_utils.utils.Files import folder_create, folder_delete_all, folder_copy\n\nfrom cdr_plugin_folder_to_folder.common_settings.Config import Config\nfrom cdr_plugin_folder_to_folder.metadata.Metadata_Service import Metadata_Service\nfrom cdr_plugin_folder_to_folder.storage.Storage import Storage\nfrom cdr_plugin_folder_to_folder.utils.Log_Duration import log_duration\n\nfrom cdr_plugin_folder_to_folder.pre_processing.Status import Status, FileStatus\n\nfrom cdr_plugin_folder_to_folder.processing.Analysis_Json import Analysis_Json\n\nlogger.basicConfig(level=logger.INFO)\n\nclass Pre_Processor:\n\n def __init__(self):\n self.config = Config()\n self.meta_service = Metadata_Service()\n self.status = Status()\n self.storage = Storage()\n self.file_name = None # set in process() method\n self.current_path = None\n self.base_folder = None\n self.dst_folder = None\n self.dst_file_name = None\n\n self.status = Status()\n self.status.reset()\n\n #self.analysis_json = Analysis_Json()\n\n @log_duration\n def clear_data_and_status_folders(self):\n data_target = self.storage.hd2_data() # todo: refactor this clean up to the storage class\n status_target = self.storage.hd2_status()\n processed_target = self.storage.hd2_processed()\n folder_delete_all(data_target)\n folder_delete_all(status_target)\n folder_delete_all(processed_target)\n folder_create(data_target)\n folder_create(status_target)\n folder_create(processed_target)\n self.status.reset()\n\n def file_hash(self, file_path):\n return self.meta_service.file_hash(file_path)\n\n def prepare_folder(self, folder_to_process):\n if folder_to_process.startswith(self.storage.hd1()):\n return folder_to_process\n\n dirname = os.path.join(self.storage.hd1(), os.path.basename(folder_to_process))\n if os.path.isdir(dirname):\n folder_delete_all(dirname)\n try:\n folder_copy(folder_to_process, dirname)\n finally:\n return dirname\n\n def process_folder(self, folder_to_process):\n if not os.path.isdir(folder_to_process):\n # todo: add an event log\n return False\n\n folder_to_process = self.prepare_folder(folder_to_process)\n\n files_count = 0\n\n for folderName, subfolders, filenames in os.walk(folder_to_process):\n for filename in filenames:\n file_path = os.path.join(folderName, filename)\n if os.path.isfile(file_path):\n files_count += 1\n\n self.status.set_files_count(files_count)\n\n for folderName, subfolders, filenames in os.walk(folder_to_process):\n for filename in filenames:\n file_path = os.path.join(folderName, filename)\n if os.path.isfile(file_path):\n self.process(file_path)\n\n return True\n\n @log_duration\n def process_files(self):\n self.status.StartStatusThread()\n self.status.set_phase_1()\n self.process_folder(self.storage.hd1())\n self.status.set_phase_2()\n self.status.StopStatusThread()\n\n @log_duration\n def process(self, file_path):\n tik = datetime.now()\n\n metadata = self.meta_service.create_metadata(file_path=file_path)\n file_name = metadata.get_file_name()\n original_hash = metadata.get_original_hash()\n status = metadata.get_rebuild_status()\n self.update_status(file_name, original_hash, status)\n\n tok = datetime.now()\n delta = tok - tik\n\n if metadata.is_in_todo():\n hash_folder_path = self.storage.hd2_data(original_hash)\n self.meta_service.set_hd1_to_hd2_copy_time(hash_folder_path, delta.total_seconds())\n else:\n self.status.set_not_copied()\n\n def update_status(self, file_name, original_hash, status):\n if status == FileStatus.INITIAL:\n self.status.add_file()\n","sub_path":"cdr_plugin_folder_to_folder/pre_processing/Pre_Processor.py","file_name":"Pre_Processor.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"395200060","text":"import rhinoscriptsyntax as rs\n\n\ndef SelectLayers():\n filter_layer = rs.GetLayer(title = 'select layer to filter by intersection')\n if not filter_layer: return None,None\n \n intersect_layer = rs.GetLayer(title = 'select layer with intersecting geometry')\n if not intersect_layer: return None,None\n \n return filter_layer,intersect_layer\n\ndef TestIntersection(obj,tester):\n # there are a few possible intersection methods in rhinoscriptsyntax\n # as an initial setup only a few intersections are handled\n # to make this script faster and more robuste best would be to intersect not with rhinoscriptsyntax\n # But use RhinoCommon methods instead.\n #\n #for now only rhinoscriptsyntax methods are used as an example below:\n \n # if both are breps ( (poly)surface or extrusion\n if rs.IsBrep(obj) and rs.IsBrep(tester):\n intersections = rs.IntersectBreps(obj,tester)\n if intersections : \n #Delete intersections if they were made\n rs.DeleteObjects(intersections)\n return True\n\n if rs.IsMesh(obj) and rs.IsMesh(tester):\n intersections = rs.MeshMeshIntersection(obj,tester)\n if intersections : \n #This method does not create a curve but returns a list of points\n #so nothing to delete\n return True\n \n #Mixed input needs to be handled different as is with curves.\n #if either is a mesh the other needs to be converted to a mesh as well\n \n #catchall return False\n return False\n \n \ndef Main():\n \n # run method to select 2 layers\n filter_layer,intersect_layer = SelectLayers()\n if not filter_layer: return \n \n # Get all objects on the layers (note that also hidden/locked are used)\n filter_objs = rs.ObjectsByLayer(filter_layer)\n intersect_objs = rs.ObjectsByLayer(intersect_layer)\n \n # test if object on filter_layer intersects with any object on intersect layer\n intersecting_objs = []\n for obj in filter_objs:\n for tester in intersect_objs:\n # here the pseudo code is: does obj intersect with tester\n # I do not know the type of objects possible so\n # a more elaborate intersection methos is needed.\n if TestIntersection(obj,tester):\n intersecting_objs.append(obj)\n break #break out of for loop to prevent unneeded tests \n \n \n if intersecting_objs:\n rs.SelectObjects(intersecting_objs)\n \nMain()","sub_path":"SelIntersect.py","file_name":"SelIntersect.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"33409894","text":"\"\"\"Module to verify a given ISBN-10 number.\"\"\"\n\n\ndef is_valid(isbn: str) -> bool:\n \"\"\"Check whether the provided ISBN-10 number is valid.\n\n :param isbn: str - ISBN-10 number to check for validity\n :return: bool - boolean value on whether provides ISBN-10 number is valid\n \"\"\"\n\n isbn_sum = 0\n vals = list(zip(isbn.replace(\"-\", \"\"), list(range(10, len(isbn) * -1, -1))))\n\n if len(vals) != 10:\n return False\n\n for number in vals:\n val, multiple = number[0], number[1]\n\n if val == \"X\" and multiple != 1:\n return False\n\n if val == \"X\":\n val = 10\n\n try:\n isbn_sum += int(val) * multiple\n except ValueError:\n return False\n\n return isbn_sum > 0 and isbn_sum % 11 == 0\n","sub_path":"exercism/python/archive/isbn-verifier/isbn_verifier.py","file_name":"isbn_verifier.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"126506273","text":"import math\nfrom collections import deque, defaultdict\nfrom sys import stdin, stdout\ninput = stdin.readline\nlistin = lambda : list(map(int, input().split()))\nmapin = lambda : map(int, input().split())\nn = int(input())\na = listin()\nfirst = [0]*(n+1)\nsecond = [0]*(n+1)\nvisited = [False]*(n+1)\nfor i in range(2*n):\n if not visited[a[i]]:\n first[a[i]] = i\n visited[a[i]] = True\n else:\n second[a[i]] = i\nans = 0\nfor i in range(1, n+1):\n ans+=abs(second[i] - second[i-1])\n ans+=abs(first[i] - first[i-1])\nprint(ans)","sub_path":"Codeforces/Codeforces Round #542 [Alex Lopashev Thanks-Round] (Div. 2) - 1130/1130B-Two Cakes.py","file_name":"1130B-Two Cakes.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"326306779","text":"from sentiment.consts import POL_THRESH_LOW, POL_THRESH_HIGH\n\nGRID_PARAMS = {\n 'svm': [\n {\n 'clf__C': [.1, .2, .3, .4, .5, .6],\n },\n {\n 'clf__C': [.1, .2, .3, .4, .5, .6],\n 'clf__dual': [False],\n 'clf__penalty': ['l1'],\n }\n ],\n 'maxent': [\n {\n 'vect__polarities__count__thresh': [\n [x / 10, y / 10] for x in POL_THRESH_LOW\n for y in POL_THRESH_HIGH],\n 'clf__C': [.1, 1, 10, 100, 1000, 5000],\n 'clf__class_weight': ['balanced'],\n 'clf__solver': ['lbfgs'],\n 'clf__multi_class': ['auto'],\n 'clf__max_iter': [1000]\n }\n ],\n 'mnb': [\n {\n 'clf__alpha': [.5, .6, .7, 1],\n }\n ]\n}\n","sub_path":"sentiment/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"433134193","text":"from django.conf import settings\nfrom django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom linebot import LineBotApi, WebhookHandler\nfrom linebot.exceptions import InvalidSignatureError, LineBotApiError\nfrom linebot.models import MessageEvent, TextSendMessage, TextMessage\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport lxml\n\nline_bot_api = LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN)\nhandler = WebhookHandler(settings.LINE_CHANNEL_SECRET)\nuser_id = settings.USER_ID\n\n\ndef ptt_crawler():\n target_url = 'https://disp.cc/b/menu'\n tt = requests.get(target_url).text\n soup = BeautifulSoup(tt, \"lxml\")\n urls = soup.select('span.ht_title > a')\n data = \"\"\n for i in urls:\n title = i.text\n link = 'https://disp.cc/b/' + i['href']\n data += '{}\\n{}\\n'.format(title, link)\n return data\n\n\ndef ptt_e_shopping():\n init_url = 'https://www.ptt.cc/bbs/e-shopping/index.html'\n\n np = requests.get(init_url).text\n soup = BeautifulSoup(np, \"lxml\")\n npl = soup.select(\n '#action-bar-container > div > div.btn-group.btn-group-paging > a:nth-of-type(2)')\n\n data = ''\n for u in npl:\n next_page = 'https://www.ptt.cc' + u['href']\n con = requests.get(next_page).text\n n_soup = BeautifulSoup(con, \"lxml\")\n data = ''\n for i in n_soup.find_all(\"div\", {\"class\": \"title\"}):\n a = i.find('a')\n if a is not None:\n title = a.text\n link = 'https://www.ptt.cc' + a.attrs['href']\n data += '{}\\n{}\\n'.format(title, link)\n else:\n pass\n return data\n\n# 之後改成傳遞參數\n\n\ndef ptt_movie():\n init_url = 'https://www.ptt.cc/bbs/movie/index.html'\n\n np = requests.get(init_url).text\n soup = BeautifulSoup(np, \"lxml\")\n npl = soup.select(\n '#action-bar-container > div > div.btn-group.btn-group-paging > a:nth-of-type(2)')\n\n data = ''\n for u in npl:\n next_page = 'https://www.ptt.cc' + u['href']\n con = requests.get(next_page).text\n n_soup = BeautifulSoup(con, \"lxml\")\n data = ''\n for i in n_soup.find_all(\"div\", {\"class\": \"title\"}):\n a = i.find('a')\n if a is not None:\n title = a.text\n link = 'https://www.ptt.cc' + a.attrs['href']\n data += '{}\\n{}\\n'.format(title, link)\n else:\n pass\n return data\n\n\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_text_message(event):\n\n if event.message.text == 'show me ptt':\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=ptt_crawler())\n )\n if event.message.text == 'ptt e-shopping':\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=ptt_e_shopping())\n )\n\n if event.message.text == 'ptt movie':\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=ptt_movie())\n )\n\n\n@handler.default()\ndef default(event):\n print(event)\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text='Currently Not Support None Text Message')\n )\n\n\n@csrf_exempt\ndef callback(request):\n if request.method == 'POST':\n signature = request.META['HTTP_X_LINE_SIGNATURE']\n body = request.body.decode('utf-8')\n\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n return HttpResponseForbidden()\n except LineBotApiError:\n return HttpResponseBadRequest()\n return HttpResponse()\n else:\n return HttpResponseBadRequest()\n","sub_path":"k_bot/pttbot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"76564444","text":"# Uso del While Infinito\r\nc=1\r\nwhile True:\r\n print(c)\r\n break\r\n# While de Validación\r\nVocal= input(\"Ingrese una vocal: \")\r\nwhile Vocal not in (\"a\",\"e\",\"i\",\"o\",\"u\"):\r\n if Vocal==\".\":\r\n break\r\n Vocal=input(\"Vocal:\")\r\nprint(\"Su vocal o punto es: {}\" .format(Vocal)) \r\n","sub_path":"Ejercicio 3 1er Parcial.py","file_name":"Ejercicio 3 1er Parcial.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"240398397","text":"l=[]\nfor i in range(int(input())):\n a,c,d,p,q,r,j=input(),0,0,0,0,0,0\n for j in a:\n if j=='@':\n p=1\n continue\n if j=='.':\n break\n if p==0:\n d+=1\n if j.isdigit() or j.isalpha() or j=='-' or j=='_':\n c+=1\n if p==1:\n r+=1\n if j.isdigit() or j.isalpha():\n q+=1\n if d==c and r==q and a[len(a)-1:len(a)-5:-1]=='moc.':\n l.append(a)\nl.sort()\nprint(l)\n","sub_path":"e_mail validation.py","file_name":"e_mail validation.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"605347998","text":"BLANK = -1\n\ndef maxNewWires(wires, gridConnections):\n\tcolors = [BLANK] * len( wires )\n\tmaxNodes = 0\n\tmaxColor = BLANK\n\n\tfor outlet in gridConnections:\n\t\tcolors[outlet] = outlet\n\t\tqueue = [outlet]\n\t\tnodes = 1\n\t\twhile queue:\n\t\t\tnode = queue.pop( 0 )\n\t\t\tfor nextNode, wire in enumerate( wires[node] ):\n\t\t\t\tif wire == \"1\" and colors[nextNode] == BLANK:\n\t\t\t\t\tnodes += 1\n\t\t\t\t\tcolors[nextNode] = outlet\n\t\t\t\t\tqueue.append( nextNode )\n\n\t\tif nodes > maxNodes:\n\t\t\tmaxNodes = nodes\n\t\t\tmaxColor = outlet\n\n\t# paint all BLANK with the maxColor\n\tfor idx in (i for i, v in enumerate( colors ) if v == BLANK ):\n\t\tcolors[idx] = maxColor\n\n\tret = 0\n\tfor idx in gridConnections:\n\t\tsameColor = [ i for i, v in enumerate( colors ) if v == idx ]\n\t\tfor i in sameColor:\n\t\t\tnodeWires = wires[i]\n\t\t\tfor j in xrange( i + 1, len( nodeWires ) ):\n\t\t\t\tif j in sameColor and nodeWires[j] == \"0\":\n\t\t\t\t\tret += 1\n\n\treturn ret\n\n","sub_path":"d1d2_under_80/AddElectricalWires/solve/python/AddElectricalWires.py","file_name":"AddElectricalWires.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"85821885","text":"# CSC 241-404\r\n# Midterm exam template\r\n# Qili Sui\r\n\r\n# You DO NOT have to write doc strings\r\n\r\n# Question 1\r\ndef countPos(lst):\r\n count=0\r\n for i in lst:\r\n if i<=0:\r\n pass\r\n elif i>0:\r\n count=count+1\r\n elif len(lst)==0:\r\n count = 0\r\n return count\r\n\r\nprint (countPos([1,3,5,-5,-3,-1]))\r\nnum = countPos([6, 4, 2, 0])\r\nprint (num)\r\nprint (countPos([3.1415, 2.178, -3.333, 17.159, 0.11]))\r\nprint (countPos([-1, -2, -3]))\r\nprint (countPos([]))\r\n\r\n# Question 2\r\ndef censorNum(s):\r\n if(len(s)==0):\r\n pass\r\n s1=''\r\n for i in s:\r\n if i in '1234567890':\r\n i = '*'\r\n s1=s1+i\r\n print(s1)\r\n\r\nprint(censorNum('1,2,3,blast off!'))\r\nprint(censorNum(\"My favourite number is 17.\"))\r\nprint(censorNum(\"This is a test. This is only a test.\"))\r\nprint(censorNum(''))\r\nprint(censorNum(\"12345\"))\r\n\r\n \r\n# Question 3\r\ndef apr(info):\r\n for i in range(len(info)):\r\n if info[i] == ' ' and info[i+1] in '0123456789':\r\n no = info[i+1]+info[i+2]+info[i+3]\r\n\r\n if (info[-1:]=='A' or info[-1:]=='a' or info[-1:]=='B' or info[-1:]=='b' \r\n or info[-2:]=='A+' or info[-2:]=='a+' or info[-2:]=='A-' or info[-2:]=='a-'\r\n or info[-2:]=='B+' or info[-2:]=='b+' or info[-2:]=='b-' or info[-2:]=='B-'):\r\n print('Congratulations, you are doing well in',info[0:3],no+'!')\r\n\r\n elif (info[-1:]=='C' or info[-1:]=='c' or info[-2:]=='C+' or info[-2:]=='c+' \r\n or info[-2:]=='C-' or info[-2:]=='c-'):\r\n print('You are passing',info[0:3],no+'.')\r\n\r\n elif(info[-1:]=='D' or info[-1:]=='d' or info[-1:]=='F' or info[-1:]=='f' \r\n or info[-2:]=='D+' or info[-2:]=='d+' or info[-2:]=='D-' or info[-2:]=='d-'):\r\n print('You need to improve your performance in',info[0:3],no+'.')\r\n\r\n else:\r\n print('An invalid grade for',info[0:3],no,'was provided.')\r\n\r\nprint(apr('CSC 241 A-'))\r\nprint(apr(\"CSC 242 c\"))\r\nprint(apr(\"CSC 373 d+\"))\r\nprint(apr('WRD 104 B+'))\r\nprint(apr('IT 130 f'))\r\nprint(apr('CSC 241 E'))\r\n\r\n\r\n# Question 4\r\ndef sentenceCount(fname):\r\n inf=open(fname,'r')\r\n con=inf.read()\r\n inf.close()\r\n\r\n count=0\r\n if len(con) == 0 :\r\n return (count)\r\n else:\r\n for i in range(len(con)):\r\n if (con[i] in '.') and (con[i+1]=='\\n'):\r\n count = count + 1\r\n elif con[i] in '!?':\r\n count = count + 1\r\n return (count)\r\n\r\n\r\nprint(sentenceCount('test1.txt'))\r\nprint(sentenceCount('test2.txt'))\r\nprint(sentenceCount('empty.txt'))\r\n","sub_path":"csc241midterm/csc241midterm.py","file_name":"csc241midterm.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"326847808","text":"#Escreva um programa que receba dois nomes de arquivos e copie o conteúdo do primeiro arquivo para o segundo arquivo. Considere que o conteúdo do arquivo de origem é um texto. Seu programa não deve copiar linhas comentadas (que começam com //)\n\nvelho = open(\"teste.txt\",\"r\")\nnovo = open(\"novo.txt\",\"w\")\n\nfor texto in velho:\n if not (\"//\" in texto):\n novo.write(texto)\n\nvelho.close()\nnovo.close()","sub_path":"Lista 11/exercício 04.py","file_name":"exercício 04.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"105225420","text":"\n#import dependencies\n\nimport os\nimport csv\n\n#Import the csvpath\ncsvpath = os.path.join('raw_data','budget_data_2.csv')\n\n#Open the csv file \n\nwith open(csvpath, 'r') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n header = next(csvreader)\n\n#create empty lists \n\n list1=(csvreader)\n date_list = []\n revenue_list = []\n revenue_change = []\n\n #loop through list1 and append rows to list \n\n for row in list1:\n date_list.append(row[0])\n revenue_list.append(float(row[1]))\n total_months = len(date_list)\n total_revenue = sum(revenue_list)\n \n #Loop through revenue list to find revenue changes \n \n for row in range(1,len(revenue_list)):\n revenue_change.append(revenue_list[row]-revenue_list[row-1])\n avg_rev_change = sum(revenue_change)/len(revenue_change)\n\n max_rev_change = max(revenue_change)\n min_rev_change = min(revenue_change)\n\n max_rev_change_date = str(date_list[revenue_change.index(max(revenue_change))])\n min_rev_change_date = str(date_list[revenue_change.index(min(revenue_change))])\n \n #Print results to the terminal \n\nprint(\"Financial Analysis\")\nprint(\"----------------------------\")\n\n\nprint(f'Total Months: {total_months}')\nprint(f'Total Revenue:$ {total_revenue}')\nprint(f'Average Revenue Change: $ {(round(avg_rev_change))}')\nprint(\"Greatest Increase in Revenue:\", max_rev_change_date,\"($\", max_rev_change,\")\")\nprint(\"Greatest Decrease in Revenue:\", min_rev_change_date,\"($\", min_rev_change,\")\")\n\n #write the text files \n\ntext_path = os.path.join('.','budget_data_2.txt')\nwith open(text_path, \"w\") as text_file:\n text_file.write(\"Financial Analysis\")\n text_file.write(\"---------------------------------\")\n text_file.write(\"Total Months: \" + str(total_months))\n text_file.write(\"Total Revenue: $\" + str(total_revenue))\n text_file.write(\"Average Revenue Change: +\"\"$\" + str(round(avg_rev_change)))\n text_file.write(\"Greatest Increase in Revenue: \" + str(max_rev_change_date)+\" $\" + str(max_rev_change))\n text_file.write(\"Greatest Decrease in Revenue: \" + str(min_rev_change_date)+\" $\" + str(min_rev_change))","sub_path":"Python_homework/PyBank/PYBANKDATA1.py","file_name":"PYBANKDATA1.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"517351771","text":"#!/usr/bin/env python3\nimport glob\nimport os\nimport shlex\nimport subprocess\n\nimport click\nimport yaml\n\n_ROOT = os.path.abspath(os.path.dirname(__file__))\n\n\ndef get_data(path):\n return os.path.join(_ROOT, 'data', path)\n\n\ndef check_code(solution_filename, python_version='2'):\n cmd = python_cmd(python_version, 'pep8', solution_filename, True)\n result = subprocess.run(\n shlex.split(cmd),\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n success = result.returncode == 0\n output = ''\n if not success:\n output = 'PEP8 check failed:\\n' + result.stdout.decode('utf-8')\n return success, output\n\n\ndef run_all_tests(solution_filename, python_version='2'):\n filenames = glob.glob(get_data('*.test'))\n output = []\n for filename in filenames:\n filebase, _ = os.path.splitext(filename)\n test_num = int(os.path.basename(filebase))\n with open(filename) as tests_file, \\\n open(filebase + '.yaml') as cfg_file, \\\n open(filebase + '.ans') as ans_file:\n success, launch_output = run_test(\n test_num,\n filename,\n tests_file,\n cfg_file,\n ans_file,\n solution_filename,\n python_version)\n if launch_output:\n output.append(launch_output)\n\n return '\\n'.join(output)\n\n\ndef run_test(test_num, test_filename, tests_file, cfg_file, ans_file,\n solution_filename, python_version):\n # todo: refactor\n output = []\n cfg = yaml.load(cfg_file)\n args = cfg.get('options', '')\n stdin = None\n if cfg.get('stdin', False):\n stdin = tests_file\n else:\n args += ' -i ' + test_filename + ' '\n if not cfg.get('stdout', False):\n args += ' -o ' + 'output.tmp '\n cmd = python_cmd(python_version, solution_filename, args)\n result = subprocess.run(\n shlex.split(cmd), stdin=stdin, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n success = True\n expecting_error = cfg.get('error', False)\n error_returncode = (result.returncode != 0)\n if not expecting_error:\n if error_returncode:\n success = False\n output.append('-' * 20)\n output.append('TEST {} failed; returncode : {} is not 0'.format(\n test_num, result.returncode))\n output.append('OUTPUT: {}'.format(result.stdout.decode('utf-8')))\n else:\n answer = ''.join(ans_file.readlines())\n if not cfg.get('stdout', False):\n if os.path.isfile('output.tmp'):\n with open('output.tmp') as fin:\n got = ''.join(fin.readlines())\n os.remove('output.tmp')\n else:\n got = ''\n else:\n got = result.stdout.decode('utf-8')\n equality = (answer == got)\n if not equality and got and got[-1] == '\\n':\n equality = (answer == got[:-1])\n\n if not equality:\n success = False\n output.append('-' * 20)\n output.append('TEST {} failed'.format(test_num))\n output.append('EXPECTED:\\n' + repr(answer))\n output.append('GOT:\\n' + repr(got))\n else:\n if not error_returncode:\n success = False\n output.append('-' * 20)\n output.append('TEST {} failed; returncode : {} is 0'.format(\n test_num, result.returncode))\n output.append('OUTPUT: {}'.format(result.stdout.decode('utf-8')))\n return success, '\\n'.join(output)\n\n\ndef python_cmd(version, filename, args, is_module=False):\n module_add = '-m' if is_module else ''\n python = 'python' + version\n return ' '.join([python, module_add, filename, args])\n\n\ndef test_cmd(cfg, python_version, solution_filename):\n args = cfg.get('options', '')\n return python_cmd(python_version, solution_filename, args)\n\n\n@click.command()\n@click.argument('filename', type=click.Path(exists=True))\n@click.option('--python_version', '-p', default='2',\n type=click.Choice(['2', '3']), help='python version to run')\ndef fmtch(filename, python_version):\n success, output = check_code(filename, python_version)\n if output:\n print(output)\n output = run_all_tests(filename, python_version)\n if output:\n click.echo(output)\n\n\nif __name__ == '__main__':\n fmtch()\n","sub_path":"fmtch/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"330016385","text":"def is_anagram(word1, word2):\r\n # Write the function code here\r\n word1_list=[]\r\n word2_list=[]\r\n word1_list.extend(word1)\r\n word2_list.extend(word2)\r\n if len(word1_list)==len(word2_list):\r\n for word in word1_list:\r\n for j in range (len(word2_list)):\r\n if word == word2_list[j]:\r\n word2_list[j] = \"#\"\r\n \r\n \r\n \r\n if (word2_list == [\"#\"]*len(word2_list)):\r\n answer = True\r\n else:\r\n answer = False\r\n \r\n return answer\r\n \r\ndef main():\r\n # Write the main function\r\n word1 = input(\"Enter the first string: \")\r\n word2 = input(\"Enter the second string: \")\r\n answer = is_anagram(word1, word2)\r\n if answer ==True:\r\n print(word1, \"and\", word2, \"are anagrams.\")\r\n else:\r\n print(word1, \"and\", word2, \"are not anagrams.\")\r\n \r\n# Call the main function\r\nmain()\r\n","sub_path":"CMPT174-LAB/L07/Lab07Q02.py","file_name":"Lab07Q02.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"59575123","text":"# ==================================================================================================================== #\r\n\"\"\"\r\n출처: https://cafe.naver.com/kyonggieon/812\r\n\r\n2번 문제. 데이터 스택 구조 만들기.\r\n\r\nRefer to the URL above for the problem's detail.\r\n(위의 URL을 참고하여 자세한 문제를 확인하시오.)\r\n\"\"\"\r\n# ==================================================================================================================== #\r\n\r\n\"\"\"\r\nList를 잘 활용할 줄 알면 금방 끝낼 수 있는 문제이다. 그 중에서 비어있는 list에서 pop을 처리하면 IndexError가 발생하는데, 이는 쉽게 try-except 문을\r\n사용하면 해결할 수 있다. 코드 실행을 시도하고 문제 없이 실행되었으면 그대로 실행되고, 에러가 발생하면 에러 발생시의 코드를 대신 실행한다.\r\n\"\"\"\r\n\r\n\r\ndef main():\r\n print(\"[스택 코드]\\nPUSH: 1\\n POP: 2\\nSHOW: 3\\n\")\r\n\r\n stacks = []\r\n\r\n while True:\r\n stack_code = input(\"스택 코드를 입력하시오: \")\r\n if stack_code is \"1\":\r\n if len(stacks) > 10:\r\n print(\"스택 데이터 포화!\\n\")\r\n continue\r\n stack_data = input(\"스택할 데이터를 입력하시오: \")\r\n stacks.append(stack_data)\r\n print(\"데이터 스택 완료!\\n\")\r\n\r\n elif stack_code is \"2\":\r\n try:\r\n stacks.pop(-1)\r\n print(\"데이터 제거 완료!\\n\")\r\n except IndexError:\r\n print(\"삭제할 스택 데이터가 없습니다.\\n\")\r\n\r\n elif stack_code is \"3\":\r\n print(str(stacks) + \"\\n\")\r\n\r\n else:\r\n print(\"스택을 종료합니다.\")\r\n break\r\n\r\n\r\nmain()\r\n","sub_path":"Et_Cetera/Extra_P003.py","file_name":"Extra_P003.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"260226908","text":"from woniuboss_inter_2.readExcel_2 import readExcel\nfrom woniuboss_inter_2.woniubossMethod_2 import Woniuboss\n\ndef runtest():\n url = \"http://192.168.3.180:8080/woniuboss/login/userLogin\"\n dataone = {'userName': 'WNCD000', 'userPass': 'woniu123', 'checkcode': '0000', 'remember': 'Y'}\n woniuboss=Woniuboss(url,dataone)\n datalist=readExcel()\n\n with open('log.txt',\"w\",encoding=\"utf-8\") as f:\n f.write(\"\")\n\n for i in datalist:\n try:\n requst_type=i[4].strip()\n title=i[0]\n url=i[5]\n data=i[6]\n code=i[7]\n text=i[9]\n asertMethod = i[8].strip()\n if requst_type==\"post\":\n content=woniuboss.req_post(url,data)\n # print(data)\n # if i[6]==\"\":\n # content = woniuboss.req_post(url,i[6])\n # else:\n # content=woniuboss.req_post(url,eval(i[6]))\n # content=getattr(woniuboss,\"req_\"+i[4])(url,data)\n # getattr(woniuboss,\"asert\"+i[8].strip())\n # 判断是否以状态码断言\n if asertMethod == \"code\":\n woniuboss.asertcode(content, code,title)\n # 判断响应正文是否相等\n elif asertMethod == \"text\":\n woniuboss.asertText(content, text,title)\n # 判断响应正文是否包含\n elif asertMethod == \"json\":\n woniuboss.asertjson(content, text,title)\n # 判断响应头部\n elif asertMethod == \"header\":\n woniuboss.asertHeaders(content, text,title)\n else:\n print(\"断言方法有问题\")\n elif requst_type==\"get\":\n content = woniuboss.req_get(url)\n # 判断是否以状态码断言\n if asertMethod == \"code\":\n woniuboss.asertcode(content, text,title)\n # 判断响应正文是否相等\n elif asertMethod == \"text\":\n woniuboss.asertText(content, text,title)\n # 判断响应正文是否包含\n elif asertMethod == \"json\":\n woniuboss.asertjson(content, text,title)\n # 判断响应头部\n elif asertMethod == \"header\":\n woniuboss.asertHeaders(content, text,title)\n else:\n print(\"断言方法有问题\")\n else:\n print(\"请求方法有问题\",i[4])\n except:\n print(\"异常,测试失败 \",i[0])\n\nif __name__ == '__main__':\n\n runtest()\n\n","sub_path":"secondProject/woniuboss_inter_2/runTest_2.py","file_name":"runTest_2.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"383089799","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 26 15:00:12 2021\r\n\r\n@author: Mingze Gong (Rouch MacTavish)\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport time \r\nfrom signal2img_And_resample import signalResample\r\nfrom mne.io import concatenate_raws, read_raw_edf\r\n\r\ndef signalStorage_local (path, low_freq=1, high_freq=60, resample_stride=25):\r\n signal = read_raw_edf (path, preload=False)\r\n signal.load_data()\r\n signal_filtered = signal.copy().filter(l_freq=low_freq, h_freq=high_freq)\r\n signal = signal_filtered.to_data_frame()\r\n \r\n channels = [3,4,7] #ECG, EMG, EEG\r\n data_list = []\r\n \r\n for channel in channels:\r\n data = list(signal.values[:,channel])\r\n data = np.array(data)\r\n data = signalResample(data, stride=resample_stride)\r\n data_list.append(data)\r\n \r\n localtime = time.localtime(time.time())\r\n filename = 'Data_' + (str(localtime[0]) + str(localtime[1]) + str(localtime[2]) + str(localtime[3]) + str(localtime[4]))\r\n np.save(filename ,data_list)\r\n print (\"Successfully Transformation !!!\")\r\n \r\n return filename","sub_path":"module_demo/data_type_transformation.py","file_name":"data_type_transformation.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"113089616","text":"from sklearn.datasets import load_boston\r\nfrom sklearn.ensemble import GradientBoostingRegressor\r\nimport pandas as pd\r\nimport os\r\nimport pickle\r\nimport shap\r\nfrom .util import decision_value_core, get_importance_list, save_pickle\r\n\r\n\r\ndef data_prepare():\r\n save_path = 'data'\r\n if not os.path.exists(save_path):\r\n os.mkdir(save_path)\r\n X, Y = load_boston(return_X_y=True)\r\n feature_names = load_boston().feature_names\r\n df = pd.DataFrame(data=X, columns=feature_names)\r\n df['PRICE'] = Y\r\n df['ID'] = ['S'+str(x) for x in list(range(len(X)))]\r\n df.to_csv(os.path.join(save_path, 'train.csv'), index=False)\r\n\r\n id_cols = df[['ID']]\r\n y = df[['PRICE']]\r\n col_names = [x for x in df.columns if x not in ['ID', 'PRICE']]\r\n x = df[col_names]\r\n model = GradientBoostingRegressor(max_depth=10)\r\n model.fit(x.values, y.values.flatten())\r\n with open(os.path.join(save_path, 'model.pkl'), 'wb') as f:\r\n pickle.dump(model, f)\r\n\r\n explainer = shap.TreeExplainer(model)\r\n shap_values = explainer.shap_values(x)\r\n df_shap = pd.DataFrame(data=shap_values, columns=col_names)\r\n importance_list = get_importance_list(df_shap).Features.to_list()\r\n decision_values = decision_value_core(df_shap, explainer.expected_value,\r\n idx_names=df['ID'].to_list(),\r\n importance_list=importance_list)\r\n save_pickle(explainer, os.path.join(save_path, 'explainer.pkl'))\r\n df_shap.to_csv(os.path.join(save_path, 'shap_values.csv'), index=False)\r\n decision_values.to_csv(os.path.join(save_path, 'decision_values.csv'), index=False)\r\n\r\n\r\n","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"456468840","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright (C) 2015-2017 by Brendt Wohlberg \n# All rights reserved. BSD 3-clause License.\n# This file is part of the SPORCO package. Details of the copyright\n# and user license can be found in the 'LICENSE.txt' file distributed\n# with the package.\n\n\"\"\"Usage example: cbpdn.ConvBPDNGradReg (colour images)\"\"\"\n\nfrom __future__ import print_function\nfrom builtins import input\nfrom builtins import range\n\nimport numpy as np\n\nfrom sporco import util\nfrom sporco import plot\nfrom sporco.admm import cbpdn\nimport sporco.metric as sm\n\n\n# Load demo image\nimg = util.ExampleImages().image('standard', 'barbara.png', scaled=True,\n zoom=0.5)[27:283,55:311]\n\n\n# Load dictionary\nDb = util.convdicts()['RGB:8x8x3x64']\n# Append impulse filters for lowpass component representation\ndi = np.zeros(Db.shape[0:3] + (3,))\ndi[0,0,...] = np.identity(3)\nD = np.concatenate((di, Db), axis=3)\n# Weights for l1 norm: no regularization on impulse filter\nwl1 = np.ones((1,)*4 + (D.shape[3],))\nwl1[...,0:3] = 0.0\n# Weights for l2 norm of gradient: regularization only on impulse filter\nwgr = np.zeros((D.shape[3]))\nwgr[0:3] = 1.0\n\n\n\n# Set up ConvBPDNGradReg options\nlmbda = 1e-2\nmu = 5e-1\nopt = cbpdn.ConvBPDNGradReg.Options({'Verbose' : True, 'MaxMainIter' : 200,\n 'HighMemSolve' : True, 'LinSolveCheck' : True,\n 'RelStopTol' : 1e-2, 'AuxVarObj' : False,\n 'rho' : 1e0, 'AutoRho' : {'Enabled' : True,\n 'Period' : 10, 'RsdlTarget' : 0.04},\n 'L1Weight' : wl1, 'GradWeight' : wgr})\n\n# Initialise and run ConvBPDNGradReg object\nb = cbpdn.ConvBPDNGradReg(D, img, lmbda, mu, opt)\nX = b.solve()\nprint(\"ConvBPDNGradReg solve time: %.2fs\" % b.timer.elapsed('solve'))\n\n# Reconstruct representation\nimgr = b.reconstruct().squeeze()\nprint(\" reconstruction PSNR: %.2fdB\\n\" % sm.psnr(img, imgr))\n\n\n# Display representation and reconstructed image\nfig1 = plot.figure(1, figsize=(14,14))\nplot.subplot(2,2,1)\nplot.imview(b.Y[...,0:3].squeeze(), fgrf=fig1, cmap=plot.cm.Blues,\n title='Lowpass component')\nplot.subplot(2,2,2)\nplot.imview(np.sum(abs(b.Y[...,3:]), axis=b.cri.axisM).squeeze(), fgrf=fig1,\n cmap=plot.cm.Blues, title='Main representation')\nplot.subplot(2,2,3)\nplot.imview(imgr, fgrf=fig1, title='Reconstructed image')\nplot.subplot(2,2,4)\nplot.imview(imgr - img, fgrf=fig1, fltscl=True,\n title='Reconstruction difference')\nfig1.show()\n\n\n# Plot functional value, residuals, and rho\nits = b.getitstat()\nfig2 = plot.figure(2, figsize=(21,7))\nplot.subplot(1,3,1)\nplot.plot(its.ObjFun, fgrf=fig2, ptyp='semilogy', xlbl='Iterations',\n ylbl='Functional')\nplot.subplot(1,3,2)\nplot.plot(np.vstack((its.PrimalRsdl, its.DualRsdl)).T, fgrf=fig2,\n ptyp='semilogy', xlbl='Iterations', ylbl='Residual',\n lgnd=['Primal', 'Dual'])\nplot.subplot(1,3,3)\nplot.plot(its.Rho, fgrf=fig2, xlbl='Iterations', ylbl='Penalty Parameter')\nfig2.show()\n\n\n# Wait for enter on keyboard\ninput()\n","sub_path":"examples/cnvsparse/demo_cbpdn_grd_clr.py","file_name":"demo_cbpdn_grd_clr.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"345684952","text":"#!/usr/local/bin/python3\n\n'''\n\nScript to add AWS IAM user to AWS IAM group\n\n'''\n\nimport boto3, botocore, sys, datetime, dateutil, pytz, os, random, string\n\ndef groupAddUser(user, group):\n iam = boto3.resource('iam')\n group = iam.Group(group)\n g = group.add_user(UserName=user)\n return\n\nwhile True:\n username = input('Enter username (or \"exit\"): ')\n if username == 'exit':\n sys.exit()\n group = input('Enter group (or \"exit\"): ')\n if group == 'exit':\n sys.exit()\n try:\n groupAddUser(username, group)\n print('User \"' + username + '\" has been added to group \"' + group + '\".')\n except botocore.exceptions.ClientError as e:\n print(e)\n","sub_path":"aws-groupmemberadd.py","file_name":"aws-groupmemberadd.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"141117953","text":"from inman.google_sheet import get_raw_data_from_google_sheets\nfrom inman.config import get_invoice_spreadsheet_id\nfrom inman.months import month_to_string\n\n\nclass Customer:\n\n def __init__(self):\n self.name = ''\n self.address = ''\n self.post = ''\n self.country = ''\n self.vat_number = ''\n\n def __str__(self):\n s1 = 'Customer {}\\naddress: {}\\n'.format(self.name, self.address)\n s2 = 'post: {}\\ncountry{}\\nvat nr.{}\\n'.format(self.post, self.country, self.vat_number)\n return s1 + s2\n\n @classmethod\n def create_customer(cls, general_data, customer_number):\n i = str(customer_number)\n customer = cls()\n customer.name = general_data['customer_' + i]\n customer.address = general_data['customer_address_' + i]\n customer.post = general_data['customer_post_' + i]\n customer.country = general_data['customer_country_' + i]\n customer.vat_number = general_data['customer_vat_nr_' + i]\n\n return customer\n\n\nclass Me:\n\n def __init__(self):\n self.name = ''\n self.address = ''\n self.post = ''\n self.country = ''\n\n self.email = ''\n self.telephone = ''\n\n self.vat_number = ''\n self.reg_number = ''\n\n self.bank = ''\n self.iban = ''\n self.bic = ''\n\n def __str__(self):\n s1 = 'Myself: {}\\naddress {}, {}, {}\\n\\n'.format(self.name, self.address, self.post, self.country)\n s2 = 'email: {}\\ntelephone: {}\\n\\n'.format(self.email, self.telephone)\n s3 = 'vat. number: {}\\nreg. number: {}\\n\\n'.format(self.vat_number, self.reg_number)\n s4 = 'bank {}\\niban: {}bic: {}\\n'.format(self.bank, self.iban, self.bic)\n return s1 + s2 + s3 + s4\n\n @classmethod\n def create_me(cls, general_data):\n me = cls()\n me.name = general_data['my_name']\n me.address = general_data['my_address']\n me.post = general_data['my_post']\n me.country = general_data['my_country']\n\n me.email = general_data['my_email']\n me.telephone = general_data['my_telephone']\n\n me.vat_number = general_data['my_vat_number']\n me.reg_number = general_data['my_reg_number']\n\n me.bank = general_data['my_bank']\n me.iban = general_data['my_iban']\n me.bic = general_data['my_bic']\n\n return me\n\n\nclass Service:\n\n def __init__(self):\n self.name_of_service = ''\n self.units = ''\n self.price_per_unit = ''\n\n def __str__(self):\n s = 'Name of service: {}\\n'.format(self.name_of_service)\n s += 'Units: {}\\n'.format(self.units)\n s += 'Price per unit: {}\\n'.format(self.price_per_unit)\n return s\n\n def get_value(self):\n units = int(self.units)\n price_per_unit = float(self.price_per_unit)\n return units * price_per_unit\n\n @classmethod\n def create_service(cls, data):\n service = cls()\n service.name_of_service = data['name']\n service.units = data['units']\n service.price_per_unit = data['price per unit']\n return service\n\n\nclass InvoiceData:\n\n def __init__(self, general_data, month_data):\n self.me = Me.create_me(general_data)\n self.customers = []\n\n i = 1\n while True:\n token = 'customer_' + str(i)\n if token in general_data:\n customer = Customer.create_customer(general_data, i)\n self.customers.append(customer)\n i += 1\n else:\n break\n self.customer_number = None\n self.set_customer_number(month_data['customer'])\n\n self.invoice_number = month_data['invoice_number']\n self.invoice_date = month_data['date']\n self.date_of_service = month_data['date_of_service']\n self.payment_due = month_data['payment_due']\n self.payment_reference = month_data['payment_reference']\n\n self.services = []\n self.set_services(month_data['services'])\n\n def set_services(self, services_data):\n for data in services_data:\n service = Service.create_service(data)\n self.services.append(service)\n\n def set_customer_number(self, costumer_number_str):\n n = int(costumer_number_str) - 1\n if not (0 <= n < len(self.customers)):\n raise ValueError('The customer number ({}) is not valid.'.format(n))\n self.customer_number = n\n\n def get_customer(self):\n return self.customers[self.customer_number]\n\n def get_value(self):\n return sum(service.get_value() for service in self.services)\n\n def __str__(self):\n s = 'Invoice data:\\n' + str(self.me) + '\\n'\n for customer in self.customers:\n s += str(customer) + '\\n'\n s += 'Customer number: {}\\n'.format(self.customer_number)\n s += 'Invoice number: {}\\n'.format(self.invoice_number)\n s += 'Invoice date: {}\\n'.format(self.invoice_date)\n s += 'Date of service: {}\\n'.format(self.date_of_service)\n s += 'Payment due: {}\\n'.format(self.payment_due)\n s += 'Payment reference: {}\\n'.format(self.payment_reference)\n return s\n\n\ndef get_general_invoice_data():\n sheet_id = get_invoice_spreadsheet_id()\n tab = 'main'\n value_range = '!A2:B40'\n\n raw_value = get_raw_data_from_google_sheets(sheet_id, tab, value_range)\n\n general_data = {}\n for line in raw_value:\n if len(line) == 2:\n key = line[0].lower().strip()\n general_data[key] = line[1].strip()\n\n return general_data\n\n\ndef get_month_invoice_data(month):\n sheet_id = get_invoice_spreadsheet_id()\n tab = month_to_string(month)\n value_range = '!A3:B40'\n\n raw_value = get_raw_data_from_google_sheets(sheet_id, tab, value_range)\n\n month_data = {}\n services = []\n is_service = False\n for line in raw_value:\n if is_service:\n if len(line) == 1 and 'service' in line[0].lower():\n services.append({})\n elif len(line) == 2:\n key = line[0].lower()\n services[-1][key] = line[1]\n else:\n if len(line) == 1 and 'service' in line[0].lower():\n services.append({})\n is_service = True\n elif len(line) == 2:\n key = line[0].lower()\n month_data[key] = line[1]\n\n new_services = []\n for service in services:\n if 'hours' in service:\n hours = service['hours']\n name = service['name']\n name = name + '\\n(per hour, ' + hours + ' hours)'\n units = hours\n price_per_unit = service['price per hour']\n new_services.append({'name': name, 'units': units, 'price per unit': price_per_unit})\n elif 'amount' in service:\n name = service['name']\n units = '1'\n price_per_unit = service['amount']\n new_services.append({'name': name, 'units': units, 'price per unit': price_per_unit})\n\n month_data['services'] = new_services\n return month_data\n\n\ndef get_invoice_data(month):\n general_data = get_general_invoice_data()\n month_data = get_month_invoice_data(month)\n invoice_data = InvoiceData(general_data, month_data)\n return invoice_data\n\n","sub_path":"inman/get_invoice_data.py","file_name":"get_invoice_data.py","file_ext":"py","file_size_in_byte":7254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"102497025","text":"import plotly as py\nimport plotly.graph_objs as go\npyplt = py.offline.plot\n# Trace\ntrace_basic = [go.Bar(\n x = ['丹麦', '冰岛', '印度','奥地利','德国','意大利','日本','比利时','法国','澳大利亚','瑞典','瑞士','美国','英国'],\n y = [7,2,6,6,15,2,10,1,15,3,4,1,6,10],\n )]\n# Layout\nlayout_basic = go.Layout(\n title = '进口药物国家---分析',\n xaxis = go.XAxis(range = [-0.5,13.5], domain = [0,1])\n )\n# Figure\nfigure_basic = go.Figure(data = trace_basic, layout = layout_basic)\n# Plot\npyplt(figure_basic, filename='1.html')\n","sub_path":"map/venv/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"467844639","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport sl4a\nimport time\nfrom ftplib import FTP\nfrom datetime import datetime\ndroid = sl4a.Android()\n\ndroid.startLocating()\n\nflag = False\n\nwhile flag == False:\n time.sleep(1)\n\n try:\n event = droid.eventWaitFor(\"location\")\n gps = event.result[\"data\"]\n date = datetime.now().strftime('%Y_%m_%d %H:%M:%S')\n flag = True\n\n except:\n flag = False\n\ndroid.stopLocating()\n\nProvider = [\"network\",\"fused\",\"gps\"]\n\nfor name in Provider:\n if (name in gps) == True:\n net_g = gps[name]\n latitude = net_g[\"latitude\"]\n longitude = net_g[\"longitude\"]\n\nftp = FTP(\"hoge\") # hoge = hostdomain\nftp.login(\"hoge\",\"piyo\") # hoge = accountname , piyo = password\n\nwritefile = (str(date) + str(\" : \") + str(latitude) + str(\" , \") + str(longitude) + (\"\\n\"))\n\nfile1 = open(\"/storage/emulated/0/com.hipipal.qpyplus/data/gps.txt\",\"r\") # read original_data\noriginal = file1.read()\nfile1.close()\n\nfile1 = open(\"/storage/emulated/0/com.hipipal.qpyplus/data/gps.txt\",\"w\")\nfile1.write(original + writefile)\nfile1.close()\n\nfile1 = open(\"/storage/emulated/0/com.hipipal.qpyplus/data/gps.txt\",\"rb\")\nftp.storbinary(\"STOR /SL4A/gps.txt\",file1)\nfile1.close()\n\nftp.quit()\n","sub_path":"gps.py","file_name":"gps.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"353268534","text":"import networkx as nx\nimport pandas as pd\nfrom buildPickle import *\nimport threading\nfrom dateFuctions import *\n\nDAY = 86400\n\ndef buildGraph(listingsDF, startDate, endDate):\n startDate = toBaseDate(startDate)\n endDate = toBaseDate(endDate)\n graph = nx.DiGraph()\n graph.add_node('start',id='start',date=startDate,price=0,jumpable=0, priceweek=0)\n graph.add_node('end',id = 'end',date=endDate,price=0,jumpable=0, priceweek=0)\n numOfdays = int((endDate - startDate)/DAY + 1)\n hashtable = [[]]\n for i in range(numOfdays+1):\n hashtable.append([])\n hashtable[0].append('start')\n hashtable[numOfdays].append('end')\n for index, listing in listingsDF.iterrows():\n id=listing['id']\n for i in listing['availability']:\n start = i['start']\n end = i['end']\n curDates = splitToDays(start, end)\n canJumpWeek = len(curDates) - 7\n for index, date in enumerate(curDates):\n if date >= startDate:\n if date >= endDate:\n break\n hashDate = int((date - startDate)/DAY) + 1\n name = str(id) + \"-\" + str(date)\n setJump = index <= canJumpWeek\n graph.add_node(name,id=listing['id'],price=listing['price']['nightly'],priceweek = listing['price']['weekly'],date=date, jumpable=setJump)\n hashtable[hashDate].append(name)\n for i in range(numOfdays+1):\n for first in hashtable[i]:\n firstNode = graph.node[first]\n for scnd in hashtable[i+1]:\n w = graph.node[scnd]['price']\n graph.add_edge(first,scnd,weight=w)\n if firstNode['jumpable']:\n date = firstNode['date'] + DAY*7\n name = str(firstNode['id']) + '-' + str(date)\n graph.add_edge(first,name,weight=firstNode['priceweek'])\n return graph\n\n\ndef buildGraphMultiThreading(picklePath, startDate, endDate):\n startDate = toBaseDate(startDate)\n endDate = toBaseDate(endDate)\n graph = nx.DiGraph()\n graph.add_node('start',id='start',date=startDate,price=0)\n graph.add_node('end',id = 'end',date=endDate,price=0)\n numOfdays = int((endDate - startDate)/DAY + 1)\n hashtable = [[]]\n\n\n for i in range(numOfdays+1):\n hashtable.append([])\n hashtable[0].append('start')\n hashtable[numOfdays].append('end')\n listings = readPickle(picklePath)\n for index, listing in listings.iterrows():\n id=listing['id']\n for i in listing['availability']:\n start = i['start']\n end = i['end']\n curDates = splitToDays(start, end)\n for date in curDates:\n if date >= startDate:\n if date >= endDate:\n break\n hashDate = int((date - startDate)/DAY) + 1\n name = str(id) + \"-\" + str(date)\n graph.add_node(name,id=listing['id'],price=listing['price']['nightly'],date=date)\n hashtable[hashDate].append(name)\n\n #\n #\n # for i in range(numOfdays+1):\n # hashtable.append([])\n # hashtable[0].append('start')\n # hashtable[numOfdays].append('end')\n # listings = readPickle(picklePath)\n # listings = listings.reset_index()\n # numOfListings = len(listings.index)\n # threadNum = 2\n # threads = []\n # gap = numOfListings//threadNum\n # print('heyyy')\n # for i in range(threadNum):\n # startIndex = i*gap\n # endIndex = startIndex + gap\n # thread = threading.Thread(target=graphMultithreadingHelper1, args=(hashtable,graph, startDate, endDate, startIndex, endIndex, listings))\n # threads.append(thread)\n # thread.start()\n # for thread in threads:\n # thread.join()\n # print('byeeee')\n threadNum =2\n threads = []\n gap = len(hashtable)//threadNum\n for i in range(threadNum):\n startIndex = i*gap\n endIndex = startIndex + gap\n thread = threading.Thread(target=graphMultithreadingHelper2, args=(hashtable,graph, startIndex, endIndex))\n threads.append(thread)\n thread.start()\n for thread in threads:\n thread.join()\n\n return graph\n\ndef graphMultithreadingHelper1(hashtable, graph, startDate, endDate, startIndex, endIndex, df):\n for index in range(startIndex, endIndex):\n id=df.loc[index]['id']\n for i in df.loc[index]['availability']:\n start = i['start']\n end = i['end']\n curDates = splitToDays(start, end)\n for date in curDates:\n if date >= startDate:\n if date >= endDate:\n break\n hashDate = int((date - startDate)/DAY) + 1\n name = str(id) + \"-\" + str(date)\n graph.add_node(name,id=df.loc[index]['id'],price=df.loc[index]['price']['nightly'],date=date)\n hashtable[hashDate].append(name)\n\ndef graphMultithreadingHelper2(hashtable, graph, startIndex, endIndex):\n for i in range(startIndex, endIndex):\n for first in hashtable[i]:\n for scnd in hashtable[i+1]:\n w = graph.node[scnd]['price']\n graph.add_edge(first,scnd,weight=w)\n\ndef splitToDays(start, end):\n dates = []\n start = toBaseDate(start)\n end = toBaseDate(end)\n while start <= end:\n dates.append(start)\n start += DAY\n return dates\n\ndef toBaseDate(unix):\n return unix - (unix%DAY)\n\ndef printResultPath(result, myGraph):\n lastID = 0\n startDate = 0\n price = 0\n cost = 0\n stops = []\n curDate = 0\n for day in (range(1, len(result))):\n listing = myGraph.node[result[day]]\n if lastID != listing['id']:\n newDate = listing['date']\n newID = listing['id']\n if(lastID!=0):\n stops.append(\"from \" + printTime(startDate) + \" to \" + printTime(newDate) + ' in id: ' + str(lastID) + \" price: \" +str(price))\n lastID = newID\n startDate = newDate\n price = 0\n oldDate = curDate\n curDate = listing['date']\n days = (curDate - oldDate) / DAY\n if days != 1:\n addition = listing['priceweek']\n else:\n addition = listing['price']\n price += addition\n cost += addition\n for section in stops:\n print(section)\n print(\"total cost = \" + str(cost))\n\ndef returnResultIds(results, graph):\n DAILY = 0\n WEEKLY = 1\n stops = []\n days = 0\n lastId = 0\n cost=0\n curId = 0\n startDate = 0\n price = [0,0]\n for node in range(1,len(results)):\n listing = graph.node[results[node]]\n if curId != listing['id']:\n if curId == 0:\n startDate = listing['date']\n price[DAILY] = listing['price']\n price[WEEKLY] = listing['priceweek']\n curId = listing['id']\n else:\n newDate = listing['date']\n days = int((newDate - startDate)/DAY)\n curPrice = (days//7)*price[WEEKLY] + (days%7)*price[DAILY]\n result = {'name':curId, 'price':curPrice, 'sdate':printTime(startDate), 'edate':printTime(newDate), 'days':days}\n stops.append(result)\n if listing['id'] != 0:\n startDate = listing['date']\n price[DAILY] = listing['price']\n price[WEEKLY] = listing['priceweek']\n curId = listing['id']\n return stops\n\ndef gbp_to_usd(gbp):\n rate = 1.4997\n return int(gbp * rate)\n","sub_path":"graphBuilder.py","file_name":"graphBuilder.py","file_ext":"py","file_size_in_byte":7693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"392444650","text":"#!/usr/bin/env python\n\"\"\"Ice diffraction detection\nAuthors: Hyun Sun Cho, Friedrich Schotte\nDate created: 2017-10-31\nDate last modified: 2017-11-01\n\"\"\"\nfrom logging import debug,warn,info,error\nfrom sample_frozen import sample_frozen\nfrom Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel\nimport wx\n__version__ = \"1.3\" # ROI \n\nclass SampleFrozenPanel(BasePanel):\n name = \"SampleFrozenPanel\"\n title = \"Sample Frozen\"\n standard_view = [\n \"Diffraction Spots\",\n \"Threshold [spots]\",\n \"Deice enabled\",\n \"Deicing\",\n ]\n parameters = [\n [[PropertyPanel,\"Diffraction Spots\",sample_frozen,\"diffraction_spots\"],{\"read_only\":True}],\n [[PropertyPanel,\"Threshold [spots]\",sample_frozen,\"threshold_N_spts\"],{\"choices\":[1,10,20,50]}],\n [[TogglePanel, \"Deice enabled\", sample_frozen,\"running\"],{\"type\":\"Off/Monitoring\"}],\n [[TogglePanel, \"Deicing\", sample_frozen,\"deicing\"],{\"type\":\"Not active/Active\"}],\n [[PropertyPanel,\"ROIX\", sample_frozen,\"ROIX\"],{\"choices\":[1000,900]}],\n [[PropertyPanel,\"ROIY\", sample_frozen,\"ROIY\"],{\"choices\":[1000,900]}],\n [[PropertyPanel,\"WIDTH\", sample_frozen,\"WIDTH\"],{\"choices\":[150,300,400]}],\n ]\n def __init__(self,parent=None):\n BasePanel.__init__(self,\n parent=parent,\n name=self.name,\n title=self.title,\n icon=\"Tool\",\n parameters=self.parameters,\n standard_view=self.standard_view,\n )\n\nif __name__ == '__main__':\n from pdb import pm\n import logging\n from tempfile import gettempdir\n logfile = gettempdir()+\"/SampleFrozenPanel.log\"\n logging.basicConfig(level=logging.INFO,\n format=\"%(asctime)s %(levelname)s: %(message)s\",\n logfile=logfile,\n )\n # Needed to initialize WX library\n if not \"app\" in globals(): app = wx.App(redirect=False)\n panel = SampleFrozenPanel()\n app.MainLoop()\n","sub_path":"SampleFrozenPanel.py","file_name":"SampleFrozenPanel.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"193152342","text":"import urwid\n\n\nclass ListWidget(urwid.WidgetWrap):\n _selectable = True\n\n def __init__ (self, id, senders, exim):\n self.id = id\n self.sender = senders[id][0]\n self.nbr_mails = senders[id][1]\n self.details = exim[self.sender]\n\n self.item = [\n urwid.AttrWrap(urwid.Text(\"%s\" % self.sender), 'body', 'focus'),\n ('fixed', 10, urwid.AttrWrap(urwid.Text(\"%s\" % self.nbr_mails), 'body', 'focus')),\n ]\n\n w = urwid.Columns(self.item)\n self.__super.__init__(w)\n\n def selectable (self):\n return True\n\n def keypress(self, size, key):\n return key\n \nclass ListDetails(urwid.WidgetWrap):\n _selectable = True\n\n def __init__ (self, key, details):\n self.details = details\n for item in self.details:\n self.item = [\n urwid.AttrWrap(urwid.Text(item), 'body', 'focus'),\n# urwid.Text(item),\n ]\n w = urwid.Columns(self.item)\n self.__super.__init__(w)\n\n def selectable (self):\n return True\n\n def keypress(self, size, key):\n return key\n\n\n\n# Exim parser function:\ndef parse_exim():\n exim={}\n bulk_threshold = 5\n e = open('exim', 'r')\n for line in e: #output.split('\\n'):\n '''\n returns dictionary {sender: {msgid: [[time_in_queue, subject], [receiver1, receiver2, ..., receiverN]\n '''\n entry = line.strip().split(' ')\n if len(entry) > 3:\n sender = entry[len(entry)-1].strip('\\n').lstrip('<').rstrip('>')\n msgid = entry[len(entry)-2]\n in_queue = entry[0]\n if sender not in exim.keys():\n exim[sender] = {}\n exim[sender][msgid] = [[in_queue], []]\n elif entry != ['\\n'] and len(entry) < 4 and '@' in entry[0]:\n exim[sender][msgid][1].append(entry[len(entry)-1].strip('\\n'))\n senders = []\n for sender in exim:\n '''\n returns number of mail each sender is sending\n '''\n senders.append([sender, len(exim[sender])])\n i = senders.index([sender, len(exim[sender])])\n for msg_id in exim[sender]:\n if len(exim[sender][msg_id][1]) > bulk_threshold:\n senders[i].append('BULK')\n\n # sorting senders by number of senders they are sending, descending\n senders.sort(key = lambda s: s[1], reverse=True)\n return exim, senders\n\n\ndef main():\n\n palette = [\n ('body','dark cyan', '', 'standout'),\n ('focus','dark red', '', 'standout'),\n ('head','light red', 'black'),\n ]\n\n\n # Unhandled input\n def keystrokes( input ):\n if input in ('q','Q'):\n raise urwid.ExitMainLoop()\n if input is 'enter':\n focus = list_list.get_focus()[0].sender\n list_details = list_list.get_focus()[0].details\n view.set_header(urwid.LineBox(urwid.AttrWrap(urwid.Text(\n 'Selected: %s' % str(list_details)), 'head')))\n\n \n exim, senders = parse_exim()\n\n items = []\n item_details = []\n for i in range(len(senders)):\n items.append(ListWidget(i, senders, exim))\n\n\n list_details = {}\n list_list = urwid.ListBox(urwid.SimpleListWalker(items))\n body = urwid.Columns([ ('weight', 1, list_list), ('weight', 2, right_col) ])\n\n header = urwid.LineBox(urwid.Text('Selected: .. '))\n footer = urwid.LineBox(urwid.Text(str(item_details)))\n\n view = urwid.AttrWrap(urwid.Frame(body=body, header=header, footer=footer), 'body')\n\n\n loop = urwid.MainLoop(view, palette, handle_mouse=False, unhandled_input=keystrokes)\n loop.run()\n\nif __name__ == '__main__':\n main()\n","sub_path":"urwid/exim_interface/old/exitop.py","file_name":"exitop.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"234977064","text":"import csv\nimport sys\n\nwith open(sys.argv[1]) as input_tier:\n reader = csv.reader(input_tier)\n\n tier = []\n for x in reader:\n tier.append(int(x[0]))\n\n\ntier_num = sys.argv[2]\ntier_file_name = \"mass_tier_\" + tier_num+'.csv'\ntier_set = set({})\n\nfor i in range(len(tier)):\n for j in range(i, len(tier)):\n tier_set.add(str(tier[i] + tier[j]))\n\n\n# commented out for performance analysis\nwith open(tier_file_name, 'w', 1) as outfile:\n\n for x in tier_set:\n outfile.write(x)\n outfile.write(',\\n')\n\n","sub_path":"Python/protein_tree/half_matrix_hash.py","file_name":"half_matrix_hash.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"298313014","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# This program is dedicated to the public domain under the CC0 license.\n\n\"\"\"\nSimple Bot to send timed Telegram messages.\nThis Bot uses the Updater class to handle the bot and the JobQueue to send\ntimed messages.\nFirst, a few handler functions are defined. Then, those functions are passed to\nthe Dispatcher and registered at their respective places.\nThen, the bot is started and runs until we press Ctrl-C on the command line.\nUsage:\nBasic Alarm Bot example, sends a message after a set time.\nPress Ctrl-C on the command line or send a signal to the process to stop the\nbot.\n\"\"\"\n\nfrom telegram.ext import Updater, CommandHandler\nimport requests\nfrom logging import Handler, Formatter\nimport datetime\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\n\ncommands = { # command description used in the \"help\" command\n 'start' : 'Get used to the bot',\n 'help' : 'Gives you information about the available commands',\n 'sendLongText': 'A test using the \\'send_chat_action\\' command',\n 'getImage' : 'A test using multi-stage messages, custom keyboard, and media sending',\n 'getVideo' : 'Today videos!'\n}\n# Define a few command handlers. These usually take the two arguments update and\n# context. Error handlers also receive the raised TelegramError object in error.\n\ndef help(update, context):\n cid = update.message.chat_id\n help_text = \"The following commands are available: \\n\"\n for key in commands: # generate help text out of the commands dictionary defined at the top\n help_text += \"/\" + key + \": \"\n help_text += commands[key] + \"\\n\"\n context.bot.send_message(cid, help_text) # send the generated help page\n\n\ndef start(update, context):\n update.message.reply_text('Hi! Use /set to set a timer')\n \n\ndef alarm(context):\n \"\"\"Send the alarm message.\"\"\"\n job = context.job\n context.bot.send_message(job.context, text='Beep!')\n\ndef hello(context):\n job = context.job\n context.bot.send_message(job.context, text='Hello whats up!')\n\n\ndef test(update, context):\n chat_id = update.message.chat_id\n context.job_queue.run_once(hello, 10, context=chat_id)\n print(chat_id)\n print(str(update))\n\ndef set_timer(update, context):\n \"\"\"Add a job to the queue.\"\"\"\n chat_id = update.message.chat_id()\n try:\n # args[0] should contain the time for the timer in seconds\n due = int(context.args[0])\n if due < 0:\n update.message.reply_text('Sorry we can not go back to future!')\n return\n\n # Add job to queue and stop current one if there is a timer already\n if 'job' in context.chat_data:\n old_job = context.chat_data['job']\n old_job.schedule_removal()\n\n\n new_job = context.job_queue.run_once(alarm, due, context=chat_id)\n context.chat_data['job'] = new_job\n\n update.message.reply_text('Timer successfully set!')\n\n except (IndexError, ValueError):\n update.message.reply_text('Usage: /set ')\n\n\n\ndef unset(update, context):\n \"\"\"Remove the job if the user changed their mind.\"\"\"\n if 'job' not in context.chat_data:\n update.message.reply_text('You have no active timer')\n return\n\n job = context.chat_data['job']\n job.schedule_removal()\n del context.chat_data['job']\n\n update.message.reply_text('Timer successfully unset!')\n\n\ndef error(update, context):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, context.error)\n\n\ndef main():\n \"\"\"Run bot.\"\"\"\n # Create the Updater and pass it your bot's token.\n # Make sure to set use_context=True to use the new context based callbacks\n # Post version 12 this will no longer be necessary\n updater = Updater(\"970406731:AAGRJVcUeDSnWZP39x70jRdcfvlmECVLHNQ\", use_context=True)\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # on different commands - answer in Telegram\n dp.add_handler(CommandHandler(\"help\", help))\n dp.add_handler(CommandHandler(\"test\", test))\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"help\", start))\n dp.add_handler(CommandHandler(\"set\", set_timer,pass_args=True,pass_job_queue=True,pass_chat_data=True))\n dp.add_handler(CommandHandler(\"unset\", unset, pass_chat_data=True))\n \n\n \n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_polling()\n\n # Block until you press Ctrl-C or the process receives SIGINT, SIGTERM or\n # SIGABRT. This should be used most of the time, since start_polling() is\n # non-blocking and will stop the bot gracefully.\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n \n \n","sub_path":"timer_message.py","file_name":"timer_message.py","file_ext":"py","file_size_in_byte":4883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"137724632","text":"# sum1 = 0;\n# sum2 = 0;\n# cnt1 = 0;\n# cnt2 = 0;\n# for i in range(1,101):\n# if i % 2 == 1:\n# sum1 += i\n# cnt1 += 1\n# else:\n# sum2 += i\n# cnt2 += 1\n# print(cnt1)\n# print(cnt2)\n# print(sum1)\n# print(sum2)\n# print(sum1/cnt1)\n# print(sum2/cnt2)\ncnt2 = 0;\ncnt3 = 0;\ncnt5 = 0;\nsum2 = 0;\nsum3 = 0;\nsum5 = 0;\nfor i in range(1,1001):\n if i % 2 == 0:\n sum2 += i\n cnt2 += 1\n if i % 3 == 0:\n sum3 += i\n cnt3 += 1\n if i % 5 == 0:\n sum5 += i\n cnt5 += 1\n\nprint(cnt2)\nprint(cnt3)\nprint(cnt5)\nprint(sum2)\nprint(sum3)\nprint(sum5)\nprint(sum2/cnt2)\nprint(sum3/cnt3)\nprint(sum5/cnt5)","sub_path":"python/day03/test04.py","file_name":"test04.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"188384014","text":"\"\"\"Detect when a timeseries shifts by more than a fixed percentage.\"\"\"\n\nimport numpy as np\nfrom scipy.stats import distributions\n\nfrom perfkit.alerts import anomaly\nfrom perfkit.alerts.detectors import train_util\nfrom perfkit.alerts.detectors import validation_util\n\n\nNAME = 'percent_change'\nDESCRIPTION = \"\"\"Flags values as anomalous when they are more than configurable\na percentage change from the previous value.\"\"\"\nCONFIG_SCHEMA = {\n 'type': 'object',\n 'properties': {\n 'min': {\n 'label': 'Maximum decrease (%)',\n 'description': 'Maximum % decrease to accept without flagging.',\n 'type': 'number',\n 'minimum': 0,\n 'exclusiveMinimum': True\n },\n 'max': {\n 'label': 'Maximum increase (%)',\n 'description': 'Maximum % increase to to accept without flagging.',\n 'type': 'number',\n 'minimum': 0,\n 'exclusiveMinimum': True\n },\n },\n 'additionalProperties': False\n }\n\n\ndef ComputeAnomalies(dates, values, config):\n \"\"\"Compute anomalies for a time series.\n\n The time series is represented as a list of datetime.datetimes and a\n list of the values we measured at those times. We identify\n measurements that look surprising (for some model of a time series)\n and return a list of them, along with the reasons we marked them as\n anomalous.\n\n Args:\n dates: list of datetime.dates. Must be unique.\n values: list of numbers.\n config: dict. Holds our parameters.\n\n Returns:\n A list of (index, Anomaly) pairs.\n\n Raises:\n AssertionError: if dates and values are of different lengths, or neither min\n nor max are specified.\n \"\"\"\n\n if len(dates) != len(values):\n raise AssertionError(\n 'ComputeAnomalies called with differently-sized columns',\n dates, values)\n\n min_threshold = config.get('min')\n max_threshold = config.get('max')\n indexes = []\n\n if not min_threshold and not max_threshold:\n raise AssertionError(\n 'Either minimum or maximum threshold must be specified.',\n config)\n\n anomalies = []\n\n for i in xrange(1, len(values)):\n percent_change = ((float(values[i] - values[i - 1]) / values[i - 1]) * 100)\n\n if min_threshold is not None and percent_change < -min_threshold:\n anomalies.append((i, anomaly.Anomaly(\n dates[i],\n values[i],\n 'Decreased by {0} percent.'.format(-percent_change))))\n elif max_threshold is not None and percent_change > max_threshold:\n indexes.append(i)\n anomalies.append((i, anomaly.Anomaly(\n dates[i],\n values[i],\n 'Increased by {0} percent.'.format(percent_change))))\n\n return anomalies\n\n\ndef ValidateConfig(config):\n \"\"\"Verifies that min and/or max is present.\"\"\"\n validation_util.CheckContainsSubset(config, ['min', 'max'], NAME)\n\n\nclass _PercentChangeClassifier(train_util.AnomalyKitClassifier):\n \"\"\"Shim to use ComputeAnomalies with sklearn.\"\"\"\n compute_anomalies = staticmethod(ComputeAnomalies)\n\n # TODO(connormccoy) Rename these keys to prevent overlapping with built-ins.\n def __init__(self, min=None, max=None): # pylint: disable=redefined-builtin\n self.min = min\n self.max = max\n\n\ndef Train(dates, values, anomalies, scoring=train_util.DEFAULT_SCORING):\n \"\"\"Optimize min and max to identify 'anomalies'.\"\"\"\n # TODO(connormccoy): Better bounds? Initializing as Unif(0, max_percent_diff).\n arr = np.array(values)\n dist = distributions.uniform(0.0, max(abs(np.diff(arr) / arr[:-1])) * 100)\n\n search_params = {'min': dist, 'max': dist}\n\n clf = _PercentChangeClassifier()\n\n return train_util.DoTrain(dates=dates, values=values, anomalies=anomalies,\n classifier=clf, search_distributions=search_params,\n scoring=scoring)\n","sub_path":"alerts/perfkit/alerts/detectors/percent_change.py","file_name":"percent_change.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"146632086","text":"def main():\r\n\r\n frase = input('Digite uma frase: ')\r\n nova_frase = ''\r\n\r\n for letra in frase:\r\n if eh_algarismo(letra) == True:\r\n letra = algarismo(letra)\r\n nova_frase += letra\r\n else:\r\n nova_frase += letra\r\n\r\n print(nova_frase)\r\n\r\ndef eh_algarismo(x):\r\n\r\n numeros = '1234567890'\r\n return x in numeros\r\n\r\ndef algarismo(x):\r\n if x == '0':\r\n return ' Zero '\r\n elif x == '1':\r\n return ' Um '\r\n elif x == '2':\r\n return ' Dois '\r\n elif x == '3':\r\n return ' Tres '\r\n elif x == '4':\r\n return ' Quatro '\r\n elif x == '5':\r\n return ' Cinco '\r\n elif x == '6':\r\n return ' Seis '\r\n elif x == '7':\r\n return ' Sete '\r\n elif x == '8':\r\n return ' Oito '\r\n elif x == '9':\r\n return ' Nove '\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Python/Fabio lista 5 for/Fabio_06_Q06.py","file_name":"Fabio_06_Q06.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"307461519","text":"\"\"\"\nConverts a google sheet to a JSON object and writes it to a file \n\"\"\"\nfrom apiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\nimport itertools\nimport sys, json, ast\nimport pprint\n\npp = pprint.PrettyPrinter(indent=2)\n\n# Setup the Sheets API\nSCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'\nSPREADSHEET_ID = '14qDT52ycqNx-XHp0x_IzSMwTRg81v2ED0Ae0wgwBlYI'\n\nDEFAULT_RANGE = 'A2:O'\n\n# Columns A-F\nSHEET_HEADERS = [\"type\", \"label\", \"condition\", \"title\", \"answers\", \"datalabel\"]\n\n# Columns B-E\nOUTPUT_RANGE = 'B2:E'\nOUTPUT_HEADERS = [\"datalabel\", \"notes\", \"short\", \"long\"]\nHOWTO_HEADERS = [\"datalabel\", \"actionlabel\", \"plan\", \"how\"]\n\n# Columns C-G\nWEIGHT_HEADERS = [\"datalabel\", \"score\", \"weight\", \"balance\"]\nWEIGHT_RANGE = 'D2:G'\n\ndef get_sheet_from_google(sheet):\n store = file.Storage('credentials.json')\n creds = store.get()\n\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)\n creds = tools.run_flow(flow, store)\n\n service = build('sheets', 'v4', http=creds.authorize(Http()))\n\n # Call the Sheets API\n result = service.spreadsheets().values().get(\n spreadsheetId=SPREADSHEET_ID, \n range=sheet).execute()\n\n return result\n\ndef main():\n\n if len(sys.argv[1:]):\n module = sys.argv[1:][0]\n else:\n raise ValueError(\"You must specify a module.\")\n\n\n if module == 'outputs':\n generate_outputs()\n else:\n generate_module(module) \n\ndef generate_outputs():\n\n weight_sheet = 'Weight_Score!%s' % (WEIGHT_RANGE)\n weight_data = get_sheet_from_google(weight_sheet)\n weight_values = weight_data.get('values', [])\n weight_object = values_to_objects(weight_values, WEIGHT_HEADERS)\n\n output_sheet = 'output!%s' % (OUTPUT_RANGE)\n output_data = get_sheet_from_google(output_sheet)\n output_values = output_data.get('values', [])\n output_object = values_to_objects(output_values, OUTPUT_HEADERS)\n\n howto_sheet = 'HowTo!%s' % (OUTPUT_RANGE)\n howto_data = get_sheet_from_google(howto_sheet)\n howto_values = howto_data.get('values', [])\n\n action_sheet = 'ActionPlan!%s' % (OUTPUT_RANGE)\n action_data = get_sheet_from_google(action_sheet)\n action_values = action_data.get('values', [])\n action_object, action_lookup = action_to_objects(action_values, howto_values)\n\n for k, v in output_object.iteritems():\n weight = weight_object.get(k, None)\n v['actions'] = action_lookup.get(k, None)\n\n if weight:\n v.update(weight)\n\n output_file = open(\"surveys/outputs.json\", \"w\")\n output_file.write(json.dumps(output_object, indent=2, sort_keys=True))\n\ndef generate_module(module):\n survey = []\n page = []\n\n survey_sheet = '%s!%s' % (module, DEFAULT_RANGE)\n survey_data = get_sheet_from_google(survey_sheet)\n survey_values = survey_data.get('values', [])\n\n for idx, row in enumerate(survey_values):\n\n ## page means new list\n if row[0] == 'page':\n survey.append(page)\n page = []\n continue\n\n answers = expand_answers(row)\n\n ## no question label means answer values belong to previous row\n if not row[1]:\n question[\"answers\"] = question[\"answers\"] + answers\n continue\n\n question = dict(zip(SHEET_HEADERS, row[:6]))\n\n question[\"answers\"] = answers \n\n del question['datalabel']\n\n page.append(question)\n\n survey_file = open(\"surveys/%s.json\" % module, \"w\")\n survey_file.write(json.dumps(survey, indent=2, sort_keys=True))\n\ndef action_to_objects(actions, howto):\n ''' return list of actions by datalabel and\n write action.json lookup file\n TODO: probably weights\n '''\n\n datalabel = ''\n actions_per_datalabel = {}\n action_object = {}\n howto_object = {}\n\n for how in howto:\n #build the how to object\n how_obj = dict(zip(HOWTO_HEADERS, how)) \n action_how = how_obj.get('how', None)\n if len(how) == 4:\n howto_object[how_obj['actionlabel']] = action_how\n\n for action in actions:\n if action and action[0]:\n datalabel = action[0]\n actions_per_datalabel[datalabel] = []\n else:\n datalabel = datalabel\n\n action_object[datalabel] = action_object.get(datalabel, {})\n\n if len(action) < 2:\n actions_per_datalabel[datalabel] = []\n else: \n actionlabel = action[1]\n actions_per_datalabel[datalabel].append(actionlabel)\n action_object[datalabel][actionlabel] = {\n 'plan': action[2],\n 'how': howto_object.get(actionlabel, None)\n }\n\n return actions_per_datalabel, action_object\n\n\ndef values_to_objects(values, header):\n data = {}\n\n for value in values:\n if not value:\n continue\n\n data[value[0]] = {} \n\n for i in itertools.izip_longest(header[1:], value[1:], ''):\n data[value[0]][i[0]] = i[1]\n\n # import pdb;pdb.set_trace()\n return data\n\ndef expand_answers(row):\n answer = []\n\n try:\n row_text = ast.literal_eval(row[4])\n except (ValueError, SyntaxError):\n row_text = row[4]\n\n if isinstance(row_text, list):\n for r in row_text:\n answer.append({\n \"text\": str(r),\n \"label\": row[5]\n })\n else:\n ans_obj = {\n \"text\": row[4],\n \"label\": row[5]\n }\n\n if '.other' in ans_obj['label']:\n ans_obj['open'] = True\n\n answer.append(ans_obj)\n\n return answer\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"sheet_to_json.py","file_name":"sheet_to_json.py","file_ext":"py","file_size_in_byte":5679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"191974380","text":"# !/Library/Frameworks/Python.framework/Versions/3.7/bin/python3\n# @blog : www.jiazhixiang.xyz\n# @Author : Jiazhixiang\n# -*- coding:utf-8 -*-\n# coding=utf-8\n\n'''\n字符\t功能\n*\t匹配前一个字符出现0次或者无限次,即可有可无\n+\t匹配前一个字符出现1次或者无限次,即至少有1次\n?\t匹配前一个字符出现1次或者0次,即要么有1次,要么没有\n{m}\t匹配前一个字符出现m次\n{m,n}\t匹配前一个字符出现从m到n次\n\n\n'''\n# 示例2:+\n# 需求:匹配出,变量名是否有效\nimport re\n\nnames = [\"name1\", \"_name\", \"2_name\", \"__name__\"]\n\nfor name in names:\n ret = re.match(\"[a-zA-Z_]+[\\w]*\", name)\n # if ret:\n # print(\"变量名 %s 符合要求\" % ret.group())\n # else:\n # print(\"变量名 %s 非法\" % name)\n\ndata = re.match(\"[a-zA-Z_]+[\\w]*\", \"name134\")\nprint(data.group())\n\ndata = re.match(\"[a-zA-Z_]+[\\d]\", \"Name134\")\nprint(data.group())\n\ndata = re.match(\"[a-zA-Z_]+[\\d]\", \"name134\")\nprint(data.group())\n\ndata = re.match(\"[a-zA-Z_]+[\\d]+\", \"name134\")\nprint(data.group())\n\n","sub_path":"02-Regular/03-2匹配多个字符.py","file_name":"03-2匹配多个字符.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"626826245","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse\nfrom django.contrib import messages\nimport logging, traceback\nimport checkout.constants as constants\nimport checkout.config as config\nimport hashlib\nimport requests\nfrom random import randint\nfrom django.views.decorators.csrf import csrf_exempt\n\n# Create your views here.\ndef home(request):\n return render(request, 'checkout/home.html')\n\ndef payment(request):\n\n\n data = {}\n txnid = get_transaction_id()\n hash_ = generate_hash(request, txnid)\n hash_string = get_hash_string(request, txnid)\n # use constants file to store constant values.\n # use test URL for testing\n data[\"action\"] = constants.PAYMENT_URL_LIVE \n data[\"amount\"] = float(constants.PAID_FEE_AMOUNT)\n data[\"productinfo\"] = constants.PAID_FEE_PRODUCT_INFO\n data[\"key\"] = config.KEY\n data[\"txnid\"] = txnid\n data[\"hash\"] = hash_\n data[\"hash_string\"] = hash_string\n data[\"firstname\"] = request.session[\"student_user\"][\"name\"]\n data[\"email\"] = request.session[\"student_user\"][\"email\"]\n data[\"phone\"] = request.session[\"student_user\"][\"mobile\"]\n data[\"service_provider\"] = constants.SERVICE_PROVIDER\n data[\"furl\"] = request.build_absolute_uri(reverse(\"students:payment_failure\"))\n data[\"surl\"] = request.build_absolute_uri(reverse(\"students:payment_success\"))\n return render(request, 'checkout/payment.html', data) \n\n\n# generate the hash\ndef generate_hash(request, txnid):\n # get keys and SALT from dashboard once account is created.\n # hashSequence = \"key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10\"\n hash_string = get_hash_string(request,txnid)\n generated_hash = hashlib.sha512(hash_string.encode('utf-8')).hexdigest().lower()\n return generated_hash\n \n\n# create hash string using all the fields\ndef get_hash_string(request, txnid):\n hash_string = config.KEY+\"|\"+txnid+\"|\"+str(float(constants.PAID_FEE_AMOUNT))+\"|\"+constants.PAID_FEE_PRODUCT_INFO+\"|\"\n hash_string += request.session[\"student_user\"][\"name\"]+\"|\"+request.session[\"student_user\"][\"email\"]+\"|\"\n hash_string += \"||||||||||\"+config.SALT\n\n return hash_string\n\n# generate a random transaction Id.\ndef get_transaction_id():\n hash_object = hashlib.sha256(str(randint(0,9999)).encode(\"utf-8\"))\n # take approprite length\n txnid = hash_object.hexdigest().lower()[0:32]\n return txnid\n\n# no csrf token require to go to Success page. \n# This page displays the success/confirmation message to user indicating the completion of transaction.\n@csrf_exempt\ndef payment_success(request):\n data = {}\n return render(request, \"checkout/success.html\", data)\n\n# no csrf token require to go to Failure page. This page displays the message and reason of failure.\n@csrf_exempt\ndef payment_failure(request):\n data = {}\n return render(request, \"checkout/failure.html\", data) ","sub_path":"payuone/checkout/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"583938193","text":"import pyperclip\n\n__command__ = \"findc\"\n__usage__ = \"findc\"\n__description__ = \"Search in clipboard content\"\n\ndef run(shell, args): \t\t\n\tprint(\"searching for \"+args[0])\n\tcontent = pyperclip.paste()\n\tresult = \"\"\n\tif content is None or len(content) == 0 :\n\t\treturn result\n\tfor line in content.splitlines() :\n\t\tif args[0].lower() in line.lower() : \n\t\t\tresult = result + line + \"\\r\\n\"\n\t\t\treturn result","sub_path":"tasks/clipboardfind.py","file_name":"clipboardfind.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"145092269","text":"import cv2\r\n\r\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\r\n\r\nimg = cv2.imread(\"news.jpg\")\r\ngrey_image = cv2.imread(\"news.jpg\", 0)\r\n#grey_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Converts image to greyscale.\r\n\r\nfaces = face_cascade.detectMultiScale(grey_image, scaleFactor=1.05, minNeighbors=5)\r\n\r\nfor x, y, h, w in faces:\r\n img=cv2.rectangle(img, (x,y),(x+w, y+h), (0,255,0), 3)\r\n # Params: img-file to draw on\r\n # (x,y)- coordinates of the left hand top of rectangle\r\n # (x+w, y+h) - Coordinates of lower right edge of rectangle\r\n # (0,233,0) - BGR value of rectangle\r\n # 3 - width of rectangle\r\n \r\n \r\nprint(type(faces))\r\nprint(faces)\r\n\r\ncv2.imshow('Gray', img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()","sub_path":"facial_detector.py","file_name":"facial_detector.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"610204861","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 20 15:26:04 2018\n\n@author: root\n\"\"\"\n\nimport scipy.io as sio\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport pandas as pd\nimport sklearn\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n\n\n\n#################### 1 - Preprocessing #################### \n\n########## 1.1 - Loading the training set and test set\n\ntraining = sio.loadmat('Training_2015.mat', squeeze_me=True)\ntest = sio.loadmat('Testset_2011.mat', squeeze_me=True)\n\n# Get variables names, both dataset have the same variables\ntraining.keys()\n\n# Extracting variables\n# Depth is the same in both dataset\nDepth_train = training['Depth']\nDepth_test = test['Depth']\n\nEchogram_train = training['Echogram']\nCleanBottom_train = training['CleanBottom']\nLongitude_train = training['Longitude']\nLatitude_train = training['Latitude']\n\n\n\nEchogram_test = test['Echogram']\nCleanBottom_test = test['CleanBottom']\nLongitude_test = test['Longitude']\nLatitude_test = test['Latitude']\n\n########## 1.2 - Getting the index of the last non Nan value\n## We start by getting indices where there CleanBottom is deeper than 500\n# and when it is not.\n\n### splitting the training CleanBottom\ndeep_index_train = CleanBottom_train >= 500\ndeep_index_train = deep_index_train.nonzero()[0]\n\nshallow_index_train = CleanBottom_train < 500\nshallow_index_train = shallow_index_train.nonzero()[0]\n\n### splitting the test CleanBottom\ndeep_index_test = CleanBottom_test >= 500\ndeep_index_test = deep_index_test.nonzero()[0]\n\nshallow_index_test = CleanBottom_test < 500\nshallow_index_test = shallow_index_test.nonzero()[0]\n\n## We create a function to get the last non Nan value\ndef last_depth_index(Echogram, shallow_index, deep_index):\n \"\"\"\n In this function we will return the last non nan value of Echogram.\n \n Arguments :\n - Echogram is the dataset of Echogram18\n - shallow_index is the indices of all pings corresponding to a bottom < 500\n - deep_index is all other pings associated with a bottom >= 500\n \n Output :\n A vector echolight wth the same length than CleanBottom but with only \n the Sv of the deepest non nan value. \n \"\"\"\n # 0 - Getting some relevant shape from the arguments\n (n,m) = Echogram.shape\n deepsize = deep_index.size\n shallowsize = shallow_index.size\n \n ## 1 - We create three dataset : lastDepthIndex, deepdepth and shallowdepth \n ## lastDepthIndex will be for each ping the index of the last non nan value.\n deepdepth = np.zeros(deepsize, dtype = int)\n shallowdepth = np.zeros(shallowsize, dtype = int)\n lastDepthIndex = np.zeros(m, dtype = int)\n \n # the indices associated with deep index does not admit any nan so we turn\n # back the last index \n deepdepth += (n-1)\n \n ## Here we get the index of the last non nan value to convince yourself that\n # it works look at the section test down below.\n shallowdepth = np.sum(~np.isnan(Echogram[:,shallow_index]), axis=0) -1\n \n ## Now it's time to fill out lastDepthIndex \n lastDepthIndex[shallow_index] = shallowdepth\n lastDepthIndex[deep_index] = deepdepth\n \n return lastDepthIndex\n\n\n\nlastDepthIndex_train = last_depth_index(Echogram_train, shallow_index_train, deep_index_train)\nlastDepthIndex_test = last_depth_index(Echogram_test, shallow_index_test, deep_index_test)\n\n\n########## 1.3 - Getting a lighted version of Echogram\n\n### For the training set\n(n_train,m_train) = Echogram_train.shape\ncolumns = np.arange(m_train)\necho_indices = list(zip(lastDepthIndex_train,columns))\n\necholight_train = np.zeros(m_train)\nfor kping in range(m_train):\n echolight_train[kping] = Echogram_train[echo_indices[kping]]\n \n### For the test set\n(n_test,m_test) = Echogram_test.shape\ncolumns = np.arange(m_test)\necho_indices = list(zip(lastDepthIndex_test,columns))\n\necholight_test = np.zeros(m_test)\nfor kping in range(m_test):\n echolight_test[kping] = Echogram_test[echo_indices[kping]]\n \n \n# Ok now we are ready to fit any model\n\n#################### 2 - Linear Regression #################### \n# Since we do not have the echogram for corresponding to depth greater than \n# 500m we set all of bottom values found greater tha 500m to 500m \n\nCleanBottom_train[deep_index_train] = 500 \nCleanBottom_test[deep_index_test] = 500\n\n## Then we select for each ping the depth corresponding to \n# the last non Nan value in Echogram\npingDepth_train = np.zeros(m_train)\nfor kping in range(m_train):\n pingDepth_train[kping] = Depth_train[lastDepthIndex_train[kping]]\n \npingDepth_test = np.zeros(m_test)\nfor kping in range(m_test):\n pingDepth_test[kping] = Depth_test[lastDepthIndex_test[kping]] \n \n \n \n# Now let's create some DataFrame to fit the model \n\n## Creating X_train and Y_train \npingDepth_train = pd.DataFrame(pingDepth_train, columns = ['pingDepth']) \nechoLight_train = pd.DataFrame(echolight_train, columns = ['echoLight'])\nlatitude_train = pd.DataFrame(Latitude_train, columns = ['latitude'])\nlongitude_train = pd.DataFrame(Longitude_train, columns = ['longitude'])\nX_train = pd.concat([pingDepth_train,longitude_train,latitude_train,echoLight_train], axis = 1)\nY_train = pd.DataFrame(CleanBottom_train, columns = ['cleanBottom']) \n\n## Creating X_test and Y_test\npingDepth_test = pd.DataFrame(pingDepth_test, columns = ['pingDepth']) \nechoLight_test = pd.DataFrame(echolight_test, columns = ['echoLight'])\nlatitude_test = pd.DataFrame(Latitude_test, columns = ['latitude'])\nlongitude_test = pd.DataFrame(Longitude_test, columns = ['longitude'])\nX_test = pd.concat([pingDepth_test,longitude_test,latitude_test,echoLight_test], axis = 1)\nY_test = pd.DataFrame(CleanBottom_test, columns = ['cleanBottom']) \n\n\n## Now let's plot and compare the data.\n## As you can see pingDepth and Y looks a lot similar\n# Let's plot both data\n## Data from the training set\npings = np.arange(m_train)\nplt.xlabel('Pings')\nplt.ylabel('Profondeur')\nplt.plot(pings,pingDepth_train)\nplt.plot(pings,Y_train)\nplt.legend(['PingDepth', 'CleanBottom']) \nplt.title('Training Set 2015')\n\n## Data from the test set\npings = np.arange(m_test)\nplt.xlabel('Pings')\nplt.ylabel('Profondeur')\nplt.plot(pings,pingDepth_test)\nplt.plot(pings,Y_test)\nplt.legend(['PingDepth', 'CleanBottom'], loc='lower right') \nplt.title('Test Set 2011')\n\n\n\n## Creating a LinearRegression object\nlm = LinearRegression()\nlm.fit(X_train,Y_train)\n\nY_pred_test = lm.predict(X_test)\nY_pred_train = lm.predict(X_train)\n\n# Measuring effectiveness of the linear model, computing training and test error;\n# mae stand for Mean Absolute Error \n\nmae_train = np.mean(abs(Y_train-Y_pred_train))\nmae_test = np.mean(abs(Y_test-Y_pred_test))\n","sub_path":"Python/Linear_Model.py","file_name":"Linear_Model.py","file_ext":"py","file_size_in_byte":6771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"49885586","text":"import unittest\n\nfrom pbxproj.pbxsections.PBXBuildFile import PBXBuildFile\nfrom pbxproj.PBXGenericObject import PBXGenericObject\nfrom pbxproj.XcodeProject import XcodeProject\n\n\nclass PBXBuildFileTest(unittest.TestCase):\n def testPrintOnSingleLine(self):\n obj = {\"isa\": \"PBXBuildFile\", \"name\": \"something\"}\n dobj = PBXBuildFile().parse(obj)\n\n self.assertEqual(dobj.__repr__(), \"{isa = PBXBuildFile; name = something; }\")\n\n def testGetComment(self):\n obj = {\n 'objects': {\n '1': {\"isa\": \"PBXBuildFile\", \"name\": \"something\", 'fileRef': 'FDDF6A571C68E5B100D7A645'},\n 'FDDF6A571C68E5B100D7A645': {'isa': 'PBXFileReference', \"name\": \"real name\"},\n \"X\": {'isa': 'phase', 'name': 'X', 'files': ['1']}\n }\n }\n dobj = XcodeProject().parse(obj)\n\n self.assertEqual(dobj.objects['1']._get_comment(), \"real name in X\")\n\n def testGetCommentForNonExistentRef(self):\n obj = {\n 'objects': {\n 'FDDF6A571C68E5B100D7A645': {'isa': 'PBXBuildFile'},\n \"X\": {'isa': 'phase', 'name': 'X', 'files': ['FDDF6A571C68E5B100D7A645']}\n }\n }\n dobj = XcodeProject().parse(obj)\n\n self.assertEqual(dobj.objects['FDDF6A571C68E5B100D7A645']._get_comment(), \"(null) in X\")\n\n def testAddAttributesWithoutSettings(self):\n dobj = PBXBuildFile.create(PBXGenericObject())\n\n dobj.add_attributes(u'Weak')\n\n self.assertIsNotNone(dobj.settings.ATTRIBUTES)\n self.assertEquals(dobj.settings.ATTRIBUTES, [u'Weak'])\n\n def testAddAttributesWithoutAttributes(self):\n dobj = PBXBuildFile.create(PBXGenericObject(), compiler_flags=\"x\")\n\n dobj.add_attributes(u'Weak')\n\n self.assertIsNotNone(dobj.settings.ATTRIBUTES)\n self.assertEquals(dobj.settings.ATTRIBUTES, [u'Weak'])\n\n def testAddAttributesWithAttributes(self):\n dobj = PBXBuildFile.create(PBXGenericObject(), attributes=\"x\")\n dobj.add_attributes(u'Weak')\n\n self.assertIsNotNone(dobj.settings.ATTRIBUTES)\n self.assertEquals(dobj.settings.ATTRIBUTES, [u'x', u'Weak'])\n\n def testRemoveAttributesWithoutSettings(self):\n dobj = PBXBuildFile.create(PBXGenericObject())\n\n dobj.remove_attributes('Weak')\n\n self.assertIsNone(dobj[u'settings'])\n\n def testRemoveAttributesWithSettings(self):\n dobj = PBXBuildFile.create(PBXGenericObject(), attributes=[\"Weak\"])\n\n dobj.remove_attributes('Weak')\n\n self.assertIsNone(dobj[u'settings'])\n\n def testAddCompilerFlagWithoutSettings(self):\n dobj = PBXBuildFile.create(PBXGenericObject())\n\n dobj.add_compiler_flags([u'Weak', '-fno-arc'])\n\n self.assertIsNotNone(dobj.settings.COMPILER_FLAGS)\n self.assertEquals(dobj.settings.COMPILER_FLAGS, u'Weak -fno-arc')\n\n def testAddCompilerFlagWithFlags(self):\n dobj = PBXBuildFile.create(PBXGenericObject(), compiler_flags=[u'Weak', '-fno-arc'])\n\n dobj.add_compiler_flags('x')\n\n self.assertIsNotNone(dobj.settings.COMPILER_FLAGS)\n self.assertEquals(dobj.settings.COMPILER_FLAGS, u'Weak -fno-arc x')\n\n def testRemoveCompilerFlagsWithoutSettings(self):\n dobj = PBXBuildFile.create(PBXGenericObject())\n\n dobj.remove_compiler_flags('Weak')\n\n self.assertIsNone(dobj[u'settings'])\n\n def testRemoveCompilerFlagsWithSettings(self):\n dobj = PBXBuildFile.create(PBXGenericObject(), compiler_flags=u'Weak')\n\n dobj.remove_compiler_flags('Weak')\n\n self.assertIsNone(dobj[u'settings'])\n","sub_path":"tests/pbxsections/TestPBXBuildFile.py","file_name":"TestPBXBuildFile.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"348932960","text":"#Instructions:https://adventofcode.com/2020/day/11\nimport os\nimport numpy as np\n\ndef get_data(filename):\n folder = os.path.dirname(os.path.abspath(__file__))\n input_file = os.path.join(folder, filename)\n data=[]\n\n with open(input_file, 'r') as filehandle:\n for line in filehandle:\n line=line.rstrip()\n l=[]\n for ch in line:\n l.append( ch)\n data.append(l)\n matrix=np.array(data)\n return matrix\n\ndata=get_data(\"test.txt\")\n#print(data)\n#data=np.array([['#','#','#','#'],['D','E','#','#'],['G','H','I','Q'],['K','L','M','L']])\n#print(data)\n#row_num=3\n#col_num=0\n#print(data[row_num][col_num])\n#print(len(data[:]))\n#print(len(data[0][:]))\n#data_next=np.copy(data)\n#data_next[1][1]=\"Z\"\n#print(data[1][1])\n#print(data_next[1][1])\n\n\n\ndef adjacent_seat(row_num,col_num,row_num_target,col_num_target):\n if row_num==row_num_target and col_num==col_num_target:\n return False\n elif abs(col_num -col_num_target)<2 and abs(row_num-row_num_target)<2:\n return True\n\ndef count_occupied_adjacent_seats(row_num_target,col_num_target):\n count=0\n for i in range(len(data)):\n for j in range(len(data[i])):\n if adjacent_seat(i,j,row_num_target,col_num_target)== True and data[i][j]==\"#\":\n count+=1\n return count\n\n\n#print(count_occupied_adjacent_seats(row_num,col_num))\n#print(\"before\")\n#print(data) \ndef one_round(data):\n data_next=np.copy(data)\n count_changes=0\n for i in range(len(data)):\n for j in range(len(data[i])):\n if data[i][j]==\"L\" and count_occupied_adjacent_seats(i,j)==0:\n data_next[i][j]=\"#\"\n count_changes+=1\n\n if data[i][j]==\"#\" and count_occupied_adjacent_seats(i,j)>=4:\n data_next[i][j]=\"L\"\n count_changes+=1\n return data_next,count_changes\n#print(\"after\")\n#print(one_round(data)[0])\n#print(\"num of changes\",one_round(data)[1])\n\n\ndef count_occupied(data):\n \n count=0\n for i in range(len(data)):\n for j in range(len(data[i])):\n if data[i][j]==\"#\" :\n count+=1\n return count\n\n\n\nchanges=1\nround_n=0\nwhile changes!=0:\n round_n+=1\n print(\"round\",round_n)\n data=one_round(data)[0]\n changes=one_round(data)[1]\n print(\"changes\",changes)\n\nprint(count_occupied(data))\n\n\n\n \n\n\n\n","sub_path":"day11/seatingSystem.py","file_name":"seatingSystem.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"573943617","text":"# -*- coding: utf-8 -*-\n# Copyright © 2019 Apple Inc. All rights reserved.\n#\n# Use of this source code is governed by a BSD-3-clause license that can\n# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n#\n\nimport turicreate as _tc\nfrom turicreate import extensions as _extensions\nfrom turicreate.toolkits._model import CustomModel as _CustomModel\nfrom turicreate.toolkits._model import PythonProxy as _PythonProxy\nfrom turicreate.toolkits.object_detector.object_detector import ObjectDetector as _ObjectDetector\nfrom turicreate.toolkits.one_shot_object_detector.util._augmentation import preview_synthetic_training_data as _preview_synthetic_training_data\nimport turicreate.toolkits._internal_utils as _tkutl\n\ndef create(data,\n target,\n backgrounds=None,\n batch_size=0,\n max_iterations=0,\n verbose=True):\n \"\"\"\n Create a :class:`OneShotObjectDetector` model.\n\n Parameters\n ----------\n data : SFrame | tc.Image\n A single starter image or an SFrame that contains the starter images\n along with their corresponding labels. These image(s) can be in either\n RGB or RGBA format. They should not be padded.\n\n target : string\n Name of the target (when data is a single image) or the target column\n name (when data is an SFrame of images).\n\n backgrounds : optional SArray\n A list of backgrounds used for synthetic data generation. When set to\n None, a set of default backgrounds are downloaded and used.\n\n batch_size : int\n The number of images per training iteration. If 0, then it will be\n automatically determined based on resource availability.\n\n max_iterations : int\n The number of training iterations. If 0, then it will be automatically\n be determined based on the amount of data you provide.\n\n verbose : bool optional\n If True, print progress updates and model details.\n\n Examples\n --------\n .. sourcecode:: python\n\n # Train an object detector model\n >>> model = turicreate.one_shot_object_detector.create(train_data, label = 'cards')\n\n # Make predictions on the training set and as column to the SFrame\n >>> test_data['predictions'] = model.predict(test_data)\n \"\"\"\n augmented_data = _preview_synthetic_training_data(data, target, backgrounds)\n model = _tc.object_detector.create( augmented_data,\n batch_size=batch_size,\n max_iterations=max_iterations,\n verbose=verbose)\n if isinstance(data, _tc.SFrame):\n num_starter_images = len(data)\n else:\n num_starter_images = 1\n state = {\n \"detector\": model,\n \"target\": target,\n \"num_classes\": model.num_classes,\n \"num_starter_images\": num_starter_images,\n \"_detector_version\": _ObjectDetector._PYTHON_OBJECT_DETECTOR_VERSION,\n }\n return OneShotObjectDetector(state)\n\nclass OneShotObjectDetector(_CustomModel):\n _PYTHON_ONE_SHOT_OBJECT_DETECTOR_VERSION = 1\n \n def __init__(self, state):\n # We use PythonProxy here so that we get tab completion\n self.__proxy__ = _PythonProxy(state)\n\n def predict(self, dataset):\n return self.__proxy__['detector'].predict(dataset)\n\n def evaluate(self, dataset, metric=\"auto\"):\n return self.__proxy__['detector'].evaluate(dataset, metric)\n\n def _get_version(self):\n return self._PYTHON_ONE_SHOT_OBJECT_DETECTOR_VERSION\n\n @classmethod\n def _native_name(cls):\n return \"one_shot_object_detector\"\n\n def _get_native_state(self):\n # make sure to not accidentally modify the proxy object.\n # take a copy of it.\n state = self.__proxy__.get_state()\n\n # We don't know how to serialize a Python class, hence we need to \n # reduce the detector to the proxy object before saving it.\n state['detector'] = state['detector']._get_native_state()\n return state\n\n @classmethod\n def _load_version(cls, state, version):\n assert(version == cls._PYTHON_ONE_SHOT_OBJECT_DETECTOR_VERSION)\n # we need to undo what we did at save and turn the proxy object\n # back into a Python class\n state['detector'] = _ObjectDetector._load_version(\n state['detector'], state[\"_detector_version\"])\n return OneShotObjectDetector(state)\n\n def __str__(self):\n \"\"\"\n Return a string description of the model to the ``print`` method.\n\n Returns\n -------\n out : string\n A description of the OneShotObjectDetector\n \"\"\"\n return self.__repr__()\n\n def __repr__(self):\n \"\"\"\n Print a string description of the model when the model name is entered\n in the terminal.\n \"\"\"\n width = 40\n sections, section_titles = self._get_summary_struct()\n detector = self.__proxy__['detector']\n out = _tkutl._toolkit_repr_print(detector, sections, section_titles,\n width=width, class_name='OneShotObjectDetector')\n return out\n\n def _get_summary_struct(self):\n \"\"\"\n Returns a structured description of the model, including (where\n relevant) the schema of the training data, description of the training\n data, training statistics, and model hyperparameters.\n\n Returns\n -------\n sections : list (of list of tuples)\n A list of summary sections.\n Each section is a list.\n Each item in a section list is a tuple of the form:\n ('